blob: 95a1b007cafd28f4fd7fc5af653d5124a67cd029 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light5643caf2017-02-08 11:39:07 -080041#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000042#include "dex_file.h"
43#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080044#include "events-inl.h"
45#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080046#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "instrumentation.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "jdwp/jdwp.h"
49#include "jdwp/jdwp_constants.h"
50#include "jdwp/jdwp_event.h"
51#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080052#include "jit/jit.h"
53#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "jni_env_ext-inl.h"
55#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080056#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080057#include "mirror/class_ext.h"
58#include "mirror/object.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080059#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080060#include "object_lock.h"
61#include "runtime.h"
62#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080063#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080064#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080065#include "verifier/method_verifier.h"
66#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080067
68namespace openjdkjvmti {
69
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070using android::base::StringPrintf;
71
Alex Lighteee0bd42017-02-14 15:31:45 +000072// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
73// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
74// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
75class ObsoleteMap {
76 public:
77 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
78 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
79 auto method_pair = id_map_.find(original);
80 if (method_pair != id_map_.end()) {
81 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
82 method_pair->second, art::kRuntimePointerSize);
83 DCHECK(res != nullptr);
84 DCHECK_EQ(original, res->GetNonObsoleteMethod());
85 return res;
86 } else {
87 return nullptr;
88 }
89 }
90
91 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
92 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
93 DCHECK(original != nullptr);
94 DCHECK(obsolete != nullptr);
95 int32_t slot = next_free_slot_++;
96 DCHECK_LT(slot, obsolete_methods_->GetLength());
97 DCHECK(nullptr ==
98 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
99 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
100 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
101 obsolete_dex_caches_->Set(slot, original_dex_cache_);
102 id_map_.insert({original, slot});
103 }
104
105 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
106 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
107 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
108 : next_free_slot_(0),
109 obsolete_methods_(obsolete_methods),
110 obsolete_dex_caches_(obsolete_dex_caches),
111 original_dex_cache_(original_dex_cache) {
112 // Figure out where the first unused slot in the obsolete_methods_ array is.
113 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
114 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
115 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
116 next_free_slot_++;
117 }
118 // Sanity check that the same slot in obsolete_dex_caches_ is free.
119 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
120 }
121
122 private:
123 int32_t next_free_slot_;
124 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
125 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
126 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
127 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
128 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
129 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
130};
131
Alex Lightdba61482016-12-21 08:20:29 -0800132// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
133// some basic sanity checks that the obsolete method is sane.
134class ObsoleteMethodStackVisitor : public art::StackVisitor {
135 protected:
136 ObsoleteMethodStackVisitor(
137 art::Thread* thread,
138 art::LinearAlloc* allocator,
139 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000140 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800141 : StackVisitor(thread,
142 /*context*/nullptr,
143 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
144 allocator_(allocator),
145 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800146 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800147
148 ~ObsoleteMethodStackVisitor() OVERRIDE {}
149
150 public:
151 // Returns true if we successfully installed obsolete methods on this thread, filling
152 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
153 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800154 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800155 art::Thread* thread,
156 art::LinearAlloc* allocator,
157 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000158 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800159 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800160 ObsoleteMethodStackVisitor visitor(thread,
161 allocator,
162 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800163 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800164 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800165 }
166
167 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000168 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800169 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800170 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800171 // We cannot ensure that the right dex file is used in inlined frames so we don't support
172 // redefining them.
173 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000174 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
175 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800176 // Create a new Obsolete Method and put it in the list.
177 art::Runtime* runtime = art::Runtime::Current();
178 art::ClassLinker* cl = runtime->GetClassLinker();
179 auto ptr_size = cl->GetImagePointerSize();
180 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800181 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800182 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
183 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800184 new_obsolete_method = new (method_storage) art::ArtMethod();
185 new_obsolete_method->CopyFrom(old_method, ptr_size);
186 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
187 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800188 new_obsolete_method->SetDontCompile();
Alex Lighteee0bd42017-02-14 15:31:45 +0000189 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800190 // Update JIT Data structures to point to the new method.
191 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
192 if (jit != nullptr) {
193 // Notify the JIT we are making this obsolete method. It will update the jit's internal
194 // structures to keep track of the new obsolete method.
195 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
196 }
Alex Lightdba61482016-12-21 08:20:29 -0800197 }
198 DCHECK(new_obsolete_method != nullptr);
199 SetMethod(new_obsolete_method);
200 }
201 return true;
202 }
203
204 private:
205 // The linear allocator we should use to make new methods.
206 art::LinearAlloc* allocator_;
207 // The set of all methods which could be obsoleted.
208 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
209 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000210 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
211 // the redefined classes ClassExt as it is filled.
212 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800213};
214
Alex Lighte4a88632017-01-10 07:41:24 -0800215jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
216 jclass klass,
217 jboolean* is_redefinable) {
218 // TODO Check for the appropriate feature flags once we have enabled them.
219 art::Thread* self = art::Thread::Current();
220 art::ScopedObjectAccess soa(self);
221 art::StackHandleScope<1> hs(self);
222 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
223 if (obj.IsNull()) {
224 return ERR(INVALID_CLASS);
225 }
226 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
227 std::string err_unused;
228 *is_redefinable =
229 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
230 return OK;
231}
232
233jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
234 /*out*/std::string* error_msg) {
235 if (klass->IsPrimitive()) {
236 *error_msg = "Modification of primitive classes is not supported";
237 return ERR(UNMODIFIABLE_CLASS);
238 } else if (klass->IsInterface()) {
239 *error_msg = "Modification of Interface classes is currently not supported";
240 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800241 } else if (klass->IsStringClass()) {
242 *error_msg = "Modification of String class is not supported";
243 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800244 } else if (klass->IsArrayClass()) {
245 *error_msg = "Modification of Array classes is not supported";
246 return ERR(UNMODIFIABLE_CLASS);
247 } else if (klass->IsProxyClass()) {
248 *error_msg = "Modification of proxy classes is not supported";
249 return ERR(UNMODIFIABLE_CLASS);
250 }
251
Alex Lighte77b48b2017-02-22 11:08:06 -0800252 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
253 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
254 *error_msg = "Class might have stack frames that cannot be made obsolete";
255 return ERR(UNMODIFIABLE_CLASS);
256 }
257 }
258
Alex Lighte4a88632017-01-10 07:41:24 -0800259 return OK;
260}
261
Alex Lighta01de592016-11-15 10:43:06 -0800262// Moves dex data to an anonymous, read-only mmap'd region.
263std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
264 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800265 const unsigned char* dex_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,
270 data_len,
271 PROT_READ|PROT_WRITE,
272 /*low_4gb*/false,
273 /*reuse*/false,
274 error_msg));
275 if (map == nullptr) {
276 return map;
277 }
278 memcpy(map->Begin(), dex_data, data_len);
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;
347 def.dex_len = definitions[i].class_byte_count;
348 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
349 // We are definitely modified.
Alex Light40528472017-03-28 09:07:36 -0700350 def.SetRedefined();
Alex Lighta7e38d82017-01-19 14:57:28 -0800351 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
352 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800353 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
354 if (res != OK) {
355 return res;
356 }
357 def_vector.push_back(std::move(def));
358 }
359 // Call all the transformation events.
360 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800361 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800362 self,
363 &def_vector);
364 if (res != OK) {
365 // Something went wrong with transformation!
366 return res;
367 }
368 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
369}
370
371jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
372 art::Runtime* runtime,
373 art::Thread* self,
374 const std::vector<ArtClassDefinition>& definitions,
375 std::string* error_msg) {
376 DCHECK(env != nullptr);
377 if (definitions.size() == 0) {
378 // We don't actually need to do anything. Just return OK.
379 return OK;
380 }
Alex Light0e692732017-01-10 15:00:05 -0800381 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
382 // are going to redefine.
383 art::jit::ScopedJitSuspend suspend_jit;
384 // Get shared mutator lock so we can lock all the classes.
385 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800386 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800387 for (const ArtClassDefinition& def : definitions) {
388 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700389 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800390 jvmtiError res = r.AddRedefinition(env, def);
391 if (res != OK) {
392 return res;
393 }
Alex Light0e692732017-01-10 15:00:05 -0800394 }
395 }
396 return r.Run();
397}
398
Alex Light6ac57502017-01-19 15:05:06 -0800399jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800400 std::string original_dex_location;
401 jvmtiError ret = OK;
402 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
403 *error_msg_ = "Unable to get original dex file location!";
404 return ret;
405 }
Alex Light52a2db52017-01-19 23:00:21 +0000406 char* generic_ptr_unused = nullptr;
407 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800408 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
409 *error_msg_ = "Unable to get class signature!";
410 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000411 }
Andreas Gampe54711412017-02-21 12:41:43 -0800412 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
413 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800414 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
415 def.dex_len,
416 def.dex_data.get(),
417 error_msg_));
418 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800419 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800420 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800421 << "in dex file " << original_dex_location << " because: " << *error_msg_;
422 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800423 return ERR(OUT_OF_MEMORY);
424 }
425 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800426 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800427 return ERR(INVALID_CLASS_FORMAT);
428 }
429 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
430 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
431 checksum,
432 std::move(map),
433 /*verify*/true,
434 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800435 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800436 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800437 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800438 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800439 return ERR(INVALID_CLASS_FORMAT);
440 }
Alex Light0e692732017-01-10 15:00:05 -0800441 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800442 Redefiner::ClassRedefinition(this,
443 def.klass,
444 dex_file.release(),
445 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700446 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800447 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800448}
449
Alex Light0e692732017-01-10 15:00:05 -0800450art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
451 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800452}
453
Alex Light0e692732017-01-10 15:00:05 -0800454art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800455 return GetMirrorClass()->GetClassLoader();
456}
457
Alex Light0e692732017-01-10 15:00:05 -0800458art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
459 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000460 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800461}
462
Alex Light0e692732017-01-10 15:00:05 -0800463void Redefiner::RecordFailure(jvmtiError result,
464 const std::string& class_sig,
465 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800466 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800467 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800468 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800469 result_ = result;
470}
471
Alex Light2f814aa2017-03-24 15:21:34 +0000472art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800473 // If we have been specifically given a new set of bytes use that
474 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800475 return art::mirror::ByteArray::AllocateAndFill(
476 driver_->self_,
477 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
478 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800479 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800480
481 // See if we already have one set.
482 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
483 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000484 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
485 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800486 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000487 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800488 }
Alex Lighta01de592016-11-15 10:43:06 -0800489 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800490
Alex Light2f814aa2017-03-24 15:21:34 +0000491 // return the current dex_cache which has the dex file in it.
492 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800493 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000494 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800495 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
496 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800497 }
Alex Light2f814aa2017-03-24 15:21:34 +0000498 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800499}
500
Alex Lightdba61482016-12-21 08:20:29 -0800501struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000502 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800503 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800504 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800505
Alex Lighteee0bd42017-02-14 15:31:45 +0000506 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
507 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800508};
509
Alex Lightdba61482016-12-21 08:20:29 -0800510void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
511 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800512 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
513 data->allocator,
514 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000515 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800516}
517
518// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
519// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800520// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
521void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800522 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
523 art::mirror::ClassExt* ext = art_klass->GetExtData();
524 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800525 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000526 // This holds pointers to the obsolete methods map fields which are updated as needed.
527 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
528 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800529 // Add all the declared methods to the map
530 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800531 if (m.IsIntrinsic()) {
532 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
533 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
534 << "methods that have already been compiled.";
535 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000536 // It is possible to simply filter out some methods where they cannot really become obsolete,
537 // such as native methods and keep their original (possibly optimized) implementations. We don't
538 // do this, however, since we would need to mark these functions (still in the classes
539 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
540 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
541 // error checking from the interpreter which ensure we don't try to start executing obsolete
542 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000543 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800544 }
545 {
Alex Light0e692732017-01-10 15:00:05 -0800546 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800547 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
548 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800549 }
Alex Lightdba61482016-12-21 08:20:29 -0800550}
551
Alex Light6161f132017-01-25 10:30:20 -0800552// Try and get the declared method. First try to get a virtual method then a direct method if that's
553// not found.
554static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
555 const char* name,
556 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
557 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
558 if (m == nullptr) {
559 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
560 }
561 return m;
562}
563
564bool Redefiner::ClassRedefinition::CheckSameMethods() {
565 art::StackHandleScope<1> hs(driver_->self_);
566 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
567 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
568
569 art::ClassDataItemIterator new_iter(*dex_file_,
570 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
571
572 // Make sure we have the same number of methods.
573 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
574 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
575 if (num_new_method != num_old_method) {
576 bool bigger = num_new_method > num_old_method;
577 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
578 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
579 StringPrintf("Total number of declared methods changed from %d to %d",
580 num_old_method, num_new_method));
581 return false;
582 }
583
584 // Skip all of the fields. We should have already checked this.
585 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
586 new_iter.Next();
587 }
588 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
589 // files have the same number of methods, which means there must be an equal amount of additions
590 // and removals.
591 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
592 // Get the data on the method we are searching for
593 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
594 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
595 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
596 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
597 // If we got past the check for the same number of methods above that means there must be at
598 // least one added and one removed method. We will return the ADDED failure message since it is
599 // easier to get a useful error report for it.
600 if (old_method == nullptr) {
601 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
602 StringPrintf("Unknown method '%s' (sig: %s) was added!",
603 new_method_name,
604 new_method_signature.ToString().c_str()));
605 return false;
606 }
607 // Since direct methods have different flags than virtual ones (specifically direct methods must
608 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
609 // virtual to direct.
610 uint32_t new_flags = new_iter.GetMethodAccessFlags();
611 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
612 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
613 StringPrintf("method '%s' (sig: %s) had different access flags",
614 new_method_name,
615 new_method_signature.ToString().c_str()));
616 return false;
617 }
618 }
619 return true;
620}
621
622bool Redefiner::ClassRedefinition::CheckSameFields() {
623 art::StackHandleScope<1> hs(driver_->self_);
624 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
625 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
626 art::ClassDataItemIterator new_iter(*dex_file_,
627 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
628 const art::DexFile& old_dex_file = h_klass->GetDexFile();
629 art::ClassDataItemIterator old_iter(old_dex_file,
630 old_dex_file.GetClassData(*h_klass->GetClassDef()));
631 // Instance and static fields can be differentiated by their flags so no need to check them
632 // separately.
633 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
634 // Get the data on the method we are searching for
635 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
636 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
637 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
638
639 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
640 // We are missing the old version of this method!
641 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
642 StringPrintf("Unknown field '%s' (type: %s) added!",
643 new_field_name,
644 new_field_type));
645 return false;
646 }
647
648 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
649 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
650 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
651
652 // Check name and type.
653 if (strcmp(old_field_name, new_field_name) != 0 ||
654 strcmp(old_field_type, new_field_type) != 0) {
655 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
656 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
657 old_field_name,
658 old_field_type,
659 new_field_name,
660 new_field_type));
661 return false;
662 }
663
664 // Since static fields have different flags than instance ones (specifically static fields must
665 // have the kAccStatic flag) we can tell if a field changes from static to instance.
666 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
667 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
668 StringPrintf("Field '%s' (sig: %s) had different access flags",
669 new_field_name,
670 new_field_type));
671 return false;
672 }
673
674 new_iter.Next();
675 old_iter.Next();
676 }
677 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
678 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
679 StringPrintf("field '%s' (sig: %s) is missing!",
680 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
681 old_iter.GetMemberIndex())),
682 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
683 old_iter.GetMemberIndex()))));
684 return false;
685 }
686 return true;
687}
688
Alex Light0e692732017-01-10 15:00:05 -0800689bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800690 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000691 // Easy check that only 1 class def is present.
692 if (dex_file_->NumClassDefs() != 1) {
693 RecordFailure(ERR(ILLEGAL_ARGUMENT),
694 StringPrintf("Expected 1 class def in dex file but found %d",
695 dex_file_->NumClassDefs()));
696 return false;
697 }
698 // Get the ClassDef from the new DexFile.
699 // Since the dex file has only a single class def the index is always 0.
700 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
701 // Get the class as it is now.
702 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
703
704 // Check the access flags didn't change.
705 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
706 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
707 "Cannot change modifiers of class by redefinition");
708 return false;
709 }
710
711 // Check class name.
712 // These should have been checked by the dexfile verifier on load.
713 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
714 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
715 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
716 if (!current_class->DescriptorEquals(descriptor)) {
717 std::string storage;
718 RecordFailure(ERR(NAMES_DONT_MATCH),
719 StringPrintf("expected file to contain class called '%s' but found '%s'!",
720 current_class->GetDescriptor(&storage),
721 descriptor));
722 return false;
723 }
724 if (current_class->IsObjectClass()) {
725 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
726 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
727 return false;
728 }
729 } else {
730 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
731 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
732 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
733 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
734 return false;
735 }
736 }
737 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
738 if (interfaces == nullptr) {
739 if (current_class->NumDirectInterfaces() != 0) {
740 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
741 return false;
742 }
743 } else {
744 DCHECK(!current_class->IsProxyClass());
745 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
746 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
747 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
748 return false;
749 }
750 // The order of interfaces is (barely) meaningful so we error if it changes.
751 const art::DexFile& orig_dex_file = current_class->GetDexFile();
752 for (uint32_t i = 0; i < interfaces->Size(); i++) {
753 if (strcmp(
754 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
755 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
756 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
757 "Interfaces changed or re-ordered");
758 return false;
759 }
760 }
761 }
Alex Light460d1b42017-01-10 15:37:17 +0000762 return true;
763}
764
Alex Light0e692732017-01-10 15:00:05 -0800765bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800766 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800767 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000768
Alex Lighte4a88632017-01-10 07:41:24 -0800769 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
770 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
771 if (res != OK) {
772 RecordFailure(res, err);
773 return false;
774 } else {
775 return true;
776 }
Alex Light460d1b42017-01-10 15:37:17 +0000777}
778
Alex Light0e692732017-01-10 15:00:05 -0800779bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000780 return CheckRedefinable() &&
781 CheckClass() &&
782 CheckSameFields() &&
783 CheckSameMethods();
784}
785
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800786class RedefinitionDataIter;
787
Alex Light0e692732017-01-10 15:00:05 -0800788// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
789// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
790// having to deal with the fact that we need to hold an arbitrary number of references live.
791class RedefinitionDataHolder {
792 public:
793 enum DataSlot : int32_t {
794 kSlotSourceClassLoader = 0,
795 kSlotJavaDexFile = 1,
796 kSlotNewDexFileCookie = 2,
797 kSlotNewDexCache = 3,
798 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800799 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800800
801 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800802 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800803 };
804
805 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
806 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
807 // the passed in handle-scope.
808 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
809 art::Runtime* runtime,
810 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800811 std::vector<Redefiner::ClassRedefinition>* redefinitions)
812 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800813 arr_(
814 hs->NewHandle(
815 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
816 self,
817 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800818 redefinitions->size() * kNumSlots))),
819 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800820
821 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
822 return arr_.IsNull();
823 }
824
825 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800826 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800827 REQUIRES_SHARED(art::Locks::mutator_lock_) {
828 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
829 }
Alex Light8c889d22017-02-06 13:58:27 -0800830 art::mirror::Object* GetJavaDexFile(jint klass_index) const
831 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800832 return GetSlot(klass_index, kSlotJavaDexFile);
833 }
Alex Light8c889d22017-02-06 13:58:27 -0800834 art::mirror::LongArray* GetNewDexFileCookie(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::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
837 }
Alex Light8c889d22017-02-06 13:58:27 -0800838 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800839 REQUIRES_SHARED(art::Locks::mutator_lock_) {
840 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
841 }
Alex Light8c889d22017-02-06 13:58:27 -0800842 art::mirror::Class* GetMirrorClass(jint klass_index) const
843 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800844 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
845 }
846
Alex Light2f814aa2017-03-24 15:21:34 +0000847 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800848 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000849 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800850 }
851
Alex Light0e692732017-01-10 15:00:05 -0800852 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
853 REQUIRES_SHARED(art::Locks::mutator_lock_) {
854 SetSlot(klass_index, kSlotSourceClassLoader, loader);
855 }
856 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
857 REQUIRES_SHARED(art::Locks::mutator_lock_) {
858 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
859 }
860 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
861 REQUIRES_SHARED(art::Locks::mutator_lock_) {
862 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
863 }
864 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
865 REQUIRES_SHARED(art::Locks::mutator_lock_) {
866 SetSlot(klass_index, kSlotNewDexCache, cache);
867 }
868 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
869 REQUIRES_SHARED(art::Locks::mutator_lock_) {
870 SetSlot(klass_index, kSlotMirrorClass, klass);
871 }
Alex Light2f814aa2017-03-24 15:21:34 +0000872 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800873 REQUIRES_SHARED(art::Locks::mutator_lock_) {
874 SetSlot(klass_index, kSlotOrigDexFile, bytes);
875 }
Alex Light0e692732017-01-10 15:00:05 -0800876
Alex Light8c889d22017-02-06 13:58:27 -0800877 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800878 return arr_->GetLength() / kNumSlots;
879 }
880
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800881 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
882 REQUIRES_SHARED(art::Locks::mutator_lock_) {
883 return redefinitions_;
884 }
885
886 bool operator==(const RedefinitionDataHolder& other) const
887 REQUIRES_SHARED(art::Locks::mutator_lock_) {
888 return arr_.Get() == other.arr_.Get();
889 }
890
891 bool operator!=(const RedefinitionDataHolder& other) const
892 REQUIRES_SHARED(art::Locks::mutator_lock_) {
893 return !(*this == other);
894 }
895
896 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
897 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
898
Alex Light0e692732017-01-10 15:00:05 -0800899 private:
Alex Light8c889d22017-02-06 13:58:27 -0800900 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800901 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800902
903 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800904 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800905 DCHECK_LT(klass_index, Length());
906 return arr_->Get((kNumSlots * klass_index) + slot);
907 }
908
909 void SetSlot(jint klass_index,
910 DataSlot slot,
911 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
912 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
913 DCHECK_LT(klass_index, Length());
914 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
915 }
916
917 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
918};
919
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800920class RedefinitionDataIter {
921 public:
922 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
923
924 RedefinitionDataIter(const RedefinitionDataIter&) = default;
925 RedefinitionDataIter(RedefinitionDataIter&&) = default;
926 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
927 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
928
929 bool operator==(const RedefinitionDataIter& other) const
930 REQUIRES_SHARED(art::Locks::mutator_lock_) {
931 return idx_ == other.idx_ && holder_ == other.holder_;
932 }
933
934 bool operator!=(const RedefinitionDataIter& other) const
935 REQUIRES_SHARED(art::Locks::mutator_lock_) {
936 return !(*this == other);
937 }
938
939 RedefinitionDataIter operator++() { // Value after modification.
940 idx_++;
941 return *this;
942 }
943
944 RedefinitionDataIter operator++(int) {
945 RedefinitionDataIter temp = *this;
946 idx_++;
947 return temp;
948 }
949
950 RedefinitionDataIter operator+(ssize_t delta) const {
951 RedefinitionDataIter temp = *this;
952 temp += delta;
953 return temp;
954 }
955
956 RedefinitionDataIter& operator+=(ssize_t delta) {
957 idx_ += delta;
958 return *this;
959 }
960
961 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
962 return (*holder_.GetRedefinitions())[idx_];
963 }
964
965 RedefinitionDataHolder& GetHolder() {
966 return holder_;
967 }
968
969 art::mirror::ClassLoader* GetSourceClassLoader() const
970 REQUIRES_SHARED(art::Locks::mutator_lock_) {
971 return holder_.GetSourceClassLoader(idx_);
972 }
973 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
974 return holder_.GetJavaDexFile(idx_);
975 }
976 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
977 return holder_.GetNewDexFileCookie(idx_);
978 }
979 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
980 return holder_.GetNewDexCache(idx_);
981 }
982 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
983 return holder_.GetMirrorClass(idx_);
984 }
Alex Light2f814aa2017-03-24 15:21:34 +0000985 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800986 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000987 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800988 }
989 int32_t GetIndex() const {
990 return idx_;
991 }
992
993 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
994 REQUIRES_SHARED(art::Locks::mutator_lock_) {
995 holder_.SetSourceClassLoader(idx_, loader);
996 }
997 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
998 holder_.SetJavaDexFile(idx_, dexfile);
999 }
1000 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1001 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1002 holder_.SetNewDexFileCookie(idx_, cookie);
1003 }
1004 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1005 holder_.SetNewDexCache(idx_, cache);
1006 }
1007 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1008 holder_.SetMirrorClass(idx_, klass);
1009 }
Alex Light2f814aa2017-03-24 15:21:34 +00001010 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001011 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001012 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001013 }
1014
1015 private:
1016 int32_t idx_;
1017 RedefinitionDataHolder& holder_;
1018};
1019
1020RedefinitionDataIter RedefinitionDataHolder::begin() {
1021 return RedefinitionDataIter(0, *this);
1022}
1023
1024RedefinitionDataIter RedefinitionDataHolder::end() {
1025 return RedefinitionDataIter(Length(), *this);
1026}
1027
1028bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001029 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1030 art::StackHandleScope<2> hs(driver_->self_);
1031 std::string error;
1032 // TODO Make verification log level lower
1033 art::verifier::MethodVerifier::FailureKind failure =
1034 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1035 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001036 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001037 hs.NewHandle(GetClassLoader()),
1038 dex_file_->GetClassDef(0), /*class_def*/
1039 nullptr, /*compiler_callbacks*/
1040 false, /*allow_soft_failures*/
1041 /*log_level*/
1042 art::verifier::HardFailLogMode::kLogWarning,
1043 &error);
1044 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
1045 if (!passes) {
1046 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1047 }
1048 return passes;
1049}
1050
Alex Light1babae02017-02-01 15:35:34 -08001051// Looks through the previously allocated cookies to see if we need to update them with another new
1052// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1053// once they are all added to the classloader.
1054bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001055 art::Handle<art::mirror::ClassLoader> source_class_loader,
1056 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001057 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001058 art::StackHandleScope<2> hs(driver_->self_);
1059 art::MutableHandle<art::mirror::LongArray> old_cookie(
1060 hs.NewHandle<art::mirror::LongArray>(nullptr));
1061 bool has_older_cookie = false;
1062 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001063 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1064 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001065 // Since every instance of this classloader should have the same cookie associated with it we
1066 // can stop looking here.
1067 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001068 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001069 break;
1070 }
1071 }
1072 if (old_cookie.IsNull()) {
1073 // No older cookie. Get it directly from the dex_file_obj
1074 // We should not have seen this classloader elsewhere.
1075 CHECK(!has_older_cookie);
1076 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1077 }
1078 // Use the old cookie to generate the new one with the new DexFile* added in.
1079 art::Handle<art::mirror::LongArray>
1080 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1081 old_cookie,
1082 dex_file_.get())));
1083 // Make sure the allocation worked.
1084 if (new_cookie.IsNull()) {
1085 return false;
1086 }
1087
1088 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001089 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001090 // If there are other copies of this same classloader we need to make sure that we all have the
1091 // same cookie.
1092 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001093 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001094 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001095 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1096 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001097 }
1098 }
1099 }
1100
1101 return true;
1102}
1103
Alex Lighta7e38d82017-01-19 14:57:28 -08001104bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001105 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001106 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001107 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001108 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001109 // This shouldn't allocate
1110 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001111 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1112 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001113 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001114 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1115 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001116 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001117 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001118 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1119 return false;
1120 }
Alex Light1babae02017-02-01 15:35:34 -08001121 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001122 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001123 driver_->self_->AssertPendingOOMException();
1124 driver_->self_->ClearException();
1125 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1126 return false;
1127 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001128 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001129 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1130 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001131 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001132 driver_->self_->ClearException();
1133 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1134 return false;
1135 }
1136
1137 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001138 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1139 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001140 driver_->self_->AssertPendingOOMException();
1141 driver_->self_->ClearException();
1142 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1143 return false;
1144 }
1145 return true;
1146}
1147
Alex Light5643caf2017-02-08 11:39:07 -08001148void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1149 DCHECK(art::Dbg::IsDebuggerActive());
1150 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1151 if (state != nullptr) {
1152 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1153 }
1154}
1155
1156void Redefiner::UnregisterAllBreakpoints() {
1157 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1158 return;
1159 }
1160 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1161 redef.UnregisterBreakpoints();
1162 }
1163}
1164
Alex Light0e692732017-01-10 15:00:05 -08001165bool Redefiner::CheckAllRedefinitionAreValid() {
1166 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1167 if (!redef.CheckRedefinitionIsValid()) {
1168 return false;
1169 }
1170 }
1171 return true;
1172}
1173
1174bool Redefiner::EnsureAllClassAllocationsFinished() {
1175 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1176 if (!redef.EnsureClassAllocationsFinished()) {
1177 return false;
1178 }
1179 }
1180 return true;
1181}
1182
1183bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001184 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001185 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001186 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001187 return false;
1188 }
Alex Light0e692732017-01-10 15:00:05 -08001189 }
1190 return true;
1191}
1192
1193void Redefiner::ClassRedefinition::ReleaseDexFile() {
1194 dex_file_.release();
1195}
1196
1197void Redefiner::ReleaseAllDexFiles() {
1198 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1199 redef.ReleaseDexFile();
1200 }
1201}
1202
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001203bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1204 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1205 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001206 return false;
1207 }
Alex Light8c889d22017-02-06 13:58:27 -08001208 }
1209 return true;
1210}
1211
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001212class ScopedDisableConcurrentAndMovingGc {
1213 public:
1214 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1215 : heap_(heap), self_(self) {
1216 if (heap_->IsGcConcurrentAndMoving()) {
1217 heap_->IncrementDisableMovingGC(self_);
1218 }
1219 }
1220
1221 ~ScopedDisableConcurrentAndMovingGc() {
1222 if (heap_->IsGcConcurrentAndMoving()) {
1223 heap_->DecrementDisableMovingGC(self_);
1224 }
1225 }
1226 private:
1227 art::gc::Heap* heap_;
1228 art::Thread* self_;
1229};
1230
Alex Lighta01de592016-11-15 10:43:06 -08001231jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001232 art::StackHandleScope<1> hs(self_);
1233 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1234 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001235 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001236 if (holder.IsNull()) {
1237 self_->AssertPendingOOMException();
1238 self_->ClearException();
1239 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1240 return result_;
1241 }
1242
Alex Lighta01de592016-11-15 10:43:06 -08001243 // First we just allocate the ClassExt and its fields that we need. These can be updated
1244 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1245 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1246 // between allocating them and pausing all threads before we can update them so we need to do a
1247 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001248 if (!CheckAllRedefinitionAreValid() ||
1249 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001250 !FinishAllRemainingAllocations(holder) ||
1251 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001252 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1253 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001254 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1255 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001256 return result_;
1257 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001258
Alex Light5643caf2017-02-08 11:39:07 -08001259 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001260 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1261 if (data.GetSourceClassLoader() == nullptr) {
1262 runtime_->GetClassLinker()->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001263 }
Alex Light7916f202017-01-27 09:00:15 -08001264 }
Alex Light5643caf2017-02-08 11:39:07 -08001265 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001266
Alex Light6abd5392017-01-05 17:53:00 -08001267 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1268 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001269 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1270
Alex Lighta01de592016-11-15 10:43:06 -08001271 // Do transition to final suspension
1272 // TODO We might want to give this its own suspended state!
1273 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001274 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1275 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1276 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001277 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001278 ClassRedefinition& redef = data.GetRedefinition();
1279 if (data.GetSourceClassLoader() != nullptr) {
1280 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001281 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001282 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001283 // TODO Rewrite so we don't do a stack walk for each and every class.
1284 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001285 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001286 }
Alex Light7532d582017-02-13 16:36:06 -08001287 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1288 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1289 // methods that have been jitted prior to the current redefinition being applied might continue
1290 // to use the old versions of the intrinsics!
Alex Lightdba61482016-12-21 08:20:29 -08001291 // TODO Shrink the obsolete method maps if possible?
Alex Light0e692732017-01-10 15:00:05 -08001292 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1293 // owns the DexFile and when ownership is transferred.
1294 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001295 return OK;
1296}
1297
Alex Light0e692732017-01-10 15:00:05 -08001298void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1299 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1300 const art::DexFile::ClassDef& class_def) {
1301 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001302 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001303 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001304 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001305 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001306 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1307 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1308 art::dex::TypeIndex method_return_idx =
1309 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1310 const auto* old_type_list = method.GetParameterTypeList();
1311 std::vector<art::dex::TypeIndex> new_type_list;
1312 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1313 new_type_list.push_back(
1314 dex_file_->GetIndexForTypeId(
1315 *dex_file_->FindTypeId(
1316 old_dex_file.GetTypeDescriptor(
1317 old_dex_file.GetTypeId(
1318 old_type_list->GetTypeItem(i).type_idx_)))));
1319 }
1320 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1321 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001322 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001323 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1324 *new_name_id,
1325 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001326 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001327 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1328 method.SetDexMethodIndex(dex_method_idx);
1329 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001330 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001331 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001332 // Clear all the intrinsics related flags.
1333 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001334 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001335 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001336 if (jit != nullptr) {
1337 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1338 }
Alex Lighta01de592016-11-15 10:43:06 -08001339 }
Alex Light200b9d72016-12-15 11:34:13 -08001340}
1341
Alex Light0e692732017-01-10 15:00:05 -08001342void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001343 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1344 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1345 for (art::ArtField& field : fields_iter) {
1346 std::string declaring_class_name;
1347 const art::DexFile::TypeId* new_declaring_id =
1348 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1349 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1350 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001351 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1352 const art::DexFile::FieldId* new_field_id =
1353 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1354 CHECK(new_field_id != nullptr);
1355 // We only need to update the index since the other data in the ArtField cannot be updated.
1356 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1357 }
1358 }
Alex Light200b9d72016-12-15 11:34:13 -08001359}
1360
1361// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001362void Redefiner::ClassRedefinition::UpdateClass(
1363 art::ObjPtr<art::mirror::Class> mclass,
1364 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001365 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001366 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1367 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1368 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001369 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001370
Alex Lighta01de592016-11-15 10:43:06 -08001371 // Update the class fields.
1372 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1373 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1374 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001375 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001376 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001377 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1378 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001379 ext->SetOriginalDexFile(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001380}
1381
Alex Lighta01de592016-11-15 10:43:06 -08001382// This function does all (java) allocations we need to do for the Class being redefined.
1383// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001384bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1385 art::StackHandleScope<2> hs(driver_->self_);
1386 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1387 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001388 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001389 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1390 return false;
1391 }
1392 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001393 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001394 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001395 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001396 driver_->self_->AssertPendingOOMException();
1397 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001398 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1399 return false;
1400 }
1401 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1402 // are only modified when all threads (other than the modifying one) are suspended we don't need
1403 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1404 // however, since that can happen at any time.
1405 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1406 // are no obsolete methods.
1407 {
Alex Light0e692732017-01-10 15:00:05 -08001408 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001409 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001410 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001411 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001412 driver_->self_->AssertPendingOOMException();
1413 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001414 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1415 return false;
1416 }
1417 }
1418 return true;
1419}
1420
1421} // namespace openjdkjvmti