blob: 48e2958773762223fed61911b884186a69bd5fc9 [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 Markob5406092018-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 Marko3e61dc02018-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"
Alex Light6161f132017-01-25 10:30:20 -080064#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080065#include "mirror/class_ext.h"
66#include "mirror/object.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070067#include "nativehelper/scoped_local_ref.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080068#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080069#include "object_lock.h"
70#include "runtime.h"
Alex Lighta26e3492017-06-27 17:55:37 -070071#include "ti_breakpoint.h"
Alex Lighteb98b082017-01-25 13:02:32 -080072#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080073#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080074#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070075#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080076
77namespace openjdkjvmti {
78
Andreas Gampe46ee31b2016-12-14 10:11:49 -080079using android::base::StringPrintf;
80
Alex Lighteee0bd42017-02-14 15:31:45 +000081// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
82// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
83// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
84class ObsoleteMap {
85 public:
86 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
87 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
88 auto method_pair = id_map_.find(original);
89 if (method_pair != id_map_.end()) {
90 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
91 method_pair->second, art::kRuntimePointerSize);
92 DCHECK(res != nullptr);
93 DCHECK_EQ(original, res->GetNonObsoleteMethod());
94 return res;
95 } else {
96 return nullptr;
97 }
98 }
99
100 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
101 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
102 DCHECK(original != nullptr);
103 DCHECK(obsolete != nullptr);
104 int32_t slot = next_free_slot_++;
105 DCHECK_LT(slot, obsolete_methods_->GetLength());
106 DCHECK(nullptr ==
107 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
108 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
109 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
110 obsolete_dex_caches_->Set(slot, original_dex_cache_);
111 id_map_.insert({original, slot});
112 }
113
114 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
115 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
116 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
117 : next_free_slot_(0),
118 obsolete_methods_(obsolete_methods),
119 obsolete_dex_caches_(obsolete_dex_caches),
120 original_dex_cache_(original_dex_cache) {
121 // Figure out where the first unused slot in the obsolete_methods_ array is.
122 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
123 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
124 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
125 next_free_slot_++;
126 }
127 // Sanity check that the same slot in obsolete_dex_caches_ is free.
128 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
129 }
130
131 private:
132 int32_t next_free_slot_;
133 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
134 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
135 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
136 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
137 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
138 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
139};
140
Alex Lightdba61482016-12-21 08:20:29 -0800141// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
142// some basic sanity checks that the obsolete method is sane.
143class ObsoleteMethodStackVisitor : public art::StackVisitor {
144 protected:
145 ObsoleteMethodStackVisitor(
146 art::Thread* thread,
147 art::LinearAlloc* allocator,
148 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000149 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800150 : StackVisitor(thread,
151 /*context*/nullptr,
152 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
153 allocator_(allocator),
154 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800155 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800156
157 ~ObsoleteMethodStackVisitor() OVERRIDE {}
158
159 public:
160 // Returns true if we successfully installed obsolete methods on this thread, filling
161 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
162 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800163 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800164 art::Thread* thread,
165 art::LinearAlloc* allocator,
166 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000167 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800168 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800169 ObsoleteMethodStackVisitor visitor(thread,
170 allocator,
171 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800172 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800173 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800174 }
175
176 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000177 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800178 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800179 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800180 // We cannot ensure that the right dex file is used in inlined frames so we don't support
181 // redefining them.
182 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000183 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
184 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800185 // Create a new Obsolete Method and put it in the list.
186 art::Runtime* runtime = art::Runtime::Current();
187 art::ClassLinker* cl = runtime->GetClassLinker();
188 auto ptr_size = cl->GetImagePointerSize();
189 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800190 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800191 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
192 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800193 new_obsolete_method = new (method_storage) art::ArtMethod();
194 new_obsolete_method->CopyFrom(old_method, ptr_size);
195 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
196 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800197 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700198 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000199 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800200 // Update JIT Data structures to point to the new method.
201 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
202 if (jit != nullptr) {
203 // Notify the JIT we are making this obsolete method. It will update the jit's internal
204 // structures to keep track of the new obsolete method.
205 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
206 }
Alex Lightdba61482016-12-21 08:20:29 -0800207 }
208 DCHECK(new_obsolete_method != nullptr);
209 SetMethod(new_obsolete_method);
210 }
211 return true;
212 }
213
214 private:
215 // The linear allocator we should use to make new methods.
216 art::LinearAlloc* allocator_;
217 // The set of all methods which could be obsoleted.
218 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
219 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000220 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
221 // the redefined classes ClassExt as it is filled.
222 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800223};
224
Alex Lighte4a88632017-01-10 07:41:24 -0800225jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
226 jclass klass,
227 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800228 art::Thread* self = art::Thread::Current();
229 art::ScopedObjectAccess soa(self);
230 art::StackHandleScope<1> hs(self);
231 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
232 if (obj.IsNull()) {
233 return ERR(INVALID_CLASS);
234 }
235 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
236 std::string err_unused;
237 *is_redefinable =
Alex Lightd3782f32018-04-05 13:49:43 -0700238 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
239 ? JNI_TRUE : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800240 return OK;
241}
242
Alex Lightd3782f32018-04-05 13:49:43 -0700243jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
244 art::Thread* self = art::Thread::Current();
245 art::ScopedObjectAccess soa(self);
246 art::StackHandleScope<1> hs(self);
247 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
248 if (obj.IsNull()) {
249 return ERR(INVALID_CLASS);
250 }
251 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
252 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
253}
254
Alex Lighte4a88632017-01-10 07:41:24 -0800255jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
256 /*out*/std::string* error_msg) {
Alex Lightd3782f32018-04-05 13:49:43 -0700257 if (!klass->IsResolved()) {
258 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
259 // the same thread as the class-linking process. If it's on another thread we will be able to
260 // wait for the preparation to finish and continue from there.
261 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
262 *error_msg = "Modification of class " + klass->PrettyClass() +
263 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
264 " Please use ClassFileLoadHook directly instead.";
265 return ERR(INTERNAL);
266 } else {
267 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
268 << "it could cause arbitrary length waits as the class is being resolved.";
269 }
270 }
Alex Lighte4a88632017-01-10 07:41:24 -0800271 if (klass->IsPrimitive()) {
272 *error_msg = "Modification of primitive classes is not supported";
273 return ERR(UNMODIFIABLE_CLASS);
274 } else if (klass->IsInterface()) {
275 *error_msg = "Modification of Interface classes is currently not supported";
276 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800277 } else if (klass->IsStringClass()) {
278 *error_msg = "Modification of String class is not supported";
279 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800280 } else if (klass->IsArrayClass()) {
281 *error_msg = "Modification of Array classes is not supported";
282 return ERR(UNMODIFIABLE_CLASS);
283 } else if (klass->IsProxyClass()) {
284 *error_msg = "Modification of proxy classes is not supported";
285 return ERR(UNMODIFIABLE_CLASS);
286 }
287
Alex Lighte77b48b2017-02-22 11:08:06 -0800288 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
289 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
290 *error_msg = "Class might have stack frames that cannot be made obsolete";
291 return ERR(UNMODIFIABLE_CLASS);
292 }
293 }
294
Alex Lighte4a88632017-01-10 07:41:24 -0800295 return OK;
296}
297
Alex Lighta01de592016-11-15 10:43:06 -0800298// Moves dex data to an anonymous, read-only mmap'd region.
299std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100300 art::ArrayRef<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800301 std::string* error_msg) {
302 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800303 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800304 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700305 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800306 PROT_READ|PROT_WRITE,
307 /*low_4gb*/false,
308 /*reuse*/false,
309 error_msg));
310 if (map == nullptr) {
311 return map;
312 }
Vladimir Markoe1993c72017-06-14 17:01:38 +0100313 memcpy(map->Begin(), data.data(), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800314 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
315 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800316 map->Protect(PROT_READ);
317 return map;
318}
319
Alex Lighta7e38d82017-01-19 14:57:28 -0800320Redefiner::ClassRedefinition::ClassRedefinition(
321 Redefiner* driver,
322 jclass klass,
323 const art::DexFile* redefined_dex_file,
324 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100325 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800326 driver_(driver),
327 klass_(klass),
328 dex_file_(redefined_dex_file),
329 class_sig_(class_sig),
330 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800331 GetMirrorClass()->MonitorEnter(driver_->self_);
332}
333
334Redefiner::ClassRedefinition::~ClassRedefinition() {
335 if (driver_ != nullptr) {
336 GetMirrorClass()->MonitorExit(driver_->self_);
337 }
338}
339
Alex Light0e692732017-01-10 15:00:05 -0800340jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800341 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800342 art::Runtime* runtime,
343 art::Thread* self,
344 jint class_count,
345 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800346 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800347 if (env == nullptr) {
348 *error_msg = "env was null!";
349 return ERR(INVALID_ENVIRONMENT);
350 } else if (class_count < 0) {
351 *error_msg = "class_count was less then 0";
352 return ERR(ILLEGAL_ARGUMENT);
353 } else if (class_count == 0) {
354 // We don't actually need to do anything. Just return OK.
355 return OK;
356 } else if (definitions == nullptr) {
357 *error_msg = "null definitions!";
358 return ERR(NULL_POINTER);
359 }
Alex Light6ac57502017-01-19 15:05:06 -0800360 std::vector<ArtClassDefinition> def_vector;
361 def_vector.reserve(class_count);
362 for (jint i = 0; i < class_count; i++) {
Alex Lightd3782f32018-04-05 13:49:43 -0700363 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800364 if (res != OK) {
365 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800366 }
Alex Light6ac57502017-01-19 15:05:06 -0800367 // We make a copy of the class_bytes to pass into the retransformation.
368 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
369 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
370 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800371 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800372 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800373 if (res != OK) {
374 return res;
375 }
376 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
377
378 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800379 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800380 if (res != OK) {
381 return res;
382 }
383 def_vector.push_back(std::move(def));
384 }
385 // Call all the transformation events.
Alex Light64e4c142018-01-30 13:46:37 -0800386 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800387 self,
388 &def_vector);
389 if (res != OK) {
390 // Something went wrong with transformation!
391 return res;
392 }
393 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
394}
395
396jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
397 art::Runtime* runtime,
398 art::Thread* self,
399 const std::vector<ArtClassDefinition>& definitions,
400 std::string* error_msg) {
401 DCHECK(env != nullptr);
402 if (definitions.size() == 0) {
403 // We don't actually need to do anything. Just return OK.
404 return OK;
405 }
Alex Light0e692732017-01-10 15:00:05 -0800406 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
407 // are going to redefine.
408 art::jit::ScopedJitSuspend suspend_jit;
409 // Get shared mutator lock so we can lock all the classes.
410 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700411 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800412 for (const ArtClassDefinition& def : definitions) {
413 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700414 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800415 jvmtiError res = r.AddRedefinition(env, def);
416 if (res != OK) {
417 return res;
418 }
Alex Light0e692732017-01-10 15:00:05 -0800419 }
420 }
421 return r.Run();
422}
423
Alex Light6ac57502017-01-19 15:05:06 -0800424jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800425 std::string original_dex_location;
426 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700427 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800428 *error_msg_ = "Unable to get original dex file location!";
429 return ret;
430 }
Alex Light52a2db52017-01-19 23:00:21 +0000431 char* generic_ptr_unused = nullptr;
432 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700433 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800434 *error_msg_ = "Unable to get class signature!";
435 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000436 }
Andreas Gampe54711412017-02-21 12:41:43 -0800437 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
438 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800439 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700440 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800441 error_msg_));
442 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800443 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700444 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800445 << "in dex file " << original_dex_location << " because: " << *error_msg_;
446 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800447 return ERR(OUT_OF_MEMORY);
448 }
449 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800450 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800451 return ERR(INVALID_CLASS_FORMAT);
452 }
453 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800454 const art::ArtDexFileLoader dex_file_loader;
455 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map->GetName(),
456 checksum,
457 std::move(map),
458 /*verify*/true,
459 /*verify_checksum*/true,
460 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800461 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700462 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800463 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800464 return ERR(INVALID_CLASS_FORMAT);
465 }
Alex Light0e692732017-01-10 15:00:05 -0800466 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800467 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700468 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800469 dex_file.release(),
470 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700471 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800472 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800473}
474
Alex Light0e692732017-01-10 15:00:05 -0800475art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
476 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800477}
478
Alex Light0e692732017-01-10 15:00:05 -0800479art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800480 return GetMirrorClass()->GetClassLoader();
481}
482
Alex Light0e692732017-01-10 15:00:05 -0800483art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
484 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700485 art::StackHandleScope<2> hs(driver_->self_);
486 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
487 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
488 art::ObjPtr<art::mirror::DexCache>::DownCast(
Vladimir Markob5406092018-05-24 11:09:38 +0100489 art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
Alex Light07f06212017-06-01 14:01:43 -0700490 if (cache.IsNull()) {
491 driver_->self_->AssertPendingOOMException();
492 return nullptr;
493 }
494 art::Handle<art::mirror::String> location(hs.NewHandle(
495 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
496 if (location.IsNull()) {
497 driver_->self_->AssertPendingOOMException();
498 return nullptr;
499 }
500 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
501 art::mirror::DexCache::InitializeDexCache(driver_->self_,
502 cache.Get(),
503 location.Get(),
504 dex_file_.get(),
505 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
506 : loader->GetAllocator(),
507 art::kRuntimePointerSize);
508 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800509}
510
Alex Light0e692732017-01-10 15:00:05 -0800511void Redefiner::RecordFailure(jvmtiError result,
512 const std::string& class_sig,
513 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800514 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800515 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800516 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800517 result_ = result;
518}
519
Alex Light2f814aa2017-03-24 15:21:34 +0000520art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800521 // If we have been specifically given a new set of bytes use that
522 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800523 return art::mirror::ByteArray::AllocateAndFill(
524 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100525 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Alex Light440b5d92017-01-24 15:32:25 -0800526 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800527 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800528
529 // See if we already have one set.
530 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
531 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000532 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
533 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800534 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000535 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800536 }
Alex Lighta01de592016-11-15 10:43:06 -0800537 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800538
Alex Light2f814aa2017-03-24 15:21:34 +0000539 // return the current dex_cache which has the dex file in it.
540 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800541 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000542 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800543 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
544 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800545 }
Alex Light2f814aa2017-03-24 15:21:34 +0000546 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800547}
548
Alex Lightdba61482016-12-21 08:20:29 -0800549struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000550 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800551 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800552 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800553
Alex Lighteee0bd42017-02-14 15:31:45 +0000554 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
555 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800556};
557
Alex Lightdba61482016-12-21 08:20:29 -0800558void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
559 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800560 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
561 data->allocator,
562 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000563 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800564}
565
566// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
567// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800568// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
569void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800570 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
571 art::mirror::ClassExt* ext = art_klass->GetExtData();
572 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800573 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000574 // This holds pointers to the obsolete methods map fields which are updated as needed.
575 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
576 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800577 // Add all the declared methods to the map
578 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800579 if (m.IsIntrinsic()) {
580 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
581 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
582 << "methods that have already been compiled.";
583 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000584 // It is possible to simply filter out some methods where they cannot really become obsolete,
585 // such as native methods and keep their original (possibly optimized) implementations. We don't
586 // do this, however, since we would need to mark these functions (still in the classes
587 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
588 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
589 // error checking from the interpreter which ensure we don't try to start executing obsolete
590 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000591 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800592 }
593 {
Alex Light0e692732017-01-10 15:00:05 -0800594 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800595 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
596 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800597 }
Alex Lightdba61482016-12-21 08:20:29 -0800598}
599
Alex Light6161f132017-01-25 10:30:20 -0800600// Try and get the declared method. First try to get a virtual method then a direct method if that's
601// not found.
602static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
Vladimir Markoba118822017-06-12 15:41:56 +0100603 art::StringPiece name,
Alex Light6161f132017-01-25 10:30:20 -0800604 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markoba118822017-06-12 15:41:56 +0100605 DCHECK(!klass->IsProxyClass());
606 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
607 if (m.GetName() == name && m.GetSignature() == sig) {
608 return &m;
609 }
Alex Light6161f132017-01-25 10:30:20 -0800610 }
Vladimir Markoba118822017-06-12 15:41:56 +0100611 return nullptr;
Alex Light6161f132017-01-25 10:30:20 -0800612}
613
614bool Redefiner::ClassRedefinition::CheckSameMethods() {
615 art::StackHandleScope<1> hs(driver_->self_);
616 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
617 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
618
619 art::ClassDataItemIterator new_iter(*dex_file_,
620 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
621
622 // Make sure we have the same number of methods.
623 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
624 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
625 if (num_new_method != num_old_method) {
626 bool bigger = num_new_method > num_old_method;
627 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
628 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
629 StringPrintf("Total number of declared methods changed from %d to %d",
630 num_old_method, num_new_method));
631 return false;
632 }
633
634 // Skip all of the fields. We should have already checked this.
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700635 new_iter.SkipAllFields();
Alex Light6161f132017-01-25 10:30:20 -0800636 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
637 // files have the same number of methods, which means there must be an equal amount of additions
638 // and removals.
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800639 for (; new_iter.HasNextMethod(); new_iter.Next()) {
Alex Light6161f132017-01-25 10:30:20 -0800640 // Get the data on the method we are searching for
641 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
642 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
643 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
644 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
645 // If we got past the check for the same number of methods above that means there must be at
646 // least one added and one removed method. We will return the ADDED failure message since it is
647 // easier to get a useful error report for it.
648 if (old_method == nullptr) {
649 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
650 StringPrintf("Unknown method '%s' (sig: %s) was added!",
651 new_method_name,
652 new_method_signature.ToString().c_str()));
653 return false;
654 }
655 // Since direct methods have different flags than virtual ones (specifically direct methods must
656 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
657 // virtual to direct.
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100658 uint32_t new_flags = new_iter.GetMethodAccessFlags();
659 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
Alex Light6161f132017-01-25 10:30:20 -0800660 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
661 StringPrintf("method '%s' (sig: %s) had different access flags",
662 new_method_name,
663 new_method_signature.ToString().c_str()));
664 return false;
665 }
666 }
667 return true;
668}
669
670bool Redefiner::ClassRedefinition::CheckSameFields() {
671 art::StackHandleScope<1> hs(driver_->self_);
672 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
673 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
674 art::ClassDataItemIterator new_iter(*dex_file_,
675 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
676 const art::DexFile& old_dex_file = h_klass->GetDexFile();
677 art::ClassDataItemIterator old_iter(old_dex_file,
678 old_dex_file.GetClassData(*h_klass->GetClassDef()));
679 // Instance and static fields can be differentiated by their flags so no need to check them
680 // separately.
681 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
682 // Get the data on the method we are searching for
683 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
684 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
685 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
686
687 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
688 // We are missing the old version of this method!
689 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
690 StringPrintf("Unknown field '%s' (type: %s) added!",
691 new_field_name,
692 new_field_type));
693 return false;
694 }
695
696 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
697 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
698 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
699
700 // Check name and type.
701 if (strcmp(old_field_name, new_field_name) != 0 ||
702 strcmp(old_field_type, new_field_type) != 0) {
703 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
704 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
705 old_field_name,
706 old_field_type,
707 new_field_name,
708 new_field_type));
709 return false;
710 }
711
712 // Since static fields have different flags than instance ones (specifically static fields must
713 // have the kAccStatic flag) we can tell if a field changes from static to instance.
714 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
715 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
716 StringPrintf("Field '%s' (sig: %s) had different access flags",
717 new_field_name,
718 new_field_type));
719 return false;
720 }
721
722 new_iter.Next();
723 old_iter.Next();
724 }
725 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
726 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
727 StringPrintf("field '%s' (sig: %s) is missing!",
728 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
729 old_iter.GetMemberIndex())),
730 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
731 old_iter.GetMemberIndex()))));
732 return false;
733 }
734 return true;
735}
736
Alex Light0e692732017-01-10 15:00:05 -0800737bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800738 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000739 // Easy check that only 1 class def is present.
740 if (dex_file_->NumClassDefs() != 1) {
741 RecordFailure(ERR(ILLEGAL_ARGUMENT),
742 StringPrintf("Expected 1 class def in dex file but found %d",
743 dex_file_->NumClassDefs()));
744 return false;
745 }
746 // Get the ClassDef from the new DexFile.
747 // Since the dex file has only a single class def the index is always 0.
748 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
749 // Get the class as it is now.
750 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
751
752 // Check the access flags didn't change.
753 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
754 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
755 "Cannot change modifiers of class by redefinition");
756 return false;
757 }
758
759 // Check class name.
760 // These should have been checked by the dexfile verifier on load.
761 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
762 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
763 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
764 if (!current_class->DescriptorEquals(descriptor)) {
765 std::string storage;
766 RecordFailure(ERR(NAMES_DONT_MATCH),
767 StringPrintf("expected file to contain class called '%s' but found '%s'!",
768 current_class->GetDescriptor(&storage),
769 descriptor));
770 return false;
771 }
772 if (current_class->IsObjectClass()) {
773 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
774 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
775 return false;
776 }
777 } else {
778 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
779 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
780 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
781 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
782 return false;
783 }
784 }
785 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
786 if (interfaces == nullptr) {
787 if (current_class->NumDirectInterfaces() != 0) {
788 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
789 return false;
790 }
791 } else {
792 DCHECK(!current_class->IsProxyClass());
793 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
794 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
795 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
796 return false;
797 }
798 // The order of interfaces is (barely) meaningful so we error if it changes.
799 const art::DexFile& orig_dex_file = current_class->GetDexFile();
800 for (uint32_t i = 0; i < interfaces->Size(); i++) {
801 if (strcmp(
802 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
803 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
804 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
805 "Interfaces changed or re-ordered");
806 return false;
807 }
808 }
809 }
Alex Light460d1b42017-01-10 15:37:17 +0000810 return true;
811}
812
Alex Light0e692732017-01-10 15:00:05 -0800813bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800814 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800815 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000816
Alex Lighte4a88632017-01-10 07:41:24 -0800817 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
818 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
819 if (res != OK) {
820 RecordFailure(res, err);
821 return false;
822 } else {
823 return true;
824 }
Alex Light460d1b42017-01-10 15:37:17 +0000825}
826
Alex Light0e692732017-01-10 15:00:05 -0800827bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000828 return CheckRedefinable() &&
829 CheckClass() &&
830 CheckSameFields() &&
831 CheckSameMethods();
832}
833
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800834class RedefinitionDataIter;
835
Alex Light0e692732017-01-10 15:00:05 -0800836// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
837// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
838// having to deal with the fact that we need to hold an arbitrary number of references live.
839class RedefinitionDataHolder {
840 public:
841 enum DataSlot : int32_t {
842 kSlotSourceClassLoader = 0,
843 kSlotJavaDexFile = 1,
844 kSlotNewDexFileCookie = 2,
845 kSlotNewDexCache = 3,
846 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800847 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700848 kSlotOldObsoleteMethods = 6,
849 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800850
851 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700852 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800853 };
854
855 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
856 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
857 // the passed in handle-scope.
858 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
859 art::Runtime* runtime,
860 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800861 std::vector<Redefiner::ClassRedefinition>* redefinitions)
862 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Vladimir Markob5406092018-05-24 11:09:38 +0100863 arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
864 self,
865 art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
866 redefinitions->size() * kNumSlots))),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800867 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800868
869 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
870 return arr_.IsNull();
871 }
872
Alex Light8c889d22017-02-06 13:58:27 -0800873 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800874 REQUIRES_SHARED(art::Locks::mutator_lock_) {
875 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
876 }
Alex Light8c889d22017-02-06 13:58:27 -0800877 art::mirror::Object* GetJavaDexFile(jint klass_index) const
878 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800879 return GetSlot(klass_index, kSlotJavaDexFile);
880 }
Alex Light8c889d22017-02-06 13:58:27 -0800881 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800882 REQUIRES_SHARED(art::Locks::mutator_lock_) {
883 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
884 }
Alex Light8c889d22017-02-06 13:58:27 -0800885 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800886 REQUIRES_SHARED(art::Locks::mutator_lock_) {
887 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
888 }
Alex Light8c889d22017-02-06 13:58:27 -0800889 art::mirror::Class* GetMirrorClass(jint klass_index) const
890 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800891 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
892 }
893
Alex Light2f814aa2017-03-24 15:21:34 +0000894 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800895 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000896 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800897 }
898
Alex Light1e3926a2017-04-07 10:38:06 -0700899 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
900 REQUIRES_SHARED(art::Locks::mutator_lock_) {
901 return art::down_cast<art::mirror::PointerArray*>(
902 GetSlot(klass_index, kSlotOldObsoleteMethods));
903 }
904
905 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
906 REQUIRES_SHARED(art::Locks::mutator_lock_) {
907 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
908 GetSlot(klass_index, kSlotOldDexCaches));
909 }
910
Alex Light0e692732017-01-10 15:00:05 -0800911 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
912 REQUIRES_SHARED(art::Locks::mutator_lock_) {
913 SetSlot(klass_index, kSlotSourceClassLoader, loader);
914 }
915 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
916 REQUIRES_SHARED(art::Locks::mutator_lock_) {
917 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
918 }
919 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
920 REQUIRES_SHARED(art::Locks::mutator_lock_) {
921 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
922 }
923 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
924 REQUIRES_SHARED(art::Locks::mutator_lock_) {
925 SetSlot(klass_index, kSlotNewDexCache, cache);
926 }
927 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
928 REQUIRES_SHARED(art::Locks::mutator_lock_) {
929 SetSlot(klass_index, kSlotMirrorClass, klass);
930 }
Alex Light2f814aa2017-03-24 15:21:34 +0000931 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800932 REQUIRES_SHARED(art::Locks::mutator_lock_) {
933 SetSlot(klass_index, kSlotOrigDexFile, bytes);
934 }
Alex Light1e3926a2017-04-07 10:38:06 -0700935 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
936 REQUIRES_SHARED(art::Locks::mutator_lock_) {
937 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
938 }
939 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
940 REQUIRES_SHARED(art::Locks::mutator_lock_) {
941 SetSlot(klass_index, kSlotOldDexCaches, caches);
942 }
Alex Light0e692732017-01-10 15:00:05 -0800943
Alex Light8c889d22017-02-06 13:58:27 -0800944 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800945 return arr_->GetLength() / kNumSlots;
946 }
947
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800948 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
949 REQUIRES_SHARED(art::Locks::mutator_lock_) {
950 return redefinitions_;
951 }
952
953 bool operator==(const RedefinitionDataHolder& other) const
954 REQUIRES_SHARED(art::Locks::mutator_lock_) {
955 return arr_.Get() == other.arr_.Get();
956 }
957
958 bool operator!=(const RedefinitionDataHolder& other) const
959 REQUIRES_SHARED(art::Locks::mutator_lock_) {
960 return !(*this == other);
961 }
962
963 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
964 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
965
Alex Light0e692732017-01-10 15:00:05 -0800966 private:
Alex Light8c889d22017-02-06 13:58:27 -0800967 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800968 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800969
970 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800971 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800972 DCHECK_LT(klass_index, Length());
973 return arr_->Get((kNumSlots * klass_index) + slot);
974 }
975
976 void SetSlot(jint klass_index,
977 DataSlot slot,
978 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
979 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
980 DCHECK_LT(klass_index, Length());
981 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
982 }
983
984 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
985};
986
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800987class RedefinitionDataIter {
988 public:
989 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
990
991 RedefinitionDataIter(const RedefinitionDataIter&) = default;
992 RedefinitionDataIter(RedefinitionDataIter&&) = default;
993 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
994 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
995
996 bool operator==(const RedefinitionDataIter& other) const
997 REQUIRES_SHARED(art::Locks::mutator_lock_) {
998 return idx_ == other.idx_ && holder_ == other.holder_;
999 }
1000
1001 bool operator!=(const RedefinitionDataIter& other) const
1002 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1003 return !(*this == other);
1004 }
1005
1006 RedefinitionDataIter operator++() { // Value after modification.
1007 idx_++;
1008 return *this;
1009 }
1010
1011 RedefinitionDataIter operator++(int) {
1012 RedefinitionDataIter temp = *this;
1013 idx_++;
1014 return temp;
1015 }
1016
1017 RedefinitionDataIter operator+(ssize_t delta) const {
1018 RedefinitionDataIter temp = *this;
1019 temp += delta;
1020 return temp;
1021 }
1022
1023 RedefinitionDataIter& operator+=(ssize_t delta) {
1024 idx_ += delta;
1025 return *this;
1026 }
1027
1028 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1029 return (*holder_.GetRedefinitions())[idx_];
1030 }
1031
1032 RedefinitionDataHolder& GetHolder() {
1033 return holder_;
1034 }
1035
1036 art::mirror::ClassLoader* GetSourceClassLoader() const
1037 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1038 return holder_.GetSourceClassLoader(idx_);
1039 }
1040 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1041 return holder_.GetJavaDexFile(idx_);
1042 }
1043 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1044 return holder_.GetNewDexFileCookie(idx_);
1045 }
1046 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1047 return holder_.GetNewDexCache(idx_);
1048 }
1049 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1050 return holder_.GetMirrorClass(idx_);
1051 }
Alex Light2f814aa2017-03-24 15:21:34 +00001052 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001053 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001054 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001055 }
Alex Light1e3926a2017-04-07 10:38:06 -07001056 art::mirror::PointerArray* GetOldObsoleteMethods() const
1057 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1058 return holder_.GetOldObsoleteMethods(idx_);
1059 }
1060 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1061 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1062 return holder_.GetOldDexCaches(idx_);
1063 }
1064
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001065 int32_t GetIndex() const {
1066 return idx_;
1067 }
1068
1069 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1070 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1071 holder_.SetSourceClassLoader(idx_, loader);
1072 }
1073 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1074 holder_.SetJavaDexFile(idx_, dexfile);
1075 }
1076 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1077 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1078 holder_.SetNewDexFileCookie(idx_, cookie);
1079 }
1080 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1081 holder_.SetNewDexCache(idx_, cache);
1082 }
1083 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1084 holder_.SetMirrorClass(idx_, klass);
1085 }
Alex Light2f814aa2017-03-24 15:21:34 +00001086 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001087 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001088 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001089 }
Alex Light1e3926a2017-04-07 10:38:06 -07001090 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1091 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1092 holder_.SetOldObsoleteMethods(idx_, methods);
1093 }
1094 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1095 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1096 holder_.SetOldDexCaches(idx_, caches);
1097 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001098
1099 private:
1100 int32_t idx_;
1101 RedefinitionDataHolder& holder_;
1102};
1103
1104RedefinitionDataIter RedefinitionDataHolder::begin() {
1105 return RedefinitionDataIter(0, *this);
1106}
1107
1108RedefinitionDataIter RedefinitionDataHolder::end() {
1109 return RedefinitionDataIter(Length(), *this);
1110}
1111
1112bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001113 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1114 art::StackHandleScope<2> hs(driver_->self_);
1115 std::string error;
1116 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001117 art::verifier::FailureKind failure =
Alex Light8c889d22017-02-06 13:58:27 -08001118 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1119 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001120 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001121 hs.NewHandle(GetClassLoader()),
1122 dex_file_->GetClassDef(0), /*class_def*/
1123 nullptr, /*compiler_callbacks*/
Alex Light53330612017-10-04 15:29:53 -07001124 true, /*allow_soft_failures*/
Alex Light8c889d22017-02-06 13:58:27 -08001125 /*log_level*/
1126 art::verifier::HardFailLogMode::kLogWarning,
1127 &error);
Alex Light53330612017-10-04 15:29:53 -07001128 switch (failure) {
1129 case art::verifier::FailureKind::kNoFailure:
1130 case art::verifier::FailureKind::kSoftFailure:
1131 return true;
1132 case art::verifier::FailureKind::kHardFailure: {
1133 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1134 return false;
1135 }
Alex Light8c889d22017-02-06 13:58:27 -08001136 }
Alex Light8c889d22017-02-06 13:58:27 -08001137}
1138
Alex Light1babae02017-02-01 15:35:34 -08001139// Looks through the previously allocated cookies to see if we need to update them with another new
1140// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1141// once they are all added to the classloader.
1142bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001143 art::Handle<art::mirror::ClassLoader> source_class_loader,
1144 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001145 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001146 art::StackHandleScope<2> hs(driver_->self_);
1147 art::MutableHandle<art::mirror::LongArray> old_cookie(
1148 hs.NewHandle<art::mirror::LongArray>(nullptr));
1149 bool has_older_cookie = false;
1150 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001151 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1152 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001153 // Since every instance of this classloader should have the same cookie associated with it we
1154 // can stop looking here.
1155 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001156 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001157 break;
1158 }
1159 }
1160 if (old_cookie.IsNull()) {
1161 // No older cookie. Get it directly from the dex_file_obj
1162 // We should not have seen this classloader elsewhere.
1163 CHECK(!has_older_cookie);
1164 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1165 }
1166 // Use the old cookie to generate the new one with the new DexFile* added in.
1167 art::Handle<art::mirror::LongArray>
1168 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1169 old_cookie,
1170 dex_file_.get())));
1171 // Make sure the allocation worked.
1172 if (new_cookie.IsNull()) {
1173 return false;
1174 }
1175
1176 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001177 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001178 // If there are other copies of this same classloader we need to make sure that we all have the
1179 // same cookie.
1180 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001181 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001182 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001183 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1184 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001185 }
1186 }
1187 }
1188
1189 return true;
1190}
1191
Alex Lighta7e38d82017-01-19 14:57:28 -08001192bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001193 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001194 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001195 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001196 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001197 // This shouldn't allocate
1198 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001199 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1200 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001201 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001202 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1203 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001204 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001205 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001206 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1207 return false;
1208 }
Alex Light1babae02017-02-01 15:35:34 -08001209 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001210 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001211 driver_->self_->AssertPendingOOMException();
1212 driver_->self_->ClearException();
1213 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1214 return false;
1215 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001216 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001217 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1218 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001219 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001220 driver_->self_->ClearException();
1221 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1222 return false;
1223 }
1224
1225 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001226 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1227 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001228 driver_->self_->AssertPendingOOMException();
1229 driver_->self_->ClearException();
1230 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1231 return false;
1232 }
1233 return true;
1234}
1235
Alex Lighta26e3492017-06-27 17:55:37 -07001236void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
1237 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass());
1238}
1239
Alex Light5643caf2017-02-08 11:39:07 -08001240void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
Alex Lighte34fe442018-02-21 17:35:55 -08001241 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1242 return;
1243 }
Alex Light5643caf2017-02-08 11:39:07 -08001244 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1245 if (state != nullptr) {
1246 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1247 }
1248}
1249
1250void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08001251 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1252 redef.UnregisterBreakpoints();
Alex Lighte34fe442018-02-21 17:35:55 -08001253 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08001254 }
1255}
1256
Alex Light0e692732017-01-10 15:00:05 -08001257bool Redefiner::CheckAllRedefinitionAreValid() {
1258 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1259 if (!redef.CheckRedefinitionIsValid()) {
1260 return false;
1261 }
1262 }
1263 return true;
1264}
1265
Alex Light1e3926a2017-04-07 10:38:06 -07001266void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1267 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1268 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1269 }
1270}
1271
1272bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1273 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1274 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001275 return false;
1276 }
1277 }
1278 return true;
1279}
1280
1281bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001282 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001283 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001284 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001285 return false;
1286 }
Alex Light0e692732017-01-10 15:00:05 -08001287 }
1288 return true;
1289}
1290
1291void Redefiner::ClassRedefinition::ReleaseDexFile() {
1292 dex_file_.release();
1293}
1294
1295void Redefiner::ReleaseAllDexFiles() {
1296 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1297 redef.ReleaseDexFile();
1298 }
1299}
1300
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001301bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1302 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1303 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001304 return false;
1305 }
Alex Light8c889d22017-02-06 13:58:27 -08001306 }
1307 return true;
1308}
1309
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001310class ScopedDisableConcurrentAndMovingGc {
1311 public:
1312 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1313 : heap_(heap), self_(self) {
1314 if (heap_->IsGcConcurrentAndMoving()) {
1315 heap_->IncrementDisableMovingGC(self_);
1316 }
1317 }
1318
1319 ~ScopedDisableConcurrentAndMovingGc() {
1320 if (heap_->IsGcConcurrentAndMoving()) {
1321 heap_->DecrementDisableMovingGC(self_);
1322 }
1323 }
1324 private:
1325 art::gc::Heap* heap_;
1326 art::Thread* self_;
1327};
1328
Alex Lighta01de592016-11-15 10:43:06 -08001329jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001330 art::StackHandleScope<1> hs(self_);
1331 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1332 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001333 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001334 if (holder.IsNull()) {
1335 self_->AssertPendingOOMException();
1336 self_->ClearException();
1337 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1338 return result_;
1339 }
1340
Alex Lighta01de592016-11-15 10:43:06 -08001341 // First we just allocate the ClassExt and its fields that we need. These can be updated
1342 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1343 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1344 // between allocating them and pausing all threads before we can update them so we need to do a
1345 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001346 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001347 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001348 !FinishAllRemainingAllocations(holder) ||
1349 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001350 return result_;
1351 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001352
Alex Light5643caf2017-02-08 11:39:07 -08001353 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001354 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001355 art::ClassLinker* cl = runtime_->GetClassLinker();
1356 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001357 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001358 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001359 }
Alex Light7916f202017-01-27 09:00:15 -08001360 }
Alex Light5643caf2017-02-08 11:39:07 -08001361 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001362
Alex Light6abd5392017-01-05 17:53:00 -08001363 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1364 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001365 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1366
Alex Lighta01de592016-11-15 10:43:06 -08001367 // Do transition to final suspension
1368 // TODO We might want to give this its own suspended state!
1369 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001370 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1371 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1372 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001373 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001374 ClassRedefinition& redef = data.GetRedefinition();
1375 if (data.GetSourceClassLoader() != nullptr) {
1376 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001377 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001378 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001379 // TODO Rewrite so we don't do a stack walk for each and every class.
1380 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001381 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001382 }
Alex Light1e3926a2017-04-07 10:38:06 -07001383 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001384 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1385 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1386 // methods that have been jitted prior to the current redefinition being applied might continue
1387 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001388 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1389 // owns the DexFile and when ownership is transferred.
1390 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001391 return OK;
1392}
1393
Alex Light0e692732017-01-10 15:00:05 -08001394void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Alex Light0e692732017-01-10 15:00:05 -08001395 const art::DexFile::ClassDef& class_def) {
1396 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001397 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001398 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001399 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001400 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07001401 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Alex Lighta01de592016-11-15 10:43:06 -08001402 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1403 art::dex::TypeIndex method_return_idx =
1404 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1405 const auto* old_type_list = method.GetParameterTypeList();
1406 std::vector<art::dex::TypeIndex> new_type_list;
1407 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1408 new_type_list.push_back(
1409 dex_file_->GetIndexForTypeId(
1410 *dex_file_->FindTypeId(
1411 old_dex_file.GetTypeDescriptor(
1412 old_dex_file.GetTypeId(
1413 old_type_list->GetTypeItem(i).type_idx_)))));
1414 }
1415 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1416 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001417 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001418 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1419 *new_name_id,
1420 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001421 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001422 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1423 method.SetDexMethodIndex(dex_method_idx);
1424 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001425 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Light7532d582017-02-13 16:36:06 -08001426 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01001427 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08001428 }
Alex Light200b9d72016-12-15 11:34:13 -08001429}
1430
Alex Light0e692732017-01-10 15:00:05 -08001431void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001432 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1433 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1434 for (art::ArtField& field : fields_iter) {
1435 std::string declaring_class_name;
1436 const art::DexFile::TypeId* new_declaring_id =
1437 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1438 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1439 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001440 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1441 const art::DexFile::FieldId* new_field_id =
1442 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1443 CHECK(new_field_id != nullptr);
1444 // We only need to update the index since the other data in the ArtField cannot be updated.
1445 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1446 }
1447 }
Alex Light200b9d72016-12-15 11:34:13 -08001448}
1449
1450// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001451void Redefiner::ClassRedefinition::UpdateClass(
1452 art::ObjPtr<art::mirror::Class> mclass,
1453 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001454 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001455 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1456 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001457 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001458 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001459
Alex Lighta01de592016-11-15 10:43:06 -08001460 // Update the class fields.
1461 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1462 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1463 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001464 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001465 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001466 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1467 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001468 ext->SetOriginalDexFile(original_dex_file);
Alex Light18e14b52018-03-05 17:48:48 -08001469
1470 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1471 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1472 // meta-data.
1473 art::jit::Jit* jit = driver_->runtime_->GetJit();
1474 if (jit != nullptr) {
1475 art::PointerSize image_pointer_size =
1476 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1477 auto code_cache = jit->GetCodeCache();
1478 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1479 // the jit about them.
1480 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1481 if (method.IsInvokable()) {
1482 code_cache->NotifyMethodRedefined(&method);
1483 }
1484 }
1485 }
Alex Lighta01de592016-11-15 10:43:06 -08001486}
1487
Alex Light1e3926a2017-04-07 10:38:06 -07001488// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1489// obsolete methods).
1490void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1491 const RedefinitionDataIter* cur_data) {
1492 art::mirror::Class* klass = GetMirrorClass();
1493 art::mirror::ClassExt* ext = klass->GetExtData();
1494 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001495 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1496 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001497 int32_t expected_length =
1498 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1499 // Check to make sure we are only undoing this one.
1500 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001501 for (int32_t i = 0; i < expected_length; i++) {
1502 art::ArtMethod* expected = nullptr;
1503 if (i < old_length) {
1504 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1505 }
1506 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001507 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1508 // obsolete methods array.
1509 return;
1510 }
1511 }
1512 // No new obsolete methods! We can get rid of the maps.
1513 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1514 }
1515}
1516
Alex Lighta01de592016-11-15 10:43:06 -08001517// This function does all (java) allocations we need to do for the Class being redefined.
1518// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001519bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1520 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001521 art::StackHandleScope<2> hs(driver_->self_);
1522 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1523 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001524 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001525 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1526 return false;
1527 }
1528 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001529 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001530 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001531 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001532 driver_->self_->AssertPendingOOMException();
1533 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001534 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1535 return false;
1536 }
Alex Light1e3926a2017-04-07 10:38:06 -07001537 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1538 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001539 // are only modified when all threads (other than the modifying one) are suspended we don't need
1540 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1541 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001542 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1543 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1544 if (!ext->ExtendObsoleteArrays(
1545 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1546 // OOM. Clear exception and return error.
1547 driver_->self_->AssertPendingOOMException();
1548 driver_->self_->ClearException();
1549 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1550 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001551 }
1552 return true;
1553}
1554
1555} // namespace openjdkjvmti