blob: 5422f486649c96ae99446877031c76728cf5be69 [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 Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Andreas Gampea1d2f952017-04-20 22:53:58 -070038#include "art_field-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080039#include "art_method-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "art_jvmti.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010041#include "base/array_ref.h"
Alex Lighta01de592016-11-15 10:43:06 -080042#include "base/logging.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080043#include "class_linker-inl.h"
Alex Light5643caf2017-02-08 11:39:07 -080044#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000045#include "dex_file.h"
46#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "events-inl.h"
48#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080049#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080050#include "instrumentation.h"
Alex Light07f06212017-06-01 14:01:43 -070051#include "intern_table.h"
Alex Light5643caf2017-02-08 11:39:07 -080052#include "jdwp/jdwp.h"
53#include "jdwp/jdwp_constants.h"
54#include "jdwp/jdwp_event.h"
55#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080056#include "jit/jit.h"
57#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080058#include "jni_env_ext-inl.h"
59#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080060#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080061#include "mirror/class_ext.h"
62#include "mirror/object.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080063#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080064#include "object_lock.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080067#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080068#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080069#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070070#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080071
72namespace openjdkjvmti {
73
Andreas Gampe46ee31b2016-12-14 10:11:49 -080074using android::base::StringPrintf;
75
Alex Lighteee0bd42017-02-14 15:31:45 +000076// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
77// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
78// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
79class ObsoleteMap {
80 public:
81 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
82 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
83 auto method_pair = id_map_.find(original);
84 if (method_pair != id_map_.end()) {
85 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
86 method_pair->second, art::kRuntimePointerSize);
87 DCHECK(res != nullptr);
88 DCHECK_EQ(original, res->GetNonObsoleteMethod());
89 return res;
90 } else {
91 return nullptr;
92 }
93 }
94
95 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
96 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
97 DCHECK(original != nullptr);
98 DCHECK(obsolete != nullptr);
99 int32_t slot = next_free_slot_++;
100 DCHECK_LT(slot, obsolete_methods_->GetLength());
101 DCHECK(nullptr ==
102 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
103 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
104 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
105 obsolete_dex_caches_->Set(slot, original_dex_cache_);
106 id_map_.insert({original, slot});
107 }
108
109 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
110 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
111 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
112 : next_free_slot_(0),
113 obsolete_methods_(obsolete_methods),
114 obsolete_dex_caches_(obsolete_dex_caches),
115 original_dex_cache_(original_dex_cache) {
116 // Figure out where the first unused slot in the obsolete_methods_ array is.
117 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
118 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
119 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
120 next_free_slot_++;
121 }
122 // Sanity check that the same slot in obsolete_dex_caches_ is free.
123 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
124 }
125
126 private:
127 int32_t next_free_slot_;
128 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
129 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
130 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
131 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
132 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
133 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
134};
135
Alex Lightdba61482016-12-21 08:20:29 -0800136// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
137// some basic sanity checks that the obsolete method is sane.
138class ObsoleteMethodStackVisitor : public art::StackVisitor {
139 protected:
140 ObsoleteMethodStackVisitor(
141 art::Thread* thread,
142 art::LinearAlloc* allocator,
143 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000144 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800145 : StackVisitor(thread,
146 /*context*/nullptr,
147 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
148 allocator_(allocator),
149 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800150 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800151
152 ~ObsoleteMethodStackVisitor() OVERRIDE {}
153
154 public:
155 // Returns true if we successfully installed obsolete methods on this thread, filling
156 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
157 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800158 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800159 art::Thread* thread,
160 art::LinearAlloc* allocator,
161 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000162 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800163 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800164 ObsoleteMethodStackVisitor visitor(thread,
165 allocator,
166 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800167 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800168 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800169 }
170
171 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000172 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800173 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800174 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800175 // We cannot ensure that the right dex file is used in inlined frames so we don't support
176 // redefining them.
177 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000178 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
179 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800180 // Create a new Obsolete Method and put it in the list.
181 art::Runtime* runtime = art::Runtime::Current();
182 art::ClassLinker* cl = runtime->GetClassLinker();
183 auto ptr_size = cl->GetImagePointerSize();
184 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800185 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800186 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
187 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800188 new_obsolete_method = new (method_storage) art::ArtMethod();
189 new_obsolete_method->CopyFrom(old_method, ptr_size);
190 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
191 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800192 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700193 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000194 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800195 // Update JIT Data structures to point to the new method.
196 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
197 if (jit != nullptr) {
198 // Notify the JIT we are making this obsolete method. It will update the jit's internal
199 // structures to keep track of the new obsolete method.
200 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
201 }
Alex Lightdba61482016-12-21 08:20:29 -0800202 }
203 DCHECK(new_obsolete_method != nullptr);
204 SetMethod(new_obsolete_method);
205 }
206 return true;
207 }
208
209 private:
210 // The linear allocator we should use to make new methods.
211 art::LinearAlloc* allocator_;
212 // The set of all methods which could be obsoleted.
213 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
214 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000215 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
216 // the redefined classes ClassExt as it is filled.
217 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800218};
219
Alex Lighte4a88632017-01-10 07:41:24 -0800220jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
221 jclass klass,
222 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800223 art::Thread* self = art::Thread::Current();
224 art::ScopedObjectAccess soa(self);
225 art::StackHandleScope<1> hs(self);
226 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
227 if (obj.IsNull()) {
228 return ERR(INVALID_CLASS);
229 }
230 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
231 std::string err_unused;
232 *is_redefinable =
233 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
234 return OK;
235}
236
237jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
238 /*out*/std::string* error_msg) {
239 if (klass->IsPrimitive()) {
240 *error_msg = "Modification of primitive classes is not supported";
241 return ERR(UNMODIFIABLE_CLASS);
242 } else if (klass->IsInterface()) {
243 *error_msg = "Modification of Interface classes is currently not supported";
244 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800245 } else if (klass->IsStringClass()) {
246 *error_msg = "Modification of String class is not supported";
247 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800248 } else if (klass->IsArrayClass()) {
249 *error_msg = "Modification of Array classes is not supported";
250 return ERR(UNMODIFIABLE_CLASS);
251 } else if (klass->IsProxyClass()) {
252 *error_msg = "Modification of proxy classes is not supported";
253 return ERR(UNMODIFIABLE_CLASS);
254 }
255
Alex Lighte77b48b2017-02-22 11:08:06 -0800256 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
257 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
258 *error_msg = "Class might have stack frames that cannot be made obsolete";
259 return ERR(UNMODIFIABLE_CLASS);
260 }
261 }
262
Alex Lighte4a88632017-01-10 07:41:24 -0800263 return OK;
264}
265
Alex Lighta01de592016-11-15 10:43:06 -0800266// Moves dex data to an anonymous, read-only mmap'd region.
267std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100268 art::ArrayRef<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800269 std::string* error_msg) {
270 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800271 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800272 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700273 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800274 PROT_READ|PROT_WRITE,
275 /*low_4gb*/false,
276 /*reuse*/false,
277 error_msg));
278 if (map == nullptr) {
279 return map;
280 }
Vladimir Markoe1993c72017-06-14 17:01:38 +0100281 memcpy(map->Begin(), data.data(), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800282 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
283 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800284 map->Protect(PROT_READ);
285 return map;
286}
287
Alex Lighta7e38d82017-01-19 14:57:28 -0800288Redefiner::ClassRedefinition::ClassRedefinition(
289 Redefiner* driver,
290 jclass klass,
291 const art::DexFile* redefined_dex_file,
292 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100293 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800294 driver_(driver),
295 klass_(klass),
296 dex_file_(redefined_dex_file),
297 class_sig_(class_sig),
298 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800299 GetMirrorClass()->MonitorEnter(driver_->self_);
300}
301
302Redefiner::ClassRedefinition::~ClassRedefinition() {
303 if (driver_ != nullptr) {
304 GetMirrorClass()->MonitorExit(driver_->self_);
305 }
306}
307
Alex Light0e692732017-01-10 15:00:05 -0800308jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800309 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800310 art::Runtime* runtime,
311 art::Thread* self,
312 jint class_count,
313 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800314 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800315 if (env == nullptr) {
316 *error_msg = "env was null!";
317 return ERR(INVALID_ENVIRONMENT);
318 } else if (class_count < 0) {
319 *error_msg = "class_count was less then 0";
320 return ERR(ILLEGAL_ARGUMENT);
321 } else if (class_count == 0) {
322 // We don't actually need to do anything. Just return OK.
323 return OK;
324 } else if (definitions == nullptr) {
325 *error_msg = "null definitions!";
326 return ERR(NULL_POINTER);
327 }
Alex Light6ac57502017-01-19 15:05:06 -0800328 std::vector<ArtClassDefinition> def_vector;
329 def_vector.reserve(class_count);
330 for (jint i = 0; i < class_count; i++) {
Alex Lightce6ee702017-03-06 15:46:43 -0800331 jboolean is_modifiable = JNI_FALSE;
332 jvmtiError res = env->IsModifiableClass(definitions[i].klass, &is_modifiable);
333 if (res != OK) {
334 return res;
335 } else if (!is_modifiable) {
336 return ERR(UNMODIFIABLE_CLASS);
337 }
Alex Light6ac57502017-01-19 15:05:06 -0800338 // We make a copy of the class_bytes to pass into the retransformation.
339 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
340 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
341 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800342 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800343 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800344 if (res != OK) {
345 return res;
346 }
347 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
348
349 ArtClassDefinition def;
Alex Lightb7354d52017-03-30 15:17:01 -0700350 res = def.Init(env, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800351 if (res != OK) {
352 return res;
353 }
354 def_vector.push_back(std::move(def));
355 }
356 // Call all the transformation events.
357 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800358 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800359 self,
360 &def_vector);
361 if (res != OK) {
362 // Something went wrong with transformation!
363 return res;
364 }
365 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
366}
367
368jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
369 art::Runtime* runtime,
370 art::Thread* self,
371 const std::vector<ArtClassDefinition>& definitions,
372 std::string* error_msg) {
373 DCHECK(env != nullptr);
374 if (definitions.size() == 0) {
375 // We don't actually need to do anything. Just return OK.
376 return OK;
377 }
Alex Light0e692732017-01-10 15:00:05 -0800378 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
379 // are going to redefine.
380 art::jit::ScopedJitSuspend suspend_jit;
381 // Get shared mutator lock so we can lock all the classes.
382 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800383 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800384 for (const ArtClassDefinition& def : definitions) {
385 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700386 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800387 jvmtiError res = r.AddRedefinition(env, def);
388 if (res != OK) {
389 return res;
390 }
Alex Light0e692732017-01-10 15:00:05 -0800391 }
392 }
393 return r.Run();
394}
395
Alex Light6ac57502017-01-19 15:05:06 -0800396jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800397 std::string original_dex_location;
398 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700399 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800400 *error_msg_ = "Unable to get original dex file location!";
401 return ret;
402 }
Alex Light52a2db52017-01-19 23:00:21 +0000403 char* generic_ptr_unused = nullptr;
404 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700405 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800406 *error_msg_ = "Unable to get class signature!";
407 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000408 }
Andreas Gampe54711412017-02-21 12:41:43 -0800409 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
410 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800411 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700412 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800413 error_msg_));
414 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800415 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700416 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800417 << "in dex file " << original_dex_location << " because: " << *error_msg_;
418 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800419 return ERR(OUT_OF_MEMORY);
420 }
421 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800422 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800423 return ERR(INVALID_CLASS_FORMAT);
424 }
425 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
426 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
427 checksum,
428 std::move(map),
429 /*verify*/true,
430 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800431 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800432 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700433 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800434 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800435 return ERR(INVALID_CLASS_FORMAT);
436 }
Alex Light0e692732017-01-10 15:00:05 -0800437 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800438 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700439 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800440 dex_file.release(),
441 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700442 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800443 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800444}
445
Alex Light0e692732017-01-10 15:00:05 -0800446art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
447 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800448}
449
Alex Light0e692732017-01-10 15:00:05 -0800450art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800451 return GetMirrorClass()->GetClassLoader();
452}
453
Alex Light0e692732017-01-10 15:00:05 -0800454art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
455 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700456 art::StackHandleScope<2> hs(driver_->self_);
457 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
458 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
459 art::ObjPtr<art::mirror::DexCache>::DownCast(
460 cl->GetClassRoot(art::ClassLinker::kJavaLangDexCache)->AllocObject(driver_->self_))));
461 if (cache.IsNull()) {
462 driver_->self_->AssertPendingOOMException();
463 return nullptr;
464 }
465 art::Handle<art::mirror::String> location(hs.NewHandle(
466 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
467 if (location.IsNull()) {
468 driver_->self_->AssertPendingOOMException();
469 return nullptr;
470 }
471 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
472 art::mirror::DexCache::InitializeDexCache(driver_->self_,
473 cache.Get(),
474 location.Get(),
475 dex_file_.get(),
476 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
477 : loader->GetAllocator(),
478 art::kRuntimePointerSize);
479 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800480}
481
Alex Light0e692732017-01-10 15:00:05 -0800482void Redefiner::RecordFailure(jvmtiError result,
483 const std::string& class_sig,
484 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800485 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800486 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800487 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800488 result_ = result;
489}
490
Alex Light2f814aa2017-03-24 15:21:34 +0000491art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800492 // If we have been specifically given a new set of bytes use that
493 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800494 return art::mirror::ByteArray::AllocateAndFill(
495 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100496 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Alex Light440b5d92017-01-24 15:32:25 -0800497 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800498 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800499
500 // See if we already have one set.
501 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
502 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000503 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
504 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800505 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000506 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800507 }
Alex Lighta01de592016-11-15 10:43:06 -0800508 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800509
Alex Light2f814aa2017-03-24 15:21:34 +0000510 // return the current dex_cache which has the dex file in it.
511 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800512 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000513 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800514 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
515 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800516 }
Alex Light2f814aa2017-03-24 15:21:34 +0000517 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800518}
519
Alex Lightdba61482016-12-21 08:20:29 -0800520struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000521 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800522 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800523 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800524
Alex Lighteee0bd42017-02-14 15:31:45 +0000525 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
526 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800527};
528
Alex Lightdba61482016-12-21 08:20:29 -0800529void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
530 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800531 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
532 data->allocator,
533 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000534 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800535}
536
537// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
538// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800539// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
540void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800541 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
542 art::mirror::ClassExt* ext = art_klass->GetExtData();
543 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800544 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000545 // This holds pointers to the obsolete methods map fields which are updated as needed.
546 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
547 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800548 // Add all the declared methods to the map
549 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800550 if (m.IsIntrinsic()) {
551 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
552 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
553 << "methods that have already been compiled.";
554 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000555 // It is possible to simply filter out some methods where they cannot really become obsolete,
556 // such as native methods and keep their original (possibly optimized) implementations. We don't
557 // do this, however, since we would need to mark these functions (still in the classes
558 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
559 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
560 // error checking from the interpreter which ensure we don't try to start executing obsolete
561 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000562 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800563 }
564 {
Alex Light0e692732017-01-10 15:00:05 -0800565 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800566 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
567 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800568 }
Alex Lightdba61482016-12-21 08:20:29 -0800569}
570
Alex Light6161f132017-01-25 10:30:20 -0800571// Try and get the declared method. First try to get a virtual method then a direct method if that's
572// not found.
573static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
574 const char* name,
575 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
576 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
577 if (m == nullptr) {
578 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
579 }
580 return m;
581}
582
583bool Redefiner::ClassRedefinition::CheckSameMethods() {
584 art::StackHandleScope<1> hs(driver_->self_);
585 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
586 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
587
588 art::ClassDataItemIterator new_iter(*dex_file_,
589 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
590
591 // Make sure we have the same number of methods.
592 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
593 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
594 if (num_new_method != num_old_method) {
595 bool bigger = num_new_method > num_old_method;
596 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
597 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
598 StringPrintf("Total number of declared methods changed from %d to %d",
599 num_old_method, num_new_method));
600 return false;
601 }
602
603 // Skip all of the fields. We should have already checked this.
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700604 new_iter.SkipAllFields();
Alex Light6161f132017-01-25 10:30:20 -0800605 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
606 // files have the same number of methods, which means there must be an equal amount of additions
607 // and removals.
608 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
609 // Get the data on the method we are searching for
610 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
611 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
612 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
613 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
614 // If we got past the check for the same number of methods above that means there must be at
615 // least one added and one removed method. We will return the ADDED failure message since it is
616 // easier to get a useful error report for it.
617 if (old_method == nullptr) {
618 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
619 StringPrintf("Unknown method '%s' (sig: %s) was added!",
620 new_method_name,
621 new_method_signature.ToString().c_str()));
622 return false;
623 }
624 // Since direct methods have different flags than virtual ones (specifically direct methods must
625 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
626 // virtual to direct.
Mathieu Chartierf044c222017-05-31 15:27:54 -0700627 uint32_t new_flags = new_iter.GetMethodAccessFlags() & ~art::kAccPreviouslyWarm;
628 if (new_flags != (old_method->GetAccessFlags() & (art::kAccValidMethodFlags ^ art::kAccPreviouslyWarm))) {
Alex Light6161f132017-01-25 10:30:20 -0800629 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
630 StringPrintf("method '%s' (sig: %s) had different access flags",
631 new_method_name,
632 new_method_signature.ToString().c_str()));
633 return false;
634 }
635 }
636 return true;
637}
638
639bool Redefiner::ClassRedefinition::CheckSameFields() {
640 art::StackHandleScope<1> hs(driver_->self_);
641 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
642 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
643 art::ClassDataItemIterator new_iter(*dex_file_,
644 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
645 const art::DexFile& old_dex_file = h_klass->GetDexFile();
646 art::ClassDataItemIterator old_iter(old_dex_file,
647 old_dex_file.GetClassData(*h_klass->GetClassDef()));
648 // Instance and static fields can be differentiated by their flags so no need to check them
649 // separately.
650 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
651 // Get the data on the method we are searching for
652 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
653 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
654 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
655
656 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
657 // We are missing the old version of this method!
658 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
659 StringPrintf("Unknown field '%s' (type: %s) added!",
660 new_field_name,
661 new_field_type));
662 return false;
663 }
664
665 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
666 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
667 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
668
669 // Check name and type.
670 if (strcmp(old_field_name, new_field_name) != 0 ||
671 strcmp(old_field_type, new_field_type) != 0) {
672 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
673 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
674 old_field_name,
675 old_field_type,
676 new_field_name,
677 new_field_type));
678 return false;
679 }
680
681 // Since static fields have different flags than instance ones (specifically static fields must
682 // have the kAccStatic flag) we can tell if a field changes from static to instance.
683 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
684 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
685 StringPrintf("Field '%s' (sig: %s) had different access flags",
686 new_field_name,
687 new_field_type));
688 return false;
689 }
690
691 new_iter.Next();
692 old_iter.Next();
693 }
694 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
695 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
696 StringPrintf("field '%s' (sig: %s) is missing!",
697 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
698 old_iter.GetMemberIndex())),
699 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
700 old_iter.GetMemberIndex()))));
701 return false;
702 }
703 return true;
704}
705
Alex Light0e692732017-01-10 15:00:05 -0800706bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800707 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000708 // Easy check that only 1 class def is present.
709 if (dex_file_->NumClassDefs() != 1) {
710 RecordFailure(ERR(ILLEGAL_ARGUMENT),
711 StringPrintf("Expected 1 class def in dex file but found %d",
712 dex_file_->NumClassDefs()));
713 return false;
714 }
715 // Get the ClassDef from the new DexFile.
716 // Since the dex file has only a single class def the index is always 0.
717 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
718 // Get the class as it is now.
719 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
720
721 // Check the access flags didn't change.
722 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
723 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
724 "Cannot change modifiers of class by redefinition");
725 return false;
726 }
727
728 // Check class name.
729 // These should have been checked by the dexfile verifier on load.
730 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
731 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
732 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
733 if (!current_class->DescriptorEquals(descriptor)) {
734 std::string storage;
735 RecordFailure(ERR(NAMES_DONT_MATCH),
736 StringPrintf("expected file to contain class called '%s' but found '%s'!",
737 current_class->GetDescriptor(&storage),
738 descriptor));
739 return false;
740 }
741 if (current_class->IsObjectClass()) {
742 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
743 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
744 return false;
745 }
746 } else {
747 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
748 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
749 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
750 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
751 return false;
752 }
753 }
754 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
755 if (interfaces == nullptr) {
756 if (current_class->NumDirectInterfaces() != 0) {
757 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
758 return false;
759 }
760 } else {
761 DCHECK(!current_class->IsProxyClass());
762 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
763 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
764 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
765 return false;
766 }
767 // The order of interfaces is (barely) meaningful so we error if it changes.
768 const art::DexFile& orig_dex_file = current_class->GetDexFile();
769 for (uint32_t i = 0; i < interfaces->Size(); i++) {
770 if (strcmp(
771 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
772 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
773 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
774 "Interfaces changed or re-ordered");
775 return false;
776 }
777 }
778 }
Alex Light460d1b42017-01-10 15:37:17 +0000779 return true;
780}
781
Alex Light0e692732017-01-10 15:00:05 -0800782bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800783 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800784 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000785
Alex Lighte4a88632017-01-10 07:41:24 -0800786 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
787 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
788 if (res != OK) {
789 RecordFailure(res, err);
790 return false;
791 } else {
792 return true;
793 }
Alex Light460d1b42017-01-10 15:37:17 +0000794}
795
Alex Light0e692732017-01-10 15:00:05 -0800796bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000797 return CheckRedefinable() &&
798 CheckClass() &&
799 CheckSameFields() &&
800 CheckSameMethods();
801}
802
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800803class RedefinitionDataIter;
804
Alex Light0e692732017-01-10 15:00:05 -0800805// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
806// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
807// having to deal with the fact that we need to hold an arbitrary number of references live.
808class RedefinitionDataHolder {
809 public:
810 enum DataSlot : int32_t {
811 kSlotSourceClassLoader = 0,
812 kSlotJavaDexFile = 1,
813 kSlotNewDexFileCookie = 2,
814 kSlotNewDexCache = 3,
815 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800816 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700817 kSlotOldObsoleteMethods = 6,
818 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800819
820 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700821 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800822 };
823
824 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
825 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
826 // the passed in handle-scope.
827 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
828 art::Runtime* runtime,
829 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800830 std::vector<Redefiner::ClassRedefinition>* redefinitions)
831 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800832 arr_(
833 hs->NewHandle(
834 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
835 self,
836 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800837 redefinitions->size() * kNumSlots))),
838 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800839
840 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
841 return arr_.IsNull();
842 }
843
Alex Light8c889d22017-02-06 13:58:27 -0800844 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800845 REQUIRES_SHARED(art::Locks::mutator_lock_) {
846 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
847 }
Alex Light8c889d22017-02-06 13:58:27 -0800848 art::mirror::Object* GetJavaDexFile(jint klass_index) const
849 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800850 return GetSlot(klass_index, kSlotJavaDexFile);
851 }
Alex Light8c889d22017-02-06 13:58:27 -0800852 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800853 REQUIRES_SHARED(art::Locks::mutator_lock_) {
854 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
855 }
Alex Light8c889d22017-02-06 13:58:27 -0800856 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800857 REQUIRES_SHARED(art::Locks::mutator_lock_) {
858 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
859 }
Alex Light8c889d22017-02-06 13:58:27 -0800860 art::mirror::Class* GetMirrorClass(jint klass_index) const
861 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800862 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
863 }
864
Alex Light2f814aa2017-03-24 15:21:34 +0000865 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800866 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000867 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800868 }
869
Alex Light1e3926a2017-04-07 10:38:06 -0700870 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
871 REQUIRES_SHARED(art::Locks::mutator_lock_) {
872 return art::down_cast<art::mirror::PointerArray*>(
873 GetSlot(klass_index, kSlotOldObsoleteMethods));
874 }
875
876 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
877 REQUIRES_SHARED(art::Locks::mutator_lock_) {
878 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
879 GetSlot(klass_index, kSlotOldDexCaches));
880 }
881
Alex Light0e692732017-01-10 15:00:05 -0800882 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
883 REQUIRES_SHARED(art::Locks::mutator_lock_) {
884 SetSlot(klass_index, kSlotSourceClassLoader, loader);
885 }
886 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
887 REQUIRES_SHARED(art::Locks::mutator_lock_) {
888 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
889 }
890 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
891 REQUIRES_SHARED(art::Locks::mutator_lock_) {
892 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
893 }
894 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
895 REQUIRES_SHARED(art::Locks::mutator_lock_) {
896 SetSlot(klass_index, kSlotNewDexCache, cache);
897 }
898 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
899 REQUIRES_SHARED(art::Locks::mutator_lock_) {
900 SetSlot(klass_index, kSlotMirrorClass, klass);
901 }
Alex Light2f814aa2017-03-24 15:21:34 +0000902 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800903 REQUIRES_SHARED(art::Locks::mutator_lock_) {
904 SetSlot(klass_index, kSlotOrigDexFile, bytes);
905 }
Alex Light1e3926a2017-04-07 10:38:06 -0700906 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
907 REQUIRES_SHARED(art::Locks::mutator_lock_) {
908 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
909 }
910 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
911 REQUIRES_SHARED(art::Locks::mutator_lock_) {
912 SetSlot(klass_index, kSlotOldDexCaches, caches);
913 }
Alex Light0e692732017-01-10 15:00:05 -0800914
Alex Light8c889d22017-02-06 13:58:27 -0800915 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800916 return arr_->GetLength() / kNumSlots;
917 }
918
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800919 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
920 REQUIRES_SHARED(art::Locks::mutator_lock_) {
921 return redefinitions_;
922 }
923
924 bool operator==(const RedefinitionDataHolder& other) const
925 REQUIRES_SHARED(art::Locks::mutator_lock_) {
926 return arr_.Get() == other.arr_.Get();
927 }
928
929 bool operator!=(const RedefinitionDataHolder& other) const
930 REQUIRES_SHARED(art::Locks::mutator_lock_) {
931 return !(*this == other);
932 }
933
934 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
935 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
936
Alex Light0e692732017-01-10 15:00:05 -0800937 private:
Alex Light8c889d22017-02-06 13:58:27 -0800938 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800939 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800940
941 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800942 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800943 DCHECK_LT(klass_index, Length());
944 return arr_->Get((kNumSlots * klass_index) + slot);
945 }
946
947 void SetSlot(jint klass_index,
948 DataSlot slot,
949 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
950 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
951 DCHECK_LT(klass_index, Length());
952 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
953 }
954
955 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
956};
957
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800958class RedefinitionDataIter {
959 public:
960 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
961
962 RedefinitionDataIter(const RedefinitionDataIter&) = default;
963 RedefinitionDataIter(RedefinitionDataIter&&) = default;
964 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
965 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
966
967 bool operator==(const RedefinitionDataIter& other) const
968 REQUIRES_SHARED(art::Locks::mutator_lock_) {
969 return idx_ == other.idx_ && holder_ == other.holder_;
970 }
971
972 bool operator!=(const RedefinitionDataIter& other) const
973 REQUIRES_SHARED(art::Locks::mutator_lock_) {
974 return !(*this == other);
975 }
976
977 RedefinitionDataIter operator++() { // Value after modification.
978 idx_++;
979 return *this;
980 }
981
982 RedefinitionDataIter operator++(int) {
983 RedefinitionDataIter temp = *this;
984 idx_++;
985 return temp;
986 }
987
988 RedefinitionDataIter operator+(ssize_t delta) const {
989 RedefinitionDataIter temp = *this;
990 temp += delta;
991 return temp;
992 }
993
994 RedefinitionDataIter& operator+=(ssize_t delta) {
995 idx_ += delta;
996 return *this;
997 }
998
999 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1000 return (*holder_.GetRedefinitions())[idx_];
1001 }
1002
1003 RedefinitionDataHolder& GetHolder() {
1004 return holder_;
1005 }
1006
1007 art::mirror::ClassLoader* GetSourceClassLoader() const
1008 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1009 return holder_.GetSourceClassLoader(idx_);
1010 }
1011 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1012 return holder_.GetJavaDexFile(idx_);
1013 }
1014 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1015 return holder_.GetNewDexFileCookie(idx_);
1016 }
1017 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1018 return holder_.GetNewDexCache(idx_);
1019 }
1020 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1021 return holder_.GetMirrorClass(idx_);
1022 }
Alex Light2f814aa2017-03-24 15:21:34 +00001023 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001024 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001025 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001026 }
Alex Light1e3926a2017-04-07 10:38:06 -07001027 art::mirror::PointerArray* GetOldObsoleteMethods() const
1028 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1029 return holder_.GetOldObsoleteMethods(idx_);
1030 }
1031 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1032 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1033 return holder_.GetOldDexCaches(idx_);
1034 }
1035
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001036 int32_t GetIndex() const {
1037 return idx_;
1038 }
1039
1040 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1041 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1042 holder_.SetSourceClassLoader(idx_, loader);
1043 }
1044 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1045 holder_.SetJavaDexFile(idx_, dexfile);
1046 }
1047 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1048 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1049 holder_.SetNewDexFileCookie(idx_, cookie);
1050 }
1051 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1052 holder_.SetNewDexCache(idx_, cache);
1053 }
1054 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1055 holder_.SetMirrorClass(idx_, klass);
1056 }
Alex Light2f814aa2017-03-24 15:21:34 +00001057 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001058 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001059 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001060 }
Alex Light1e3926a2017-04-07 10:38:06 -07001061 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1062 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1063 holder_.SetOldObsoleteMethods(idx_, methods);
1064 }
1065 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1066 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1067 holder_.SetOldDexCaches(idx_, caches);
1068 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001069
1070 private:
1071 int32_t idx_;
1072 RedefinitionDataHolder& holder_;
1073};
1074
1075RedefinitionDataIter RedefinitionDataHolder::begin() {
1076 return RedefinitionDataIter(0, *this);
1077}
1078
1079RedefinitionDataIter RedefinitionDataHolder::end() {
1080 return RedefinitionDataIter(Length(), *this);
1081}
1082
1083bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001084 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1085 art::StackHandleScope<2> hs(driver_->self_);
1086 std::string error;
1087 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001088 art::verifier::FailureKind failure =
Alex Light8c889d22017-02-06 13:58:27 -08001089 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1090 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001091 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001092 hs.NewHandle(GetClassLoader()),
1093 dex_file_->GetClassDef(0), /*class_def*/
1094 nullptr, /*compiler_callbacks*/
1095 false, /*allow_soft_failures*/
1096 /*log_level*/
1097 art::verifier::HardFailLogMode::kLogWarning,
1098 &error);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001099 bool passes = failure == art::verifier::FailureKind::kNoFailure;
Alex Light8c889d22017-02-06 13:58:27 -08001100 if (!passes) {
1101 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1102 }
1103 return passes;
1104}
1105
Alex Light1babae02017-02-01 15:35:34 -08001106// Looks through the previously allocated cookies to see if we need to update them with another new
1107// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1108// once they are all added to the classloader.
1109bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001110 art::Handle<art::mirror::ClassLoader> source_class_loader,
1111 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001112 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001113 art::StackHandleScope<2> hs(driver_->self_);
1114 art::MutableHandle<art::mirror::LongArray> old_cookie(
1115 hs.NewHandle<art::mirror::LongArray>(nullptr));
1116 bool has_older_cookie = false;
1117 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001118 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1119 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001120 // Since every instance of this classloader should have the same cookie associated with it we
1121 // can stop looking here.
1122 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001123 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001124 break;
1125 }
1126 }
1127 if (old_cookie.IsNull()) {
1128 // No older cookie. Get it directly from the dex_file_obj
1129 // We should not have seen this classloader elsewhere.
1130 CHECK(!has_older_cookie);
1131 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1132 }
1133 // Use the old cookie to generate the new one with the new DexFile* added in.
1134 art::Handle<art::mirror::LongArray>
1135 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1136 old_cookie,
1137 dex_file_.get())));
1138 // Make sure the allocation worked.
1139 if (new_cookie.IsNull()) {
1140 return false;
1141 }
1142
1143 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001144 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001145 // If there are other copies of this same classloader we need to make sure that we all have the
1146 // same cookie.
1147 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001148 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001149 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001150 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1151 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001152 }
1153 }
1154 }
1155
1156 return true;
1157}
1158
Alex Lighta7e38d82017-01-19 14:57:28 -08001159bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001160 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001161 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001162 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001163 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001164 // This shouldn't allocate
1165 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001166 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1167 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001168 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001169 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1170 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001171 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001172 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001173 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1174 return false;
1175 }
Alex Light1babae02017-02-01 15:35:34 -08001176 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001177 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001178 driver_->self_->AssertPendingOOMException();
1179 driver_->self_->ClearException();
1180 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1181 return false;
1182 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001183 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001184 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1185 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001186 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001187 driver_->self_->ClearException();
1188 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1189 return false;
1190 }
1191
1192 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001193 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1194 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001195 driver_->self_->AssertPendingOOMException();
1196 driver_->self_->ClearException();
1197 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1198 return false;
1199 }
1200 return true;
1201}
1202
Alex Light5643caf2017-02-08 11:39:07 -08001203void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1204 DCHECK(art::Dbg::IsDebuggerActive());
1205 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1206 if (state != nullptr) {
1207 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1208 }
1209}
1210
1211void Redefiner::UnregisterAllBreakpoints() {
1212 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1213 return;
1214 }
1215 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1216 redef.UnregisterBreakpoints();
1217 }
1218}
1219
Alex Light0e692732017-01-10 15:00:05 -08001220bool Redefiner::CheckAllRedefinitionAreValid() {
1221 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1222 if (!redef.CheckRedefinitionIsValid()) {
1223 return false;
1224 }
1225 }
1226 return true;
1227}
1228
Alex Light1e3926a2017-04-07 10:38:06 -07001229void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1230 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1231 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1232 }
1233}
1234
1235bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1236 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1237 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001238 return false;
1239 }
1240 }
1241 return true;
1242}
1243
1244bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001245 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001246 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001247 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001248 return false;
1249 }
Alex Light0e692732017-01-10 15:00:05 -08001250 }
1251 return true;
1252}
1253
1254void Redefiner::ClassRedefinition::ReleaseDexFile() {
1255 dex_file_.release();
1256}
1257
1258void Redefiner::ReleaseAllDexFiles() {
1259 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1260 redef.ReleaseDexFile();
1261 }
1262}
1263
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001264bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1265 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1266 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001267 return false;
1268 }
Alex Light8c889d22017-02-06 13:58:27 -08001269 }
1270 return true;
1271}
1272
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001273class ScopedDisableConcurrentAndMovingGc {
1274 public:
1275 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1276 : heap_(heap), self_(self) {
1277 if (heap_->IsGcConcurrentAndMoving()) {
1278 heap_->IncrementDisableMovingGC(self_);
1279 }
1280 }
1281
1282 ~ScopedDisableConcurrentAndMovingGc() {
1283 if (heap_->IsGcConcurrentAndMoving()) {
1284 heap_->DecrementDisableMovingGC(self_);
1285 }
1286 }
1287 private:
1288 art::gc::Heap* heap_;
1289 art::Thread* self_;
1290};
1291
Alex Lighta01de592016-11-15 10:43:06 -08001292jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001293 art::StackHandleScope<1> hs(self_);
1294 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1295 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001296 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001297 if (holder.IsNull()) {
1298 self_->AssertPendingOOMException();
1299 self_->ClearException();
1300 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1301 return result_;
1302 }
1303
Alex Lighta01de592016-11-15 10:43:06 -08001304 // First we just allocate the ClassExt and its fields that we need. These can be updated
1305 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1306 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1307 // between allocating them and pausing all threads before we can update them so we need to do a
1308 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001309 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001310 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001311 !FinishAllRemainingAllocations(holder) ||
1312 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001313 return result_;
1314 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001315
Alex Light5643caf2017-02-08 11:39:07 -08001316 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001317 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001318 art::ClassLinker* cl = runtime_->GetClassLinker();
1319 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001320 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001321 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001322 }
Alex Light7916f202017-01-27 09:00:15 -08001323 }
Alex Light5643caf2017-02-08 11:39:07 -08001324 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001325
Alex Light6abd5392017-01-05 17:53:00 -08001326 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1327 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001328 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1329
Alex Lighta01de592016-11-15 10:43:06 -08001330 // Do transition to final suspension
1331 // TODO We might want to give this its own suspended state!
1332 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001333 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1334 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1335 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001336 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001337 ClassRedefinition& redef = data.GetRedefinition();
1338 if (data.GetSourceClassLoader() != nullptr) {
1339 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001340 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001341 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001342 // TODO Rewrite so we don't do a stack walk for each and every class.
1343 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001344 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001345 }
Alex Light1e3926a2017-04-07 10:38:06 -07001346 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001347 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1348 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1349 // methods that have been jitted prior to the current redefinition being applied might continue
1350 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001351 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1352 // owns the DexFile and when ownership is transferred.
1353 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001354 return OK;
1355}
1356
Alex Light0e692732017-01-10 15:00:05 -08001357void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1358 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1359 const art::DexFile::ClassDef& class_def) {
1360 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001361 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001362 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001363 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001364 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001365 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1366 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1367 art::dex::TypeIndex method_return_idx =
1368 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1369 const auto* old_type_list = method.GetParameterTypeList();
1370 std::vector<art::dex::TypeIndex> new_type_list;
1371 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1372 new_type_list.push_back(
1373 dex_file_->GetIndexForTypeId(
1374 *dex_file_->FindTypeId(
1375 old_dex_file.GetTypeDescriptor(
1376 old_dex_file.GetTypeId(
1377 old_type_list->GetTypeItem(i).type_idx_)))));
1378 }
1379 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1380 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001381 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001382 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1383 *new_name_id,
1384 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001385 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001386 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1387 method.SetDexMethodIndex(dex_method_idx);
1388 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001389 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001390 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001391 // Clear all the intrinsics related flags.
1392 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001393 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001394 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001395 if (jit != nullptr) {
1396 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1397 }
Alex Lighta01de592016-11-15 10:43:06 -08001398 }
Alex Light200b9d72016-12-15 11:34:13 -08001399}
1400
Alex Light0e692732017-01-10 15:00:05 -08001401void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001402 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1403 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1404 for (art::ArtField& field : fields_iter) {
1405 std::string declaring_class_name;
1406 const art::DexFile::TypeId* new_declaring_id =
1407 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1408 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1409 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001410 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1411 const art::DexFile::FieldId* new_field_id =
1412 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1413 CHECK(new_field_id != nullptr);
1414 // We only need to update the index since the other data in the ArtField cannot be updated.
1415 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1416 }
1417 }
Alex Light200b9d72016-12-15 11:34:13 -08001418}
1419
1420// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001421void Redefiner::ClassRedefinition::UpdateClass(
1422 art::ObjPtr<art::mirror::Class> mclass,
1423 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001424 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001425 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1426 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1427 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001428 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001429
Alex Lighta01de592016-11-15 10:43:06 -08001430 // Update the class fields.
1431 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1432 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1433 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001434 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001435 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001436 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1437 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001438 ext->SetOriginalDexFile(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001439}
1440
Alex Light1e3926a2017-04-07 10:38:06 -07001441// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1442// obsolete methods).
1443void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1444 const RedefinitionDataIter* cur_data) {
1445 art::mirror::Class* klass = GetMirrorClass();
1446 art::mirror::ClassExt* ext = klass->GetExtData();
1447 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001448 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1449 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001450 int32_t expected_length =
1451 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1452 // Check to make sure we are only undoing this one.
1453 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001454 for (int32_t i = 0; i < expected_length; i++) {
1455 art::ArtMethod* expected = nullptr;
1456 if (i < old_length) {
1457 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1458 }
1459 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001460 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1461 // obsolete methods array.
1462 return;
1463 }
1464 }
1465 // No new obsolete methods! We can get rid of the maps.
1466 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1467 }
1468}
1469
Alex Lighta01de592016-11-15 10:43:06 -08001470// This function does all (java) allocations we need to do for the Class being redefined.
1471// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001472bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1473 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001474 art::StackHandleScope<2> hs(driver_->self_);
1475 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1476 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001477 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001478 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1479 return false;
1480 }
1481 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001482 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001483 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001484 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001485 driver_->self_->AssertPendingOOMException();
1486 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001487 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1488 return false;
1489 }
Alex Light1e3926a2017-04-07 10:38:06 -07001490 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1491 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001492 // are only modified when all threads (other than the modifying one) are suspended we don't need
1493 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1494 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001495 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1496 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1497 if (!ext->ExtendObsoleteArrays(
1498 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1499 // OOM. Clear exception and return error.
1500 driver_->self_->AssertPendingOOMException();
1501 driver_->self_->ClearException();
1502 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1503 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001504 }
1505 return true;
1506}
1507
1508} // namespace openjdkjvmti