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