blob: 73e37199ed27f27e255ecc06d5dfa81a27262584 [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>
35
Andreas Gampe57943812017-12-06 21:39:13 -080036#include <android-base/logging.h>
37#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080038
Andreas Gampea1d2f952017-04-20 22:53:58 -070039#include "art_field-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "art_jvmti.h"
Steven Morelande431e272017-07-18 16:53:49 -070041#include "art_method-inl.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010042#include "base/array_ref.h"
Vladimir Markoba118822017-06-12 15:41:56 +010043#include "base/stringpiece.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"
David Sehr9e734c72018-01-04 17:56:19 -080048#include "dex/dex_file.h"
49#include "dex/dex_file_loader.h"
50#include "dex/dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080051#include "events-inl.h"
52#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080053#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "instrumentation.h"
Alex Light07f06212017-06-01 14:01:43 -070055#include "intern_table.h"
Alex Light5643caf2017-02-08 11:39:07 -080056#include "jdwp/jdwp.h"
57#include "jdwp/jdwp_constants.h"
58#include "jdwp/jdwp_event.h"
59#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080060#include "jit/jit.h"
61#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010062#include "jni/jni_env_ext-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080063#include "jvmti_allocator.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010064#include "linear_alloc.h"
Alex Light6161f132017-01-25 10:30:20 -080065#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080066#include "mirror/class_ext.h"
67#include "mirror/object.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070068#include "nativehelper/scoped_local_ref.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080069#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080070#include "object_lock.h"
71#include "runtime.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010072#include "stack.h"
73#include "thread_list.h"
Alex Lighta26e3492017-06-27 17:55:37 -070074#include "ti_breakpoint.h"
Alex Lighteb98b082017-01-25 13:02:32 -080075#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080076#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080077#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070078#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080079
80namespace openjdkjvmti {
81
Andreas Gampe46ee31b2016-12-14 10:11:49 -080082using android::base::StringPrintf;
83
Alex Lighteee0bd42017-02-14 15:31:45 +000084// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
85// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
86// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
87class ObsoleteMap {
88 public:
89 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
90 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
91 auto method_pair = id_map_.find(original);
92 if (method_pair != id_map_.end()) {
93 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
94 method_pair->second, art::kRuntimePointerSize);
95 DCHECK(res != nullptr);
96 DCHECK_EQ(original, res->GetNonObsoleteMethod());
97 return res;
98 } else {
99 return nullptr;
100 }
101 }
102
103 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
104 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
105 DCHECK(original != nullptr);
106 DCHECK(obsolete != nullptr);
107 int32_t slot = next_free_slot_++;
108 DCHECK_LT(slot, obsolete_methods_->GetLength());
109 DCHECK(nullptr ==
110 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
111 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
112 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
113 obsolete_dex_caches_->Set(slot, original_dex_cache_);
114 id_map_.insert({original, slot});
115 }
116
117 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
118 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
119 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
120 : next_free_slot_(0),
121 obsolete_methods_(obsolete_methods),
122 obsolete_dex_caches_(obsolete_dex_caches),
123 original_dex_cache_(original_dex_cache) {
124 // Figure out where the first unused slot in the obsolete_methods_ array is.
125 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
126 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
127 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
128 next_free_slot_++;
129 }
130 // Sanity check that the same slot in obsolete_dex_caches_ is free.
131 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
132 }
133
134 private:
135 int32_t next_free_slot_;
136 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
137 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
138 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
139 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
140 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
141 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
142};
143
Alex Lightdba61482016-12-21 08:20:29 -0800144// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
145// some basic sanity checks that the obsolete method is sane.
146class ObsoleteMethodStackVisitor : public art::StackVisitor {
147 protected:
148 ObsoleteMethodStackVisitor(
149 art::Thread* thread,
150 art::LinearAlloc* allocator,
151 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000152 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800153 : StackVisitor(thread,
154 /*context*/nullptr,
155 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
156 allocator_(allocator),
157 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800158 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800159
160 ~ObsoleteMethodStackVisitor() OVERRIDE {}
161
162 public:
163 // Returns true if we successfully installed obsolete methods on this thread, filling
164 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
165 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800166 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800167 art::Thread* thread,
168 art::LinearAlloc* allocator,
169 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000170 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800171 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800172 ObsoleteMethodStackVisitor visitor(thread,
173 allocator,
174 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800175 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800176 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800177 }
178
179 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000180 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800181 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800182 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800183 // We cannot ensure that the right dex file is used in inlined frames so we don't support
184 // redefining them.
185 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000186 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
187 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800188 // Create a new Obsolete Method and put it in the list.
189 art::Runtime* runtime = art::Runtime::Current();
190 art::ClassLinker* cl = runtime->GetClassLinker();
191 auto ptr_size = cl->GetImagePointerSize();
192 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800193 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800194 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
195 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800196 new_obsolete_method = new (method_storage) art::ArtMethod();
197 new_obsolete_method->CopyFrom(old_method, ptr_size);
198 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
199 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800200 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700201 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000202 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800203 // Update JIT Data structures to point to the new method.
204 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
205 if (jit != nullptr) {
206 // Notify the JIT we are making this obsolete method. It will update the jit's internal
207 // structures to keep track of the new obsolete method.
208 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
209 }
Alex Lightdba61482016-12-21 08:20:29 -0800210 }
211 DCHECK(new_obsolete_method != nullptr);
212 SetMethod(new_obsolete_method);
213 }
214 return true;
215 }
216
217 private:
218 // The linear allocator we should use to make new methods.
219 art::LinearAlloc* allocator_;
220 // The set of all methods which could be obsoleted.
221 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
222 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000223 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
224 // the redefined classes ClassExt as it is filled.
225 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800226};
227
Alex Lighte4a88632017-01-10 07:41:24 -0800228jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
229 jclass klass,
230 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800231 art::Thread* self = art::Thread::Current();
232 art::ScopedObjectAccess soa(self);
233 art::StackHandleScope<1> hs(self);
234 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
235 if (obj.IsNull()) {
236 return ERR(INVALID_CLASS);
237 }
238 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
239 std::string err_unused;
240 *is_redefinable =
Alex Light9e7859c2018-04-05 13:49:43 -0700241 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
242 ? JNI_TRUE : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800243 return OK;
244}
245
Alex Light9e7859c2018-04-05 13:49:43 -0700246jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
247 art::Thread* self = art::Thread::Current();
248 art::ScopedObjectAccess soa(self);
249 art::StackHandleScope<1> hs(self);
250 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
251 if (obj.IsNull()) {
252 return ERR(INVALID_CLASS);
253 }
254 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
255 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
256}
257
Alex Lighte4a88632017-01-10 07:41:24 -0800258jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
259 /*out*/std::string* error_msg) {
Alex Light9e7859c2018-04-05 13:49:43 -0700260 if (!klass->IsResolved()) {
261 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
262 // the same thread as the class-linking process. If it's on another thread we will be able to
263 // wait for the preparation to finish and continue from there.
264 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
265 *error_msg = "Modification of class " + klass->PrettyClass() +
266 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
267 " Please use ClassFileLoadHook directly instead.";
268 return ERR(INTERNAL);
269 } else {
270 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
271 << "it could cause arbitrary length waits as the class is being resolved.";
272 }
273 }
Alex Lighte4a88632017-01-10 07:41:24 -0800274 if (klass->IsPrimitive()) {
275 *error_msg = "Modification of primitive classes is not supported";
276 return ERR(UNMODIFIABLE_CLASS);
277 } else if (klass->IsInterface()) {
278 *error_msg = "Modification of Interface classes is currently not supported";
279 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800280 } else if (klass->IsStringClass()) {
281 *error_msg = "Modification of String class is not supported";
282 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800283 } else if (klass->IsArrayClass()) {
284 *error_msg = "Modification of Array classes is not supported";
285 return ERR(UNMODIFIABLE_CLASS);
286 } else if (klass->IsProxyClass()) {
287 *error_msg = "Modification of proxy classes is not supported";
288 return ERR(UNMODIFIABLE_CLASS);
289 }
290
Alex Lighte77b48b2017-02-22 11:08:06 -0800291 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
292 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
293 *error_msg = "Class might have stack frames that cannot be made obsolete";
294 return ERR(UNMODIFIABLE_CLASS);
295 }
296 }
297
Alex Lighte4a88632017-01-10 07:41:24 -0800298 return OK;
299}
300
Alex Lighta01de592016-11-15 10:43:06 -0800301// Moves dex data to an anonymous, read-only mmap'd region.
302std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100303 art::ArrayRef<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800304 std::string* error_msg) {
305 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800306 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800307 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700308 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800309 PROT_READ|PROT_WRITE,
310 /*low_4gb*/false,
311 /*reuse*/false,
312 error_msg));
313 if (map == nullptr) {
314 return map;
315 }
Vladimir Markoe1993c72017-06-14 17:01:38 +0100316 memcpy(map->Begin(), data.data(), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800317 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
318 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800319 map->Protect(PROT_READ);
320 return map;
321}
322
Alex Lighta7e38d82017-01-19 14:57:28 -0800323Redefiner::ClassRedefinition::ClassRedefinition(
324 Redefiner* driver,
325 jclass klass,
326 const art::DexFile* redefined_dex_file,
327 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100328 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800329 driver_(driver),
330 klass_(klass),
331 dex_file_(redefined_dex_file),
332 class_sig_(class_sig),
333 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800334 GetMirrorClass()->MonitorEnter(driver_->self_);
335}
336
337Redefiner::ClassRedefinition::~ClassRedefinition() {
338 if (driver_ != nullptr) {
339 GetMirrorClass()->MonitorExit(driver_->self_);
340 }
341}
342
Alex Light0e692732017-01-10 15:00:05 -0800343jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800344 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800345 art::Runtime* runtime,
346 art::Thread* self,
347 jint class_count,
348 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800349 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800350 if (env == nullptr) {
351 *error_msg = "env was null!";
352 return ERR(INVALID_ENVIRONMENT);
353 } else if (class_count < 0) {
354 *error_msg = "class_count was less then 0";
355 return ERR(ILLEGAL_ARGUMENT);
356 } else if (class_count == 0) {
357 // We don't actually need to do anything. Just return OK.
358 return OK;
359 } else if (definitions == nullptr) {
360 *error_msg = "null definitions!";
361 return ERR(NULL_POINTER);
362 }
Alex Light6ac57502017-01-19 15:05:06 -0800363 std::vector<ArtClassDefinition> def_vector;
364 def_vector.reserve(class_count);
365 for (jint i = 0; i < class_count; i++) {
Alex Light9e7859c2018-04-05 13:49:43 -0700366 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800367 if (res != OK) {
368 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800369 }
Alex Light6ac57502017-01-19 15:05:06 -0800370 // We make a copy of the class_bytes to pass into the retransformation.
371 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
372 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
373 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800374 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800375 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800376 if (res != OK) {
377 return res;
378 }
379 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
380
381 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800382 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800383 if (res != OK) {
384 return res;
385 }
386 def_vector.push_back(std::move(def));
387 }
388 // Call all the transformation events.
Alex Light64e4c142018-01-30 13:46:37 -0800389 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800390 self,
391 &def_vector);
392 if (res != OK) {
393 // Something went wrong with transformation!
394 return res;
395 }
396 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
397}
398
399jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
400 art::Runtime* runtime,
401 art::Thread* self,
402 const std::vector<ArtClassDefinition>& definitions,
403 std::string* error_msg) {
404 DCHECK(env != nullptr);
405 if (definitions.size() == 0) {
406 // We don't actually need to do anything. Just return OK.
407 return OK;
408 }
Alex Light0e692732017-01-10 15:00:05 -0800409 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
410 // are going to redefine.
411 art::jit::ScopedJitSuspend suspend_jit;
412 // Get shared mutator lock so we can lock all the classes.
413 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700414 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800415 for (const ArtClassDefinition& def : definitions) {
416 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700417 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800418 jvmtiError res = r.AddRedefinition(env, def);
419 if (res != OK) {
420 return res;
421 }
Alex Light0e692732017-01-10 15:00:05 -0800422 }
423 }
424 return r.Run();
425}
426
Alex Light6ac57502017-01-19 15:05:06 -0800427jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800428 std::string original_dex_location;
429 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700430 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800431 *error_msg_ = "Unable to get original dex file location!";
432 return ret;
433 }
Alex Light52a2db52017-01-19 23:00:21 +0000434 char* generic_ptr_unused = nullptr;
435 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700436 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800437 *error_msg_ = "Unable to get class signature!";
438 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000439 }
Andreas Gampe54711412017-02-21 12:41:43 -0800440 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
441 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800442 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700443 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800444 error_msg_));
445 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800446 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700447 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800448 << "in dex file " << original_dex_location << " because: " << *error_msg_;
449 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800450 return ERR(OUT_OF_MEMORY);
451 }
452 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800453 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800454 return ERR(INVALID_CLASS_FORMAT);
455 }
456 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800457 const art::ArtDexFileLoader dex_file_loader;
458 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map->GetName(),
459 checksum,
460 std::move(map),
461 /*verify*/true,
462 /*verify_checksum*/true,
463 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800464 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700465 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800466 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800467 return ERR(INVALID_CLASS_FORMAT);
468 }
Alex Light0e692732017-01-10 15:00:05 -0800469 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800470 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700471 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800472 dex_file.release(),
473 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700474 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800475 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800476}
477
Alex Light0e692732017-01-10 15:00:05 -0800478art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
479 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800480}
481
Alex Light0e692732017-01-10 15:00:05 -0800482art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800483 return GetMirrorClass()->GetClassLoader();
484}
485
Alex Light0e692732017-01-10 15:00:05 -0800486art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
487 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700488 art::StackHandleScope<2> hs(driver_->self_);
489 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
490 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
491 art::ObjPtr<art::mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100492 art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
Alex Light07f06212017-06-01 14:01:43 -0700493 if (cache.IsNull()) {
494 driver_->self_->AssertPendingOOMException();
495 return nullptr;
496 }
497 art::Handle<art::mirror::String> location(hs.NewHandle(
498 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
499 if (location.IsNull()) {
500 driver_->self_->AssertPendingOOMException();
501 return nullptr;
502 }
503 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
504 art::mirror::DexCache::InitializeDexCache(driver_->self_,
505 cache.Get(),
506 location.Get(),
507 dex_file_.get(),
508 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
509 : loader->GetAllocator(),
510 art::kRuntimePointerSize);
511 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800512}
513
Alex Light0e692732017-01-10 15:00:05 -0800514void Redefiner::RecordFailure(jvmtiError result,
515 const std::string& class_sig,
516 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800517 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800518 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800519 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800520 result_ = result;
521}
522
Alex Light2f814aa2017-03-24 15:21:34 +0000523art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800524 // If we have been specifically given a new set of bytes use that
525 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800526 return art::mirror::ByteArray::AllocateAndFill(
527 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100528 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Alex Light440b5d92017-01-24 15:32:25 -0800529 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800530 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800531
532 // See if we already have one set.
533 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
534 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000535 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
536 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800537 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000538 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800539 }
Alex Lighta01de592016-11-15 10:43:06 -0800540 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800541
Alex Light2f814aa2017-03-24 15:21:34 +0000542 // return the current dex_cache which has the dex file in it.
543 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800544 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000545 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800546 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
547 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800548 }
Alex Light2f814aa2017-03-24 15:21:34 +0000549 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800550}
551
Alex Lightdba61482016-12-21 08:20:29 -0800552struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000553 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800554 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800555 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800556
Alex Lighteee0bd42017-02-14 15:31:45 +0000557 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
558 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800559};
560
Alex Lightdba61482016-12-21 08:20:29 -0800561void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
562 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800563 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
564 data->allocator,
565 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000566 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800567}
568
569// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
570// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800571// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
572void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800573 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
574 art::mirror::ClassExt* ext = art_klass->GetExtData();
575 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800576 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000577 // This holds pointers to the obsolete methods map fields which are updated as needed.
578 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
579 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800580 // Add all the declared methods to the map
581 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800582 if (m.IsIntrinsic()) {
583 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
584 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
585 << "methods that have already been compiled.";
586 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000587 // It is possible to simply filter out some methods where they cannot really become obsolete,
588 // such as native methods and keep their original (possibly optimized) implementations. We don't
589 // do this, however, since we would need to mark these functions (still in the classes
590 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
591 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
592 // error checking from the interpreter which ensure we don't try to start executing obsolete
593 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000594 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800595 }
596 {
Alex Light0e692732017-01-10 15:00:05 -0800597 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800598 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
599 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800600 }
Alex Lightdba61482016-12-21 08:20:29 -0800601}
602
Alex Light6161f132017-01-25 10:30:20 -0800603// Try and get the declared method. First try to get a virtual method then a direct method if that's
604// not found.
605static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
Vladimir Markoba118822017-06-12 15:41:56 +0100606 art::StringPiece name,
Alex Light6161f132017-01-25 10:30:20 -0800607 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markoba118822017-06-12 15:41:56 +0100608 DCHECK(!klass->IsProxyClass());
609 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
610 if (m.GetName() == name && m.GetSignature() == sig) {
611 return &m;
612 }
Alex Light6161f132017-01-25 10:30:20 -0800613 }
Vladimir Markoba118822017-06-12 15:41:56 +0100614 return nullptr;
Alex Light6161f132017-01-25 10:30:20 -0800615}
616
617bool Redefiner::ClassRedefinition::CheckSameMethods() {
618 art::StackHandleScope<1> hs(driver_->self_);
619 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
620 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
621
622 art::ClassDataItemIterator new_iter(*dex_file_,
623 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
624
625 // Make sure we have the same number of methods.
626 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
627 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
628 if (num_new_method != num_old_method) {
629 bool bigger = num_new_method > num_old_method;
630 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
631 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
632 StringPrintf("Total number of declared methods changed from %d to %d",
633 num_old_method, num_new_method));
634 return false;
635 }
636
637 // Skip all of the fields. We should have already checked this.
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700638 new_iter.SkipAllFields();
Alex Light6161f132017-01-25 10:30:20 -0800639 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
640 // files have the same number of methods, which means there must be an equal amount of additions
641 // and removals.
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800642 for (; new_iter.HasNextMethod(); new_iter.Next()) {
Alex Light6161f132017-01-25 10:30:20 -0800643 // Get the data on the method we are searching for
644 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
645 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
646 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
647 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
648 // If we got past the check for the same number of methods above that means there must be at
649 // least one added and one removed method. We will return the ADDED failure message since it is
650 // easier to get a useful error report for it.
651 if (old_method == nullptr) {
652 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
653 StringPrintf("Unknown method '%s' (sig: %s) was added!",
654 new_method_name,
655 new_method_signature.ToString().c_str()));
656 return false;
657 }
658 // Since direct methods have different flags than virtual ones (specifically direct methods must
659 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
660 // virtual to direct.
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100661 uint32_t new_flags = new_iter.GetMethodAccessFlags();
662 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
Alex Light6161f132017-01-25 10:30:20 -0800663 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
664 StringPrintf("method '%s' (sig: %s) had different access flags",
665 new_method_name,
666 new_method_signature.ToString().c_str()));
667 return false;
668 }
669 }
670 return true;
671}
672
673bool Redefiner::ClassRedefinition::CheckSameFields() {
674 art::StackHandleScope<1> hs(driver_->self_);
675 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
676 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
677 art::ClassDataItemIterator new_iter(*dex_file_,
678 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
679 const art::DexFile& old_dex_file = h_klass->GetDexFile();
680 art::ClassDataItemIterator old_iter(old_dex_file,
681 old_dex_file.GetClassData(*h_klass->GetClassDef()));
682 // Instance and static fields can be differentiated by their flags so no need to check them
683 // separately.
684 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
685 // Get the data on the method we are searching for
686 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
687 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
688 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
689
690 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
691 // We are missing the old version of this method!
692 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
693 StringPrintf("Unknown field '%s' (type: %s) added!",
694 new_field_name,
695 new_field_type));
696 return false;
697 }
698
699 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
700 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
701 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
702
703 // Check name and type.
704 if (strcmp(old_field_name, new_field_name) != 0 ||
705 strcmp(old_field_type, new_field_type) != 0) {
706 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
707 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
708 old_field_name,
709 old_field_type,
710 new_field_name,
711 new_field_type));
712 return false;
713 }
714
715 // Since static fields have different flags than instance ones (specifically static fields must
716 // have the kAccStatic flag) we can tell if a field changes from static to instance.
717 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
718 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
719 StringPrintf("Field '%s' (sig: %s) had different access flags",
720 new_field_name,
721 new_field_type));
722 return false;
723 }
724
725 new_iter.Next();
726 old_iter.Next();
727 }
728 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
729 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
730 StringPrintf("field '%s' (sig: %s) is missing!",
731 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
732 old_iter.GetMemberIndex())),
733 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
734 old_iter.GetMemberIndex()))));
735 return false;
736 }
737 return true;
738}
739
Alex Light0e692732017-01-10 15:00:05 -0800740bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800741 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000742 // Easy check that only 1 class def is present.
743 if (dex_file_->NumClassDefs() != 1) {
744 RecordFailure(ERR(ILLEGAL_ARGUMENT),
745 StringPrintf("Expected 1 class def in dex file but found %d",
746 dex_file_->NumClassDefs()));
747 return false;
748 }
749 // Get the ClassDef from the new DexFile.
750 // Since the dex file has only a single class def the index is always 0.
751 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
752 // Get the class as it is now.
753 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
754
755 // Check the access flags didn't change.
756 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
757 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
758 "Cannot change modifiers of class by redefinition");
759 return false;
760 }
761
762 // Check class name.
763 // These should have been checked by the dexfile verifier on load.
764 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
765 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
766 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
767 if (!current_class->DescriptorEquals(descriptor)) {
768 std::string storage;
769 RecordFailure(ERR(NAMES_DONT_MATCH),
770 StringPrintf("expected file to contain class called '%s' but found '%s'!",
771 current_class->GetDescriptor(&storage),
772 descriptor));
773 return false;
774 }
775 if (current_class->IsObjectClass()) {
776 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
777 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
778 return false;
779 }
780 } else {
781 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
782 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
783 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
784 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
785 return false;
786 }
787 }
788 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
789 if (interfaces == nullptr) {
790 if (current_class->NumDirectInterfaces() != 0) {
791 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
792 return false;
793 }
794 } else {
795 DCHECK(!current_class->IsProxyClass());
796 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
797 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
798 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
799 return false;
800 }
801 // The order of interfaces is (barely) meaningful so we error if it changes.
802 const art::DexFile& orig_dex_file = current_class->GetDexFile();
803 for (uint32_t i = 0; i < interfaces->Size(); i++) {
804 if (strcmp(
805 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
806 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
807 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
808 "Interfaces changed or re-ordered");
809 return false;
810 }
811 }
812 }
Alex Light460d1b42017-01-10 15:37:17 +0000813 return true;
814}
815
Alex Light0e692732017-01-10 15:00:05 -0800816bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800817 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800818 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000819
Alex Lighte4a88632017-01-10 07:41:24 -0800820 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
821 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
822 if (res != OK) {
823 RecordFailure(res, err);
824 return false;
825 } else {
826 return true;
827 }
Alex Light460d1b42017-01-10 15:37:17 +0000828}
829
Alex Light0e692732017-01-10 15:00:05 -0800830bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000831 return CheckRedefinable() &&
832 CheckClass() &&
833 CheckSameFields() &&
834 CheckSameMethods();
835}
836
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800837class RedefinitionDataIter;
838
Alex Light0e692732017-01-10 15:00:05 -0800839// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
840// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
841// having to deal with the fact that we need to hold an arbitrary number of references live.
842class RedefinitionDataHolder {
843 public:
844 enum DataSlot : int32_t {
845 kSlotSourceClassLoader = 0,
846 kSlotJavaDexFile = 1,
847 kSlotNewDexFileCookie = 2,
848 kSlotNewDexCache = 3,
849 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800850 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700851 kSlotOldObsoleteMethods = 6,
852 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800853
854 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700855 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800856 };
857
858 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
859 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
860 // the passed in handle-scope.
861 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
862 art::Runtime* runtime,
863 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800864 std::vector<Redefiner::ClassRedefinition>* redefinitions)
865 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100866 arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
867 self,
868 art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
869 redefinitions->size() * kNumSlots))),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800870 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800871
872 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
873 return arr_.IsNull();
874 }
875
Alex Light8c889d22017-02-06 13:58:27 -0800876 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800877 REQUIRES_SHARED(art::Locks::mutator_lock_) {
878 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
879 }
Alex Light8c889d22017-02-06 13:58:27 -0800880 art::mirror::Object* GetJavaDexFile(jint klass_index) const
881 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800882 return GetSlot(klass_index, kSlotJavaDexFile);
883 }
Alex Light8c889d22017-02-06 13:58:27 -0800884 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800885 REQUIRES_SHARED(art::Locks::mutator_lock_) {
886 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
887 }
Alex Light8c889d22017-02-06 13:58:27 -0800888 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800889 REQUIRES_SHARED(art::Locks::mutator_lock_) {
890 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
891 }
Alex Light8c889d22017-02-06 13:58:27 -0800892 art::mirror::Class* GetMirrorClass(jint klass_index) const
893 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800894 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
895 }
896
Alex Light2f814aa2017-03-24 15:21:34 +0000897 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800898 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000899 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800900 }
901
Alex Light1e3926a2017-04-07 10:38:06 -0700902 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
903 REQUIRES_SHARED(art::Locks::mutator_lock_) {
904 return art::down_cast<art::mirror::PointerArray*>(
905 GetSlot(klass_index, kSlotOldObsoleteMethods));
906 }
907
908 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
909 REQUIRES_SHARED(art::Locks::mutator_lock_) {
910 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
911 GetSlot(klass_index, kSlotOldDexCaches));
912 }
913
Alex Light0e692732017-01-10 15:00:05 -0800914 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
915 REQUIRES_SHARED(art::Locks::mutator_lock_) {
916 SetSlot(klass_index, kSlotSourceClassLoader, loader);
917 }
918 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
919 REQUIRES_SHARED(art::Locks::mutator_lock_) {
920 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
921 }
922 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
923 REQUIRES_SHARED(art::Locks::mutator_lock_) {
924 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
925 }
926 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
927 REQUIRES_SHARED(art::Locks::mutator_lock_) {
928 SetSlot(klass_index, kSlotNewDexCache, cache);
929 }
930 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
931 REQUIRES_SHARED(art::Locks::mutator_lock_) {
932 SetSlot(klass_index, kSlotMirrorClass, klass);
933 }
Alex Light2f814aa2017-03-24 15:21:34 +0000934 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800935 REQUIRES_SHARED(art::Locks::mutator_lock_) {
936 SetSlot(klass_index, kSlotOrigDexFile, bytes);
937 }
Alex Light1e3926a2017-04-07 10:38:06 -0700938 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
939 REQUIRES_SHARED(art::Locks::mutator_lock_) {
940 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
941 }
942 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
943 REQUIRES_SHARED(art::Locks::mutator_lock_) {
944 SetSlot(klass_index, kSlotOldDexCaches, caches);
945 }
Alex Light0e692732017-01-10 15:00:05 -0800946
Alex Light8c889d22017-02-06 13:58:27 -0800947 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800948 return arr_->GetLength() / kNumSlots;
949 }
950
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800951 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
952 REQUIRES_SHARED(art::Locks::mutator_lock_) {
953 return redefinitions_;
954 }
955
956 bool operator==(const RedefinitionDataHolder& other) const
957 REQUIRES_SHARED(art::Locks::mutator_lock_) {
958 return arr_.Get() == other.arr_.Get();
959 }
960
961 bool operator!=(const RedefinitionDataHolder& other) const
962 REQUIRES_SHARED(art::Locks::mutator_lock_) {
963 return !(*this == other);
964 }
965
966 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
967 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
968
Alex Light0e692732017-01-10 15:00:05 -0800969 private:
Alex Light8c889d22017-02-06 13:58:27 -0800970 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800971 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800972
973 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800974 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800975 DCHECK_LT(klass_index, Length());
976 return arr_->Get((kNumSlots * klass_index) + slot);
977 }
978
979 void SetSlot(jint klass_index,
980 DataSlot slot,
981 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
982 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
983 DCHECK_LT(klass_index, Length());
984 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
985 }
986
987 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
988};
989
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800990class RedefinitionDataIter {
991 public:
992 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
993
994 RedefinitionDataIter(const RedefinitionDataIter&) = default;
995 RedefinitionDataIter(RedefinitionDataIter&&) = default;
996 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
997 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
998
999 bool operator==(const RedefinitionDataIter& other) const
1000 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1001 return idx_ == other.idx_ && holder_ == other.holder_;
1002 }
1003
1004 bool operator!=(const RedefinitionDataIter& other) const
1005 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1006 return !(*this == other);
1007 }
1008
1009 RedefinitionDataIter operator++() { // Value after modification.
1010 idx_++;
1011 return *this;
1012 }
1013
1014 RedefinitionDataIter operator++(int) {
1015 RedefinitionDataIter temp = *this;
1016 idx_++;
1017 return temp;
1018 }
1019
1020 RedefinitionDataIter operator+(ssize_t delta) const {
1021 RedefinitionDataIter temp = *this;
1022 temp += delta;
1023 return temp;
1024 }
1025
1026 RedefinitionDataIter& operator+=(ssize_t delta) {
1027 idx_ += delta;
1028 return *this;
1029 }
1030
1031 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1032 return (*holder_.GetRedefinitions())[idx_];
1033 }
1034
1035 RedefinitionDataHolder& GetHolder() {
1036 return holder_;
1037 }
1038
1039 art::mirror::ClassLoader* GetSourceClassLoader() const
1040 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1041 return holder_.GetSourceClassLoader(idx_);
1042 }
1043 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1044 return holder_.GetJavaDexFile(idx_);
1045 }
1046 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1047 return holder_.GetNewDexFileCookie(idx_);
1048 }
1049 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1050 return holder_.GetNewDexCache(idx_);
1051 }
1052 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1053 return holder_.GetMirrorClass(idx_);
1054 }
Alex Light2f814aa2017-03-24 15:21:34 +00001055 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001056 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001057 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001058 }
Alex Light1e3926a2017-04-07 10:38:06 -07001059 art::mirror::PointerArray* GetOldObsoleteMethods() const
1060 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1061 return holder_.GetOldObsoleteMethods(idx_);
1062 }
1063 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1064 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1065 return holder_.GetOldDexCaches(idx_);
1066 }
1067
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001068 int32_t GetIndex() const {
1069 return idx_;
1070 }
1071
1072 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1073 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1074 holder_.SetSourceClassLoader(idx_, loader);
1075 }
1076 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1077 holder_.SetJavaDexFile(idx_, dexfile);
1078 }
1079 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1080 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1081 holder_.SetNewDexFileCookie(idx_, cookie);
1082 }
1083 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1084 holder_.SetNewDexCache(idx_, cache);
1085 }
1086 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1087 holder_.SetMirrorClass(idx_, klass);
1088 }
Alex Light2f814aa2017-03-24 15:21:34 +00001089 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001090 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001091 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001092 }
Alex Light1e3926a2017-04-07 10:38:06 -07001093 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1094 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1095 holder_.SetOldObsoleteMethods(idx_, methods);
1096 }
1097 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1098 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1099 holder_.SetOldDexCaches(idx_, caches);
1100 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001101
1102 private:
1103 int32_t idx_;
1104 RedefinitionDataHolder& holder_;
1105};
1106
1107RedefinitionDataIter RedefinitionDataHolder::begin() {
1108 return RedefinitionDataIter(0, *this);
1109}
1110
1111RedefinitionDataIter RedefinitionDataHolder::end() {
1112 return RedefinitionDataIter(Length(), *this);
1113}
1114
1115bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001116 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1117 art::StackHandleScope<2> hs(driver_->self_);
1118 std::string error;
1119 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001120 art::verifier::FailureKind failure =
Alex Light8c889d22017-02-06 13:58:27 -08001121 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1122 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001123 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001124 hs.NewHandle(GetClassLoader()),
1125 dex_file_->GetClassDef(0), /*class_def*/
1126 nullptr, /*compiler_callbacks*/
Alex Light53330612017-10-04 15:29:53 -07001127 true, /*allow_soft_failures*/
Alex Light8c889d22017-02-06 13:58:27 -08001128 /*log_level*/
1129 art::verifier::HardFailLogMode::kLogWarning,
1130 &error);
Alex Light53330612017-10-04 15:29:53 -07001131 switch (failure) {
1132 case art::verifier::FailureKind::kNoFailure:
1133 case art::verifier::FailureKind::kSoftFailure:
1134 return true;
1135 case art::verifier::FailureKind::kHardFailure: {
1136 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1137 return false;
1138 }
Alex Light8c889d22017-02-06 13:58:27 -08001139 }
Alex Light8c889d22017-02-06 13:58:27 -08001140}
1141
Alex Light1babae02017-02-01 15:35:34 -08001142// Looks through the previously allocated cookies to see if we need to update them with another new
1143// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1144// once they are all added to the classloader.
1145bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001146 art::Handle<art::mirror::ClassLoader> source_class_loader,
1147 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001148 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001149 art::StackHandleScope<2> hs(driver_->self_);
1150 art::MutableHandle<art::mirror::LongArray> old_cookie(
1151 hs.NewHandle<art::mirror::LongArray>(nullptr));
1152 bool has_older_cookie = false;
1153 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001154 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1155 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001156 // Since every instance of this classloader should have the same cookie associated with it we
1157 // can stop looking here.
1158 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001159 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001160 break;
1161 }
1162 }
1163 if (old_cookie.IsNull()) {
1164 // No older cookie. Get it directly from the dex_file_obj
1165 // We should not have seen this classloader elsewhere.
1166 CHECK(!has_older_cookie);
1167 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1168 }
1169 // Use the old cookie to generate the new one with the new DexFile* added in.
1170 art::Handle<art::mirror::LongArray>
1171 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1172 old_cookie,
1173 dex_file_.get())));
1174 // Make sure the allocation worked.
1175 if (new_cookie.IsNull()) {
1176 return false;
1177 }
1178
1179 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001180 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001181 // If there are other copies of this same classloader we need to make sure that we all have the
1182 // same cookie.
1183 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001184 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001185 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001186 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1187 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001188 }
1189 }
1190 }
1191
1192 return true;
1193}
1194
Alex Lighta7e38d82017-01-19 14:57:28 -08001195bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001196 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001197 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001198 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001199 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001200 // This shouldn't allocate
1201 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001202 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1203 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001204 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001205 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1206 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001207 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001208 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001209 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1210 return false;
1211 }
Alex Light1babae02017-02-01 15:35:34 -08001212 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001213 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001214 driver_->self_->AssertPendingOOMException();
1215 driver_->self_->ClearException();
1216 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1217 return false;
1218 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001219 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001220 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1221 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001222 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001223 driver_->self_->ClearException();
1224 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1225 return false;
1226 }
1227
1228 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001229 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1230 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001231 driver_->self_->AssertPendingOOMException();
1232 driver_->self_->ClearException();
1233 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1234 return false;
1235 }
1236 return true;
1237}
1238
Alex Lighta26e3492017-06-27 17:55:37 -07001239void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
1240 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass());
1241}
1242
Alex Light5643caf2017-02-08 11:39:07 -08001243void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
Alex Lighte34fe442018-02-21 17:35:55 -08001244 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1245 return;
1246 }
Alex Light5643caf2017-02-08 11:39:07 -08001247 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1248 if (state != nullptr) {
1249 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1250 }
1251}
1252
1253void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08001254 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1255 redef.UnregisterBreakpoints();
Alex Lighte34fe442018-02-21 17:35:55 -08001256 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08001257 }
1258}
1259
Alex Light0e692732017-01-10 15:00:05 -08001260bool Redefiner::CheckAllRedefinitionAreValid() {
1261 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1262 if (!redef.CheckRedefinitionIsValid()) {
1263 return false;
1264 }
1265 }
1266 return true;
1267}
1268
Alex Light1e3926a2017-04-07 10:38:06 -07001269void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1270 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1271 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1272 }
1273}
1274
1275bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1276 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1277 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001278 return false;
1279 }
1280 }
1281 return true;
1282}
1283
1284bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001285 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001286 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001287 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001288 return false;
1289 }
Alex Light0e692732017-01-10 15:00:05 -08001290 }
1291 return true;
1292}
1293
1294void Redefiner::ClassRedefinition::ReleaseDexFile() {
1295 dex_file_.release();
1296}
1297
1298void Redefiner::ReleaseAllDexFiles() {
1299 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1300 redef.ReleaseDexFile();
1301 }
1302}
1303
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001304bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1305 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1306 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001307 return false;
1308 }
Alex Light8c889d22017-02-06 13:58:27 -08001309 }
1310 return true;
1311}
1312
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001313class ScopedDisableConcurrentAndMovingGc {
1314 public:
1315 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1316 : heap_(heap), self_(self) {
1317 if (heap_->IsGcConcurrentAndMoving()) {
1318 heap_->IncrementDisableMovingGC(self_);
1319 }
1320 }
1321
1322 ~ScopedDisableConcurrentAndMovingGc() {
1323 if (heap_->IsGcConcurrentAndMoving()) {
1324 heap_->DecrementDisableMovingGC(self_);
1325 }
1326 }
1327 private:
1328 art::gc::Heap* heap_;
1329 art::Thread* self_;
1330};
1331
Alex Lighta01de592016-11-15 10:43:06 -08001332jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001333 art::StackHandleScope<1> hs(self_);
1334 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1335 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001336 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001337 if (holder.IsNull()) {
1338 self_->AssertPendingOOMException();
1339 self_->ClearException();
1340 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1341 return result_;
1342 }
1343
Alex Lighta01de592016-11-15 10:43:06 -08001344 // First we just allocate the ClassExt and its fields that we need. These can be updated
1345 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1346 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1347 // between allocating them and pausing all threads before we can update them so we need to do a
1348 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001349 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001350 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001351 !FinishAllRemainingAllocations(holder) ||
1352 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001353 return result_;
1354 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001355
Alex Light5643caf2017-02-08 11:39:07 -08001356 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001357 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001358 art::ClassLinker* cl = runtime_->GetClassLinker();
1359 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001360 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001361 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001362 }
Alex Light7916f202017-01-27 09:00:15 -08001363 }
Alex Light5643caf2017-02-08 11:39:07 -08001364 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001365
Alex Light6abd5392017-01-05 17:53:00 -08001366 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1367 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001368 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1369
Alex Lighta01de592016-11-15 10:43:06 -08001370 // Do transition to final suspension
1371 // TODO We might want to give this its own suspended state!
1372 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001373 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1374 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1375 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001376 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001377 ClassRedefinition& redef = data.GetRedefinition();
1378 if (data.GetSourceClassLoader() != nullptr) {
1379 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001380 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001381 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001382 // TODO Rewrite so we don't do a stack walk for each and every class.
1383 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001384 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001385 }
Alex Light1e3926a2017-04-07 10:38:06 -07001386 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001387 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1388 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1389 // methods that have been jitted prior to the current redefinition being applied might continue
1390 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001391 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1392 // owns the DexFile and when ownership is transferred.
1393 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001394 return OK;
1395}
1396
Alex Light0e692732017-01-10 15:00:05 -08001397void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Alex Light0e692732017-01-10 15:00:05 -08001398 const art::DexFile::ClassDef& class_def) {
1399 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001400 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001401 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001402 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001403 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07001404 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Alex Lighta01de592016-11-15 10:43:06 -08001405 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1406 art::dex::TypeIndex method_return_idx =
1407 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1408 const auto* old_type_list = method.GetParameterTypeList();
1409 std::vector<art::dex::TypeIndex> new_type_list;
1410 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1411 new_type_list.push_back(
1412 dex_file_->GetIndexForTypeId(
1413 *dex_file_->FindTypeId(
1414 old_dex_file.GetTypeDescriptor(
1415 old_dex_file.GetTypeId(
1416 old_type_list->GetTypeItem(i).type_idx_)))));
1417 }
1418 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1419 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001420 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001421 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1422 *new_name_id,
1423 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001424 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001425 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1426 method.SetDexMethodIndex(dex_method_idx);
1427 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001428 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Light7532d582017-02-13 16:36:06 -08001429 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01001430 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08001431 }
Alex Light200b9d72016-12-15 11:34:13 -08001432}
1433
Alex Light0e692732017-01-10 15:00:05 -08001434void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001435 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1436 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1437 for (art::ArtField& field : fields_iter) {
1438 std::string declaring_class_name;
1439 const art::DexFile::TypeId* new_declaring_id =
1440 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1441 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1442 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001443 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1444 const art::DexFile::FieldId* new_field_id =
1445 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1446 CHECK(new_field_id != nullptr);
1447 // We only need to update the index since the other data in the ArtField cannot be updated.
1448 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1449 }
1450 }
Alex Light200b9d72016-12-15 11:34:13 -08001451}
1452
1453// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001454void Redefiner::ClassRedefinition::UpdateClass(
1455 art::ObjPtr<art::mirror::Class> mclass,
1456 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001457 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001458 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1459 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001460 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001461 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001462
Alex Lighta01de592016-11-15 10:43:06 -08001463 // Update the class fields.
1464 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1465 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1466 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001467 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001468 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001469 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1470 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001471 ext->SetOriginalDexFile(original_dex_file);
Alex Light035105f2018-03-05 17:48:48 -08001472
1473 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1474 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1475 // meta-data.
1476 art::jit::Jit* jit = driver_->runtime_->GetJit();
1477 if (jit != nullptr) {
1478 art::PointerSize image_pointer_size =
1479 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1480 auto code_cache = jit->GetCodeCache();
1481 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1482 // the jit about them.
1483 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1484 if (method.IsInvokable()) {
1485 code_cache->NotifyMethodRedefined(&method);
1486 }
1487 }
1488 }
Alex Lighta01de592016-11-15 10:43:06 -08001489}
1490
Alex Light1e3926a2017-04-07 10:38:06 -07001491// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1492// obsolete methods).
1493void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1494 const RedefinitionDataIter* cur_data) {
1495 art::mirror::Class* klass = GetMirrorClass();
1496 art::mirror::ClassExt* ext = klass->GetExtData();
1497 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001498 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1499 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001500 int32_t expected_length =
1501 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1502 // Check to make sure we are only undoing this one.
1503 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001504 for (int32_t i = 0; i < expected_length; i++) {
1505 art::ArtMethod* expected = nullptr;
1506 if (i < old_length) {
1507 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1508 }
1509 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001510 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1511 // obsolete methods array.
1512 return;
1513 }
1514 }
1515 // No new obsolete methods! We can get rid of the maps.
1516 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1517 }
1518}
1519
Alex Lighta01de592016-11-15 10:43:06 -08001520// This function does all (java) allocations we need to do for the Class being redefined.
1521// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001522bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1523 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001524 art::StackHandleScope<2> hs(driver_->self_);
1525 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1526 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001527 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001528 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1529 return false;
1530 }
1531 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001532 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001533 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001534 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001535 driver_->self_->AssertPendingOOMException();
1536 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001537 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1538 return false;
1539 }
Alex Light1e3926a2017-04-07 10:38:06 -07001540 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1541 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001542 // are only modified when all threads (other than the modifying one) are suspended we don't need
1543 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1544 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001545 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1546 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1547 if (!ext->ExtendObsoleteArrays(
1548 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1549 // OOM. Clear exception and return error.
1550 driver_->self_->AssertPendingOOMException();
1551 driver_->self_->ClearException();
1552 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1553 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001554 }
1555 return true;
1556}
1557
1558} // namespace openjdkjvmti