blob: 6e0d9a0be82b2335f6d1f908147f619cab2817ae [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
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light5643caf2017-02-08 11:39:07 -080041#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000042#include "dex_file.h"
43#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080044#include "events-inl.h"
45#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080046#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "instrumentation.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "jdwp/jdwp.h"
49#include "jdwp/jdwp_constants.h"
50#include "jdwp/jdwp_event.h"
51#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080052#include "jit/jit.h"
53#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "jni_env_ext-inl.h"
55#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080056#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080057#include "mirror/class_ext.h"
58#include "mirror/object.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080059#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080060#include "object_lock.h"
61#include "runtime.h"
62#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080063#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080064#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080065#include "verifier/method_verifier.h"
66#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080067
68namespace openjdkjvmti {
69
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070using android::base::StringPrintf;
71
Alex Lighteee0bd42017-02-14 15:31:45 +000072// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
73// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
74// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
75class ObsoleteMap {
76 public:
77 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
78 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
79 auto method_pair = id_map_.find(original);
80 if (method_pair != id_map_.end()) {
81 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
82 method_pair->second, art::kRuntimePointerSize);
83 DCHECK(res != nullptr);
84 DCHECK_EQ(original, res->GetNonObsoleteMethod());
85 return res;
86 } else {
87 return nullptr;
88 }
89 }
90
91 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
92 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
93 DCHECK(original != nullptr);
94 DCHECK(obsolete != nullptr);
95 int32_t slot = next_free_slot_++;
96 DCHECK_LT(slot, obsolete_methods_->GetLength());
97 DCHECK(nullptr ==
98 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
99 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
100 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
101 obsolete_dex_caches_->Set(slot, original_dex_cache_);
102 id_map_.insert({original, slot});
103 }
104
105 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
106 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
107 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
108 : next_free_slot_(0),
109 obsolete_methods_(obsolete_methods),
110 obsolete_dex_caches_(obsolete_dex_caches),
111 original_dex_cache_(original_dex_cache) {
112 // Figure out where the first unused slot in the obsolete_methods_ array is.
113 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
114 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
115 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
116 next_free_slot_++;
117 }
118 // Sanity check that the same slot in obsolete_dex_caches_ is free.
119 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
120 }
121
122 private:
123 int32_t next_free_slot_;
124 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
125 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
126 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
127 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
128 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
129 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
130};
131
Alex Lightdba61482016-12-21 08:20:29 -0800132// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
133// some basic sanity checks that the obsolete method is sane.
134class ObsoleteMethodStackVisitor : public art::StackVisitor {
135 protected:
136 ObsoleteMethodStackVisitor(
137 art::Thread* thread,
138 art::LinearAlloc* allocator,
139 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000140 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800141 : StackVisitor(thread,
142 /*context*/nullptr,
143 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
144 allocator_(allocator),
145 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800146 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800147
148 ~ObsoleteMethodStackVisitor() OVERRIDE {}
149
150 public:
151 // Returns true if we successfully installed obsolete methods on this thread, filling
152 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
153 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800154 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800155 art::Thread* thread,
156 art::LinearAlloc* allocator,
157 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000158 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800159 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800160 ObsoleteMethodStackVisitor visitor(thread,
161 allocator,
162 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800163 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800164 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800165 }
166
167 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000168 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800169 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800170 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800171 // We cannot ensure that the right dex file is used in inlined frames so we don't support
172 // redefining them.
173 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000174 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
175 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800176 // Create a new Obsolete Method and put it in the list.
177 art::Runtime* runtime = art::Runtime::Current();
178 art::ClassLinker* cl = runtime->GetClassLinker();
179 auto ptr_size = cl->GetImagePointerSize();
180 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800181 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800182 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
183 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800184 new_obsolete_method = new (method_storage) art::ArtMethod();
185 new_obsolete_method->CopyFrom(old_method, ptr_size);
186 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
187 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800188 new_obsolete_method->SetDontCompile();
Alex Lighteee0bd42017-02-14 15:31:45 +0000189 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800190 // Update JIT Data structures to point to the new method.
191 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
192 if (jit != nullptr) {
193 // Notify the JIT we are making this obsolete method. It will update the jit's internal
194 // structures to keep track of the new obsolete method.
195 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
196 }
Alex Lightdba61482016-12-21 08:20:29 -0800197 }
198 DCHECK(new_obsolete_method != nullptr);
199 SetMethod(new_obsolete_method);
200 }
201 return true;
202 }
203
204 private:
205 // The linear allocator we should use to make new methods.
206 art::LinearAlloc* allocator_;
207 // The set of all methods which could be obsoleted.
208 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
209 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000210 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
211 // the redefined classes ClassExt as it is filled.
212 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800213};
214
Alex Lighte4a88632017-01-10 07:41:24 -0800215jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
216 jclass klass,
217 jboolean* is_redefinable) {
218 // TODO Check for the appropriate feature flags once we have enabled them.
219 art::Thread* self = art::Thread::Current();
220 art::ScopedObjectAccess soa(self);
221 art::StackHandleScope<1> hs(self);
222 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
223 if (obj.IsNull()) {
224 return ERR(INVALID_CLASS);
225 }
226 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
227 std::string err_unused;
228 *is_redefinable =
229 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
230 return OK;
231}
232
233jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
234 /*out*/std::string* error_msg) {
235 if (klass->IsPrimitive()) {
236 *error_msg = "Modification of primitive classes is not supported";
237 return ERR(UNMODIFIABLE_CLASS);
238 } else if (klass->IsInterface()) {
239 *error_msg = "Modification of Interface classes is currently not supported";
240 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800241 } else if (klass->IsStringClass()) {
242 *error_msg = "Modification of String class is not supported";
243 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800244 } else if (klass->IsArrayClass()) {
245 *error_msg = "Modification of Array classes is not supported";
246 return ERR(UNMODIFIABLE_CLASS);
247 } else if (klass->IsProxyClass()) {
248 *error_msg = "Modification of proxy classes is not supported";
249 return ERR(UNMODIFIABLE_CLASS);
250 }
251
Alex Lighte77b48b2017-02-22 11:08:06 -0800252 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
253 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
254 *error_msg = "Class might have stack frames that cannot be made obsolete";
255 return ERR(UNMODIFIABLE_CLASS);
256 }
257 }
258
Alex Lighte4a88632017-01-10 07:41:24 -0800259 return OK;
260}
261
Alex Lighta01de592016-11-15 10:43:06 -0800262// Moves dex data to an anonymous, read-only mmap'd region.
263std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700264 art::ArraySlice<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800265 std::string* error_msg) {
266 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800267 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800268 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700269 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800270 PROT_READ|PROT_WRITE,
271 /*low_4gb*/false,
272 /*reuse*/false,
273 error_msg));
274 if (map == nullptr) {
275 return map;
276 }
Alex Lightb7354d52017-03-30 15:17:01 -0700277 memcpy(map->Begin(), &data.At(0), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800278 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
279 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800280 map->Protect(PROT_READ);
281 return map;
282}
283
Alex Lighta7e38d82017-01-19 14:57:28 -0800284Redefiner::ClassRedefinition::ClassRedefinition(
285 Redefiner* driver,
286 jclass klass,
287 const art::DexFile* redefined_dex_file,
288 const char* class_sig,
289 art::ArraySlice<const unsigned char> orig_dex_file) :
290 driver_(driver),
291 klass_(klass),
292 dex_file_(redefined_dex_file),
293 class_sig_(class_sig),
294 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800295 GetMirrorClass()->MonitorEnter(driver_->self_);
296}
297
298Redefiner::ClassRedefinition::~ClassRedefinition() {
299 if (driver_ != nullptr) {
300 GetMirrorClass()->MonitorExit(driver_->self_);
301 }
302}
303
Alex Light0e692732017-01-10 15:00:05 -0800304jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800305 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800306 art::Runtime* runtime,
307 art::Thread* self,
308 jint class_count,
309 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800310 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800311 if (env == nullptr) {
312 *error_msg = "env was null!";
313 return ERR(INVALID_ENVIRONMENT);
314 } else if (class_count < 0) {
315 *error_msg = "class_count was less then 0";
316 return ERR(ILLEGAL_ARGUMENT);
317 } else if (class_count == 0) {
318 // We don't actually need to do anything. Just return OK.
319 return OK;
320 } else if (definitions == nullptr) {
321 *error_msg = "null definitions!";
322 return ERR(NULL_POINTER);
323 }
Alex Light6ac57502017-01-19 15:05:06 -0800324 std::vector<ArtClassDefinition> def_vector;
325 def_vector.reserve(class_count);
326 for (jint i = 0; i < class_count; i++) {
Alex Lightce6ee702017-03-06 15:46:43 -0800327 jboolean is_modifiable = JNI_FALSE;
328 jvmtiError res = env->IsModifiableClass(definitions[i].klass, &is_modifiable);
329 if (res != OK) {
330 return res;
331 } else if (!is_modifiable) {
332 return ERR(UNMODIFIABLE_CLASS);
333 }
Alex Light6ac57502017-01-19 15:05:06 -0800334 // We make a copy of the class_bytes to pass into the retransformation.
335 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
336 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
337 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800338 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800339 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800340 if (res != OK) {
341 return res;
342 }
343 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
344
345 ArtClassDefinition def;
Alex Lightb7354d52017-03-30 15:17:01 -0700346 res = def.Init(env, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800347 if (res != OK) {
348 return res;
349 }
350 def_vector.push_back(std::move(def));
351 }
352 // Call all the transformation events.
353 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800354 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800355 self,
356 &def_vector);
357 if (res != OK) {
358 // Something went wrong with transformation!
359 return res;
360 }
361 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
362}
363
364jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
365 art::Runtime* runtime,
366 art::Thread* self,
367 const std::vector<ArtClassDefinition>& definitions,
368 std::string* error_msg) {
369 DCHECK(env != nullptr);
370 if (definitions.size() == 0) {
371 // We don't actually need to do anything. Just return OK.
372 return OK;
373 }
Alex Light0e692732017-01-10 15:00:05 -0800374 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
375 // are going to redefine.
376 art::jit::ScopedJitSuspend suspend_jit;
377 // Get shared mutator lock so we can lock all the classes.
378 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800379 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800380 for (const ArtClassDefinition& def : definitions) {
381 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700382 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800383 jvmtiError res = r.AddRedefinition(env, def);
384 if (res != OK) {
385 return res;
386 }
Alex Light0e692732017-01-10 15:00:05 -0800387 }
388 }
389 return r.Run();
390}
391
Alex Light6ac57502017-01-19 15:05:06 -0800392jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800393 std::string original_dex_location;
394 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700395 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800396 *error_msg_ = "Unable to get original dex file location!";
397 return ret;
398 }
Alex Light52a2db52017-01-19 23:00:21 +0000399 char* generic_ptr_unused = nullptr;
400 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700401 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800402 *error_msg_ = "Unable to get class signature!";
403 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000404 }
Andreas Gampe54711412017-02-21 12:41:43 -0800405 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
406 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800407 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700408 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800409 error_msg_));
410 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800411 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700412 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800413 << "in dex file " << original_dex_location << " because: " << *error_msg_;
414 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800415 return ERR(OUT_OF_MEMORY);
416 }
417 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800418 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800419 return ERR(INVALID_CLASS_FORMAT);
420 }
421 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
422 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
423 checksum,
424 std::move(map),
425 /*verify*/true,
426 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800427 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800428 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700429 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800430 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800431 return ERR(INVALID_CLASS_FORMAT);
432 }
Alex Light0e692732017-01-10 15:00:05 -0800433 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800434 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700435 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800436 dex_file.release(),
437 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700438 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800439 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800440}
441
Alex Light0e692732017-01-10 15:00:05 -0800442art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
443 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800444}
445
Alex Light0e692732017-01-10 15:00:05 -0800446art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800447 return GetMirrorClass()->GetClassLoader();
448}
449
Alex Light0e692732017-01-10 15:00:05 -0800450art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
451 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000452 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800453}
454
Alex Light0e692732017-01-10 15:00:05 -0800455void Redefiner::RecordFailure(jvmtiError result,
456 const std::string& class_sig,
457 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800458 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800459 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800460 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800461 result_ = result;
462}
463
Alex Light2f814aa2017-03-24 15:21:34 +0000464art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800465 // If we have been specifically given a new set of bytes use that
466 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800467 return art::mirror::ByteArray::AllocateAndFill(
468 driver_->self_,
469 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
470 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800471 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800472
473 // See if we already have one set.
474 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
475 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000476 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
477 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800478 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000479 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800480 }
Alex Lighta01de592016-11-15 10:43:06 -0800481 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800482
Alex Light2f814aa2017-03-24 15:21:34 +0000483 // return the current dex_cache which has the dex file in it.
484 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800485 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000486 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800487 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
488 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800489 }
Alex Light2f814aa2017-03-24 15:21:34 +0000490 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800491}
492
Alex Lightdba61482016-12-21 08:20:29 -0800493struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000494 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800495 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800496 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800497
Alex Lighteee0bd42017-02-14 15:31:45 +0000498 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
499 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800500};
501
Alex Lightdba61482016-12-21 08:20:29 -0800502void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
503 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800504 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
505 data->allocator,
506 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000507 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800508}
509
510// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
511// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800512// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
513void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800514 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
515 art::mirror::ClassExt* ext = art_klass->GetExtData();
516 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800517 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000518 // This holds pointers to the obsolete methods map fields which are updated as needed.
519 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
520 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800521 // Add all the declared methods to the map
522 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800523 if (m.IsIntrinsic()) {
524 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
525 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
526 << "methods that have already been compiled.";
527 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000528 // It is possible to simply filter out some methods where they cannot really become obsolete,
529 // such as native methods and keep their original (possibly optimized) implementations. We don't
530 // do this, however, since we would need to mark these functions (still in the classes
531 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
532 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
533 // error checking from the interpreter which ensure we don't try to start executing obsolete
534 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000535 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800536 }
537 {
Alex Light0e692732017-01-10 15:00:05 -0800538 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800539 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
540 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800541 }
Alex Lightdba61482016-12-21 08:20:29 -0800542}
543
Alex Light6161f132017-01-25 10:30:20 -0800544// Try and get the declared method. First try to get a virtual method then a direct method if that's
545// not found.
546static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
547 const char* name,
548 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
549 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
550 if (m == nullptr) {
551 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
552 }
553 return m;
554}
555
556bool Redefiner::ClassRedefinition::CheckSameMethods() {
557 art::StackHandleScope<1> hs(driver_->self_);
558 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
559 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
560
561 art::ClassDataItemIterator new_iter(*dex_file_,
562 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
563
564 // Make sure we have the same number of methods.
565 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
566 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
567 if (num_new_method != num_old_method) {
568 bool bigger = num_new_method > num_old_method;
569 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
570 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
571 StringPrintf("Total number of declared methods changed from %d to %d",
572 num_old_method, num_new_method));
573 return false;
574 }
575
576 // Skip all of the fields. We should have already checked this.
577 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
578 new_iter.Next();
579 }
580 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
581 // files have the same number of methods, which means there must be an equal amount of additions
582 // and removals.
583 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
584 // Get the data on the method we are searching for
585 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
586 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
587 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
588 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
589 // If we got past the check for the same number of methods above that means there must be at
590 // least one added and one removed method. We will return the ADDED failure message since it is
591 // easier to get a useful error report for it.
592 if (old_method == nullptr) {
593 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
594 StringPrintf("Unknown method '%s' (sig: %s) was added!",
595 new_method_name,
596 new_method_signature.ToString().c_str()));
597 return false;
598 }
599 // Since direct methods have different flags than virtual ones (specifically direct methods must
600 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
601 // virtual to direct.
602 uint32_t new_flags = new_iter.GetMethodAccessFlags();
603 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
604 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
605 StringPrintf("method '%s' (sig: %s) had different access flags",
606 new_method_name,
607 new_method_signature.ToString().c_str()));
608 return false;
609 }
610 }
611 return true;
612}
613
614bool Redefiner::ClassRedefinition::CheckSameFields() {
615 art::StackHandleScope<1> hs(driver_->self_);
616 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
617 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
618 art::ClassDataItemIterator new_iter(*dex_file_,
619 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
620 const art::DexFile& old_dex_file = h_klass->GetDexFile();
621 art::ClassDataItemIterator old_iter(old_dex_file,
622 old_dex_file.GetClassData(*h_klass->GetClassDef()));
623 // Instance and static fields can be differentiated by their flags so no need to check them
624 // separately.
625 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
626 // Get the data on the method we are searching for
627 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
628 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
629 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
630
631 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
632 // We are missing the old version of this method!
633 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
634 StringPrintf("Unknown field '%s' (type: %s) added!",
635 new_field_name,
636 new_field_type));
637 return false;
638 }
639
640 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
641 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
642 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
643
644 // Check name and type.
645 if (strcmp(old_field_name, new_field_name) != 0 ||
646 strcmp(old_field_type, new_field_type) != 0) {
647 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
648 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
649 old_field_name,
650 old_field_type,
651 new_field_name,
652 new_field_type));
653 return false;
654 }
655
656 // Since static fields have different flags than instance ones (specifically static fields must
657 // have the kAccStatic flag) we can tell if a field changes from static to instance.
658 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
659 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
660 StringPrintf("Field '%s' (sig: %s) had different access flags",
661 new_field_name,
662 new_field_type));
663 return false;
664 }
665
666 new_iter.Next();
667 old_iter.Next();
668 }
669 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
670 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
671 StringPrintf("field '%s' (sig: %s) is missing!",
672 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
673 old_iter.GetMemberIndex())),
674 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
675 old_iter.GetMemberIndex()))));
676 return false;
677 }
678 return true;
679}
680
Alex Light0e692732017-01-10 15:00:05 -0800681bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800682 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000683 // Easy check that only 1 class def is present.
684 if (dex_file_->NumClassDefs() != 1) {
685 RecordFailure(ERR(ILLEGAL_ARGUMENT),
686 StringPrintf("Expected 1 class def in dex file but found %d",
687 dex_file_->NumClassDefs()));
688 return false;
689 }
690 // Get the ClassDef from the new DexFile.
691 // Since the dex file has only a single class def the index is always 0.
692 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
693 // Get the class as it is now.
694 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
695
696 // Check the access flags didn't change.
697 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
698 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
699 "Cannot change modifiers of class by redefinition");
700 return false;
701 }
702
703 // Check class name.
704 // These should have been checked by the dexfile verifier on load.
705 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
706 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
707 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
708 if (!current_class->DescriptorEquals(descriptor)) {
709 std::string storage;
710 RecordFailure(ERR(NAMES_DONT_MATCH),
711 StringPrintf("expected file to contain class called '%s' but found '%s'!",
712 current_class->GetDescriptor(&storage),
713 descriptor));
714 return false;
715 }
716 if (current_class->IsObjectClass()) {
717 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
718 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
719 return false;
720 }
721 } else {
722 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
723 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
724 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
725 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
726 return false;
727 }
728 }
729 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
730 if (interfaces == nullptr) {
731 if (current_class->NumDirectInterfaces() != 0) {
732 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
733 return false;
734 }
735 } else {
736 DCHECK(!current_class->IsProxyClass());
737 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
738 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
739 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
740 return false;
741 }
742 // The order of interfaces is (barely) meaningful so we error if it changes.
743 const art::DexFile& orig_dex_file = current_class->GetDexFile();
744 for (uint32_t i = 0; i < interfaces->Size(); i++) {
745 if (strcmp(
746 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
747 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
748 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
749 "Interfaces changed or re-ordered");
750 return false;
751 }
752 }
753 }
Alex Light460d1b42017-01-10 15:37:17 +0000754 return true;
755}
756
Alex Light0e692732017-01-10 15:00:05 -0800757bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800758 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800759 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000760
Alex Lighte4a88632017-01-10 07:41:24 -0800761 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
762 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
763 if (res != OK) {
764 RecordFailure(res, err);
765 return false;
766 } else {
767 return true;
768 }
Alex Light460d1b42017-01-10 15:37:17 +0000769}
770
Alex Light0e692732017-01-10 15:00:05 -0800771bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000772 return CheckRedefinable() &&
773 CheckClass() &&
774 CheckSameFields() &&
775 CheckSameMethods();
776}
777
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800778class RedefinitionDataIter;
779
Alex Light0e692732017-01-10 15:00:05 -0800780// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
781// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
782// having to deal with the fact that we need to hold an arbitrary number of references live.
783class RedefinitionDataHolder {
784 public:
785 enum DataSlot : int32_t {
786 kSlotSourceClassLoader = 0,
787 kSlotJavaDexFile = 1,
788 kSlotNewDexFileCookie = 2,
789 kSlotNewDexCache = 3,
790 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800791 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800792
793 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800794 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800795 };
796
797 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
798 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
799 // the passed in handle-scope.
800 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
801 art::Runtime* runtime,
802 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800803 std::vector<Redefiner::ClassRedefinition>* redefinitions)
804 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800805 arr_(
806 hs->NewHandle(
807 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
808 self,
809 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800810 redefinitions->size() * kNumSlots))),
811 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800812
813 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
814 return arr_.IsNull();
815 }
816
817 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800818 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800819 REQUIRES_SHARED(art::Locks::mutator_lock_) {
820 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
821 }
Alex Light8c889d22017-02-06 13:58:27 -0800822 art::mirror::Object* GetJavaDexFile(jint klass_index) const
823 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800824 return GetSlot(klass_index, kSlotJavaDexFile);
825 }
Alex Light8c889d22017-02-06 13:58:27 -0800826 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800827 REQUIRES_SHARED(art::Locks::mutator_lock_) {
828 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
829 }
Alex Light8c889d22017-02-06 13:58:27 -0800830 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800831 REQUIRES_SHARED(art::Locks::mutator_lock_) {
832 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
833 }
Alex Light8c889d22017-02-06 13:58:27 -0800834 art::mirror::Class* GetMirrorClass(jint klass_index) const
835 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800836 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
837 }
838
Alex Light2f814aa2017-03-24 15:21:34 +0000839 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800840 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000841 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800842 }
843
Alex Light0e692732017-01-10 15:00:05 -0800844 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
845 REQUIRES_SHARED(art::Locks::mutator_lock_) {
846 SetSlot(klass_index, kSlotSourceClassLoader, loader);
847 }
848 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
849 REQUIRES_SHARED(art::Locks::mutator_lock_) {
850 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
851 }
852 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
853 REQUIRES_SHARED(art::Locks::mutator_lock_) {
854 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
855 }
856 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
857 REQUIRES_SHARED(art::Locks::mutator_lock_) {
858 SetSlot(klass_index, kSlotNewDexCache, cache);
859 }
860 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
861 REQUIRES_SHARED(art::Locks::mutator_lock_) {
862 SetSlot(klass_index, kSlotMirrorClass, klass);
863 }
Alex Light2f814aa2017-03-24 15:21:34 +0000864 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800865 REQUIRES_SHARED(art::Locks::mutator_lock_) {
866 SetSlot(klass_index, kSlotOrigDexFile, bytes);
867 }
Alex Light0e692732017-01-10 15:00:05 -0800868
Alex Light8c889d22017-02-06 13:58:27 -0800869 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800870 return arr_->GetLength() / kNumSlots;
871 }
872
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800873 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
874 REQUIRES_SHARED(art::Locks::mutator_lock_) {
875 return redefinitions_;
876 }
877
878 bool operator==(const RedefinitionDataHolder& other) const
879 REQUIRES_SHARED(art::Locks::mutator_lock_) {
880 return arr_.Get() == other.arr_.Get();
881 }
882
883 bool operator!=(const RedefinitionDataHolder& other) const
884 REQUIRES_SHARED(art::Locks::mutator_lock_) {
885 return !(*this == other);
886 }
887
888 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
889 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
890
Alex Light0e692732017-01-10 15:00:05 -0800891 private:
Alex Light8c889d22017-02-06 13:58:27 -0800892 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800893 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800894
895 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800896 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800897 DCHECK_LT(klass_index, Length());
898 return arr_->Get((kNumSlots * klass_index) + slot);
899 }
900
901 void SetSlot(jint klass_index,
902 DataSlot slot,
903 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
904 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
905 DCHECK_LT(klass_index, Length());
906 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
907 }
908
909 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
910};
911
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800912class RedefinitionDataIter {
913 public:
914 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
915
916 RedefinitionDataIter(const RedefinitionDataIter&) = default;
917 RedefinitionDataIter(RedefinitionDataIter&&) = default;
918 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
919 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
920
921 bool operator==(const RedefinitionDataIter& other) const
922 REQUIRES_SHARED(art::Locks::mutator_lock_) {
923 return idx_ == other.idx_ && holder_ == other.holder_;
924 }
925
926 bool operator!=(const RedefinitionDataIter& other) const
927 REQUIRES_SHARED(art::Locks::mutator_lock_) {
928 return !(*this == other);
929 }
930
931 RedefinitionDataIter operator++() { // Value after modification.
932 idx_++;
933 return *this;
934 }
935
936 RedefinitionDataIter operator++(int) {
937 RedefinitionDataIter temp = *this;
938 idx_++;
939 return temp;
940 }
941
942 RedefinitionDataIter operator+(ssize_t delta) const {
943 RedefinitionDataIter temp = *this;
944 temp += delta;
945 return temp;
946 }
947
948 RedefinitionDataIter& operator+=(ssize_t delta) {
949 idx_ += delta;
950 return *this;
951 }
952
953 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
954 return (*holder_.GetRedefinitions())[idx_];
955 }
956
957 RedefinitionDataHolder& GetHolder() {
958 return holder_;
959 }
960
961 art::mirror::ClassLoader* GetSourceClassLoader() const
962 REQUIRES_SHARED(art::Locks::mutator_lock_) {
963 return holder_.GetSourceClassLoader(idx_);
964 }
965 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
966 return holder_.GetJavaDexFile(idx_);
967 }
968 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
969 return holder_.GetNewDexFileCookie(idx_);
970 }
971 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
972 return holder_.GetNewDexCache(idx_);
973 }
974 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
975 return holder_.GetMirrorClass(idx_);
976 }
Alex Light2f814aa2017-03-24 15:21:34 +0000977 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800978 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000979 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800980 }
981 int32_t GetIndex() const {
982 return idx_;
983 }
984
985 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
986 REQUIRES_SHARED(art::Locks::mutator_lock_) {
987 holder_.SetSourceClassLoader(idx_, loader);
988 }
989 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
990 holder_.SetJavaDexFile(idx_, dexfile);
991 }
992 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
993 REQUIRES_SHARED(art::Locks::mutator_lock_) {
994 holder_.SetNewDexFileCookie(idx_, cookie);
995 }
996 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
997 holder_.SetNewDexCache(idx_, cache);
998 }
999 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1000 holder_.SetMirrorClass(idx_, klass);
1001 }
Alex Light2f814aa2017-03-24 15:21:34 +00001002 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001003 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001004 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001005 }
1006
1007 private:
1008 int32_t idx_;
1009 RedefinitionDataHolder& holder_;
1010};
1011
1012RedefinitionDataIter RedefinitionDataHolder::begin() {
1013 return RedefinitionDataIter(0, *this);
1014}
1015
1016RedefinitionDataIter RedefinitionDataHolder::end() {
1017 return RedefinitionDataIter(Length(), *this);
1018}
1019
1020bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001021 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1022 art::StackHandleScope<2> hs(driver_->self_);
1023 std::string error;
1024 // TODO Make verification log level lower
1025 art::verifier::MethodVerifier::FailureKind failure =
1026 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1027 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001028 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001029 hs.NewHandle(GetClassLoader()),
1030 dex_file_->GetClassDef(0), /*class_def*/
1031 nullptr, /*compiler_callbacks*/
1032 false, /*allow_soft_failures*/
1033 /*log_level*/
1034 art::verifier::HardFailLogMode::kLogWarning,
1035 &error);
1036 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
1037 if (!passes) {
1038 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1039 }
1040 return passes;
1041}
1042
Alex Light1babae02017-02-01 15:35:34 -08001043// Looks through the previously allocated cookies to see if we need to update them with another new
1044// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1045// once they are all added to the classloader.
1046bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001047 art::Handle<art::mirror::ClassLoader> source_class_loader,
1048 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001049 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001050 art::StackHandleScope<2> hs(driver_->self_);
1051 art::MutableHandle<art::mirror::LongArray> old_cookie(
1052 hs.NewHandle<art::mirror::LongArray>(nullptr));
1053 bool has_older_cookie = false;
1054 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001055 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1056 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001057 // Since every instance of this classloader should have the same cookie associated with it we
1058 // can stop looking here.
1059 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001060 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001061 break;
1062 }
1063 }
1064 if (old_cookie.IsNull()) {
1065 // No older cookie. Get it directly from the dex_file_obj
1066 // We should not have seen this classloader elsewhere.
1067 CHECK(!has_older_cookie);
1068 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1069 }
1070 // Use the old cookie to generate the new one with the new DexFile* added in.
1071 art::Handle<art::mirror::LongArray>
1072 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1073 old_cookie,
1074 dex_file_.get())));
1075 // Make sure the allocation worked.
1076 if (new_cookie.IsNull()) {
1077 return false;
1078 }
1079
1080 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001081 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001082 // If there are other copies of this same classloader we need to make sure that we all have the
1083 // same cookie.
1084 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001085 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001086 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001087 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1088 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001089 }
1090 }
1091 }
1092
1093 return true;
1094}
1095
Alex Lighta7e38d82017-01-19 14:57:28 -08001096bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001097 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001098 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001099 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001100 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001101 // This shouldn't allocate
1102 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001103 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1104 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001105 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001106 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1107 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001108 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001109 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001110 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1111 return false;
1112 }
Alex Light1babae02017-02-01 15:35:34 -08001113 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001114 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001115 driver_->self_->AssertPendingOOMException();
1116 driver_->self_->ClearException();
1117 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1118 return false;
1119 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001120 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001121 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1122 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001123 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001124 driver_->self_->ClearException();
1125 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1126 return false;
1127 }
1128
1129 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001130 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1131 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001132 driver_->self_->AssertPendingOOMException();
1133 driver_->self_->ClearException();
1134 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1135 return false;
1136 }
1137 return true;
1138}
1139
Alex Light5643caf2017-02-08 11:39:07 -08001140void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1141 DCHECK(art::Dbg::IsDebuggerActive());
1142 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1143 if (state != nullptr) {
1144 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1145 }
1146}
1147
1148void Redefiner::UnregisterAllBreakpoints() {
1149 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1150 return;
1151 }
1152 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1153 redef.UnregisterBreakpoints();
1154 }
1155}
1156
Alex Light0e692732017-01-10 15:00:05 -08001157bool Redefiner::CheckAllRedefinitionAreValid() {
1158 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1159 if (!redef.CheckRedefinitionIsValid()) {
1160 return false;
1161 }
1162 }
1163 return true;
1164}
1165
1166bool Redefiner::EnsureAllClassAllocationsFinished() {
1167 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1168 if (!redef.EnsureClassAllocationsFinished()) {
1169 return false;
1170 }
1171 }
1172 return true;
1173}
1174
1175bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001176 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001177 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001178 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001179 return false;
1180 }
Alex Light0e692732017-01-10 15:00:05 -08001181 }
1182 return true;
1183}
1184
1185void Redefiner::ClassRedefinition::ReleaseDexFile() {
1186 dex_file_.release();
1187}
1188
1189void Redefiner::ReleaseAllDexFiles() {
1190 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1191 redef.ReleaseDexFile();
1192 }
1193}
1194
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001195bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1196 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1197 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001198 return false;
1199 }
Alex Light8c889d22017-02-06 13:58:27 -08001200 }
1201 return true;
1202}
1203
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001204class ScopedDisableConcurrentAndMovingGc {
1205 public:
1206 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1207 : heap_(heap), self_(self) {
1208 if (heap_->IsGcConcurrentAndMoving()) {
1209 heap_->IncrementDisableMovingGC(self_);
1210 }
1211 }
1212
1213 ~ScopedDisableConcurrentAndMovingGc() {
1214 if (heap_->IsGcConcurrentAndMoving()) {
1215 heap_->DecrementDisableMovingGC(self_);
1216 }
1217 }
1218 private:
1219 art::gc::Heap* heap_;
1220 art::Thread* self_;
1221};
1222
Alex Lighta01de592016-11-15 10:43:06 -08001223jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001224 art::StackHandleScope<1> hs(self_);
1225 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1226 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001227 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001228 if (holder.IsNull()) {
1229 self_->AssertPendingOOMException();
1230 self_->ClearException();
1231 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1232 return result_;
1233 }
1234
Alex Lighta01de592016-11-15 10:43:06 -08001235 // First we just allocate the ClassExt and its fields that we need. These can be updated
1236 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1237 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1238 // between allocating them and pausing all threads before we can update them so we need to do a
1239 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001240 if (!CheckAllRedefinitionAreValid() ||
1241 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001242 !FinishAllRemainingAllocations(holder) ||
1243 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001244 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1245 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001246 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1247 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001248 return result_;
1249 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001250
Alex Light5643caf2017-02-08 11:39:07 -08001251 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001252 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1253 if (data.GetSourceClassLoader() == nullptr) {
1254 runtime_->GetClassLinker()->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001255 }
Alex Light7916f202017-01-27 09:00:15 -08001256 }
Alex Light5643caf2017-02-08 11:39:07 -08001257 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001258
Alex Light6abd5392017-01-05 17:53:00 -08001259 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1260 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001261 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1262
Alex Lighta01de592016-11-15 10:43:06 -08001263 // Do transition to final suspension
1264 // TODO We might want to give this its own suspended state!
1265 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001266 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1267 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1268 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001269 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001270 ClassRedefinition& redef = data.GetRedefinition();
1271 if (data.GetSourceClassLoader() != nullptr) {
1272 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001273 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001274 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001275 // TODO Rewrite so we don't do a stack walk for each and every class.
1276 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001277 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001278 }
Alex Light7532d582017-02-13 16:36:06 -08001279 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1280 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1281 // methods that have been jitted prior to the current redefinition being applied might continue
1282 // to use the old versions of the intrinsics!
Alex Lightdba61482016-12-21 08:20:29 -08001283 // TODO Shrink the obsolete method maps if possible?
Alex Light0e692732017-01-10 15:00:05 -08001284 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1285 // owns the DexFile and when ownership is transferred.
1286 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001287 return OK;
1288}
1289
Alex Light0e692732017-01-10 15:00:05 -08001290void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1291 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1292 const art::DexFile::ClassDef& class_def) {
1293 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001294 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001295 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001296 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001297 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001298 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1299 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1300 art::dex::TypeIndex method_return_idx =
1301 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1302 const auto* old_type_list = method.GetParameterTypeList();
1303 std::vector<art::dex::TypeIndex> new_type_list;
1304 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1305 new_type_list.push_back(
1306 dex_file_->GetIndexForTypeId(
1307 *dex_file_->FindTypeId(
1308 old_dex_file.GetTypeDescriptor(
1309 old_dex_file.GetTypeId(
1310 old_type_list->GetTypeItem(i).type_idx_)))));
1311 }
1312 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1313 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001314 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001315 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1316 *new_name_id,
1317 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001318 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001319 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1320 method.SetDexMethodIndex(dex_method_idx);
1321 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001322 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001323 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001324 // Clear all the intrinsics related flags.
1325 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001326 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001327 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001328 if (jit != nullptr) {
1329 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1330 }
Alex Lighta01de592016-11-15 10:43:06 -08001331 }
Alex Light200b9d72016-12-15 11:34:13 -08001332}
1333
Alex Light0e692732017-01-10 15:00:05 -08001334void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001335 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1336 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1337 for (art::ArtField& field : fields_iter) {
1338 std::string declaring_class_name;
1339 const art::DexFile::TypeId* new_declaring_id =
1340 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1341 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1342 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001343 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1344 const art::DexFile::FieldId* new_field_id =
1345 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1346 CHECK(new_field_id != nullptr);
1347 // We only need to update the index since the other data in the ArtField cannot be updated.
1348 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1349 }
1350 }
Alex Light200b9d72016-12-15 11:34:13 -08001351}
1352
1353// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001354void Redefiner::ClassRedefinition::UpdateClass(
1355 art::ObjPtr<art::mirror::Class> mclass,
1356 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001357 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001358 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1359 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1360 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001361 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001362
Alex Lighta01de592016-11-15 10:43:06 -08001363 // Update the class fields.
1364 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1365 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1366 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001367 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001368 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001369 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1370 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001371 ext->SetOriginalDexFile(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001372}
1373
Alex Lighta01de592016-11-15 10:43:06 -08001374// This function does all (java) allocations we need to do for the Class being redefined.
1375// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001376bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1377 art::StackHandleScope<2> hs(driver_->self_);
1378 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1379 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001380 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001381 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1382 return false;
1383 }
1384 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001385 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001386 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001387 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001388 driver_->self_->AssertPendingOOMException();
1389 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001390 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1391 return false;
1392 }
1393 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1394 // are only modified when all threads (other than the modifying one) are suspended we don't need
1395 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1396 // however, since that can happen at any time.
1397 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1398 // are no obsolete methods.
1399 {
Alex Light0e692732017-01-10 15:00:05 -08001400 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001401 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001402 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001403 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001404 driver_->self_->AssertPendingOOMException();
1405 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001406 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1407 return false;
1408 }
1409 }
1410 return true;
1411}
1412
1413} // namespace openjdkjvmti