blob: e51ae4d25587516c85e5d91944665b3d4b024b0b [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
34#include <limits>
Vladimir Markoeb37ba52019-02-05 14:10:38 +000035#include <string_view>
Alex Lighta01de592016-11-15 10:43:06 -080036
Andreas Gampe57943812017-12-06 21:39:13 -080037#include <android-base/logging.h>
38#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080039
Andreas Gampea1d2f952017-04-20 22:53:58 -070040#include "art_field-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080041#include "art_jvmti.h"
Steven Morelande431e272017-07-18 16:53:49 -070042#include "art_method-inl.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010043#include "base/array_ref.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080044#include "class_linker-inl.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010045#include "class_root.h"
Alex Light5643caf2017-02-08 11:39:07 -080046#include "debugger.h"
David Sehr013fd802018-01-11 22:55:24 -080047#include "dex/art_dex_file_loader.h"
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -070048#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080049#include "dex/dex_file.h"
50#include "dex/dex_file_loader.h"
51#include "dex/dex_file_types.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080052#include "dex/signature-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080053#include "events-inl.h"
54#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080055#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080056#include "instrumentation.h"
Alex Light07f06212017-06-01 14:01:43 -070057#include "intern_table.h"
Alex Light5643caf2017-02-08 11:39:07 -080058#include "jdwp/jdwp.h"
59#include "jdwp/jdwp_constants.h"
60#include "jdwp/jdwp_event.h"
61#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080062#include "jit/jit.h"
63#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010064#include "jni/jni_env_ext-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080065#include "jvmti_allocator.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010066#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070067#include "mirror/array-alloc-inl.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070068#include "mirror/class-alloc-inl.h"
Alex Light6161f132017-01-25 10:30:20 -080069#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080070#include "mirror/class_ext.h"
71#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070072#include "mirror/object_array-alloc-inl.h"
73#include "mirror/object_array-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070074#include "nativehelper/scoped_local_ref.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080075#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080076#include "object_lock.h"
77#include "runtime.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010078#include "stack.h"
79#include "thread_list.h"
Alex Lighta26e3492017-06-27 17:55:37 -070080#include "ti_breakpoint.h"
Alex Lighteb98b082017-01-25 13:02:32 -080081#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080082#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080083#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070084#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080085
86namespace openjdkjvmti {
87
Andreas Gampe46ee31b2016-12-14 10:11:49 -080088using android::base::StringPrintf;
89
Alex Lighteee0bd42017-02-14 15:31:45 +000090// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
91// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
92// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
93class ObsoleteMap {
94 public:
95 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
96 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
97 auto method_pair = id_map_.find(original);
98 if (method_pair != id_map_.end()) {
99 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
100 method_pair->second, art::kRuntimePointerSize);
101 DCHECK(res != nullptr);
102 DCHECK_EQ(original, res->GetNonObsoleteMethod());
103 return res;
104 } else {
105 return nullptr;
106 }
107 }
108
109 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
110 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
111 DCHECK(original != nullptr);
112 DCHECK(obsolete != nullptr);
113 int32_t slot = next_free_slot_++;
114 DCHECK_LT(slot, obsolete_methods_->GetLength());
115 DCHECK(nullptr ==
116 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
117 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
118 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
119 obsolete_dex_caches_->Set(slot, original_dex_cache_);
120 id_map_.insert({original, slot});
121 }
122
123 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
124 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
125 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
126 : next_free_slot_(0),
127 obsolete_methods_(obsolete_methods),
128 obsolete_dex_caches_(obsolete_dex_caches),
129 original_dex_cache_(original_dex_cache) {
130 // Figure out where the first unused slot in the obsolete_methods_ array is.
131 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
132 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
133 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
134 next_free_slot_++;
135 }
136 // Sanity check that the same slot in obsolete_dex_caches_ is free.
137 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
138 }
139
140 private:
141 int32_t next_free_slot_;
142 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
143 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
144 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
145 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
146 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
147 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
148};
149
Alex Lightdba61482016-12-21 08:20:29 -0800150// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
151// some basic sanity checks that the obsolete method is sane.
152class ObsoleteMethodStackVisitor : public art::StackVisitor {
153 protected:
154 ObsoleteMethodStackVisitor(
155 art::Thread* thread,
156 art::LinearAlloc* allocator,
157 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000158 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800159 : StackVisitor(thread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700160 /*context=*/nullptr,
Alex Lightdba61482016-12-21 08:20:29 -0800161 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
162 allocator_(allocator),
163 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800164 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800165
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100166 ~ObsoleteMethodStackVisitor() override {}
Alex Lightdba61482016-12-21 08:20:29 -0800167
168 public:
169 // Returns true if we successfully installed obsolete methods on this thread, filling
170 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
171 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800172 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800173 art::Thread* thread,
174 art::LinearAlloc* allocator,
175 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000176 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800177 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800178 ObsoleteMethodStackVisitor visitor(thread,
179 allocator,
180 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800181 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800182 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800183 }
184
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100185 bool VisitFrame() override REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000186 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800187 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800188 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800189 // We cannot ensure that the right dex file is used in inlined frames so we don't support
190 // redefining them.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000191 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition: "
192 << old_method->PrettyMethod() << " is inlined into "
193 << GetOuterMethod()->PrettyMethod();
Alex Lighteee0bd42017-02-14 15:31:45 +0000194 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
195 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800196 // Create a new Obsolete Method and put it in the list.
197 art::Runtime* runtime = art::Runtime::Current();
198 art::ClassLinker* cl = runtime->GetClassLinker();
199 auto ptr_size = cl->GetImagePointerSize();
200 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800201 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800202 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
203 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800204 new_obsolete_method = new (method_storage) art::ArtMethod();
205 new_obsolete_method->CopyFrom(old_method, ptr_size);
206 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
207 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800208 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700209 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000210 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800211 // Update JIT Data structures to point to the new method.
212 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
213 if (jit != nullptr) {
214 // Notify the JIT we are making this obsolete method. It will update the jit's internal
215 // structures to keep track of the new obsolete method.
216 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
217 }
Alex Lightdba61482016-12-21 08:20:29 -0800218 }
219 DCHECK(new_obsolete_method != nullptr);
220 SetMethod(new_obsolete_method);
221 }
222 return true;
223 }
224
225 private:
226 // The linear allocator we should use to make new methods.
227 art::LinearAlloc* allocator_;
228 // The set of all methods which could be obsoleted.
229 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
230 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000231 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
232 // the redefined classes ClassExt as it is filled.
233 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800234};
235
Alex Lighte4a88632017-01-10 07:41:24 -0800236jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
237 jclass klass,
238 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800239 art::Thread* self = art::Thread::Current();
240 art::ScopedObjectAccess soa(self);
241 art::StackHandleScope<1> hs(self);
242 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
Alex Light413a8ad2019-02-14 10:19:44 -0800243 if (obj.IsNull() || !obj->IsClass()) {
Alex Lighte4a88632017-01-10 07:41:24 -0800244 return ERR(INVALID_CLASS);
245 }
246 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
247 std::string err_unused;
248 *is_redefinable =
Alex Light9e7859c2018-04-05 13:49:43 -0700249 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
250 ? JNI_TRUE : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800251 return OK;
252}
253
Alex Light9e7859c2018-04-05 13:49:43 -0700254jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
255 art::Thread* self = art::Thread::Current();
256 art::ScopedObjectAccess soa(self);
257 art::StackHandleScope<1> hs(self);
258 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
Alex Light413a8ad2019-02-14 10:19:44 -0800259 if (obj.IsNull() || !obj->IsClass()) {
Alex Light9e7859c2018-04-05 13:49:43 -0700260 return ERR(INVALID_CLASS);
261 }
262 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
263 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
264}
265
Alex Lighte4a88632017-01-10 07:41:24 -0800266jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
267 /*out*/std::string* error_msg) {
Alex Light9e7859c2018-04-05 13:49:43 -0700268 if (!klass->IsResolved()) {
269 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
270 // the same thread as the class-linking process. If it's on another thread we will be able to
271 // wait for the preparation to finish and continue from there.
272 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
273 *error_msg = "Modification of class " + klass->PrettyClass() +
274 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
275 " Please use ClassFileLoadHook directly instead.";
276 return ERR(INTERNAL);
277 } else {
278 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
279 << "it could cause arbitrary length waits as the class is being resolved.";
280 }
281 }
Alex Lighte4a88632017-01-10 07:41:24 -0800282 if (klass->IsPrimitive()) {
283 *error_msg = "Modification of primitive classes is not supported";
284 return ERR(UNMODIFIABLE_CLASS);
285 } else if (klass->IsInterface()) {
286 *error_msg = "Modification of Interface classes is currently not supported";
287 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800288 } else if (klass->IsStringClass()) {
289 *error_msg = "Modification of String class is not supported";
290 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800291 } else if (klass->IsArrayClass()) {
292 *error_msg = "Modification of Array classes is not supported";
293 return ERR(UNMODIFIABLE_CLASS);
294 } else if (klass->IsProxyClass()) {
295 *error_msg = "Modification of proxy classes is not supported";
296 return ERR(UNMODIFIABLE_CLASS);
297 }
298
Alex Lighte77b48b2017-02-22 11:08:06 -0800299 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
300 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
301 *error_msg = "Class might have stack frames that cannot be made obsolete";
302 return ERR(UNMODIFIABLE_CLASS);
303 }
304 }
305
Alex Lighte4a88632017-01-10 07:41:24 -0800306 return OK;
307}
308
Alex Lighta01de592016-11-15 10:43:06 -0800309// Moves dex data to an anonymous, read-only mmap'd region.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100310art::MemMap Redefiner::MoveDataToMemMap(const std::string& original_location,
311 art::ArrayRef<const unsigned char> data,
312 std::string* error_msg) {
313 art::MemMap map = art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800314 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lightb7354d52017-03-30 15:17:01 -0700315 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800316 PROT_READ|PROT_WRITE,
Andreas Gampe6e897762018-10-16 13:09:32 -0700317 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100318 error_msg);
319 if (LIKELY(map.IsValid())) {
320 memcpy(map.Begin(), data.data(), data.size());
321 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
322 // programs from corrupting it.
323 map.Protect(PROT_READ);
Alex Lighta01de592016-11-15 10:43:06 -0800324 }
Alex Lighta01de592016-11-15 10:43:06 -0800325 return map;
326}
327
Alex Lighta7e38d82017-01-19 14:57:28 -0800328Redefiner::ClassRedefinition::ClassRedefinition(
329 Redefiner* driver,
330 jclass klass,
331 const art::DexFile* redefined_dex_file,
332 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100333 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800334 driver_(driver),
335 klass_(klass),
336 dex_file_(redefined_dex_file),
337 class_sig_(class_sig),
338 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800339 GetMirrorClass()->MonitorEnter(driver_->self_);
340}
341
342Redefiner::ClassRedefinition::~ClassRedefinition() {
343 if (driver_ != nullptr) {
344 GetMirrorClass()->MonitorExit(driver_->self_);
345 }
346}
347
Alex Light0e692732017-01-10 15:00:05 -0800348jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800349 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800350 art::Runtime* runtime,
351 art::Thread* self,
352 jint class_count,
353 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800354 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800355 if (env == nullptr) {
356 *error_msg = "env was null!";
357 return ERR(INVALID_ENVIRONMENT);
358 } else if (class_count < 0) {
359 *error_msg = "class_count was less then 0";
360 return ERR(ILLEGAL_ARGUMENT);
361 } else if (class_count == 0) {
362 // We don't actually need to do anything. Just return OK.
363 return OK;
364 } else if (definitions == nullptr) {
365 *error_msg = "null definitions!";
366 return ERR(NULL_POINTER);
367 }
Alex Light6ac57502017-01-19 15:05:06 -0800368 std::vector<ArtClassDefinition> def_vector;
369 def_vector.reserve(class_count);
370 for (jint i = 0; i < class_count; i++) {
Alex Light9e7859c2018-04-05 13:49:43 -0700371 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800372 if (res != OK) {
373 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800374 }
Alex Light6ac57502017-01-19 15:05:06 -0800375 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800376 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800377 if (res != OK) {
378 return res;
379 }
380 def_vector.push_back(std::move(def));
381 }
382 // Call all the transformation events.
Alex Light64e4c142018-01-30 13:46:37 -0800383 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800384 self,
385 &def_vector);
386 if (res != OK) {
387 // Something went wrong with transformation!
388 return res;
389 }
390 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
391}
392
393jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
394 art::Runtime* runtime,
395 art::Thread* self,
396 const std::vector<ArtClassDefinition>& definitions,
397 std::string* error_msg) {
398 DCHECK(env != nullptr);
399 if (definitions.size() == 0) {
400 // We don't actually need to do anything. Just return OK.
401 return OK;
402 }
Alex Light0e692732017-01-10 15:00:05 -0800403 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
404 // are going to redefine.
405 art::jit::ScopedJitSuspend suspend_jit;
406 // Get shared mutator lock so we can lock all the classes.
407 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700408 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800409 for (const ArtClassDefinition& def : definitions) {
410 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700411 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800412 jvmtiError res = r.AddRedefinition(env, def);
413 if (res != OK) {
414 return res;
415 }
Alex Light0e692732017-01-10 15:00:05 -0800416 }
417 }
418 return r.Run();
419}
420
Alex Light6ac57502017-01-19 15:05:06 -0800421jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800422 std::string original_dex_location;
423 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700424 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800425 *error_msg_ = "Unable to get original dex file location!";
426 return ret;
427 }
Alex Light52a2db52017-01-19 23:00:21 +0000428 char* generic_ptr_unused = nullptr;
429 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700430 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800431 *error_msg_ = "Unable to get class signature!";
432 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000433 }
Andreas Gampe54711412017-02-21 12:41:43 -0800434 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
435 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100436 art::MemMap map = MoveDataToMemMap(original_dex_location, def.GetDexData(), error_msg_);
Alex Light6ac57502017-01-19 15:05:06 -0800437 std::ostringstream os;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100438 if (!map.IsValid()) {
Alex Lightb7354d52017-03-30 15:17:01 -0700439 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800440 << "in dex file " << original_dex_location << " because: " << *error_msg_;
441 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800442 return ERR(OUT_OF_MEMORY);
443 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100444 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800445 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800446 return ERR(INVALID_CLASS_FORMAT);
447 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100448 std::string name = map.GetName();
449 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800450 const art::ArtDexFileLoader dex_file_loader;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100451 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(name,
David Sehr013fd802018-01-11 22:55:24 -0800452 checksum,
453 std::move(map),
Andreas Gampe6e897762018-10-16 13:09:32 -0700454 /*verify=*/true,
455 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800456 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800457 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700458 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800459 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800460 return ERR(INVALID_CLASS_FORMAT);
461 }
Alex Light0e692732017-01-10 15:00:05 -0800462 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800463 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700464 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800465 dex_file.release(),
466 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700467 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800468 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800469}
470
Alex Light0e692732017-01-10 15:00:05 -0800471art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
472 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800473}
474
Alex Light0e692732017-01-10 15:00:05 -0800475art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800476 return GetMirrorClass()->GetClassLoader();
477}
478
Alex Light0e692732017-01-10 15:00:05 -0800479art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
480 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700481 art::StackHandleScope<2> hs(driver_->self_);
482 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
483 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
484 art::ObjPtr<art::mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100485 art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
Alex Light07f06212017-06-01 14:01:43 -0700486 if (cache.IsNull()) {
487 driver_->self_->AssertPendingOOMException();
488 return nullptr;
489 }
490 art::Handle<art::mirror::String> location(hs.NewHandle(
491 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
492 if (location.IsNull()) {
493 driver_->self_->AssertPendingOOMException();
494 return nullptr;
495 }
496 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
497 art::mirror::DexCache::InitializeDexCache(driver_->self_,
498 cache.Get(),
499 location.Get(),
500 dex_file_.get(),
501 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
502 : loader->GetAllocator(),
503 art::kRuntimePointerSize);
504 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800505}
506
Alex Light0e692732017-01-10 15:00:05 -0800507void Redefiner::RecordFailure(jvmtiError result,
508 const std::string& class_sig,
509 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800510 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800511 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800512 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800513 result_ = result;
514}
515
Alex Light2f814aa2017-03-24 15:21:34 +0000516art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800517 // If we have been specifically given a new set of bytes use that
518 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800519 return art::mirror::ByteArray::AllocateAndFill(
520 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100521 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Vladimir Markobcf17522018-06-01 13:14:32 +0100522 original_dex_file_.size()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800523 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800524
525 // See if we already have one set.
526 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
527 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000528 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
529 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800530 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000531 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800532 }
Alex Lighta01de592016-11-15 10:43:06 -0800533 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800534
Alex Light2f814aa2017-03-24 15:21:34 +0000535 // return the current dex_cache which has the dex file in it.
536 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800537 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000538 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800539 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
540 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800541 }
Alex Light2f814aa2017-03-24 15:21:34 +0000542 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800543}
544
Alex Lightdba61482016-12-21 08:20:29 -0800545struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000546 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800547 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800548 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800549
Alex Lighteee0bd42017-02-14 15:31:45 +0000550 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
551 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800552};
553
Alex Lightdba61482016-12-21 08:20:29 -0800554void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
555 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800556 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
557 data->allocator,
558 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000559 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800560}
561
562// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
563// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800564// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
Vladimir Markod93e3742018-07-18 10:58:13 +0100565void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(
566 art::ObjPtr<art::mirror::Class> art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800567 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
Vladimir Markod93e3742018-07-18 10:58:13 +0100568 art::ObjPtr<art::mirror::ClassExt> ext = art_klass->GetExtData();
Alex Lightdba61482016-12-21 08:20:29 -0800569 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800570 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000571 // This holds pointers to the obsolete methods map fields which are updated as needed.
572 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
573 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800574 // Add all the declared methods to the map
575 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800576 if (m.IsIntrinsic()) {
577 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
578 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
579 << "methods that have already been compiled.";
580 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000581 // It is possible to simply filter out some methods where they cannot really become obsolete,
582 // such as native methods and keep their original (possibly optimized) implementations. We don't
583 // do this, however, since we would need to mark these functions (still in the classes
584 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
585 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
586 // error checking from the interpreter which ensure we don't try to start executing obsolete
587 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000588 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800589 }
590 {
Alex Light0e692732017-01-10 15:00:05 -0800591 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800592 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
593 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800594 }
Alex Lightdba61482016-12-21 08:20:29 -0800595}
596
Alex Light6161f132017-01-25 10:30:20 -0800597// Try and get the declared method. First try to get a virtual method then a direct method if that's
598// not found.
599static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
Vladimir Markoeb37ba52019-02-05 14:10:38 +0000600 std::string_view name,
Alex Light6161f132017-01-25 10:30:20 -0800601 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markoba118822017-06-12 15:41:56 +0100602 DCHECK(!klass->IsProxyClass());
603 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
604 if (m.GetName() == name && m.GetSignature() == sig) {
605 return &m;
606 }
Alex Light6161f132017-01-25 10:30:20 -0800607 }
Vladimir Markoba118822017-06-12 15:41:56 +0100608 return nullptr;
Alex Light6161f132017-01-25 10:30:20 -0800609}
610
611bool Redefiner::ClassRedefinition::CheckSameMethods() {
612 art::StackHandleScope<1> hs(driver_->self_);
613 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
614 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
615
Alex Light6161f132017-01-25 10:30:20 -0800616 // Make sure we have the same number of methods.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700617 art::ClassAccessor accessor(*dex_file_, dex_file_->GetClassDef(0));
618 uint32_t num_new_method = accessor.NumMethods();
Alex Light6161f132017-01-25 10:30:20 -0800619 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
620 if (num_new_method != num_old_method) {
621 bool bigger = num_new_method > num_old_method;
622 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
623 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
624 StringPrintf("Total number of declared methods changed from %d to %d",
625 num_old_method, num_new_method));
626 return false;
627 }
628
629 // Skip all of the fields. We should have already checked this.
Alex Light6161f132017-01-25 10:30:20 -0800630 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
631 // files have the same number of methods, which means there must be an equal amount of additions
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700632 // and removals. We should have already checked the fields.
633 for (const art::ClassAccessor::Method& method : accessor.GetMethods()) {
Alex Light6161f132017-01-25 10:30:20 -0800634 // Get the data on the method we are searching for
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800635 const art::dex::MethodId& new_method_id = dex_file_->GetMethodId(method.GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800636 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
637 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
638 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
639 // If we got past the check for the same number of methods above that means there must be at
640 // least one added and one removed method. We will return the ADDED failure message since it is
641 // easier to get a useful error report for it.
642 if (old_method == nullptr) {
643 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
644 StringPrintf("Unknown method '%s' (sig: %s) was added!",
645 new_method_name,
646 new_method_signature.ToString().c_str()));
647 return false;
648 }
649 // Since direct methods have different flags than virtual ones (specifically direct methods must
650 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
651 // virtual to direct.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700652 uint32_t new_flags = method.GetAccessFlags();
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100653 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
Alex Light6161f132017-01-25 10:30:20 -0800654 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
655 StringPrintf("method '%s' (sig: %s) had different access flags",
656 new_method_name,
657 new_method_signature.ToString().c_str()));
658 return false;
659 }
660 }
661 return true;
662}
663
664bool Redefiner::ClassRedefinition::CheckSameFields() {
665 art::StackHandleScope<1> hs(driver_->self_);
666 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
667 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700668 art::ClassAccessor new_accessor(*dex_file_, dex_file_->GetClassDef(0));
669
Alex Light6161f132017-01-25 10:30:20 -0800670 const art::DexFile& old_dex_file = h_klass->GetDexFile();
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700671 art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
Alex Light6161f132017-01-25 10:30:20 -0800672 // Instance and static fields can be differentiated by their flags so no need to check them
673 // separately.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700674 auto old_fields = old_accessor.GetFields();
675 auto old_iter = old_fields.begin();
676 for (const art::ClassAccessor::Field& new_field : new_accessor.GetFields()) {
Alex Light6161f132017-01-25 10:30:20 -0800677 // Get the data on the method we are searching for
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800678 const art::dex::FieldId& new_field_id = dex_file_->GetFieldId(new_field.GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800679 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
680 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
681
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700682 if (old_iter == old_fields.end()) {
Alex Light6161f132017-01-25 10:30:20 -0800683 // We are missing the old version of this method!
684 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
685 StringPrintf("Unknown field '%s' (type: %s) added!",
686 new_field_name,
687 new_field_type));
688 return false;
689 }
690
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800691 const art::dex::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter->GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800692 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
693 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
694
695 // Check name and type.
696 if (strcmp(old_field_name, new_field_name) != 0 ||
697 strcmp(old_field_type, new_field_type) != 0) {
698 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
699 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
700 old_field_name,
701 old_field_type,
702 new_field_name,
703 new_field_type));
704 return false;
705 }
706
707 // Since static fields have different flags than instance ones (specifically static fields must
708 // have the kAccStatic flag) we can tell if a field changes from static to instance.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700709 if (new_field.GetAccessFlags() != old_iter->GetAccessFlags()) {
Alex Light6161f132017-01-25 10:30:20 -0800710 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
711 StringPrintf("Field '%s' (sig: %s) had different access flags",
712 new_field_name,
713 new_field_type));
714 return false;
715 }
716
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700717 ++old_iter;
Alex Light6161f132017-01-25 10:30:20 -0800718 }
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700719 if (old_iter != old_fields.end()) {
Alex Light6161f132017-01-25 10:30:20 -0800720 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
721 StringPrintf("field '%s' (sig: %s) is missing!",
722 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700723 old_iter->GetIndex())),
Alex Light6161f132017-01-25 10:30:20 -0800724 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700725 old_iter->GetIndex()))));
Alex Light6161f132017-01-25 10:30:20 -0800726 return false;
727 }
728 return true;
729}
730
Alex Light0e692732017-01-10 15:00:05 -0800731bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800732 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000733 // Easy check that only 1 class def is present.
734 if (dex_file_->NumClassDefs() != 1) {
735 RecordFailure(ERR(ILLEGAL_ARGUMENT),
736 StringPrintf("Expected 1 class def in dex file but found %d",
737 dex_file_->NumClassDefs()));
738 return false;
739 }
740 // Get the ClassDef from the new DexFile.
741 // Since the dex file has only a single class def the index is always 0.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800742 const art::dex::ClassDef& def = dex_file_->GetClassDef(0);
Alex Light460d1b42017-01-10 15:37:17 +0000743 // Get the class as it is now.
744 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
745
746 // Check the access flags didn't change.
747 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
748 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
749 "Cannot change modifiers of class by redefinition");
750 return false;
751 }
752
753 // Check class name.
754 // These should have been checked by the dexfile verifier on load.
755 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
756 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
757 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
758 if (!current_class->DescriptorEquals(descriptor)) {
759 std::string storage;
760 RecordFailure(ERR(NAMES_DONT_MATCH),
761 StringPrintf("expected file to contain class called '%s' but found '%s'!",
762 current_class->GetDescriptor(&storage),
763 descriptor));
764 return false;
765 }
766 if (current_class->IsObjectClass()) {
767 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
768 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
769 return false;
770 }
771 } else {
772 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
773 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
774 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
775 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
776 return false;
777 }
778 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800779 const art::dex::TypeList* interfaces = dex_file_->GetInterfacesList(def);
Alex Light460d1b42017-01-10 15:37:17 +0000780 if (interfaces == nullptr) {
781 if (current_class->NumDirectInterfaces() != 0) {
782 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
783 return false;
784 }
785 } else {
786 DCHECK(!current_class->IsProxyClass());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800787 const art::dex::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
Alex Light460d1b42017-01-10 15:37:17 +0000788 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
789 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
790 return false;
791 }
792 // The order of interfaces is (barely) meaningful so we error if it changes.
793 const art::DexFile& orig_dex_file = current_class->GetDexFile();
794 for (uint32_t i = 0; i < interfaces->Size(); i++) {
795 if (strcmp(
796 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
797 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
798 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
799 "Interfaces changed or re-ordered");
800 return false;
801 }
802 }
803 }
Alex Light460d1b42017-01-10 15:37:17 +0000804 return true;
805}
806
Alex Light0e692732017-01-10 15:00:05 -0800807bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800808 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800809 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000810
Alex Lighte4a88632017-01-10 07:41:24 -0800811 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
812 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
813 if (res != OK) {
814 RecordFailure(res, err);
815 return false;
816 } else {
817 return true;
818 }
Alex Light460d1b42017-01-10 15:37:17 +0000819}
820
Alex Light0e692732017-01-10 15:00:05 -0800821bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000822 return CheckRedefinable() &&
823 CheckClass() &&
824 CheckSameFields() &&
825 CheckSameMethods();
826}
827
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800828class RedefinitionDataIter;
829
Alex Light0e692732017-01-10 15:00:05 -0800830// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
831// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
832// having to deal with the fact that we need to hold an arbitrary number of references live.
833class RedefinitionDataHolder {
834 public:
835 enum DataSlot : int32_t {
836 kSlotSourceClassLoader = 0,
837 kSlotJavaDexFile = 1,
838 kSlotNewDexFileCookie = 2,
839 kSlotNewDexCache = 3,
840 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800841 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700842 kSlotOldObsoleteMethods = 6,
843 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800844
845 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700846 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800847 };
848
849 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
850 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
851 // the passed in handle-scope.
852 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
853 art::Runtime* runtime,
854 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800855 std::vector<Redefiner::ClassRedefinition>* redefinitions)
856 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100857 arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
858 self,
859 art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
860 redefinitions->size() * kNumSlots))),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800861 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800862
863 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
864 return arr_.IsNull();
865 }
866
Vladimir Markod93e3742018-07-18 10:58:13 +0100867 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800868 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100869 return art::ObjPtr<art::mirror::ClassLoader>::DownCast(
870 GetSlot(klass_index, kSlotSourceClassLoader));
Alex Light0e692732017-01-10 15:00:05 -0800871 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100872 art::ObjPtr<art::mirror::Object> GetJavaDexFile(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -0800873 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800874 return GetSlot(klass_index, kSlotJavaDexFile);
875 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100876 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800877 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100878 return art::ObjPtr<art::mirror::LongArray>::DownCast(
879 GetSlot(klass_index, kSlotNewDexFileCookie));
Alex Light0e692732017-01-10 15:00:05 -0800880 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100881 art::ObjPtr<art::mirror::DexCache> GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800882 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100883 return art::ObjPtr<art::mirror::DexCache>::DownCast(GetSlot(klass_index, kSlotNewDexCache));
Alex Light0e692732017-01-10 15:00:05 -0800884 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100885 art::ObjPtr<art::mirror::Class> GetMirrorClass(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -0800886 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100887 return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotMirrorClass));
Alex Light0e692732017-01-10 15:00:05 -0800888 }
889
Vladimir Markod93e3742018-07-18 10:58:13 +0100890 art::ObjPtr<art::mirror::Object> GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800891 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100892 return art::ObjPtr<art::mirror::Object>::DownCast(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800893 }
894
Vladimir Markod93e3742018-07-18 10:58:13 +0100895 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods(jint klass_index) const
Alex Light1e3926a2017-04-07 10:38:06 -0700896 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100897 return art::ObjPtr<art::mirror::PointerArray>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -0700898 GetSlot(klass_index, kSlotOldObsoleteMethods));
899 }
900
Vladimir Markod93e3742018-07-18 10:58:13 +0100901 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches(
902 jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
903 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -0700904 GetSlot(klass_index, kSlotOldDexCaches));
905 }
906
Vladimir Markod93e3742018-07-18 10:58:13 +0100907 void SetSourceClassLoader(jint klass_index, art::ObjPtr<art::mirror::ClassLoader> loader)
Alex Light0e692732017-01-10 15:00:05 -0800908 REQUIRES_SHARED(art::Locks::mutator_lock_) {
909 SetSlot(klass_index, kSlotSourceClassLoader, loader);
910 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100911 void SetJavaDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> dexfile)
Alex Light0e692732017-01-10 15:00:05 -0800912 REQUIRES_SHARED(art::Locks::mutator_lock_) {
913 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
914 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100915 void SetNewDexFileCookie(jint klass_index, art::ObjPtr<art::mirror::LongArray> cookie)
Alex Light0e692732017-01-10 15:00:05 -0800916 REQUIRES_SHARED(art::Locks::mutator_lock_) {
917 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
918 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100919 void SetNewDexCache(jint klass_index, art::ObjPtr<art::mirror::DexCache> cache)
Alex Light0e692732017-01-10 15:00:05 -0800920 REQUIRES_SHARED(art::Locks::mutator_lock_) {
921 SetSlot(klass_index, kSlotNewDexCache, cache);
922 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100923 void SetMirrorClass(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
Alex Light0e692732017-01-10 15:00:05 -0800924 REQUIRES_SHARED(art::Locks::mutator_lock_) {
925 SetSlot(klass_index, kSlotMirrorClass, klass);
926 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100927 void SetOriginalDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800928 REQUIRES_SHARED(art::Locks::mutator_lock_) {
929 SetSlot(klass_index, kSlotOrigDexFile, bytes);
930 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100931 void SetOldObsoleteMethods(jint klass_index, art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -0700932 REQUIRES_SHARED(art::Locks::mutator_lock_) {
933 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
934 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100935 void SetOldDexCaches(jint klass_index,
936 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -0700937 REQUIRES_SHARED(art::Locks::mutator_lock_) {
938 SetSlot(klass_index, kSlotOldDexCaches, caches);
939 }
Alex Light0e692732017-01-10 15:00:05 -0800940
Alex Light8c889d22017-02-06 13:58:27 -0800941 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800942 return arr_->GetLength() / kNumSlots;
943 }
944
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800945 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
946 REQUIRES_SHARED(art::Locks::mutator_lock_) {
947 return redefinitions_;
948 }
949
950 bool operator==(const RedefinitionDataHolder& other) const
951 REQUIRES_SHARED(art::Locks::mutator_lock_) {
952 return arr_.Get() == other.arr_.Get();
953 }
954
955 bool operator!=(const RedefinitionDataHolder& other) const
956 REQUIRES_SHARED(art::Locks::mutator_lock_) {
957 return !(*this == other);
958 }
959
960 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
961 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
962
Alex Light0e692732017-01-10 15:00:05 -0800963 private:
Alex Light8c889d22017-02-06 13:58:27 -0800964 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800965 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800966
Vladimir Markod93e3742018-07-18 10:58:13 +0100967 art::ObjPtr<art::mirror::Object> GetSlot(jint klass_index, DataSlot slot) const
968 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800969 DCHECK_LT(klass_index, Length());
970 return arr_->Get((kNumSlots * klass_index) + slot);
971 }
972
973 void SetSlot(jint klass_index,
974 DataSlot slot,
975 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
976 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
977 DCHECK_LT(klass_index, Length());
978 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
979 }
980
981 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
982};
983
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800984class RedefinitionDataIter {
985 public:
986 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
987
988 RedefinitionDataIter(const RedefinitionDataIter&) = default;
989 RedefinitionDataIter(RedefinitionDataIter&&) = default;
990 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
991 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
992
993 bool operator==(const RedefinitionDataIter& other) const
994 REQUIRES_SHARED(art::Locks::mutator_lock_) {
995 return idx_ == other.idx_ && holder_ == other.holder_;
996 }
997
998 bool operator!=(const RedefinitionDataIter& other) const
999 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1000 return !(*this == other);
1001 }
1002
1003 RedefinitionDataIter operator++() { // Value after modification.
1004 idx_++;
1005 return *this;
1006 }
1007
1008 RedefinitionDataIter operator++(int) {
1009 RedefinitionDataIter temp = *this;
1010 idx_++;
1011 return temp;
1012 }
1013
1014 RedefinitionDataIter operator+(ssize_t delta) const {
1015 RedefinitionDataIter temp = *this;
1016 temp += delta;
1017 return temp;
1018 }
1019
1020 RedefinitionDataIter& operator+=(ssize_t delta) {
1021 idx_ += delta;
1022 return *this;
1023 }
1024
1025 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1026 return (*holder_.GetRedefinitions())[idx_];
1027 }
1028
1029 RedefinitionDataHolder& GetHolder() {
1030 return holder_;
1031 }
1032
Vladimir Markod93e3742018-07-18 10:58:13 +01001033 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001034 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1035 return holder_.GetSourceClassLoader(idx_);
1036 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001037 art::ObjPtr<art::mirror::Object> GetJavaDexFile() const
1038 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001039 return holder_.GetJavaDexFile(idx_);
1040 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001041 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie() const
1042 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001043 return holder_.GetNewDexFileCookie(idx_);
1044 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001045 art::ObjPtr<art::mirror::DexCache> GetNewDexCache() const
1046 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001047 return holder_.GetNewDexCache(idx_);
1048 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001049 art::ObjPtr<art::mirror::Class> GetMirrorClass() const
1050 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001051 return holder_.GetMirrorClass(idx_);
1052 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001053 art::ObjPtr<art::mirror::Object> GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001054 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001055 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001056 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001057 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods() const
Alex Light1e3926a2017-04-07 10:38:06 -07001058 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1059 return holder_.GetOldObsoleteMethods(idx_);
1060 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001061 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches() const
Alex Light1e3926a2017-04-07 10:38:06 -07001062 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1063 return holder_.GetOldDexCaches(idx_);
1064 }
1065
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001066 int32_t GetIndex() const {
1067 return idx_;
1068 }
1069
1070 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1071 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1072 holder_.SetSourceClassLoader(idx_, loader);
1073 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001074 void SetJavaDexFile(art::ObjPtr<art::mirror::Object> dexfile)
1075 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001076 holder_.SetJavaDexFile(idx_, dexfile);
1077 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001078 void SetNewDexFileCookie(art::ObjPtr<art::mirror::LongArray> cookie)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001079 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1080 holder_.SetNewDexFileCookie(idx_, cookie);
1081 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001082 void SetNewDexCache(art::ObjPtr<art::mirror::DexCache> cache)
1083 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001084 holder_.SetNewDexCache(idx_, cache);
1085 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001086 void SetMirrorClass(art::ObjPtr<art::mirror::Class> klass)
1087 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001088 holder_.SetMirrorClass(idx_, klass);
1089 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001090 void SetOriginalDexFile(art::ObjPtr<art::mirror::Object> bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001091 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001092 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001093 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001094 void SetOldObsoleteMethods(art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -07001095 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1096 holder_.SetOldObsoleteMethods(idx_, methods);
1097 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001098 void SetOldDexCaches(art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -07001099 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1100 holder_.SetOldDexCaches(idx_, caches);
1101 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001102
1103 private:
1104 int32_t idx_;
1105 RedefinitionDataHolder& holder_;
1106};
1107
1108RedefinitionDataIter RedefinitionDataHolder::begin() {
1109 return RedefinitionDataIter(0, *this);
1110}
1111
1112RedefinitionDataIter RedefinitionDataHolder::end() {
1113 return RedefinitionDataIter(Length(), *this);
1114}
1115
1116bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001117 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1118 art::StackHandleScope<2> hs(driver_->self_);
1119 std::string error;
1120 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001121 art::verifier::FailureKind failure =
Alex Light8c889d22017-02-06 13:58:27 -08001122 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1123 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001124 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001125 hs.NewHandle(GetClassLoader()),
Andreas Gampe6e897762018-10-16 13:09:32 -07001126 /*class_def=*/ dex_file_->GetClassDef(0),
1127 /*callbacks=*/ nullptr,
1128 /*allow_soft_failures=*/ true,
1129 /*log_level=*/
Alex Light8c889d22017-02-06 13:58:27 -08001130 art::verifier::HardFailLogMode::kLogWarning,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001131 art::Runtime::Current()->GetTargetSdkVersion(),
Alex Light8c889d22017-02-06 13:58:27 -08001132 &error);
Alex Light53330612017-10-04 15:29:53 -07001133 switch (failure) {
1134 case art::verifier::FailureKind::kNoFailure:
1135 case art::verifier::FailureKind::kSoftFailure:
1136 return true;
1137 case art::verifier::FailureKind::kHardFailure: {
1138 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1139 return false;
1140 }
Alex Light8c889d22017-02-06 13:58:27 -08001141 }
Alex Light8c889d22017-02-06 13:58:27 -08001142}
1143
Alex Light1babae02017-02-01 15:35:34 -08001144// Looks through the previously allocated cookies to see if we need to update them with another new
1145// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1146// once they are all added to the classloader.
1147bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001148 art::Handle<art::mirror::ClassLoader> source_class_loader,
1149 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001150 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001151 art::StackHandleScope<2> hs(driver_->self_);
1152 art::MutableHandle<art::mirror::LongArray> old_cookie(
1153 hs.NewHandle<art::mirror::LongArray>(nullptr));
1154 bool has_older_cookie = false;
1155 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001156 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1157 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001158 // Since every instance of this classloader should have the same cookie associated with it we
1159 // can stop looking here.
1160 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001161 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001162 break;
1163 }
1164 }
1165 if (old_cookie.IsNull()) {
1166 // No older cookie. Get it directly from the dex_file_obj
1167 // We should not have seen this classloader elsewhere.
1168 CHECK(!has_older_cookie);
1169 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1170 }
1171 // Use the old cookie to generate the new one with the new DexFile* added in.
1172 art::Handle<art::mirror::LongArray>
1173 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1174 old_cookie,
1175 dex_file_.get())));
1176 // Make sure the allocation worked.
1177 if (new_cookie.IsNull()) {
1178 return false;
1179 }
1180
1181 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001182 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001183 // If there are other copies of this same classloader we need to make sure that we all have the
1184 // same cookie.
1185 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001186 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001187 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001188 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1189 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001190 }
1191 }
1192 }
1193
1194 return true;
1195}
1196
Alex Lighta7e38d82017-01-19 14:57:28 -08001197bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001198 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001199 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001200 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001201 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001202 // This shouldn't allocate
1203 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001204 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1205 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001206 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001207 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1208 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001209 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001210 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001211 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1212 return false;
1213 }
Alex Light1babae02017-02-01 15:35:34 -08001214 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001215 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001216 driver_->self_->AssertPendingOOMException();
1217 driver_->self_->ClearException();
1218 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1219 return false;
1220 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001221 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001222 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1223 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001224 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001225 driver_->self_->ClearException();
1226 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1227 return false;
1228 }
1229
1230 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001231 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1232 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001233 driver_->self_->AssertPendingOOMException();
1234 driver_->self_->ClearException();
1235 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1236 return false;
1237 }
1238 return true;
1239}
1240
Alex Lighta26e3492017-06-27 17:55:37 -07001241void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
1242 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass());
1243}
1244
Alex Light5643caf2017-02-08 11:39:07 -08001245void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
Alex Lighte34fe442018-02-21 17:35:55 -08001246 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1247 return;
1248 }
Alex Light5643caf2017-02-08 11:39:07 -08001249 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1250 if (state != nullptr) {
1251 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1252 }
1253}
1254
1255void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08001256 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1257 redef.UnregisterBreakpoints();
Alex Lighte34fe442018-02-21 17:35:55 -08001258 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08001259 }
1260}
1261
Alex Light0e692732017-01-10 15:00:05 -08001262bool Redefiner::CheckAllRedefinitionAreValid() {
1263 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1264 if (!redef.CheckRedefinitionIsValid()) {
1265 return false;
1266 }
1267 }
1268 return true;
1269}
1270
Alex Light1e3926a2017-04-07 10:38:06 -07001271void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1272 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1273 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1274 }
1275}
1276
1277bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1278 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1279 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001280 return false;
1281 }
1282 }
1283 return true;
1284}
1285
1286bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001287 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001288 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001289 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001290 return false;
1291 }
Alex Light0e692732017-01-10 15:00:05 -08001292 }
1293 return true;
1294}
1295
1296void Redefiner::ClassRedefinition::ReleaseDexFile() {
Andreas Gampeafaf7f82018-10-16 11:32:38 -07001297 dex_file_.release(); // NOLINT b/117926937
Alex Light0e692732017-01-10 15:00:05 -08001298}
1299
1300void Redefiner::ReleaseAllDexFiles() {
1301 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1302 redef.ReleaseDexFile();
1303 }
1304}
1305
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001306bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1307 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1308 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001309 return false;
1310 }
Alex Light8c889d22017-02-06 13:58:27 -08001311 }
1312 return true;
1313}
1314
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001315class ScopedDisableConcurrentAndMovingGc {
1316 public:
1317 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1318 : heap_(heap), self_(self) {
1319 if (heap_->IsGcConcurrentAndMoving()) {
1320 heap_->IncrementDisableMovingGC(self_);
1321 }
1322 }
1323
1324 ~ScopedDisableConcurrentAndMovingGc() {
1325 if (heap_->IsGcConcurrentAndMoving()) {
1326 heap_->DecrementDisableMovingGC(self_);
1327 }
1328 }
1329 private:
1330 art::gc::Heap* heap_;
1331 art::Thread* self_;
1332};
1333
Alex Lighta01de592016-11-15 10:43:06 -08001334jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001335 art::StackHandleScope<1> hs(self_);
1336 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1337 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001338 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001339 if (holder.IsNull()) {
1340 self_->AssertPendingOOMException();
1341 self_->ClearException();
1342 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1343 return result_;
1344 }
1345
Alex Lighta01de592016-11-15 10:43:06 -08001346 // First we just allocate the ClassExt and its fields that we need. These can be updated
1347 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1348 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1349 // between allocating them and pausing all threads before we can update them so we need to do a
1350 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001351 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001352 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001353 !FinishAllRemainingAllocations(holder) ||
1354 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001355 return result_;
1356 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001357
Alex Light5643caf2017-02-08 11:39:07 -08001358 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001359 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001360 art::ClassLinker* cl = runtime_->GetClassLinker();
1361 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001362 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001363 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001364 }
Alex Light7916f202017-01-27 09:00:15 -08001365 }
Alex Light5643caf2017-02-08 11:39:07 -08001366 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001367
Alex Light6abd5392017-01-05 17:53:00 -08001368 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1369 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001370 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1371
Alex Lighta01de592016-11-15 10:43:06 -08001372 // Do transition to final suspension
1373 // TODO We might want to give this its own suspended state!
1374 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001375 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
Andreas Gampe6e897762018-10-16 13:09:32 -07001376 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend=*/true);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001377 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001378 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001379 ClassRedefinition& redef = data.GetRedefinition();
1380 if (data.GetSourceClassLoader() != nullptr) {
1381 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001382 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001383 art::ObjPtr<art::mirror::Class> klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001384 // TODO Rewrite so we don't do a stack walk for each and every class.
1385 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001386 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001387 }
Alex Light1e3926a2017-04-07 10:38:06 -07001388 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001389 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1390 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1391 // methods that have been jitted prior to the current redefinition being applied might continue
1392 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001393 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1394 // owns the DexFile and when ownership is transferred.
1395 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001396 return OK;
1397}
1398
Alex Light0e692732017-01-10 15:00:05 -08001399void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001400 const art::dex::ClassDef& class_def) {
Alex Light0e692732017-01-10 15:00:05 -08001401 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001402 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001403 const art::dex::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001404 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001405 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07001406 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001407 const art::dex::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
Alex Lighta01de592016-11-15 10:43:06 -08001408 art::dex::TypeIndex method_return_idx =
1409 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1410 const auto* old_type_list = method.GetParameterTypeList();
1411 std::vector<art::dex::TypeIndex> new_type_list;
1412 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1413 new_type_list.push_back(
1414 dex_file_->GetIndexForTypeId(
1415 *dex_file_->FindTypeId(
1416 old_dex_file.GetTypeDescriptor(
1417 old_dex_file.GetTypeId(
1418 old_type_list->GetTypeItem(i).type_idx_)))));
1419 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001420 const art::dex::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx, new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001421 CHECK(proto_id != nullptr || old_type_list == nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001422 const art::dex::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1423 *new_name_id,
1424 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001425 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001426 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1427 method.SetDexMethodIndex(dex_method_idx);
1428 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001429 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Light7532d582017-02-13 16:36:06 -08001430 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01001431 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08001432 }
Alex Light200b9d72016-12-15 11:34:13 -08001433}
1434
Alex Light0e692732017-01-10 15:00:05 -08001435void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001436 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1437 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1438 for (art::ArtField& field : fields_iter) {
1439 std::string declaring_class_name;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001440 const art::dex::TypeId* new_declaring_id =
Alex Light200b9d72016-12-15 11:34:13 -08001441 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001442 const art::dex::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1443 const art::dex::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001444 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001445 const art::dex::FieldId* new_field_id =
Alex Light200b9d72016-12-15 11:34:13 -08001446 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1447 CHECK(new_field_id != nullptr);
1448 // We only need to update the index since the other data in the ArtField cannot be updated.
1449 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1450 }
1451 }
Alex Light200b9d72016-12-15 11:34:13 -08001452}
1453
1454// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001455void Redefiner::ClassRedefinition::UpdateClass(
1456 art::ObjPtr<art::mirror::Class> mclass,
1457 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001458 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001459 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001460 const art::dex::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001461 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001462 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001463
David Brazdil1a658632018-12-01 17:54:26 +00001464 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1465 CHECK(!ext.IsNull());
1466 ext->SetOriginalDexFile(original_dex_file);
1467
1468 // If this is the first time the class is being redefined, store
1469 // the native DexFile pointer and initial ClassDef index in ClassExt.
1470 // This preserves the pointer for hiddenapi access checks which need
1471 // to read access flags from the initial DexFile.
1472 if (ext->GetPreRedefineDexFile() == nullptr) {
1473 ext->SetPreRedefineDexFile(&mclass->GetDexFile());
1474 ext->SetPreRedefineClassDefIndex(mclass->GetDexClassDefIndex());
1475 }
1476
Alex Lighta01de592016-11-15 10:43:06 -08001477 // Update the class fields.
1478 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1479 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1480 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001481 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001482 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Light035105f2018-03-05 17:48:48 -08001483
1484 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1485 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1486 // meta-data.
1487 art::jit::Jit* jit = driver_->runtime_->GetJit();
1488 if (jit != nullptr) {
1489 art::PointerSize image_pointer_size =
1490 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1491 auto code_cache = jit->GetCodeCache();
1492 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1493 // the jit about them.
1494 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1495 if (method.IsInvokable()) {
1496 code_cache->NotifyMethodRedefined(&method);
1497 }
1498 }
1499 }
Alex Lighta01de592016-11-15 10:43:06 -08001500}
1501
Alex Light1e3926a2017-04-07 10:38:06 -07001502// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1503// obsolete methods).
1504void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1505 const RedefinitionDataIter* cur_data) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001506 art::ObjPtr<art::mirror::Class> klass = GetMirrorClass();
1507 art::ObjPtr<art::mirror::ClassExt> ext = klass->GetExtData();
1508 art::ObjPtr<art::mirror::PointerArray> methods = ext->GetObsoleteMethods();
1509 art::ObjPtr<art::mirror::PointerArray> old_methods = cur_data->GetOldObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001510 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001511 int32_t expected_length =
1512 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1513 // Check to make sure we are only undoing this one.
1514 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001515 for (int32_t i = 0; i < expected_length; i++) {
1516 art::ArtMethod* expected = nullptr;
1517 if (i < old_length) {
1518 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1519 }
1520 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001521 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1522 // obsolete methods array.
1523 return;
1524 }
1525 }
1526 // No new obsolete methods! We can get rid of the maps.
1527 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1528 }
1529}
1530
Alex Lighta01de592016-11-15 10:43:06 -08001531// This function does all (java) allocations we need to do for the Class being redefined.
1532// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001533bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1534 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001535 art::StackHandleScope<2> hs(driver_->self_);
1536 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1537 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001538 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001539 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1540 return false;
1541 }
1542 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001543 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001544 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001545 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001546 driver_->self_->AssertPendingOOMException();
1547 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001548 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1549 return false;
1550 }
Alex Light1e3926a2017-04-07 10:38:06 -07001551 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1552 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001553 // are only modified when all threads (other than the modifying one) are suspended we don't need
1554 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1555 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001556 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1557 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1558 if (!ext->ExtendObsoleteArrays(
1559 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1560 // OOM. Clear exception and return error.
1561 driver_->self_->AssertPendingOOMException();
1562 driver_->self_->ClearException();
1563 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1564 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001565 }
1566 return true;
1567}
1568
1569} // namespace openjdkjvmti