blob: debee913eeabfc10fae6c461738ef8781992e176 [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 Lighta26e3492017-06-27 17:55:37 -070067#include "ti_breakpoint.h"
Alex Lighteb98b082017-01-25 13:02:32 -080068#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080069#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080070#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070071#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080072
73namespace openjdkjvmti {
74
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075using android::base::StringPrintf;
76
Alex Lighteee0bd42017-02-14 15:31:45 +000077// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
78// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
79// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
80class ObsoleteMap {
81 public:
82 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
83 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
84 auto method_pair = id_map_.find(original);
85 if (method_pair != id_map_.end()) {
86 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
87 method_pair->second, art::kRuntimePointerSize);
88 DCHECK(res != nullptr);
89 DCHECK_EQ(original, res->GetNonObsoleteMethod());
90 return res;
91 } else {
92 return nullptr;
93 }
94 }
95
96 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
97 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
98 DCHECK(original != nullptr);
99 DCHECK(obsolete != nullptr);
100 int32_t slot = next_free_slot_++;
101 DCHECK_LT(slot, obsolete_methods_->GetLength());
102 DCHECK(nullptr ==
103 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
104 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
105 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
106 obsolete_dex_caches_->Set(slot, original_dex_cache_);
107 id_map_.insert({original, slot});
108 }
109
110 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
111 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
112 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
113 : next_free_slot_(0),
114 obsolete_methods_(obsolete_methods),
115 obsolete_dex_caches_(obsolete_dex_caches),
116 original_dex_cache_(original_dex_cache) {
117 // Figure out where the first unused slot in the obsolete_methods_ array is.
118 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
119 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
120 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
121 next_free_slot_++;
122 }
123 // Sanity check that the same slot in obsolete_dex_caches_ is free.
124 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
125 }
126
127 private:
128 int32_t next_free_slot_;
129 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
130 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
131 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
132 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
133 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
134 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
135};
136
Alex Lightdba61482016-12-21 08:20:29 -0800137// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
138// some basic sanity checks that the obsolete method is sane.
139class ObsoleteMethodStackVisitor : public art::StackVisitor {
140 protected:
141 ObsoleteMethodStackVisitor(
142 art::Thread* thread,
143 art::LinearAlloc* allocator,
144 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000145 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800146 : StackVisitor(thread,
147 /*context*/nullptr,
148 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
149 allocator_(allocator),
150 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800151 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800152
153 ~ObsoleteMethodStackVisitor() OVERRIDE {}
154
155 public:
156 // Returns true if we successfully installed obsolete methods on this thread, filling
157 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
158 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800159 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800160 art::Thread* thread,
161 art::LinearAlloc* allocator,
162 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000163 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800164 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800165 ObsoleteMethodStackVisitor visitor(thread,
166 allocator,
167 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800168 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800169 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800170 }
171
172 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000173 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800174 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800175 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800176 // We cannot ensure that the right dex file is used in inlined frames so we don't support
177 // redefining them.
178 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000179 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
180 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800181 // Create a new Obsolete Method and put it in the list.
182 art::Runtime* runtime = art::Runtime::Current();
183 art::ClassLinker* cl = runtime->GetClassLinker();
184 auto ptr_size = cl->GetImagePointerSize();
185 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800186 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800187 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
188 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800189 new_obsolete_method = new (method_storage) art::ArtMethod();
190 new_obsolete_method->CopyFrom(old_method, ptr_size);
191 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
192 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800193 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700194 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000195 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800196 // Update JIT Data structures to point to the new method.
197 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
198 if (jit != nullptr) {
199 // Notify the JIT we are making this obsolete method. It will update the jit's internal
200 // structures to keep track of the new obsolete method.
201 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
202 }
Alex Lightdba61482016-12-21 08:20:29 -0800203 }
204 DCHECK(new_obsolete_method != nullptr);
205 SetMethod(new_obsolete_method);
206 }
207 return true;
208 }
209
210 private:
211 // The linear allocator we should use to make new methods.
212 art::LinearAlloc* allocator_;
213 // The set of all methods which could be obsoleted.
214 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
215 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000216 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
217 // the redefined classes ClassExt as it is filled.
218 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800219};
220
Alex Lighte4a88632017-01-10 07:41:24 -0800221jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
222 jclass klass,
223 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800224 art::Thread* self = art::Thread::Current();
225 art::ScopedObjectAccess soa(self);
226 art::StackHandleScope<1> hs(self);
227 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
228 if (obj.IsNull()) {
229 return ERR(INVALID_CLASS);
230 }
231 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
232 std::string err_unused;
233 *is_redefinable =
234 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
235 return OK;
236}
237
238jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
239 /*out*/std::string* error_msg) {
240 if (klass->IsPrimitive()) {
241 *error_msg = "Modification of primitive classes is not supported";
242 return ERR(UNMODIFIABLE_CLASS);
243 } else if (klass->IsInterface()) {
244 *error_msg = "Modification of Interface classes is currently not supported";
245 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800246 } else if (klass->IsStringClass()) {
247 *error_msg = "Modification of String class is not supported";
248 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800249 } else if (klass->IsArrayClass()) {
250 *error_msg = "Modification of Array classes is not supported";
251 return ERR(UNMODIFIABLE_CLASS);
252 } else if (klass->IsProxyClass()) {
253 *error_msg = "Modification of proxy classes is not supported";
254 return ERR(UNMODIFIABLE_CLASS);
255 }
256
Alex Lighte77b48b2017-02-22 11:08:06 -0800257 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
258 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
259 *error_msg = "Class might have stack frames that cannot be made obsolete";
260 return ERR(UNMODIFIABLE_CLASS);
261 }
262 }
263
Alex Lighte4a88632017-01-10 07:41:24 -0800264 return OK;
265}
266
Alex Lighta01de592016-11-15 10:43:06 -0800267// Moves dex data to an anonymous, read-only mmap'd region.
268std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100269 art::ArrayRef<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800270 std::string* error_msg) {
271 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800272 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800273 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700274 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800275 PROT_READ|PROT_WRITE,
276 /*low_4gb*/false,
277 /*reuse*/false,
278 error_msg));
279 if (map == nullptr) {
280 return map;
281 }
Vladimir Markoe1993c72017-06-14 17:01:38 +0100282 memcpy(map->Begin(), data.data(), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800283 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
284 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800285 map->Protect(PROT_READ);
286 return map;
287}
288
Alex Lighta7e38d82017-01-19 14:57:28 -0800289Redefiner::ClassRedefinition::ClassRedefinition(
290 Redefiner* driver,
291 jclass klass,
292 const art::DexFile* redefined_dex_file,
293 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100294 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800295 driver_(driver),
296 klass_(klass),
297 dex_file_(redefined_dex_file),
298 class_sig_(class_sig),
299 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800300 GetMirrorClass()->MonitorEnter(driver_->self_);
301}
302
303Redefiner::ClassRedefinition::~ClassRedefinition() {
304 if (driver_ != nullptr) {
305 GetMirrorClass()->MonitorExit(driver_->self_);
306 }
307}
308
Alex Light0e692732017-01-10 15:00:05 -0800309jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800310 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800311 art::Runtime* runtime,
312 art::Thread* self,
313 jint class_count,
314 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800315 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800316 if (env == nullptr) {
317 *error_msg = "env was null!";
318 return ERR(INVALID_ENVIRONMENT);
319 } else if (class_count < 0) {
320 *error_msg = "class_count was less then 0";
321 return ERR(ILLEGAL_ARGUMENT);
322 } else if (class_count == 0) {
323 // We don't actually need to do anything. Just return OK.
324 return OK;
325 } else if (definitions == nullptr) {
326 *error_msg = "null definitions!";
327 return ERR(NULL_POINTER);
328 }
Alex Light6ac57502017-01-19 15:05:06 -0800329 std::vector<ArtClassDefinition> def_vector;
330 def_vector.reserve(class_count);
331 for (jint i = 0; i < class_count; i++) {
Alex Lightce6ee702017-03-06 15:46:43 -0800332 jboolean is_modifiable = JNI_FALSE;
333 jvmtiError res = env->IsModifiableClass(definitions[i].klass, &is_modifiable);
334 if (res != OK) {
335 return res;
336 } else if (!is_modifiable) {
337 return ERR(UNMODIFIABLE_CLASS);
338 }
Alex Light6ac57502017-01-19 15:05:06 -0800339 // We make a copy of the class_bytes to pass into the retransformation.
340 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
341 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
342 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800343 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800344 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800345 if (res != OK) {
346 return res;
347 }
348 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
349
350 ArtClassDefinition def;
Alex Lightb7354d52017-03-30 15:17:01 -0700351 res = def.Init(env, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800352 if (res != OK) {
353 return res;
354 }
355 def_vector.push_back(std::move(def));
356 }
357 // Call all the transformation events.
358 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800359 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800360 self,
361 &def_vector);
362 if (res != OK) {
363 // Something went wrong with transformation!
364 return res;
365 }
366 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
367}
368
369jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
370 art::Runtime* runtime,
371 art::Thread* self,
372 const std::vector<ArtClassDefinition>& definitions,
373 std::string* error_msg) {
374 DCHECK(env != nullptr);
375 if (definitions.size() == 0) {
376 // We don't actually need to do anything. Just return OK.
377 return OK;
378 }
Alex Light0e692732017-01-10 15:00:05 -0800379 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
380 // are going to redefine.
381 art::jit::ScopedJitSuspend suspend_jit;
382 // Get shared mutator lock so we can lock all the classes.
383 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700384 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800385 for (const ArtClassDefinition& def : definitions) {
386 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700387 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800388 jvmtiError res = r.AddRedefinition(env, def);
389 if (res != OK) {
390 return res;
391 }
Alex Light0e692732017-01-10 15:00:05 -0800392 }
393 }
394 return r.Run();
395}
396
Alex Light6ac57502017-01-19 15:05:06 -0800397jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800398 std::string original_dex_location;
399 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700400 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800401 *error_msg_ = "Unable to get original dex file location!";
402 return ret;
403 }
Alex Light52a2db52017-01-19 23:00:21 +0000404 char* generic_ptr_unused = nullptr;
405 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700406 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800407 *error_msg_ = "Unable to get class signature!";
408 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000409 }
Andreas Gampe54711412017-02-21 12:41:43 -0800410 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
411 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800412 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700413 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800414 error_msg_));
415 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800416 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700417 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800418 << "in dex file " << original_dex_location << " because: " << *error_msg_;
419 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800420 return ERR(OUT_OF_MEMORY);
421 }
422 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800423 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800424 return ERR(INVALID_CLASS_FORMAT);
425 }
426 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
427 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
428 checksum,
429 std::move(map),
430 /*verify*/true,
431 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800432 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800433 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700434 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800435 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800436 return ERR(INVALID_CLASS_FORMAT);
437 }
Alex Light0e692732017-01-10 15:00:05 -0800438 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800439 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700440 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800441 dex_file.release(),
442 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700443 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800444 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800445}
446
Alex Light0e692732017-01-10 15:00:05 -0800447art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
448 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800449}
450
Alex Light0e692732017-01-10 15:00:05 -0800451art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800452 return GetMirrorClass()->GetClassLoader();
453}
454
Alex Light0e692732017-01-10 15:00:05 -0800455art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
456 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700457 art::StackHandleScope<2> hs(driver_->self_);
458 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
459 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
460 art::ObjPtr<art::mirror::DexCache>::DownCast(
461 cl->GetClassRoot(art::ClassLinker::kJavaLangDexCache)->AllocObject(driver_->self_))));
462 if (cache.IsNull()) {
463 driver_->self_->AssertPendingOOMException();
464 return nullptr;
465 }
466 art::Handle<art::mirror::String> location(hs.NewHandle(
467 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
468 if (location.IsNull()) {
469 driver_->self_->AssertPendingOOMException();
470 return nullptr;
471 }
472 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
473 art::mirror::DexCache::InitializeDexCache(driver_->self_,
474 cache.Get(),
475 location.Get(),
476 dex_file_.get(),
477 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
478 : loader->GetAllocator(),
479 art::kRuntimePointerSize);
480 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800481}
482
Alex Light0e692732017-01-10 15:00:05 -0800483void Redefiner::RecordFailure(jvmtiError result,
484 const std::string& class_sig,
485 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800486 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800487 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800488 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800489 result_ = result;
490}
491
Alex Light2f814aa2017-03-24 15:21:34 +0000492art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800493 // If we have been specifically given a new set of bytes use that
494 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800495 return art::mirror::ByteArray::AllocateAndFill(
496 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100497 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Alex Light440b5d92017-01-24 15:32:25 -0800498 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800499 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800500
501 // See if we already have one set.
502 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
503 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000504 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
505 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800506 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000507 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800508 }
Alex Lighta01de592016-11-15 10:43:06 -0800509 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800510
Alex Light2f814aa2017-03-24 15:21:34 +0000511 // return the current dex_cache which has the dex file in it.
512 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800513 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000514 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800515 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
516 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800517 }
Alex Light2f814aa2017-03-24 15:21:34 +0000518 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800519}
520
Alex Lightdba61482016-12-21 08:20:29 -0800521struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000522 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800523 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800524 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800525
Alex Lighteee0bd42017-02-14 15:31:45 +0000526 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
527 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800528};
529
Alex Lightdba61482016-12-21 08:20:29 -0800530void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
531 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800532 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
533 data->allocator,
534 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000535 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800536}
537
538// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
539// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800540// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
541void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800542 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
543 art::mirror::ClassExt* ext = art_klass->GetExtData();
544 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800545 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000546 // This holds pointers to the obsolete methods map fields which are updated as needed.
547 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
548 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800549 // Add all the declared methods to the map
550 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800551 if (m.IsIntrinsic()) {
552 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
553 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
554 << "methods that have already been compiled.";
555 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000556 // It is possible to simply filter out some methods where they cannot really become obsolete,
557 // such as native methods and keep their original (possibly optimized) implementations. We don't
558 // do this, however, since we would need to mark these functions (still in the classes
559 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
560 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
561 // error checking from the interpreter which ensure we don't try to start executing obsolete
562 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000563 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800564 }
565 {
Alex Light0e692732017-01-10 15:00:05 -0800566 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800567 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
568 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800569 }
Alex Lightdba61482016-12-21 08:20:29 -0800570}
571
Alex Light6161f132017-01-25 10:30:20 -0800572// Try and get the declared method. First try to get a virtual method then a direct method if that's
573// not found.
574static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
575 const char* name,
576 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
577 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
578 if (m == nullptr) {
579 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
580 }
581 return m;
582}
583
584bool Redefiner::ClassRedefinition::CheckSameMethods() {
585 art::StackHandleScope<1> hs(driver_->self_);
586 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
587 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
588
589 art::ClassDataItemIterator new_iter(*dex_file_,
590 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
591
592 // Make sure we have the same number of methods.
593 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
594 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
595 if (num_new_method != num_old_method) {
596 bool bigger = num_new_method > num_old_method;
597 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
598 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
599 StringPrintf("Total number of declared methods changed from %d to %d",
600 num_old_method, num_new_method));
601 return false;
602 }
603
604 // Skip all of the fields. We should have already checked this.
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700605 new_iter.SkipAllFields();
Alex Light6161f132017-01-25 10:30:20 -0800606 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
607 // files have the same number of methods, which means there must be an equal amount of additions
608 // and removals.
609 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
610 // Get the data on the method we are searching for
611 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
612 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
613 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
614 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
615 // If we got past the check for the same number of methods above that means there must be at
616 // least one added and one removed method. We will return the ADDED failure message since it is
617 // easier to get a useful error report for it.
618 if (old_method == nullptr) {
619 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
620 StringPrintf("Unknown method '%s' (sig: %s) was added!",
621 new_method_name,
622 new_method_signature.ToString().c_str()));
623 return false;
624 }
625 // Since direct methods have different flags than virtual ones (specifically direct methods must
626 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
627 // virtual to direct.
Mathieu Chartierf044c222017-05-31 15:27:54 -0700628 uint32_t new_flags = new_iter.GetMethodAccessFlags() & ~art::kAccPreviouslyWarm;
629 if (new_flags != (old_method->GetAccessFlags() & (art::kAccValidMethodFlags ^ art::kAccPreviouslyWarm))) {
Alex Light6161f132017-01-25 10:30:20 -0800630 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
631 StringPrintf("method '%s' (sig: %s) had different access flags",
632 new_method_name,
633 new_method_signature.ToString().c_str()));
634 return false;
635 }
636 }
637 return true;
638}
639
640bool Redefiner::ClassRedefinition::CheckSameFields() {
641 art::StackHandleScope<1> hs(driver_->self_);
642 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
643 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
644 art::ClassDataItemIterator new_iter(*dex_file_,
645 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
646 const art::DexFile& old_dex_file = h_klass->GetDexFile();
647 art::ClassDataItemIterator old_iter(old_dex_file,
648 old_dex_file.GetClassData(*h_klass->GetClassDef()));
649 // Instance and static fields can be differentiated by their flags so no need to check them
650 // separately.
651 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
652 // Get the data on the method we are searching for
653 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
654 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
655 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
656
657 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
658 // We are missing the old version of this method!
659 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
660 StringPrintf("Unknown field '%s' (type: %s) added!",
661 new_field_name,
662 new_field_type));
663 return false;
664 }
665
666 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
667 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
668 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
669
670 // Check name and type.
671 if (strcmp(old_field_name, new_field_name) != 0 ||
672 strcmp(old_field_type, new_field_type) != 0) {
673 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
674 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
675 old_field_name,
676 old_field_type,
677 new_field_name,
678 new_field_type));
679 return false;
680 }
681
682 // Since static fields have different flags than instance ones (specifically static fields must
683 // have the kAccStatic flag) we can tell if a field changes from static to instance.
684 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
685 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
686 StringPrintf("Field '%s' (sig: %s) had different access flags",
687 new_field_name,
688 new_field_type));
689 return false;
690 }
691
692 new_iter.Next();
693 old_iter.Next();
694 }
695 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
696 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
697 StringPrintf("field '%s' (sig: %s) is missing!",
698 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
699 old_iter.GetMemberIndex())),
700 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
701 old_iter.GetMemberIndex()))));
702 return false;
703 }
704 return true;
705}
706
Alex Light0e692732017-01-10 15:00:05 -0800707bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800708 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000709 // Easy check that only 1 class def is present.
710 if (dex_file_->NumClassDefs() != 1) {
711 RecordFailure(ERR(ILLEGAL_ARGUMENT),
712 StringPrintf("Expected 1 class def in dex file but found %d",
713 dex_file_->NumClassDefs()));
714 return false;
715 }
716 // Get the ClassDef from the new DexFile.
717 // Since the dex file has only a single class def the index is always 0.
718 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
719 // Get the class as it is now.
720 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
721
722 // Check the access flags didn't change.
723 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
724 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
725 "Cannot change modifiers of class by redefinition");
726 return false;
727 }
728
729 // Check class name.
730 // These should have been checked by the dexfile verifier on load.
731 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
732 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
733 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
734 if (!current_class->DescriptorEquals(descriptor)) {
735 std::string storage;
736 RecordFailure(ERR(NAMES_DONT_MATCH),
737 StringPrintf("expected file to contain class called '%s' but found '%s'!",
738 current_class->GetDescriptor(&storage),
739 descriptor));
740 return false;
741 }
742 if (current_class->IsObjectClass()) {
743 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
744 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
745 return false;
746 }
747 } else {
748 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
749 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
750 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
751 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
752 return false;
753 }
754 }
755 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
756 if (interfaces == nullptr) {
757 if (current_class->NumDirectInterfaces() != 0) {
758 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
759 return false;
760 }
761 } else {
762 DCHECK(!current_class->IsProxyClass());
763 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
764 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
765 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
766 return false;
767 }
768 // The order of interfaces is (barely) meaningful so we error if it changes.
769 const art::DexFile& orig_dex_file = current_class->GetDexFile();
770 for (uint32_t i = 0; i < interfaces->Size(); i++) {
771 if (strcmp(
772 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
773 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
774 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
775 "Interfaces changed or re-ordered");
776 return false;
777 }
778 }
779 }
Alex Light460d1b42017-01-10 15:37:17 +0000780 return true;
781}
782
Alex Light0e692732017-01-10 15:00:05 -0800783bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800784 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800785 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000786
Alex Lighte4a88632017-01-10 07:41:24 -0800787 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
788 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
789 if (res != OK) {
790 RecordFailure(res, err);
791 return false;
792 } else {
793 return true;
794 }
Alex Light460d1b42017-01-10 15:37:17 +0000795}
796
Alex Light0e692732017-01-10 15:00:05 -0800797bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000798 return CheckRedefinable() &&
799 CheckClass() &&
800 CheckSameFields() &&
801 CheckSameMethods();
802}
803
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800804class RedefinitionDataIter;
805
Alex Light0e692732017-01-10 15:00:05 -0800806// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
807// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
808// having to deal with the fact that we need to hold an arbitrary number of references live.
809class RedefinitionDataHolder {
810 public:
811 enum DataSlot : int32_t {
812 kSlotSourceClassLoader = 0,
813 kSlotJavaDexFile = 1,
814 kSlotNewDexFileCookie = 2,
815 kSlotNewDexCache = 3,
816 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800817 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700818 kSlotOldObsoleteMethods = 6,
819 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800820
821 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700822 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800823 };
824
825 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
826 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
827 // the passed in handle-scope.
828 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
829 art::Runtime* runtime,
830 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800831 std::vector<Redefiner::ClassRedefinition>* redefinitions)
832 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800833 arr_(
834 hs->NewHandle(
835 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
836 self,
837 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800838 redefinitions->size() * kNumSlots))),
839 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800840
841 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
842 return arr_.IsNull();
843 }
844
Alex Light8c889d22017-02-06 13:58:27 -0800845 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800846 REQUIRES_SHARED(art::Locks::mutator_lock_) {
847 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
848 }
Alex Light8c889d22017-02-06 13:58:27 -0800849 art::mirror::Object* GetJavaDexFile(jint klass_index) const
850 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800851 return GetSlot(klass_index, kSlotJavaDexFile);
852 }
Alex Light8c889d22017-02-06 13:58:27 -0800853 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800854 REQUIRES_SHARED(art::Locks::mutator_lock_) {
855 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
856 }
Alex Light8c889d22017-02-06 13:58:27 -0800857 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800858 REQUIRES_SHARED(art::Locks::mutator_lock_) {
859 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
860 }
Alex Light8c889d22017-02-06 13:58:27 -0800861 art::mirror::Class* GetMirrorClass(jint klass_index) const
862 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800863 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
864 }
865
Alex Light2f814aa2017-03-24 15:21:34 +0000866 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800867 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000868 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800869 }
870
Alex Light1e3926a2017-04-07 10:38:06 -0700871 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
872 REQUIRES_SHARED(art::Locks::mutator_lock_) {
873 return art::down_cast<art::mirror::PointerArray*>(
874 GetSlot(klass_index, kSlotOldObsoleteMethods));
875 }
876
877 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
878 REQUIRES_SHARED(art::Locks::mutator_lock_) {
879 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
880 GetSlot(klass_index, kSlotOldDexCaches));
881 }
882
Alex Light0e692732017-01-10 15:00:05 -0800883 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
884 REQUIRES_SHARED(art::Locks::mutator_lock_) {
885 SetSlot(klass_index, kSlotSourceClassLoader, loader);
886 }
887 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
888 REQUIRES_SHARED(art::Locks::mutator_lock_) {
889 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
890 }
891 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
892 REQUIRES_SHARED(art::Locks::mutator_lock_) {
893 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
894 }
895 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
896 REQUIRES_SHARED(art::Locks::mutator_lock_) {
897 SetSlot(klass_index, kSlotNewDexCache, cache);
898 }
899 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
900 REQUIRES_SHARED(art::Locks::mutator_lock_) {
901 SetSlot(klass_index, kSlotMirrorClass, klass);
902 }
Alex Light2f814aa2017-03-24 15:21:34 +0000903 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800904 REQUIRES_SHARED(art::Locks::mutator_lock_) {
905 SetSlot(klass_index, kSlotOrigDexFile, bytes);
906 }
Alex Light1e3926a2017-04-07 10:38:06 -0700907 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
908 REQUIRES_SHARED(art::Locks::mutator_lock_) {
909 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
910 }
911 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
912 REQUIRES_SHARED(art::Locks::mutator_lock_) {
913 SetSlot(klass_index, kSlotOldDexCaches, caches);
914 }
Alex Light0e692732017-01-10 15:00:05 -0800915
Alex Light8c889d22017-02-06 13:58:27 -0800916 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800917 return arr_->GetLength() / kNumSlots;
918 }
919
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800920 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
921 REQUIRES_SHARED(art::Locks::mutator_lock_) {
922 return redefinitions_;
923 }
924
925 bool operator==(const RedefinitionDataHolder& other) const
926 REQUIRES_SHARED(art::Locks::mutator_lock_) {
927 return arr_.Get() == other.arr_.Get();
928 }
929
930 bool operator!=(const RedefinitionDataHolder& other) const
931 REQUIRES_SHARED(art::Locks::mutator_lock_) {
932 return !(*this == other);
933 }
934
935 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
936 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
937
Alex Light0e692732017-01-10 15:00:05 -0800938 private:
Alex Light8c889d22017-02-06 13:58:27 -0800939 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800940 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800941
942 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800943 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800944 DCHECK_LT(klass_index, Length());
945 return arr_->Get((kNumSlots * klass_index) + slot);
946 }
947
948 void SetSlot(jint klass_index,
949 DataSlot slot,
950 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
951 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
952 DCHECK_LT(klass_index, Length());
953 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
954 }
955
956 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
957};
958
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800959class RedefinitionDataIter {
960 public:
961 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
962
963 RedefinitionDataIter(const RedefinitionDataIter&) = default;
964 RedefinitionDataIter(RedefinitionDataIter&&) = default;
965 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
966 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
967
968 bool operator==(const RedefinitionDataIter& other) const
969 REQUIRES_SHARED(art::Locks::mutator_lock_) {
970 return idx_ == other.idx_ && holder_ == other.holder_;
971 }
972
973 bool operator!=(const RedefinitionDataIter& other) const
974 REQUIRES_SHARED(art::Locks::mutator_lock_) {
975 return !(*this == other);
976 }
977
978 RedefinitionDataIter operator++() { // Value after modification.
979 idx_++;
980 return *this;
981 }
982
983 RedefinitionDataIter operator++(int) {
984 RedefinitionDataIter temp = *this;
985 idx_++;
986 return temp;
987 }
988
989 RedefinitionDataIter operator+(ssize_t delta) const {
990 RedefinitionDataIter temp = *this;
991 temp += delta;
992 return temp;
993 }
994
995 RedefinitionDataIter& operator+=(ssize_t delta) {
996 idx_ += delta;
997 return *this;
998 }
999
1000 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1001 return (*holder_.GetRedefinitions())[idx_];
1002 }
1003
1004 RedefinitionDataHolder& GetHolder() {
1005 return holder_;
1006 }
1007
1008 art::mirror::ClassLoader* GetSourceClassLoader() const
1009 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1010 return holder_.GetSourceClassLoader(idx_);
1011 }
1012 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1013 return holder_.GetJavaDexFile(idx_);
1014 }
1015 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1016 return holder_.GetNewDexFileCookie(idx_);
1017 }
1018 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1019 return holder_.GetNewDexCache(idx_);
1020 }
1021 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1022 return holder_.GetMirrorClass(idx_);
1023 }
Alex Light2f814aa2017-03-24 15:21:34 +00001024 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001025 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001026 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001027 }
Alex Light1e3926a2017-04-07 10:38:06 -07001028 art::mirror::PointerArray* GetOldObsoleteMethods() const
1029 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1030 return holder_.GetOldObsoleteMethods(idx_);
1031 }
1032 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1033 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1034 return holder_.GetOldDexCaches(idx_);
1035 }
1036
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001037 int32_t GetIndex() const {
1038 return idx_;
1039 }
1040
1041 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1042 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1043 holder_.SetSourceClassLoader(idx_, loader);
1044 }
1045 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1046 holder_.SetJavaDexFile(idx_, dexfile);
1047 }
1048 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1049 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1050 holder_.SetNewDexFileCookie(idx_, cookie);
1051 }
1052 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1053 holder_.SetNewDexCache(idx_, cache);
1054 }
1055 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1056 holder_.SetMirrorClass(idx_, klass);
1057 }
Alex Light2f814aa2017-03-24 15:21:34 +00001058 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001059 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001060 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001061 }
Alex Light1e3926a2017-04-07 10:38:06 -07001062 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1063 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1064 holder_.SetOldObsoleteMethods(idx_, methods);
1065 }
1066 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1067 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1068 holder_.SetOldDexCaches(idx_, caches);
1069 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001070
1071 private:
1072 int32_t idx_;
1073 RedefinitionDataHolder& holder_;
1074};
1075
1076RedefinitionDataIter RedefinitionDataHolder::begin() {
1077 return RedefinitionDataIter(0, *this);
1078}
1079
1080RedefinitionDataIter RedefinitionDataHolder::end() {
1081 return RedefinitionDataIter(Length(), *this);
1082}
1083
1084bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001085 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1086 art::StackHandleScope<2> hs(driver_->self_);
1087 std::string error;
1088 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001089 art::verifier::FailureKind failure =
Alex Light8c889d22017-02-06 13:58:27 -08001090 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1091 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001092 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001093 hs.NewHandle(GetClassLoader()),
1094 dex_file_->GetClassDef(0), /*class_def*/
1095 nullptr, /*compiler_callbacks*/
1096 false, /*allow_soft_failures*/
1097 /*log_level*/
1098 art::verifier::HardFailLogMode::kLogWarning,
1099 &error);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001100 bool passes = failure == art::verifier::FailureKind::kNoFailure;
Alex Light8c889d22017-02-06 13:58:27 -08001101 if (!passes) {
1102 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1103 }
1104 return passes;
1105}
1106
Alex Light1babae02017-02-01 15:35:34 -08001107// Looks through the previously allocated cookies to see if we need to update them with another new
1108// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1109// once they are all added to the classloader.
1110bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001111 art::Handle<art::mirror::ClassLoader> source_class_loader,
1112 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001113 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001114 art::StackHandleScope<2> hs(driver_->self_);
1115 art::MutableHandle<art::mirror::LongArray> old_cookie(
1116 hs.NewHandle<art::mirror::LongArray>(nullptr));
1117 bool has_older_cookie = false;
1118 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001119 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1120 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001121 // Since every instance of this classloader should have the same cookie associated with it we
1122 // can stop looking here.
1123 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001124 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001125 break;
1126 }
1127 }
1128 if (old_cookie.IsNull()) {
1129 // No older cookie. Get it directly from the dex_file_obj
1130 // We should not have seen this classloader elsewhere.
1131 CHECK(!has_older_cookie);
1132 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1133 }
1134 // Use the old cookie to generate the new one with the new DexFile* added in.
1135 art::Handle<art::mirror::LongArray>
1136 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1137 old_cookie,
1138 dex_file_.get())));
1139 // Make sure the allocation worked.
1140 if (new_cookie.IsNull()) {
1141 return false;
1142 }
1143
1144 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001145 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001146 // If there are other copies of this same classloader we need to make sure that we all have the
1147 // same cookie.
1148 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001149 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001150 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001151 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1152 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001153 }
1154 }
1155 }
1156
1157 return true;
1158}
1159
Alex Lighta7e38d82017-01-19 14:57:28 -08001160bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001161 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001162 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001163 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001164 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001165 // This shouldn't allocate
1166 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001167 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1168 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001169 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001170 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1171 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001172 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001173 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001174 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1175 return false;
1176 }
Alex Light1babae02017-02-01 15:35:34 -08001177 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001178 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001179 driver_->self_->AssertPendingOOMException();
1180 driver_->self_->ClearException();
1181 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1182 return false;
1183 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001184 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001185 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1186 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001187 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001188 driver_->self_->ClearException();
1189 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1190 return false;
1191 }
1192
1193 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001194 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1195 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001196 driver_->self_->AssertPendingOOMException();
1197 driver_->self_->ClearException();
1198 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1199 return false;
1200 }
1201 return true;
1202}
1203
Alex Lighta26e3492017-06-27 17:55:37 -07001204void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
1205 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass());
1206}
1207
Alex Light5643caf2017-02-08 11:39:07 -08001208void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1209 DCHECK(art::Dbg::IsDebuggerActive());
1210 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1211 if (state != nullptr) {
1212 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1213 }
1214}
1215
1216void Redefiner::UnregisterAllBreakpoints() {
1217 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1218 return;
1219 }
1220 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1221 redef.UnregisterBreakpoints();
1222 }
1223}
1224
Alex Light0e692732017-01-10 15:00:05 -08001225bool Redefiner::CheckAllRedefinitionAreValid() {
1226 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1227 if (!redef.CheckRedefinitionIsValid()) {
1228 return false;
1229 }
1230 }
1231 return true;
1232}
1233
Alex Light1e3926a2017-04-07 10:38:06 -07001234void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1235 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1236 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1237 }
1238}
1239
1240bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1241 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1242 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001243 return false;
1244 }
1245 }
1246 return true;
1247}
1248
1249bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001250 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001251 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001252 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001253 return false;
1254 }
Alex Light0e692732017-01-10 15:00:05 -08001255 }
1256 return true;
1257}
1258
1259void Redefiner::ClassRedefinition::ReleaseDexFile() {
1260 dex_file_.release();
1261}
1262
1263void Redefiner::ReleaseAllDexFiles() {
1264 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1265 redef.ReleaseDexFile();
1266 }
1267}
1268
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001269bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1270 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1271 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001272 return false;
1273 }
Alex Light8c889d22017-02-06 13:58:27 -08001274 }
1275 return true;
1276}
1277
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001278class ScopedDisableConcurrentAndMovingGc {
1279 public:
1280 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1281 : heap_(heap), self_(self) {
1282 if (heap_->IsGcConcurrentAndMoving()) {
1283 heap_->IncrementDisableMovingGC(self_);
1284 }
1285 }
1286
1287 ~ScopedDisableConcurrentAndMovingGc() {
1288 if (heap_->IsGcConcurrentAndMoving()) {
1289 heap_->DecrementDisableMovingGC(self_);
1290 }
1291 }
1292 private:
1293 art::gc::Heap* heap_;
1294 art::Thread* self_;
1295};
1296
Alex Lighta01de592016-11-15 10:43:06 -08001297jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001298 art::StackHandleScope<1> hs(self_);
1299 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1300 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001301 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001302 if (holder.IsNull()) {
1303 self_->AssertPendingOOMException();
1304 self_->ClearException();
1305 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1306 return result_;
1307 }
1308
Alex Lighta01de592016-11-15 10:43:06 -08001309 // First we just allocate the ClassExt and its fields that we need. These can be updated
1310 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1311 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1312 // between allocating them and pausing all threads before we can update them so we need to do a
1313 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001314 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001315 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001316 !FinishAllRemainingAllocations(holder) ||
1317 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001318 return result_;
1319 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001320
Alex Light5643caf2017-02-08 11:39:07 -08001321 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001322 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001323 art::ClassLinker* cl = runtime_->GetClassLinker();
1324 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001325 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001326 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001327 }
Alex Light7916f202017-01-27 09:00:15 -08001328 }
Alex Light5643caf2017-02-08 11:39:07 -08001329 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001330
Alex Light6abd5392017-01-05 17:53:00 -08001331 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1332 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001333 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1334
Alex Lighta01de592016-11-15 10:43:06 -08001335 // Do transition to final suspension
1336 // TODO We might want to give this its own suspended state!
1337 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001338 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1339 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1340 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001341 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001342 ClassRedefinition& redef = data.GetRedefinition();
1343 if (data.GetSourceClassLoader() != nullptr) {
1344 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001345 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001346 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001347 // TODO Rewrite so we don't do a stack walk for each and every class.
1348 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001349 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Lighta26e3492017-06-27 17:55:37 -07001350 redef.UnregisterJvmtiBreakpoints();
Alex Light0e692732017-01-10 15:00:05 -08001351 }
Alex Light1e3926a2017-04-07 10:38:06 -07001352 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001353 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1354 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1355 // methods that have been jitted prior to the current redefinition being applied might continue
1356 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001357 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1358 // owns the DexFile and when ownership is transferred.
1359 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001360 return OK;
1361}
1362
Alex Light0e692732017-01-10 15:00:05 -08001363void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1364 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1365 const art::DexFile::ClassDef& class_def) {
1366 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001367 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001368 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001369 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001370 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001371 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1372 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1373 art::dex::TypeIndex method_return_idx =
1374 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1375 const auto* old_type_list = method.GetParameterTypeList();
1376 std::vector<art::dex::TypeIndex> new_type_list;
1377 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1378 new_type_list.push_back(
1379 dex_file_->GetIndexForTypeId(
1380 *dex_file_->FindTypeId(
1381 old_dex_file.GetTypeDescriptor(
1382 old_dex_file.GetTypeId(
1383 old_type_list->GetTypeItem(i).type_idx_)))));
1384 }
1385 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1386 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001387 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001388 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1389 *new_name_id,
1390 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001391 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001392 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1393 method.SetDexMethodIndex(dex_method_idx);
1394 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001395 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001396 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001397 // Clear all the intrinsics related flags.
1398 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001399 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001400 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001401 if (jit != nullptr) {
1402 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1403 }
Alex Lighta01de592016-11-15 10:43:06 -08001404 }
Alex Light200b9d72016-12-15 11:34:13 -08001405}
1406
Alex Light0e692732017-01-10 15:00:05 -08001407void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001408 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1409 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1410 for (art::ArtField& field : fields_iter) {
1411 std::string declaring_class_name;
1412 const art::DexFile::TypeId* new_declaring_id =
1413 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1414 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1415 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001416 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1417 const art::DexFile::FieldId* new_field_id =
1418 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1419 CHECK(new_field_id != nullptr);
1420 // We only need to update the index since the other data in the ArtField cannot be updated.
1421 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1422 }
1423 }
Alex Light200b9d72016-12-15 11:34:13 -08001424}
1425
1426// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001427void Redefiner::ClassRedefinition::UpdateClass(
1428 art::ObjPtr<art::mirror::Class> mclass,
1429 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001430 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001431 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1432 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1433 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001434 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001435
Alex Lighta01de592016-11-15 10:43:06 -08001436 // Update the class fields.
1437 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1438 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1439 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001440 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001441 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001442 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1443 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001444 ext->SetOriginalDexFile(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001445}
1446
Alex Light1e3926a2017-04-07 10:38:06 -07001447// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1448// obsolete methods).
1449void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1450 const RedefinitionDataIter* cur_data) {
1451 art::mirror::Class* klass = GetMirrorClass();
1452 art::mirror::ClassExt* ext = klass->GetExtData();
1453 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001454 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1455 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001456 int32_t expected_length =
1457 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1458 // Check to make sure we are only undoing this one.
1459 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001460 for (int32_t i = 0; i < expected_length; i++) {
1461 art::ArtMethod* expected = nullptr;
1462 if (i < old_length) {
1463 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1464 }
1465 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001466 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1467 // obsolete methods array.
1468 return;
1469 }
1470 }
1471 // No new obsolete methods! We can get rid of the maps.
1472 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1473 }
1474}
1475
Alex Lighta01de592016-11-15 10:43:06 -08001476// This function does all (java) allocations we need to do for the Class being redefined.
1477// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001478bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1479 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001480 art::StackHandleScope<2> hs(driver_->self_);
1481 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1482 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001483 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001484 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1485 return false;
1486 }
1487 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001488 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001489 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001490 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001491 driver_->self_->AssertPendingOOMException();
1492 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001493 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1494 return false;
1495 }
Alex Light1e3926a2017-04-07 10:38:06 -07001496 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1497 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001498 // are only modified when all threads (other than the modifying one) are suspended we don't need
1499 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1500 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001501 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1502 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1503 if (!ext->ExtendObsoleteArrays(
1504 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1505 // OOM. Clear exception and return error.
1506 driver_->self_->AssertPendingOOMException();
1507 driver_->self_->ClearException();
1508 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1509 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001510 }
1511 return true;
1512}
1513
1514} // namespace openjdkjvmti