blob: 41ed86237f46e027e584c62dcc91a01898059690 [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 Light5643caf2017-02-08 11:39:07 -080051#include "jdwp/jdwp.h"
52#include "jdwp/jdwp_constants.h"
53#include "jdwp/jdwp_event.h"
54#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080055#include "jit/jit.h"
56#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080057#include "jni_env_ext-inl.h"
58#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080059#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080060#include "mirror/class_ext.h"
61#include "mirror/object.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080062#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080063#include "object_lock.h"
64#include "runtime.h"
65#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080066#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080067#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080068#include "verifier/method_verifier.h"
69#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080070
71namespace openjdkjvmti {
72
Andreas Gampe46ee31b2016-12-14 10:11:49 -080073using android::base::StringPrintf;
74
Alex Lighteee0bd42017-02-14 15:31:45 +000075// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
76// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
77// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
78class ObsoleteMap {
79 public:
80 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
81 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
82 auto method_pair = id_map_.find(original);
83 if (method_pair != id_map_.end()) {
84 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
85 method_pair->second, art::kRuntimePointerSize);
86 DCHECK(res != nullptr);
87 DCHECK_EQ(original, res->GetNonObsoleteMethod());
88 return res;
89 } else {
90 return nullptr;
91 }
92 }
93
94 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
95 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
96 DCHECK(original != nullptr);
97 DCHECK(obsolete != nullptr);
98 int32_t slot = next_free_slot_++;
99 DCHECK_LT(slot, obsolete_methods_->GetLength());
100 DCHECK(nullptr ==
101 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
102 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
103 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
104 obsolete_dex_caches_->Set(slot, original_dex_cache_);
105 id_map_.insert({original, slot});
106 }
107
108 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
109 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
110 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
111 : next_free_slot_(0),
112 obsolete_methods_(obsolete_methods),
113 obsolete_dex_caches_(obsolete_dex_caches),
114 original_dex_cache_(original_dex_cache) {
115 // Figure out where the first unused slot in the obsolete_methods_ array is.
116 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
117 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
118 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
119 next_free_slot_++;
120 }
121 // Sanity check that the same slot in obsolete_dex_caches_ is free.
122 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
123 }
124
125 private:
126 int32_t next_free_slot_;
127 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
128 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
129 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
130 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
131 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
132 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
133};
134
Alex Lightdba61482016-12-21 08:20:29 -0800135// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
136// some basic sanity checks that the obsolete method is sane.
137class ObsoleteMethodStackVisitor : public art::StackVisitor {
138 protected:
139 ObsoleteMethodStackVisitor(
140 art::Thread* thread,
141 art::LinearAlloc* allocator,
142 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000143 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800144 : StackVisitor(thread,
145 /*context*/nullptr,
146 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
147 allocator_(allocator),
148 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800149 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800150
151 ~ObsoleteMethodStackVisitor() OVERRIDE {}
152
153 public:
154 // Returns true if we successfully installed obsolete methods on this thread, filling
155 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
156 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800157 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800158 art::Thread* thread,
159 art::LinearAlloc* allocator,
160 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000161 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800162 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800163 ObsoleteMethodStackVisitor visitor(thread,
164 allocator,
165 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800166 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800167 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800168 }
169
170 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000171 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800172 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800173 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800174 // We cannot ensure that the right dex file is used in inlined frames so we don't support
175 // redefining them.
176 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000177 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
178 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800179 // Create a new Obsolete Method and put it in the list.
180 art::Runtime* runtime = art::Runtime::Current();
181 art::ClassLinker* cl = runtime->GetClassLinker();
182 auto ptr_size = cl->GetImagePointerSize();
183 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800184 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800185 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
186 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800187 new_obsolete_method = new (method_storage) art::ArtMethod();
188 new_obsolete_method->CopyFrom(old_method, ptr_size);
189 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
190 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800191 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700192 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000193 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800194 // Update JIT Data structures to point to the new method.
195 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
196 if (jit != nullptr) {
197 // Notify the JIT we are making this obsolete method. It will update the jit's internal
198 // structures to keep track of the new obsolete method.
199 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
200 }
Alex Lightdba61482016-12-21 08:20:29 -0800201 }
202 DCHECK(new_obsolete_method != nullptr);
203 SetMethod(new_obsolete_method);
204 }
205 return true;
206 }
207
208 private:
209 // The linear allocator we should use to make new methods.
210 art::LinearAlloc* allocator_;
211 // The set of all methods which could be obsoleted.
212 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
213 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000214 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
215 // the redefined classes ClassExt as it is filled.
216 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800217};
218
Alex Lighte4a88632017-01-10 07:41:24 -0800219jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
220 jclass klass,
221 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800222 art::Thread* self = art::Thread::Current();
223 art::ScopedObjectAccess soa(self);
224 art::StackHandleScope<1> hs(self);
225 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
226 if (obj.IsNull()) {
227 return ERR(INVALID_CLASS);
228 }
229 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
230 std::string err_unused;
231 *is_redefinable =
232 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
233 return OK;
234}
235
236jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
237 /*out*/std::string* error_msg) {
238 if (klass->IsPrimitive()) {
239 *error_msg = "Modification of primitive classes is not supported";
240 return ERR(UNMODIFIABLE_CLASS);
241 } else if (klass->IsInterface()) {
242 *error_msg = "Modification of Interface classes is currently not supported";
243 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800244 } else if (klass->IsStringClass()) {
245 *error_msg = "Modification of String class is not supported";
246 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800247 } else if (klass->IsArrayClass()) {
248 *error_msg = "Modification of Array classes is not supported";
249 return ERR(UNMODIFIABLE_CLASS);
250 } else if (klass->IsProxyClass()) {
251 *error_msg = "Modification of proxy classes is not supported";
252 return ERR(UNMODIFIABLE_CLASS);
253 }
254
Alex Lighte77b48b2017-02-22 11:08:06 -0800255 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
256 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
257 *error_msg = "Class might have stack frames that cannot be made obsolete";
258 return ERR(UNMODIFIABLE_CLASS);
259 }
260 }
261
Alex Lighte4a88632017-01-10 07:41:24 -0800262 return OK;
263}
264
Alex Lighta01de592016-11-15 10:43:06 -0800265// Moves dex data to an anonymous, read-only mmap'd region.
266std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700267 art::ArraySlice<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800268 std::string* error_msg) {
269 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800270 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800271 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700272 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800273 PROT_READ|PROT_WRITE,
274 /*low_4gb*/false,
275 /*reuse*/false,
276 error_msg));
277 if (map == nullptr) {
278 return map;
279 }
Alex Lightb7354d52017-03-30 15:17:01 -0700280 memcpy(map->Begin(), &data.At(0), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800281 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
282 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800283 map->Protect(PROT_READ);
284 return map;
285}
286
Alex Lighta7e38d82017-01-19 14:57:28 -0800287Redefiner::ClassRedefinition::ClassRedefinition(
288 Redefiner* driver,
289 jclass klass,
290 const art::DexFile* redefined_dex_file,
291 const char* class_sig,
292 art::ArraySlice<const unsigned char> orig_dex_file) :
293 driver_(driver),
294 klass_(klass),
295 dex_file_(redefined_dex_file),
296 class_sig_(class_sig),
297 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800298 GetMirrorClass()->MonitorEnter(driver_->self_);
299}
300
301Redefiner::ClassRedefinition::~ClassRedefinition() {
302 if (driver_ != nullptr) {
303 GetMirrorClass()->MonitorExit(driver_->self_);
304 }
305}
306
Alex Light0e692732017-01-10 15:00:05 -0800307jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800308 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800309 art::Runtime* runtime,
310 art::Thread* self,
311 jint class_count,
312 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800313 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800314 if (env == nullptr) {
315 *error_msg = "env was null!";
316 return ERR(INVALID_ENVIRONMENT);
317 } else if (class_count < 0) {
318 *error_msg = "class_count was less then 0";
319 return ERR(ILLEGAL_ARGUMENT);
320 } else if (class_count == 0) {
321 // We don't actually need to do anything. Just return OK.
322 return OK;
323 } else if (definitions == nullptr) {
324 *error_msg = "null definitions!";
325 return ERR(NULL_POINTER);
326 }
Alex Light6ac57502017-01-19 15:05:06 -0800327 std::vector<ArtClassDefinition> def_vector;
328 def_vector.reserve(class_count);
329 for (jint i = 0; i < class_count; i++) {
Alex Lightce6ee702017-03-06 15:46:43 -0800330 jboolean is_modifiable = JNI_FALSE;
331 jvmtiError res = env->IsModifiableClass(definitions[i].klass, &is_modifiable);
332 if (res != OK) {
333 return res;
334 } else if (!is_modifiable) {
335 return ERR(UNMODIFIABLE_CLASS);
336 }
Alex Light6ac57502017-01-19 15:05:06 -0800337 // We make a copy of the class_bytes to pass into the retransformation.
338 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
339 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
340 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800341 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800342 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800343 if (res != OK) {
344 return res;
345 }
346 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
347
348 ArtClassDefinition def;
Alex Lightb7354d52017-03-30 15:17:01 -0700349 res = def.Init(env, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800350 if (res != OK) {
351 return res;
352 }
353 def_vector.push_back(std::move(def));
354 }
355 // Call all the transformation events.
356 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800357 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800358 self,
359 &def_vector);
360 if (res != OK) {
361 // Something went wrong with transformation!
362 return res;
363 }
364 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
365}
366
367jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
368 art::Runtime* runtime,
369 art::Thread* self,
370 const std::vector<ArtClassDefinition>& definitions,
371 std::string* error_msg) {
372 DCHECK(env != nullptr);
373 if (definitions.size() == 0) {
374 // We don't actually need to do anything. Just return OK.
375 return OK;
376 }
Alex Light0e692732017-01-10 15:00:05 -0800377 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
378 // are going to redefine.
379 art::jit::ScopedJitSuspend suspend_jit;
380 // Get shared mutator lock so we can lock all the classes.
381 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800382 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800383 for (const ArtClassDefinition& def : definitions) {
384 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700385 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800386 jvmtiError res = r.AddRedefinition(env, def);
387 if (res != OK) {
388 return res;
389 }
Alex Light0e692732017-01-10 15:00:05 -0800390 }
391 }
392 return r.Run();
393}
394
Alex Light6ac57502017-01-19 15:05:06 -0800395jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800396 std::string original_dex_location;
397 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700398 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800399 *error_msg_ = "Unable to get original dex file location!";
400 return ret;
401 }
Alex Light52a2db52017-01-19 23:00:21 +0000402 char* generic_ptr_unused = nullptr;
403 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700404 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800405 *error_msg_ = "Unable to get class signature!";
406 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000407 }
Andreas Gampe54711412017-02-21 12:41:43 -0800408 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
409 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800410 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700411 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800412 error_msg_));
413 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800414 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700415 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800416 << "in dex file " << original_dex_location << " because: " << *error_msg_;
417 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800418 return ERR(OUT_OF_MEMORY);
419 }
420 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800421 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800422 return ERR(INVALID_CLASS_FORMAT);
423 }
424 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
425 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
426 checksum,
427 std::move(map),
428 /*verify*/true,
429 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800430 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800431 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700432 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800433 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800434 return ERR(INVALID_CLASS_FORMAT);
435 }
Alex Light0e692732017-01-10 15:00:05 -0800436 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800437 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700438 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800439 dex_file.release(),
440 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700441 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800442 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800443}
444
Alex Light0e692732017-01-10 15:00:05 -0800445art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
446 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800447}
448
Alex Light0e692732017-01-10 15:00:05 -0800449art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800450 return GetMirrorClass()->GetClassLoader();
451}
452
Alex Light0e692732017-01-10 15:00:05 -0800453art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
454 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000455 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800456}
457
Alex Light0e692732017-01-10 15:00:05 -0800458void Redefiner::RecordFailure(jvmtiError result,
459 const std::string& class_sig,
460 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800461 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800462 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800463 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800464 result_ = result;
465}
466
Alex Light2f814aa2017-03-24 15:21:34 +0000467art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800468 // If we have been specifically given a new set of bytes use that
469 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800470 return art::mirror::ByteArray::AllocateAndFill(
471 driver_->self_,
472 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
473 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800474 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800475
476 // See if we already have one set.
477 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
478 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000479 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
480 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800481 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000482 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800483 }
Alex Lighta01de592016-11-15 10:43:06 -0800484 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800485
Alex Light2f814aa2017-03-24 15:21:34 +0000486 // return the current dex_cache which has the dex file in it.
487 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800488 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000489 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800490 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
491 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800492 }
Alex Light2f814aa2017-03-24 15:21:34 +0000493 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800494}
495
Alex Lightdba61482016-12-21 08:20:29 -0800496struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000497 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800498 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800499 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800500
Alex Lighteee0bd42017-02-14 15:31:45 +0000501 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
502 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800503};
504
Alex Lightdba61482016-12-21 08:20:29 -0800505void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
506 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800507 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
508 data->allocator,
509 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000510 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800511}
512
513// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
514// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800515// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
516void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800517 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
518 art::mirror::ClassExt* ext = art_klass->GetExtData();
519 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800520 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000521 // This holds pointers to the obsolete methods map fields which are updated as needed.
522 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
523 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800524 // Add all the declared methods to the map
525 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800526 if (m.IsIntrinsic()) {
527 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
528 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
529 << "methods that have already been compiled.";
530 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000531 // It is possible to simply filter out some methods where they cannot really become obsolete,
532 // such as native methods and keep their original (possibly optimized) implementations. We don't
533 // do this, however, since we would need to mark these functions (still in the classes
534 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
535 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
536 // error checking from the interpreter which ensure we don't try to start executing obsolete
537 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000538 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800539 }
540 {
Alex Light0e692732017-01-10 15:00:05 -0800541 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800542 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
543 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800544 }
Alex Lightdba61482016-12-21 08:20:29 -0800545}
546
Alex Light6161f132017-01-25 10:30:20 -0800547// Try and get the declared method. First try to get a virtual method then a direct method if that's
548// not found.
549static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
550 const char* name,
551 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
552 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
553 if (m == nullptr) {
554 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
555 }
556 return m;
557}
558
559bool Redefiner::ClassRedefinition::CheckSameMethods() {
560 art::StackHandleScope<1> hs(driver_->self_);
561 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
562 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
563
564 art::ClassDataItemIterator new_iter(*dex_file_,
565 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
566
567 // Make sure we have the same number of methods.
568 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
569 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
570 if (num_new_method != num_old_method) {
571 bool bigger = num_new_method > num_old_method;
572 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
573 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
574 StringPrintf("Total number of declared methods changed from %d to %d",
575 num_old_method, num_new_method));
576 return false;
577 }
578
579 // Skip all of the fields. We should have already checked this.
580 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
581 new_iter.Next();
582 }
583 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
584 // files have the same number of methods, which means there must be an equal amount of additions
585 // and removals.
586 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
587 // Get the data on the method we are searching for
588 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
589 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
590 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
591 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
592 // If we got past the check for the same number of methods above that means there must be at
593 // least one added and one removed method. We will return the ADDED failure message since it is
594 // easier to get a useful error report for it.
595 if (old_method == nullptr) {
596 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
597 StringPrintf("Unknown method '%s' (sig: %s) was added!",
598 new_method_name,
599 new_method_signature.ToString().c_str()));
600 return false;
601 }
602 // Since direct methods have different flags than virtual ones (specifically direct methods must
603 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
604 // virtual to direct.
605 uint32_t new_flags = new_iter.GetMethodAccessFlags();
606 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
607 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
608 StringPrintf("method '%s' (sig: %s) had different access flags",
609 new_method_name,
610 new_method_signature.ToString().c_str()));
611 return false;
612 }
613 }
614 return true;
615}
616
617bool Redefiner::ClassRedefinition::CheckSameFields() {
618 art::StackHandleScope<1> hs(driver_->self_);
619 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
620 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
621 art::ClassDataItemIterator new_iter(*dex_file_,
622 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
623 const art::DexFile& old_dex_file = h_klass->GetDexFile();
624 art::ClassDataItemIterator old_iter(old_dex_file,
625 old_dex_file.GetClassData(*h_klass->GetClassDef()));
626 // Instance and static fields can be differentiated by their flags so no need to check them
627 // separately.
628 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
629 // Get the data on the method we are searching for
630 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
631 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
632 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
633
634 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
635 // We are missing the old version of this method!
636 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
637 StringPrintf("Unknown field '%s' (type: %s) added!",
638 new_field_name,
639 new_field_type));
640 return false;
641 }
642
643 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
644 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
645 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
646
647 // Check name and type.
648 if (strcmp(old_field_name, new_field_name) != 0 ||
649 strcmp(old_field_type, new_field_type) != 0) {
650 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
651 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
652 old_field_name,
653 old_field_type,
654 new_field_name,
655 new_field_type));
656 return false;
657 }
658
659 // Since static fields have different flags than instance ones (specifically static fields must
660 // have the kAccStatic flag) we can tell if a field changes from static to instance.
661 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
662 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
663 StringPrintf("Field '%s' (sig: %s) had different access flags",
664 new_field_name,
665 new_field_type));
666 return false;
667 }
668
669 new_iter.Next();
670 old_iter.Next();
671 }
672 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
673 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
674 StringPrintf("field '%s' (sig: %s) is missing!",
675 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
676 old_iter.GetMemberIndex())),
677 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
678 old_iter.GetMemberIndex()))));
679 return false;
680 }
681 return true;
682}
683
Alex Light0e692732017-01-10 15:00:05 -0800684bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800685 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000686 // Easy check that only 1 class def is present.
687 if (dex_file_->NumClassDefs() != 1) {
688 RecordFailure(ERR(ILLEGAL_ARGUMENT),
689 StringPrintf("Expected 1 class def in dex file but found %d",
690 dex_file_->NumClassDefs()));
691 return false;
692 }
693 // Get the ClassDef from the new DexFile.
694 // Since the dex file has only a single class def the index is always 0.
695 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
696 // Get the class as it is now.
697 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
698
699 // Check the access flags didn't change.
700 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
701 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
702 "Cannot change modifiers of class by redefinition");
703 return false;
704 }
705
706 // Check class name.
707 // These should have been checked by the dexfile verifier on load.
708 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
709 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
710 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
711 if (!current_class->DescriptorEquals(descriptor)) {
712 std::string storage;
713 RecordFailure(ERR(NAMES_DONT_MATCH),
714 StringPrintf("expected file to contain class called '%s' but found '%s'!",
715 current_class->GetDescriptor(&storage),
716 descriptor));
717 return false;
718 }
719 if (current_class->IsObjectClass()) {
720 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
721 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
722 return false;
723 }
724 } else {
725 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
726 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
727 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
728 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
729 return false;
730 }
731 }
732 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
733 if (interfaces == nullptr) {
734 if (current_class->NumDirectInterfaces() != 0) {
735 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
736 return false;
737 }
738 } else {
739 DCHECK(!current_class->IsProxyClass());
740 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
741 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
742 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
743 return false;
744 }
745 // The order of interfaces is (barely) meaningful so we error if it changes.
746 const art::DexFile& orig_dex_file = current_class->GetDexFile();
747 for (uint32_t i = 0; i < interfaces->Size(); i++) {
748 if (strcmp(
749 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
750 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
751 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
752 "Interfaces changed or re-ordered");
753 return false;
754 }
755 }
756 }
Alex Light460d1b42017-01-10 15:37:17 +0000757 return true;
758}
759
Alex Light0e692732017-01-10 15:00:05 -0800760bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800761 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800762 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000763
Alex Lighte4a88632017-01-10 07:41:24 -0800764 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
765 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
766 if (res != OK) {
767 RecordFailure(res, err);
768 return false;
769 } else {
770 return true;
771 }
Alex Light460d1b42017-01-10 15:37:17 +0000772}
773
Alex Light0e692732017-01-10 15:00:05 -0800774bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000775 return CheckRedefinable() &&
776 CheckClass() &&
777 CheckSameFields() &&
778 CheckSameMethods();
779}
780
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800781class RedefinitionDataIter;
782
Alex Light0e692732017-01-10 15:00:05 -0800783// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
784// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
785// having to deal with the fact that we need to hold an arbitrary number of references live.
786class RedefinitionDataHolder {
787 public:
788 enum DataSlot : int32_t {
789 kSlotSourceClassLoader = 0,
790 kSlotJavaDexFile = 1,
791 kSlotNewDexFileCookie = 2,
792 kSlotNewDexCache = 3,
793 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800794 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700795 kSlotOldObsoleteMethods = 6,
796 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800797
798 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700799 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800800 };
801
802 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
803 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
804 // the passed in handle-scope.
805 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
806 art::Runtime* runtime,
807 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800808 std::vector<Redefiner::ClassRedefinition>* redefinitions)
809 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800810 arr_(
811 hs->NewHandle(
812 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
813 self,
814 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800815 redefinitions->size() * kNumSlots))),
816 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800817
818 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
819 return arr_.IsNull();
820 }
821
Alex Light8c889d22017-02-06 13:58:27 -0800822 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800823 REQUIRES_SHARED(art::Locks::mutator_lock_) {
824 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
825 }
Alex Light8c889d22017-02-06 13:58:27 -0800826 art::mirror::Object* GetJavaDexFile(jint klass_index) const
827 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800828 return GetSlot(klass_index, kSlotJavaDexFile);
829 }
Alex Light8c889d22017-02-06 13:58:27 -0800830 art::mirror::LongArray* GetNewDexFileCookie(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::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
833 }
Alex Light8c889d22017-02-06 13:58:27 -0800834 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800835 REQUIRES_SHARED(art::Locks::mutator_lock_) {
836 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
837 }
Alex Light8c889d22017-02-06 13:58:27 -0800838 art::mirror::Class* GetMirrorClass(jint klass_index) const
839 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800840 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
841 }
842
Alex Light2f814aa2017-03-24 15:21:34 +0000843 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800844 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000845 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800846 }
847
Alex Light1e3926a2017-04-07 10:38:06 -0700848 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
849 REQUIRES_SHARED(art::Locks::mutator_lock_) {
850 return art::down_cast<art::mirror::PointerArray*>(
851 GetSlot(klass_index, kSlotOldObsoleteMethods));
852 }
853
854 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
855 REQUIRES_SHARED(art::Locks::mutator_lock_) {
856 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
857 GetSlot(klass_index, kSlotOldDexCaches));
858 }
859
Alex Light0e692732017-01-10 15:00:05 -0800860 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
861 REQUIRES_SHARED(art::Locks::mutator_lock_) {
862 SetSlot(klass_index, kSlotSourceClassLoader, loader);
863 }
864 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
865 REQUIRES_SHARED(art::Locks::mutator_lock_) {
866 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
867 }
868 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
869 REQUIRES_SHARED(art::Locks::mutator_lock_) {
870 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
871 }
872 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
873 REQUIRES_SHARED(art::Locks::mutator_lock_) {
874 SetSlot(klass_index, kSlotNewDexCache, cache);
875 }
876 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
877 REQUIRES_SHARED(art::Locks::mutator_lock_) {
878 SetSlot(klass_index, kSlotMirrorClass, klass);
879 }
Alex Light2f814aa2017-03-24 15:21:34 +0000880 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800881 REQUIRES_SHARED(art::Locks::mutator_lock_) {
882 SetSlot(klass_index, kSlotOrigDexFile, bytes);
883 }
Alex Light1e3926a2017-04-07 10:38:06 -0700884 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
885 REQUIRES_SHARED(art::Locks::mutator_lock_) {
886 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
887 }
888 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
889 REQUIRES_SHARED(art::Locks::mutator_lock_) {
890 SetSlot(klass_index, kSlotOldDexCaches, caches);
891 }
Alex Light0e692732017-01-10 15:00:05 -0800892
Alex Light8c889d22017-02-06 13:58:27 -0800893 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800894 return arr_->GetLength() / kNumSlots;
895 }
896
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800897 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
898 REQUIRES_SHARED(art::Locks::mutator_lock_) {
899 return redefinitions_;
900 }
901
902 bool operator==(const RedefinitionDataHolder& other) const
903 REQUIRES_SHARED(art::Locks::mutator_lock_) {
904 return arr_.Get() == other.arr_.Get();
905 }
906
907 bool operator!=(const RedefinitionDataHolder& other) const
908 REQUIRES_SHARED(art::Locks::mutator_lock_) {
909 return !(*this == other);
910 }
911
912 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
913 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
914
Alex Light0e692732017-01-10 15:00:05 -0800915 private:
Alex Light8c889d22017-02-06 13:58:27 -0800916 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800917 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800918
919 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800920 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800921 DCHECK_LT(klass_index, Length());
922 return arr_->Get((kNumSlots * klass_index) + slot);
923 }
924
925 void SetSlot(jint klass_index,
926 DataSlot slot,
927 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
928 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
929 DCHECK_LT(klass_index, Length());
930 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
931 }
932
933 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
934};
935
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800936class RedefinitionDataIter {
937 public:
938 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
939
940 RedefinitionDataIter(const RedefinitionDataIter&) = default;
941 RedefinitionDataIter(RedefinitionDataIter&&) = default;
942 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
943 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
944
945 bool operator==(const RedefinitionDataIter& other) const
946 REQUIRES_SHARED(art::Locks::mutator_lock_) {
947 return idx_ == other.idx_ && holder_ == other.holder_;
948 }
949
950 bool operator!=(const RedefinitionDataIter& other) const
951 REQUIRES_SHARED(art::Locks::mutator_lock_) {
952 return !(*this == other);
953 }
954
955 RedefinitionDataIter operator++() { // Value after modification.
956 idx_++;
957 return *this;
958 }
959
960 RedefinitionDataIter operator++(int) {
961 RedefinitionDataIter temp = *this;
962 idx_++;
963 return temp;
964 }
965
966 RedefinitionDataIter operator+(ssize_t delta) const {
967 RedefinitionDataIter temp = *this;
968 temp += delta;
969 return temp;
970 }
971
972 RedefinitionDataIter& operator+=(ssize_t delta) {
973 idx_ += delta;
974 return *this;
975 }
976
977 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
978 return (*holder_.GetRedefinitions())[idx_];
979 }
980
981 RedefinitionDataHolder& GetHolder() {
982 return holder_;
983 }
984
985 art::mirror::ClassLoader* GetSourceClassLoader() const
986 REQUIRES_SHARED(art::Locks::mutator_lock_) {
987 return holder_.GetSourceClassLoader(idx_);
988 }
989 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
990 return holder_.GetJavaDexFile(idx_);
991 }
992 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
993 return holder_.GetNewDexFileCookie(idx_);
994 }
995 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
996 return holder_.GetNewDexCache(idx_);
997 }
998 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
999 return holder_.GetMirrorClass(idx_);
1000 }
Alex Light2f814aa2017-03-24 15:21:34 +00001001 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001002 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001003 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001004 }
Alex Light1e3926a2017-04-07 10:38:06 -07001005 art::mirror::PointerArray* GetOldObsoleteMethods() const
1006 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1007 return holder_.GetOldObsoleteMethods(idx_);
1008 }
1009 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1010 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1011 return holder_.GetOldDexCaches(idx_);
1012 }
1013
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001014 int32_t GetIndex() const {
1015 return idx_;
1016 }
1017
1018 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1019 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1020 holder_.SetSourceClassLoader(idx_, loader);
1021 }
1022 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1023 holder_.SetJavaDexFile(idx_, dexfile);
1024 }
1025 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1026 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1027 holder_.SetNewDexFileCookie(idx_, cookie);
1028 }
1029 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1030 holder_.SetNewDexCache(idx_, cache);
1031 }
1032 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1033 holder_.SetMirrorClass(idx_, klass);
1034 }
Alex Light2f814aa2017-03-24 15:21:34 +00001035 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001036 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001037 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001038 }
Alex Light1e3926a2017-04-07 10:38:06 -07001039 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1040 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1041 holder_.SetOldObsoleteMethods(idx_, methods);
1042 }
1043 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1044 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1045 holder_.SetOldDexCaches(idx_, caches);
1046 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001047
1048 private:
1049 int32_t idx_;
1050 RedefinitionDataHolder& holder_;
1051};
1052
1053RedefinitionDataIter RedefinitionDataHolder::begin() {
1054 return RedefinitionDataIter(0, *this);
1055}
1056
1057RedefinitionDataIter RedefinitionDataHolder::end() {
1058 return RedefinitionDataIter(Length(), *this);
1059}
1060
1061bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001062 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1063 art::StackHandleScope<2> hs(driver_->self_);
1064 std::string error;
1065 // TODO Make verification log level lower
1066 art::verifier::MethodVerifier::FailureKind failure =
1067 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1068 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001069 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001070 hs.NewHandle(GetClassLoader()),
1071 dex_file_->GetClassDef(0), /*class_def*/
1072 nullptr, /*compiler_callbacks*/
1073 false, /*allow_soft_failures*/
1074 /*log_level*/
1075 art::verifier::HardFailLogMode::kLogWarning,
1076 &error);
1077 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
1078 if (!passes) {
1079 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1080 }
1081 return passes;
1082}
1083
Alex Light1babae02017-02-01 15:35:34 -08001084// Looks through the previously allocated cookies to see if we need to update them with another new
1085// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1086// once they are all added to the classloader.
1087bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001088 art::Handle<art::mirror::ClassLoader> source_class_loader,
1089 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001090 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001091 art::StackHandleScope<2> hs(driver_->self_);
1092 art::MutableHandle<art::mirror::LongArray> old_cookie(
1093 hs.NewHandle<art::mirror::LongArray>(nullptr));
1094 bool has_older_cookie = false;
1095 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001096 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1097 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001098 // Since every instance of this classloader should have the same cookie associated with it we
1099 // can stop looking here.
1100 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001101 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001102 break;
1103 }
1104 }
1105 if (old_cookie.IsNull()) {
1106 // No older cookie. Get it directly from the dex_file_obj
1107 // We should not have seen this classloader elsewhere.
1108 CHECK(!has_older_cookie);
1109 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1110 }
1111 // Use the old cookie to generate the new one with the new DexFile* added in.
1112 art::Handle<art::mirror::LongArray>
1113 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1114 old_cookie,
1115 dex_file_.get())));
1116 // Make sure the allocation worked.
1117 if (new_cookie.IsNull()) {
1118 return false;
1119 }
1120
1121 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001122 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001123 // If there are other copies of this same classloader we need to make sure that we all have the
1124 // same cookie.
1125 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001126 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001127 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001128 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1129 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001130 }
1131 }
1132 }
1133
1134 return true;
1135}
1136
Alex Lighta7e38d82017-01-19 14:57:28 -08001137bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001138 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001139 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001140 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001141 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001142 // This shouldn't allocate
1143 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001144 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1145 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001146 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001147 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1148 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001149 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001150 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001151 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1152 return false;
1153 }
Alex Light1babae02017-02-01 15:35:34 -08001154 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001155 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001156 driver_->self_->AssertPendingOOMException();
1157 driver_->self_->ClearException();
1158 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1159 return false;
1160 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001161 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001162 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1163 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001164 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001165 driver_->self_->ClearException();
1166 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1167 return false;
1168 }
1169
1170 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001171 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1172 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001173 driver_->self_->AssertPendingOOMException();
1174 driver_->self_->ClearException();
1175 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1176 return false;
1177 }
1178 return true;
1179}
1180
Alex Light5643caf2017-02-08 11:39:07 -08001181void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1182 DCHECK(art::Dbg::IsDebuggerActive());
1183 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1184 if (state != nullptr) {
1185 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1186 }
1187}
1188
1189void Redefiner::UnregisterAllBreakpoints() {
1190 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1191 return;
1192 }
1193 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1194 redef.UnregisterBreakpoints();
1195 }
1196}
1197
Alex Light0e692732017-01-10 15:00:05 -08001198bool Redefiner::CheckAllRedefinitionAreValid() {
1199 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1200 if (!redef.CheckRedefinitionIsValid()) {
1201 return false;
1202 }
1203 }
1204 return true;
1205}
1206
Alex Light1e3926a2017-04-07 10:38:06 -07001207void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1208 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1209 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1210 }
1211}
1212
1213bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1214 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1215 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001216 return false;
1217 }
1218 }
1219 return true;
1220}
1221
1222bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001223 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001224 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001225 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001226 return false;
1227 }
Alex Light0e692732017-01-10 15:00:05 -08001228 }
1229 return true;
1230}
1231
1232void Redefiner::ClassRedefinition::ReleaseDexFile() {
1233 dex_file_.release();
1234}
1235
1236void Redefiner::ReleaseAllDexFiles() {
1237 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1238 redef.ReleaseDexFile();
1239 }
1240}
1241
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001242bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1243 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1244 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001245 return false;
1246 }
Alex Light8c889d22017-02-06 13:58:27 -08001247 }
1248 return true;
1249}
1250
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001251class ScopedDisableConcurrentAndMovingGc {
1252 public:
1253 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1254 : heap_(heap), self_(self) {
1255 if (heap_->IsGcConcurrentAndMoving()) {
1256 heap_->IncrementDisableMovingGC(self_);
1257 }
1258 }
1259
1260 ~ScopedDisableConcurrentAndMovingGc() {
1261 if (heap_->IsGcConcurrentAndMoving()) {
1262 heap_->DecrementDisableMovingGC(self_);
1263 }
1264 }
1265 private:
1266 art::gc::Heap* heap_;
1267 art::Thread* self_;
1268};
1269
Alex Lighta01de592016-11-15 10:43:06 -08001270jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001271 art::StackHandleScope<1> hs(self_);
1272 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1273 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001274 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001275 if (holder.IsNull()) {
1276 self_->AssertPendingOOMException();
1277 self_->ClearException();
1278 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1279 return result_;
1280 }
1281
Alex Lighta01de592016-11-15 10:43:06 -08001282 // First we just allocate the ClassExt and its fields that we need. These can be updated
1283 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1284 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1285 // between allocating them and pausing all threads before we can update them so we need to do a
1286 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001287 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001288 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001289 !FinishAllRemainingAllocations(holder) ||
1290 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001291 return result_;
1292 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001293
Alex Light5643caf2017-02-08 11:39:07 -08001294 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001295 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1296 if (data.GetSourceClassLoader() == nullptr) {
1297 runtime_->GetClassLinker()->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001298 }
Alex Light7916f202017-01-27 09:00:15 -08001299 }
Alex Light5643caf2017-02-08 11:39:07 -08001300 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001301
Alex Light6abd5392017-01-05 17:53:00 -08001302 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1303 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001304 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1305
Alex Lighta01de592016-11-15 10:43:06 -08001306 // Do transition to final suspension
1307 // TODO We might want to give this its own suspended state!
1308 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001309 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1310 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1311 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001312 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001313 ClassRedefinition& redef = data.GetRedefinition();
1314 if (data.GetSourceClassLoader() != nullptr) {
1315 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001316 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001317 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001318 // TODO Rewrite so we don't do a stack walk for each and every class.
1319 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001320 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001321 }
Alex Light1e3926a2017-04-07 10:38:06 -07001322 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001323 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1324 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1325 // methods that have been jitted prior to the current redefinition being applied might continue
1326 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001327 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1328 // owns the DexFile and when ownership is transferred.
1329 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001330 return OK;
1331}
1332
Alex Light0e692732017-01-10 15:00:05 -08001333void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1334 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1335 const art::DexFile::ClassDef& class_def) {
1336 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001337 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001338 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001339 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001340 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001341 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1342 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1343 art::dex::TypeIndex method_return_idx =
1344 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1345 const auto* old_type_list = method.GetParameterTypeList();
1346 std::vector<art::dex::TypeIndex> new_type_list;
1347 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1348 new_type_list.push_back(
1349 dex_file_->GetIndexForTypeId(
1350 *dex_file_->FindTypeId(
1351 old_dex_file.GetTypeDescriptor(
1352 old_dex_file.GetTypeId(
1353 old_type_list->GetTypeItem(i).type_idx_)))));
1354 }
1355 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1356 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001357 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001358 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1359 *new_name_id,
1360 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001361 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001362 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1363 method.SetDexMethodIndex(dex_method_idx);
1364 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001365 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001366 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001367 // Clear all the intrinsics related flags.
1368 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001369 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001370 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001371 if (jit != nullptr) {
1372 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1373 }
Alex Lighta01de592016-11-15 10:43:06 -08001374 }
Alex Light200b9d72016-12-15 11:34:13 -08001375}
1376
Alex Light0e692732017-01-10 15:00:05 -08001377void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001378 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1379 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1380 for (art::ArtField& field : fields_iter) {
1381 std::string declaring_class_name;
1382 const art::DexFile::TypeId* new_declaring_id =
1383 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1384 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1385 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001386 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1387 const art::DexFile::FieldId* new_field_id =
1388 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1389 CHECK(new_field_id != nullptr);
1390 // We only need to update the index since the other data in the ArtField cannot be updated.
1391 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1392 }
1393 }
Alex Light200b9d72016-12-15 11:34:13 -08001394}
1395
1396// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001397void Redefiner::ClassRedefinition::UpdateClass(
1398 art::ObjPtr<art::mirror::Class> mclass,
1399 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001400 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001401 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1402 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1403 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001404 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001405
Alex Lighta01de592016-11-15 10:43:06 -08001406 // Update the class fields.
1407 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1408 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1409 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001410 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001411 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001412 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1413 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001414 ext->SetOriginalDexFile(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001415}
1416
Alex Light1e3926a2017-04-07 10:38:06 -07001417// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1418// obsolete methods).
1419void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1420 const RedefinitionDataIter* cur_data) {
1421 art::mirror::Class* klass = GetMirrorClass();
1422 art::mirror::ClassExt* ext = klass->GetExtData();
1423 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001424 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1425 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001426 int32_t expected_length =
1427 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1428 // Check to make sure we are only undoing this one.
1429 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001430 for (int32_t i = 0; i < expected_length; i++) {
1431 art::ArtMethod* expected = nullptr;
1432 if (i < old_length) {
1433 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1434 }
1435 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001436 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1437 // obsolete methods array.
1438 return;
1439 }
1440 }
1441 // No new obsolete methods! We can get rid of the maps.
1442 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1443 }
1444}
1445
Alex Lighta01de592016-11-15 10:43:06 -08001446// This function does all (java) allocations we need to do for the Class being redefined.
1447// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001448bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1449 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001450 art::StackHandleScope<2> hs(driver_->self_);
1451 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1452 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001453 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001454 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1455 return false;
1456 }
1457 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001458 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001459 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001460 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001461 driver_->self_->AssertPendingOOMException();
1462 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001463 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1464 return false;
1465 }
Alex Light1e3926a2017-04-07 10:38:06 -07001466 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1467 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001468 // are only modified when all threads (other than the modifying one) are suspended we don't need
1469 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1470 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001471 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1472 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1473 if (!ext->ExtendObsoleteArrays(
1474 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1475 // OOM. Clear exception and return error.
1476 driver_->self_->AssertPendingOOMException();
1477 driver_->self_->ClearException();
1478 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1479 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001480 }
1481 return true;
1482}
1483
1484} // namespace openjdkjvmti