blob: 7d95de823e924197f4235b2e34a0cbe7704be4d5 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light5643caf2017-02-08 11:39:07 -080041#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000042#include "dex_file.h"
43#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080044#include "events-inl.h"
45#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080046#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "instrumentation.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "jdwp/jdwp.h"
49#include "jdwp/jdwp_constants.h"
50#include "jdwp/jdwp_event.h"
51#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080052#include "jit/jit.h"
53#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "jni_env_ext-inl.h"
55#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080056#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080057#include "mirror/class_ext.h"
58#include "mirror/object.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080059#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080060#include "object_lock.h"
61#include "runtime.h"
62#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080063#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080064#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080065#include "verifier/method_verifier.h"
66#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080067
68namespace openjdkjvmti {
69
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070using android::base::StringPrintf;
71
Alex Lighteee0bd42017-02-14 15:31:45 +000072// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
73// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
74// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
75class ObsoleteMap {
76 public:
77 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
78 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
79 auto method_pair = id_map_.find(original);
80 if (method_pair != id_map_.end()) {
81 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
82 method_pair->second, art::kRuntimePointerSize);
83 DCHECK(res != nullptr);
84 DCHECK_EQ(original, res->GetNonObsoleteMethod());
85 return res;
86 } else {
87 return nullptr;
88 }
89 }
90
91 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
92 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
93 DCHECK(original != nullptr);
94 DCHECK(obsolete != nullptr);
95 int32_t slot = next_free_slot_++;
96 DCHECK_LT(slot, obsolete_methods_->GetLength());
97 DCHECK(nullptr ==
98 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
99 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
100 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
101 obsolete_dex_caches_->Set(slot, original_dex_cache_);
102 id_map_.insert({original, slot});
103 }
104
105 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
106 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
107 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
108 : next_free_slot_(0),
109 obsolete_methods_(obsolete_methods),
110 obsolete_dex_caches_(obsolete_dex_caches),
111 original_dex_cache_(original_dex_cache) {
112 // Figure out where the first unused slot in the obsolete_methods_ array is.
113 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
114 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
115 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
116 next_free_slot_++;
117 }
118 // Sanity check that the same slot in obsolete_dex_caches_ is free.
119 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
120 }
121
122 private:
123 int32_t next_free_slot_;
124 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
125 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
126 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
127 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
128 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
129 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
130};
131
Alex Lightdba61482016-12-21 08:20:29 -0800132// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
133// some basic sanity checks that the obsolete method is sane.
134class ObsoleteMethodStackVisitor : public art::StackVisitor {
135 protected:
136 ObsoleteMethodStackVisitor(
137 art::Thread* thread,
138 art::LinearAlloc* allocator,
139 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000140 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800141 : StackVisitor(thread,
142 /*context*/nullptr,
143 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
144 allocator_(allocator),
145 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800146 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800147
148 ~ObsoleteMethodStackVisitor() OVERRIDE {}
149
150 public:
151 // Returns true if we successfully installed obsolete methods on this thread, filling
152 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
153 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800154 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800155 art::Thread* thread,
156 art::LinearAlloc* allocator,
157 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000158 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800159 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800160 ObsoleteMethodStackVisitor visitor(thread,
161 allocator,
162 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800163 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800164 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800165 }
166
167 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000168 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800169 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800170 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800171 // We cannot ensure that the right dex file is used in inlined frames so we don't support
172 // redefining them.
173 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000174 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
175 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800176 // Create a new Obsolete Method and put it in the list.
177 art::Runtime* runtime = art::Runtime::Current();
178 art::ClassLinker* cl = runtime->GetClassLinker();
179 auto ptr_size = cl->GetImagePointerSize();
180 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800181 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800182 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
183 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800184 new_obsolete_method = new (method_storage) art::ArtMethod();
185 new_obsolete_method->CopyFrom(old_method, ptr_size);
186 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
187 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800188 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700189 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000190 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800191 // Update JIT Data structures to point to the new method.
192 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
193 if (jit != nullptr) {
194 // Notify the JIT we are making this obsolete method. It will update the jit's internal
195 // structures to keep track of the new obsolete method.
196 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
197 }
Alex Lightdba61482016-12-21 08:20:29 -0800198 }
199 DCHECK(new_obsolete_method != nullptr);
200 SetMethod(new_obsolete_method);
201 }
202 return true;
203 }
204
205 private:
206 // The linear allocator we should use to make new methods.
207 art::LinearAlloc* allocator_;
208 // The set of all methods which could be obsoleted.
209 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
210 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000211 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
212 // the redefined classes ClassExt as it is filled.
213 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800214};
215
Alex Lighte4a88632017-01-10 07:41:24 -0800216jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
217 jclass klass,
218 jboolean* is_redefinable) {
219 // TODO Check for the appropriate feature flags once we have enabled them.
220 art::Thread* self = art::Thread::Current();
221 art::ScopedObjectAccess soa(self);
222 art::StackHandleScope<1> hs(self);
223 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
224 if (obj.IsNull()) {
225 return ERR(INVALID_CLASS);
226 }
227 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
228 std::string err_unused;
229 *is_redefinable =
230 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
231 return OK;
232}
233
234jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
235 /*out*/std::string* error_msg) {
236 if (klass->IsPrimitive()) {
237 *error_msg = "Modification of primitive classes is not supported";
238 return ERR(UNMODIFIABLE_CLASS);
239 } else if (klass->IsInterface()) {
240 *error_msg = "Modification of Interface classes is currently not supported";
241 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800242 } else if (klass->IsStringClass()) {
243 *error_msg = "Modification of String class is not supported";
244 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800245 } else if (klass->IsArrayClass()) {
246 *error_msg = "Modification of Array classes is not supported";
247 return ERR(UNMODIFIABLE_CLASS);
248 } else if (klass->IsProxyClass()) {
249 *error_msg = "Modification of proxy classes is not supported";
250 return ERR(UNMODIFIABLE_CLASS);
251 }
252
Alex Lighte77b48b2017-02-22 11:08:06 -0800253 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
254 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
255 *error_msg = "Class might have stack frames that cannot be made obsolete";
256 return ERR(UNMODIFIABLE_CLASS);
257 }
258 }
259
Alex Lighte4a88632017-01-10 07:41:24 -0800260 return OK;
261}
262
Alex Lighta01de592016-11-15 10:43:06 -0800263// Moves dex data to an anonymous, read-only mmap'd region.
264std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700265 art::ArraySlice<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800266 std::string* error_msg) {
267 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800268 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800269 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700270 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800271 PROT_READ|PROT_WRITE,
272 /*low_4gb*/false,
273 /*reuse*/false,
274 error_msg));
275 if (map == nullptr) {
276 return map;
277 }
Alex Lightb7354d52017-03-30 15:17:01 -0700278 memcpy(map->Begin(), &data.At(0), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800279 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
280 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800281 map->Protect(PROT_READ);
282 return map;
283}
284
Alex Lighta7e38d82017-01-19 14:57:28 -0800285Redefiner::ClassRedefinition::ClassRedefinition(
286 Redefiner* driver,
287 jclass klass,
288 const art::DexFile* redefined_dex_file,
289 const char* class_sig,
290 art::ArraySlice<const unsigned char> orig_dex_file) :
291 driver_(driver),
292 klass_(klass),
293 dex_file_(redefined_dex_file),
294 class_sig_(class_sig),
295 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800296 GetMirrorClass()->MonitorEnter(driver_->self_);
297}
298
299Redefiner::ClassRedefinition::~ClassRedefinition() {
300 if (driver_ != nullptr) {
301 GetMirrorClass()->MonitorExit(driver_->self_);
302 }
303}
304
Alex Light0e692732017-01-10 15:00:05 -0800305jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800306 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800307 art::Runtime* runtime,
308 art::Thread* self,
309 jint class_count,
310 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800311 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800312 if (env == nullptr) {
313 *error_msg = "env was null!";
314 return ERR(INVALID_ENVIRONMENT);
315 } else if (class_count < 0) {
316 *error_msg = "class_count was less then 0";
317 return ERR(ILLEGAL_ARGUMENT);
318 } else if (class_count == 0) {
319 // We don't actually need to do anything. Just return OK.
320 return OK;
321 } else if (definitions == nullptr) {
322 *error_msg = "null definitions!";
323 return ERR(NULL_POINTER);
324 }
Alex Light6ac57502017-01-19 15:05:06 -0800325 std::vector<ArtClassDefinition> def_vector;
326 def_vector.reserve(class_count);
327 for (jint i = 0; i < class_count; i++) {
Alex Lightce6ee702017-03-06 15:46:43 -0800328 jboolean is_modifiable = JNI_FALSE;
329 jvmtiError res = env->IsModifiableClass(definitions[i].klass, &is_modifiable);
330 if (res != OK) {
331 return res;
332 } else if (!is_modifiable) {
333 return ERR(UNMODIFIABLE_CLASS);
334 }
Alex Light6ac57502017-01-19 15:05:06 -0800335 // We make a copy of the class_bytes to pass into the retransformation.
336 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
337 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
338 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800339 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800340 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800341 if (res != OK) {
342 return res;
343 }
344 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
345
346 ArtClassDefinition def;
Alex Lightb7354d52017-03-30 15:17:01 -0700347 res = def.Init(env, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800348 if (res != OK) {
349 return res;
350 }
351 def_vector.push_back(std::move(def));
352 }
353 // Call all the transformation events.
354 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800355 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800356 self,
357 &def_vector);
358 if (res != OK) {
359 // Something went wrong with transformation!
360 return res;
361 }
362 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
363}
364
365jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
366 art::Runtime* runtime,
367 art::Thread* self,
368 const std::vector<ArtClassDefinition>& definitions,
369 std::string* error_msg) {
370 DCHECK(env != nullptr);
371 if (definitions.size() == 0) {
372 // We don't actually need to do anything. Just return OK.
373 return OK;
374 }
Alex Light0e692732017-01-10 15:00:05 -0800375 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
376 // are going to redefine.
377 art::jit::ScopedJitSuspend suspend_jit;
378 // Get shared mutator lock so we can lock all the classes.
379 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800380 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800381 for (const ArtClassDefinition& def : definitions) {
382 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700383 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800384 jvmtiError res = r.AddRedefinition(env, def);
385 if (res != OK) {
386 return res;
387 }
Alex Light0e692732017-01-10 15:00:05 -0800388 }
389 }
390 return r.Run();
391}
392
Alex Light6ac57502017-01-19 15:05:06 -0800393jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800394 std::string original_dex_location;
395 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700396 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800397 *error_msg_ = "Unable to get original dex file location!";
398 return ret;
399 }
Alex Light52a2db52017-01-19 23:00:21 +0000400 char* generic_ptr_unused = nullptr;
401 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700402 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800403 *error_msg_ = "Unable to get class signature!";
404 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000405 }
Andreas Gampe54711412017-02-21 12:41:43 -0800406 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
407 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800408 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700409 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800410 error_msg_));
411 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800412 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700413 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800414 << "in dex file " << original_dex_location << " because: " << *error_msg_;
415 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800416 return ERR(OUT_OF_MEMORY);
417 }
418 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800419 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800420 return ERR(INVALID_CLASS_FORMAT);
421 }
422 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
423 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
424 checksum,
425 std::move(map),
426 /*verify*/true,
427 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800428 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800429 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700430 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800431 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800432 return ERR(INVALID_CLASS_FORMAT);
433 }
Alex Light0e692732017-01-10 15:00:05 -0800434 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800435 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700436 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800437 dex_file.release(),
438 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700439 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800440 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800441}
442
Alex Light0e692732017-01-10 15:00:05 -0800443art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
444 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800445}
446
Alex Light0e692732017-01-10 15:00:05 -0800447art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800448 return GetMirrorClass()->GetClassLoader();
449}
450
Alex Light0e692732017-01-10 15:00:05 -0800451art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
452 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000453 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800454}
455
Alex Light0e692732017-01-10 15:00:05 -0800456void Redefiner::RecordFailure(jvmtiError result,
457 const std::string& class_sig,
458 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800459 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800460 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800461 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800462 result_ = result;
463}
464
Alex Light2f814aa2017-03-24 15:21:34 +0000465art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800466 // If we have been specifically given a new set of bytes use that
467 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800468 return art::mirror::ByteArray::AllocateAndFill(
469 driver_->self_,
470 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
471 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800472 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800473
474 // See if we already have one set.
475 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
476 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000477 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
478 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800479 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000480 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800481 }
Alex Lighta01de592016-11-15 10:43:06 -0800482 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800483
Alex Light2f814aa2017-03-24 15:21:34 +0000484 // return the current dex_cache which has the dex file in it.
485 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800486 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000487 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800488 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
489 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800490 }
Alex Light2f814aa2017-03-24 15:21:34 +0000491 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800492}
493
Alex Lightdba61482016-12-21 08:20:29 -0800494struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000495 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800496 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800497 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800498
Alex Lighteee0bd42017-02-14 15:31:45 +0000499 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
500 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800501};
502
Alex Lightdba61482016-12-21 08:20:29 -0800503void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
504 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800505 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
506 data->allocator,
507 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000508 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800509}
510
511// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
512// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800513// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
514void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800515 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
516 art::mirror::ClassExt* ext = art_klass->GetExtData();
517 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800518 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000519 // This holds pointers to the obsolete methods map fields which are updated as needed.
520 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
521 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800522 // Add all the declared methods to the map
523 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800524 if (m.IsIntrinsic()) {
525 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
526 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
527 << "methods that have already been compiled.";
528 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000529 // It is possible to simply filter out some methods where they cannot really become obsolete,
530 // such as native methods and keep their original (possibly optimized) implementations. We don't
531 // do this, however, since we would need to mark these functions (still in the classes
532 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
533 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
534 // error checking from the interpreter which ensure we don't try to start executing obsolete
535 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000536 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800537 }
538 {
Alex Light0e692732017-01-10 15:00:05 -0800539 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800540 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
541 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800542 }
Alex Lightdba61482016-12-21 08:20:29 -0800543}
544
Alex Light6161f132017-01-25 10:30:20 -0800545// Try and get the declared method. First try to get a virtual method then a direct method if that's
546// not found.
547static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
548 const char* name,
549 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
550 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
551 if (m == nullptr) {
552 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
553 }
554 return m;
555}
556
557bool Redefiner::ClassRedefinition::CheckSameMethods() {
558 art::StackHandleScope<1> hs(driver_->self_);
559 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
560 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
561
562 art::ClassDataItemIterator new_iter(*dex_file_,
563 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
564
565 // Make sure we have the same number of methods.
566 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
567 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
568 if (num_new_method != num_old_method) {
569 bool bigger = num_new_method > num_old_method;
570 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
571 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
572 StringPrintf("Total number of declared methods changed from %d to %d",
573 num_old_method, num_new_method));
574 return false;
575 }
576
577 // Skip all of the fields. We should have already checked this.
578 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
579 new_iter.Next();
580 }
581 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
582 // files have the same number of methods, which means there must be an equal amount of additions
583 // and removals.
584 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
585 // Get the data on the method we are searching for
586 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
587 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
588 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
589 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
590 // If we got past the check for the same number of methods above that means there must be at
591 // least one added and one removed method. We will return the ADDED failure message since it is
592 // easier to get a useful error report for it.
593 if (old_method == nullptr) {
594 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
595 StringPrintf("Unknown method '%s' (sig: %s) was added!",
596 new_method_name,
597 new_method_signature.ToString().c_str()));
598 return false;
599 }
600 // Since direct methods have different flags than virtual ones (specifically direct methods must
601 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
602 // virtual to direct.
603 uint32_t new_flags = new_iter.GetMethodAccessFlags();
604 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
605 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
606 StringPrintf("method '%s' (sig: %s) had different access flags",
607 new_method_name,
608 new_method_signature.ToString().c_str()));
609 return false;
610 }
611 }
612 return true;
613}
614
615bool Redefiner::ClassRedefinition::CheckSameFields() {
616 art::StackHandleScope<1> hs(driver_->self_);
617 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
618 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
619 art::ClassDataItemIterator new_iter(*dex_file_,
620 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
621 const art::DexFile& old_dex_file = h_klass->GetDexFile();
622 art::ClassDataItemIterator old_iter(old_dex_file,
623 old_dex_file.GetClassData(*h_klass->GetClassDef()));
624 // Instance and static fields can be differentiated by their flags so no need to check them
625 // separately.
626 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
627 // Get the data on the method we are searching for
628 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
629 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
630 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
631
632 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
633 // We are missing the old version of this method!
634 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
635 StringPrintf("Unknown field '%s' (type: %s) added!",
636 new_field_name,
637 new_field_type));
638 return false;
639 }
640
641 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
642 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
643 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
644
645 // Check name and type.
646 if (strcmp(old_field_name, new_field_name) != 0 ||
647 strcmp(old_field_type, new_field_type) != 0) {
648 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
649 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
650 old_field_name,
651 old_field_type,
652 new_field_name,
653 new_field_type));
654 return false;
655 }
656
657 // Since static fields have different flags than instance ones (specifically static fields must
658 // have the kAccStatic flag) we can tell if a field changes from static to instance.
659 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
660 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
661 StringPrintf("Field '%s' (sig: %s) had different access flags",
662 new_field_name,
663 new_field_type));
664 return false;
665 }
666
667 new_iter.Next();
668 old_iter.Next();
669 }
670 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
671 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
672 StringPrintf("field '%s' (sig: %s) is missing!",
673 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
674 old_iter.GetMemberIndex())),
675 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
676 old_iter.GetMemberIndex()))));
677 return false;
678 }
679 return true;
680}
681
Alex Light0e692732017-01-10 15:00:05 -0800682bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800683 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000684 // Easy check that only 1 class def is present.
685 if (dex_file_->NumClassDefs() != 1) {
686 RecordFailure(ERR(ILLEGAL_ARGUMENT),
687 StringPrintf("Expected 1 class def in dex file but found %d",
688 dex_file_->NumClassDefs()));
689 return false;
690 }
691 // Get the ClassDef from the new DexFile.
692 // Since the dex file has only a single class def the index is always 0.
693 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
694 // Get the class as it is now.
695 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
696
697 // Check the access flags didn't change.
698 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
699 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
700 "Cannot change modifiers of class by redefinition");
701 return false;
702 }
703
704 // Check class name.
705 // These should have been checked by the dexfile verifier on load.
706 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
707 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
708 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
709 if (!current_class->DescriptorEquals(descriptor)) {
710 std::string storage;
711 RecordFailure(ERR(NAMES_DONT_MATCH),
712 StringPrintf("expected file to contain class called '%s' but found '%s'!",
713 current_class->GetDescriptor(&storage),
714 descriptor));
715 return false;
716 }
717 if (current_class->IsObjectClass()) {
718 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
719 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
720 return false;
721 }
722 } else {
723 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
724 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
725 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
726 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
727 return false;
728 }
729 }
730 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
731 if (interfaces == nullptr) {
732 if (current_class->NumDirectInterfaces() != 0) {
733 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
734 return false;
735 }
736 } else {
737 DCHECK(!current_class->IsProxyClass());
738 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
739 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
740 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
741 return false;
742 }
743 // The order of interfaces is (barely) meaningful so we error if it changes.
744 const art::DexFile& orig_dex_file = current_class->GetDexFile();
745 for (uint32_t i = 0; i < interfaces->Size(); i++) {
746 if (strcmp(
747 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
748 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
749 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
750 "Interfaces changed or re-ordered");
751 return false;
752 }
753 }
754 }
Alex Light460d1b42017-01-10 15:37:17 +0000755 return true;
756}
757
Alex Light0e692732017-01-10 15:00:05 -0800758bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800759 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800760 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000761
Alex Lighte4a88632017-01-10 07:41:24 -0800762 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
763 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
764 if (res != OK) {
765 RecordFailure(res, err);
766 return false;
767 } else {
768 return true;
769 }
Alex Light460d1b42017-01-10 15:37:17 +0000770}
771
Alex Light0e692732017-01-10 15:00:05 -0800772bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000773 return CheckRedefinable() &&
774 CheckClass() &&
775 CheckSameFields() &&
776 CheckSameMethods();
777}
778
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800779class RedefinitionDataIter;
780
Alex Light0e692732017-01-10 15:00:05 -0800781// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
782// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
783// having to deal with the fact that we need to hold an arbitrary number of references live.
784class RedefinitionDataHolder {
785 public:
786 enum DataSlot : int32_t {
787 kSlotSourceClassLoader = 0,
788 kSlotJavaDexFile = 1,
789 kSlotNewDexFileCookie = 2,
790 kSlotNewDexCache = 3,
791 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800792 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800793
794 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800795 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800796 };
797
798 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
799 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
800 // the passed in handle-scope.
801 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
802 art::Runtime* runtime,
803 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800804 std::vector<Redefiner::ClassRedefinition>* redefinitions)
805 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800806 arr_(
807 hs->NewHandle(
808 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
809 self,
810 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800811 redefinitions->size() * kNumSlots))),
812 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800813
814 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
815 return arr_.IsNull();
816 }
817
818 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800819 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800820 REQUIRES_SHARED(art::Locks::mutator_lock_) {
821 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
822 }
Alex Light8c889d22017-02-06 13:58:27 -0800823 art::mirror::Object* GetJavaDexFile(jint klass_index) const
824 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800825 return GetSlot(klass_index, kSlotJavaDexFile);
826 }
Alex Light8c889d22017-02-06 13:58:27 -0800827 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800828 REQUIRES_SHARED(art::Locks::mutator_lock_) {
829 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
830 }
Alex Light8c889d22017-02-06 13:58:27 -0800831 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800832 REQUIRES_SHARED(art::Locks::mutator_lock_) {
833 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
834 }
Alex Light8c889d22017-02-06 13:58:27 -0800835 art::mirror::Class* GetMirrorClass(jint klass_index) const
836 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800837 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
838 }
839
Alex Light2f814aa2017-03-24 15:21:34 +0000840 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800841 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000842 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800843 }
844
Alex Light0e692732017-01-10 15:00:05 -0800845 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
846 REQUIRES_SHARED(art::Locks::mutator_lock_) {
847 SetSlot(klass_index, kSlotSourceClassLoader, loader);
848 }
849 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
850 REQUIRES_SHARED(art::Locks::mutator_lock_) {
851 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
852 }
853 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
854 REQUIRES_SHARED(art::Locks::mutator_lock_) {
855 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
856 }
857 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
858 REQUIRES_SHARED(art::Locks::mutator_lock_) {
859 SetSlot(klass_index, kSlotNewDexCache, cache);
860 }
861 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
862 REQUIRES_SHARED(art::Locks::mutator_lock_) {
863 SetSlot(klass_index, kSlotMirrorClass, klass);
864 }
Alex Light2f814aa2017-03-24 15:21:34 +0000865 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800866 REQUIRES_SHARED(art::Locks::mutator_lock_) {
867 SetSlot(klass_index, kSlotOrigDexFile, bytes);
868 }
Alex Light0e692732017-01-10 15:00:05 -0800869
Alex Light8c889d22017-02-06 13:58:27 -0800870 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800871 return arr_->GetLength() / kNumSlots;
872 }
873
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800874 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
875 REQUIRES_SHARED(art::Locks::mutator_lock_) {
876 return redefinitions_;
877 }
878
879 bool operator==(const RedefinitionDataHolder& other) const
880 REQUIRES_SHARED(art::Locks::mutator_lock_) {
881 return arr_.Get() == other.arr_.Get();
882 }
883
884 bool operator!=(const RedefinitionDataHolder& other) const
885 REQUIRES_SHARED(art::Locks::mutator_lock_) {
886 return !(*this == other);
887 }
888
889 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
890 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
891
Alex Light0e692732017-01-10 15:00:05 -0800892 private:
Alex Light8c889d22017-02-06 13:58:27 -0800893 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800894 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800895
896 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800897 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800898 DCHECK_LT(klass_index, Length());
899 return arr_->Get((kNumSlots * klass_index) + slot);
900 }
901
902 void SetSlot(jint klass_index,
903 DataSlot slot,
904 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
905 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
906 DCHECK_LT(klass_index, Length());
907 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
908 }
909
910 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
911};
912
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800913class RedefinitionDataIter {
914 public:
915 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
916
917 RedefinitionDataIter(const RedefinitionDataIter&) = default;
918 RedefinitionDataIter(RedefinitionDataIter&&) = default;
919 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
920 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
921
922 bool operator==(const RedefinitionDataIter& other) const
923 REQUIRES_SHARED(art::Locks::mutator_lock_) {
924 return idx_ == other.idx_ && holder_ == other.holder_;
925 }
926
927 bool operator!=(const RedefinitionDataIter& other) const
928 REQUIRES_SHARED(art::Locks::mutator_lock_) {
929 return !(*this == other);
930 }
931
932 RedefinitionDataIter operator++() { // Value after modification.
933 idx_++;
934 return *this;
935 }
936
937 RedefinitionDataIter operator++(int) {
938 RedefinitionDataIter temp = *this;
939 idx_++;
940 return temp;
941 }
942
943 RedefinitionDataIter operator+(ssize_t delta) const {
944 RedefinitionDataIter temp = *this;
945 temp += delta;
946 return temp;
947 }
948
949 RedefinitionDataIter& operator+=(ssize_t delta) {
950 idx_ += delta;
951 return *this;
952 }
953
954 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
955 return (*holder_.GetRedefinitions())[idx_];
956 }
957
958 RedefinitionDataHolder& GetHolder() {
959 return holder_;
960 }
961
962 art::mirror::ClassLoader* GetSourceClassLoader() const
963 REQUIRES_SHARED(art::Locks::mutator_lock_) {
964 return holder_.GetSourceClassLoader(idx_);
965 }
966 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
967 return holder_.GetJavaDexFile(idx_);
968 }
969 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
970 return holder_.GetNewDexFileCookie(idx_);
971 }
972 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
973 return holder_.GetNewDexCache(idx_);
974 }
975 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
976 return holder_.GetMirrorClass(idx_);
977 }
Alex Light2f814aa2017-03-24 15:21:34 +0000978 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800979 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000980 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800981 }
982 int32_t GetIndex() const {
983 return idx_;
984 }
985
986 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
987 REQUIRES_SHARED(art::Locks::mutator_lock_) {
988 holder_.SetSourceClassLoader(idx_, loader);
989 }
990 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
991 holder_.SetJavaDexFile(idx_, dexfile);
992 }
993 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
994 REQUIRES_SHARED(art::Locks::mutator_lock_) {
995 holder_.SetNewDexFileCookie(idx_, cookie);
996 }
997 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
998 holder_.SetNewDexCache(idx_, cache);
999 }
1000 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1001 holder_.SetMirrorClass(idx_, klass);
1002 }
Alex Light2f814aa2017-03-24 15:21:34 +00001003 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001004 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001005 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001006 }
1007
1008 private:
1009 int32_t idx_;
1010 RedefinitionDataHolder& holder_;
1011};
1012
1013RedefinitionDataIter RedefinitionDataHolder::begin() {
1014 return RedefinitionDataIter(0, *this);
1015}
1016
1017RedefinitionDataIter RedefinitionDataHolder::end() {
1018 return RedefinitionDataIter(Length(), *this);
1019}
1020
1021bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001022 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1023 art::StackHandleScope<2> hs(driver_->self_);
1024 std::string error;
1025 // TODO Make verification log level lower
1026 art::verifier::MethodVerifier::FailureKind failure =
1027 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1028 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001029 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001030 hs.NewHandle(GetClassLoader()),
1031 dex_file_->GetClassDef(0), /*class_def*/
1032 nullptr, /*compiler_callbacks*/
1033 false, /*allow_soft_failures*/
1034 /*log_level*/
1035 art::verifier::HardFailLogMode::kLogWarning,
1036 &error);
1037 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
1038 if (!passes) {
1039 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1040 }
1041 return passes;
1042}
1043
Alex Light1babae02017-02-01 15:35:34 -08001044// Looks through the previously allocated cookies to see if we need to update them with another new
1045// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1046// once they are all added to the classloader.
1047bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001048 art::Handle<art::mirror::ClassLoader> source_class_loader,
1049 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001050 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001051 art::StackHandleScope<2> hs(driver_->self_);
1052 art::MutableHandle<art::mirror::LongArray> old_cookie(
1053 hs.NewHandle<art::mirror::LongArray>(nullptr));
1054 bool has_older_cookie = false;
1055 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001056 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1057 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001058 // Since every instance of this classloader should have the same cookie associated with it we
1059 // can stop looking here.
1060 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001061 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001062 break;
1063 }
1064 }
1065 if (old_cookie.IsNull()) {
1066 // No older cookie. Get it directly from the dex_file_obj
1067 // We should not have seen this classloader elsewhere.
1068 CHECK(!has_older_cookie);
1069 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1070 }
1071 // Use the old cookie to generate the new one with the new DexFile* added in.
1072 art::Handle<art::mirror::LongArray>
1073 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1074 old_cookie,
1075 dex_file_.get())));
1076 // Make sure the allocation worked.
1077 if (new_cookie.IsNull()) {
1078 return false;
1079 }
1080
1081 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001082 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001083 // If there are other copies of this same classloader we need to make sure that we all have the
1084 // same cookie.
1085 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001086 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001087 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001088 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1089 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001090 }
1091 }
1092 }
1093
1094 return true;
1095}
1096
Alex Lighta7e38d82017-01-19 14:57:28 -08001097bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001098 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001099 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001100 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001101 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001102 // This shouldn't allocate
1103 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001104 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1105 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001106 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001107 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1108 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001109 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001110 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001111 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1112 return false;
1113 }
Alex Light1babae02017-02-01 15:35:34 -08001114 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001115 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001116 driver_->self_->AssertPendingOOMException();
1117 driver_->self_->ClearException();
1118 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1119 return false;
1120 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001121 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001122 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1123 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001124 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001125 driver_->self_->ClearException();
1126 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1127 return false;
1128 }
1129
1130 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001131 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1132 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001133 driver_->self_->AssertPendingOOMException();
1134 driver_->self_->ClearException();
1135 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1136 return false;
1137 }
1138 return true;
1139}
1140
Alex Light5643caf2017-02-08 11:39:07 -08001141void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1142 DCHECK(art::Dbg::IsDebuggerActive());
1143 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1144 if (state != nullptr) {
1145 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1146 }
1147}
1148
1149void Redefiner::UnregisterAllBreakpoints() {
1150 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1151 return;
1152 }
1153 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1154 redef.UnregisterBreakpoints();
1155 }
1156}
1157
Alex Light0e692732017-01-10 15:00:05 -08001158bool Redefiner::CheckAllRedefinitionAreValid() {
1159 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1160 if (!redef.CheckRedefinitionIsValid()) {
1161 return false;
1162 }
1163 }
1164 return true;
1165}
1166
1167bool Redefiner::EnsureAllClassAllocationsFinished() {
1168 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1169 if (!redef.EnsureClassAllocationsFinished()) {
1170 return false;
1171 }
1172 }
1173 return true;
1174}
1175
1176bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001177 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001178 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001179 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001180 return false;
1181 }
Alex Light0e692732017-01-10 15:00:05 -08001182 }
1183 return true;
1184}
1185
1186void Redefiner::ClassRedefinition::ReleaseDexFile() {
1187 dex_file_.release();
1188}
1189
1190void Redefiner::ReleaseAllDexFiles() {
1191 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1192 redef.ReleaseDexFile();
1193 }
1194}
1195
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001196bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1197 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1198 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001199 return false;
1200 }
Alex Light8c889d22017-02-06 13:58:27 -08001201 }
1202 return true;
1203}
1204
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001205class ScopedDisableConcurrentAndMovingGc {
1206 public:
1207 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1208 : heap_(heap), self_(self) {
1209 if (heap_->IsGcConcurrentAndMoving()) {
1210 heap_->IncrementDisableMovingGC(self_);
1211 }
1212 }
1213
1214 ~ScopedDisableConcurrentAndMovingGc() {
1215 if (heap_->IsGcConcurrentAndMoving()) {
1216 heap_->DecrementDisableMovingGC(self_);
1217 }
1218 }
1219 private:
1220 art::gc::Heap* heap_;
1221 art::Thread* self_;
1222};
1223
Alex Lighta01de592016-11-15 10:43:06 -08001224jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001225 art::StackHandleScope<1> hs(self_);
1226 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1227 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001228 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001229 if (holder.IsNull()) {
1230 self_->AssertPendingOOMException();
1231 self_->ClearException();
1232 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1233 return result_;
1234 }
1235
Alex Lighta01de592016-11-15 10:43:06 -08001236 // First we just allocate the ClassExt and its fields that we need. These can be updated
1237 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1238 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1239 // between allocating them and pausing all threads before we can update them so we need to do a
1240 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001241 if (!CheckAllRedefinitionAreValid() ||
1242 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001243 !FinishAllRemainingAllocations(holder) ||
1244 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001245 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1246 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001247 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1248 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001249 return result_;
1250 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001251
Alex Light5643caf2017-02-08 11:39:07 -08001252 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001253 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1254 if (data.GetSourceClassLoader() == nullptr) {
1255 runtime_->GetClassLinker()->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001256 }
Alex Light7916f202017-01-27 09:00:15 -08001257 }
Alex Light5643caf2017-02-08 11:39:07 -08001258 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001259
Alex Light6abd5392017-01-05 17:53:00 -08001260 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1261 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001262 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1263
Alex Lighta01de592016-11-15 10:43:06 -08001264 // Do transition to final suspension
1265 // TODO We might want to give this its own suspended state!
1266 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001267 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1268 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1269 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001270 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001271 ClassRedefinition& redef = data.GetRedefinition();
1272 if (data.GetSourceClassLoader() != nullptr) {
1273 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001274 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001275 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001276 // TODO Rewrite so we don't do a stack walk for each and every class.
1277 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001278 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001279 }
Alex Light7532d582017-02-13 16:36:06 -08001280 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1281 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1282 // methods that have been jitted prior to the current redefinition being applied might continue
1283 // to use the old versions of the intrinsics!
Alex Lightdba61482016-12-21 08:20:29 -08001284 // TODO Shrink the obsolete method maps if possible?
Alex Light0e692732017-01-10 15:00:05 -08001285 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1286 // owns the DexFile and when ownership is transferred.
1287 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001288 return OK;
1289}
1290
Alex Light0e692732017-01-10 15:00:05 -08001291void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1292 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1293 const art::DexFile::ClassDef& class_def) {
1294 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001295 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001296 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001297 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001298 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001299 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1300 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1301 art::dex::TypeIndex method_return_idx =
1302 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1303 const auto* old_type_list = method.GetParameterTypeList();
1304 std::vector<art::dex::TypeIndex> new_type_list;
1305 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1306 new_type_list.push_back(
1307 dex_file_->GetIndexForTypeId(
1308 *dex_file_->FindTypeId(
1309 old_dex_file.GetTypeDescriptor(
1310 old_dex_file.GetTypeId(
1311 old_type_list->GetTypeItem(i).type_idx_)))));
1312 }
1313 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1314 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001315 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001316 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1317 *new_name_id,
1318 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001319 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001320 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1321 method.SetDexMethodIndex(dex_method_idx);
1322 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001323 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001324 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001325 // Clear all the intrinsics related flags.
1326 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001327 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001328 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001329 if (jit != nullptr) {
1330 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1331 }
Alex Lighta01de592016-11-15 10:43:06 -08001332 }
Alex Light200b9d72016-12-15 11:34:13 -08001333}
1334
Alex Light0e692732017-01-10 15:00:05 -08001335void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001336 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1337 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1338 for (art::ArtField& field : fields_iter) {
1339 std::string declaring_class_name;
1340 const art::DexFile::TypeId* new_declaring_id =
1341 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1342 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1343 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001344 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1345 const art::DexFile::FieldId* new_field_id =
1346 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1347 CHECK(new_field_id != nullptr);
1348 // We only need to update the index since the other data in the ArtField cannot be updated.
1349 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1350 }
1351 }
Alex Light200b9d72016-12-15 11:34:13 -08001352}
1353
1354// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001355void Redefiner::ClassRedefinition::UpdateClass(
1356 art::ObjPtr<art::mirror::Class> mclass,
1357 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001358 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001359 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1360 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1361 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001362 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001363
Alex Lighta01de592016-11-15 10:43:06 -08001364 // Update the class fields.
1365 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1366 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1367 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001368 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001369 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001370 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1371 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001372 ext->SetOriginalDexFile(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001373}
1374
Alex Lighta01de592016-11-15 10:43:06 -08001375// This function does all (java) allocations we need to do for the Class being redefined.
1376// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001377bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1378 art::StackHandleScope<2> hs(driver_->self_);
1379 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1380 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001381 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001382 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1383 return false;
1384 }
1385 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001386 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001387 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001388 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001389 driver_->self_->AssertPendingOOMException();
1390 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001391 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1392 return false;
1393 }
1394 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1395 // are only modified when all threads (other than the modifying one) are suspended we don't need
1396 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1397 // however, since that can happen at any time.
1398 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1399 // are no obsolete methods.
1400 {
Alex Light0e692732017-01-10 15:00:05 -08001401 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001402 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001403 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001404 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001405 driver_->self_->AssertPendingOOMException();
1406 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001407 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1408 return false;
1409 }
1410 }
1411 return true;
1412}
1413
1414} // namespace openjdkjvmti