1 /* 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
36 #include <android-base/logging.h>
37 #include <android-base/stringprintf.h>
38
39 #include "art_field-inl.h"
40 #include "art_jvmti.h"
41 #include "art_method-inl.h"
42 #include "base/array_ref.h"
43 #include "base/stringpiece.h"
44 #include "class_linker-inl.h"
45 #include "debugger.h"
46 #include "dex/art_dex_file_loader.h"
47 #include "dex/dex_file.h"
48 #include "dex/dex_file_loader.h"
49 #include "dex/dex_file_types.h"
50 #include "events-inl.h"
51 #include "gc/allocation_listener.h"
52 #include "gc/heap.h"
53 #include "instrumentation.h"
54 #include "intern_table.h"
55 #include "jdwp/jdwp.h"
56 #include "jdwp/jdwp_constants.h"
57 #include "jdwp/jdwp_event.h"
58 #include "jdwp/object_registry.h"
59 #include "jit/jit.h"
60 #include "jit/jit_code_cache.h"
61 #include "jni_env_ext-inl.h"
62 #include "jvmti_allocator.h"
63 #include "mirror/class-inl.h"
64 #include "mirror/class_ext.h"
65 #include "mirror/object.h"
66 #include "nativehelper/scoped_local_ref.h"
67 #include "non_debuggable_classes.h"
68 #include "object_lock.h"
69 #include "runtime.h"
70 #include "ti_breakpoint.h"
71 #include "ti_class_loader.h"
72 #include "transform.h"
73 #include "verifier/method_verifier.h"
74 #include "verifier/verifier_enums.h"
75
76 namespace openjdkjvmti {
77
78 using android::base::StringPrintf;
79
80 // A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
81 // they are created. This ensures that we can always call any method of an obsolete ArtMethod object
82 // almost as soon as they are created since the GetObsoleteDexCache method will succeed.
83 class ObsoleteMap {
84 public:
FindObsoleteVersion(art::ArtMethod * original)85 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
86 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
87 auto method_pair = id_map_.find(original);
88 if (method_pair != id_map_.end()) {
89 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
90 method_pair->second, art::kRuntimePointerSize);
91 DCHECK(res != nullptr);
92 DCHECK_EQ(original, res->GetNonObsoleteMethod());
93 return res;
94 } else {
95 return nullptr;
96 }
97 }
98
RecordObsolete(art::ArtMethod * original,art::ArtMethod * obsolete)99 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
100 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
101 DCHECK(original != nullptr);
102 DCHECK(obsolete != nullptr);
103 int32_t slot = next_free_slot_++;
104 DCHECK_LT(slot, obsolete_methods_->GetLength());
105 DCHECK(nullptr ==
106 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
107 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
108 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
109 obsolete_dex_caches_->Set(slot, original_dex_cache_);
110 id_map_.insert({original, slot});
111 }
112
ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,art::ObjPtr<art::mirror::DexCache> original_dex_cache)113 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
114 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
115 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
116 : next_free_slot_(0),
117 obsolete_methods_(obsolete_methods),
118 obsolete_dex_caches_(obsolete_dex_caches),
119 original_dex_cache_(original_dex_cache) {
120 // Figure out where the first unused slot in the obsolete_methods_ array is.
121 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
122 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
123 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
124 next_free_slot_++;
125 }
126 // Sanity check that the same slot in obsolete_dex_caches_ is free.
127 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
128 }
129
130 private:
131 int32_t next_free_slot_;
132 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
133 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
134 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
135 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
136 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
137 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
138 };
139
140 // This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
141 // some basic sanity checks that the obsolete method is sane.
142 class ObsoleteMethodStackVisitor : public art::StackVisitor {
143 protected:
ObsoleteMethodStackVisitor(art::Thread * thread,art::LinearAlloc * allocator,const std::unordered_set<art::ArtMethod * > & obsoleted_methods,ObsoleteMap * obsolete_maps)144 ObsoleteMethodStackVisitor(
145 art::Thread* thread,
146 art::LinearAlloc* allocator,
147 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
148 ObsoleteMap* obsolete_maps)
149 : StackVisitor(thread,
150 /*context*/nullptr,
151 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
152 allocator_(allocator),
153 obsoleted_methods_(obsoleted_methods),
154 obsolete_maps_(obsolete_maps) { }
155
~ObsoleteMethodStackVisitor()156 ~ObsoleteMethodStackVisitor() OVERRIDE {}
157
158 public:
159 // Returns true if we successfully installed obsolete methods on this thread, filling
160 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
161 // The stack is cleaned up when we fail.
UpdateObsoleteFrames(art::Thread * thread,art::LinearAlloc * allocator,const std::unordered_set<art::ArtMethod * > & obsoleted_methods,ObsoleteMap * obsolete_maps)162 static void UpdateObsoleteFrames(
163 art::Thread* thread,
164 art::LinearAlloc* allocator,
165 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
166 ObsoleteMap* obsolete_maps)
167 REQUIRES(art::Locks::mutator_lock_) {
168 ObsoleteMethodStackVisitor visitor(thread,
169 allocator,
170 obsoleted_methods,
171 obsolete_maps);
172 visitor.WalkStack();
173 }
174
VisitFrame()175 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
176 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
177 art::ArtMethod* old_method = GetMethod();
178 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
179 // We cannot ensure that the right dex file is used in inlined frames so we don't support
180 // redefining them.
181 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
182 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
183 if (new_obsolete_method == nullptr) {
184 // Create a new Obsolete Method and put it in the list.
185 art::Runtime* runtime = art::Runtime::Current();
186 art::ClassLinker* cl = runtime->GetClassLinker();
187 auto ptr_size = cl->GetImagePointerSize();
188 const size_t method_size = art::ArtMethod::Size(ptr_size);
189 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
190 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
191 << old_method->PrettyMethod() << "'";
192 new_obsolete_method = new (method_storage) art::ArtMethod();
193 new_obsolete_method->CopyFrom(old_method, ptr_size);
194 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
195 new_obsolete_method->SetIsObsolete();
196 new_obsolete_method->SetDontCompile();
197 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
198 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
199 // Update JIT Data structures to point to the new method.
200 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
201 if (jit != nullptr) {
202 // Notify the JIT we are making this obsolete method. It will update the jit's internal
203 // structures to keep track of the new obsolete method.
204 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
205 }
206 }
207 DCHECK(new_obsolete_method != nullptr);
208 SetMethod(new_obsolete_method);
209 }
210 return true;
211 }
212
213 private:
214 // The linear allocator we should use to make new methods.
215 art::LinearAlloc* allocator_;
216 // The set of all methods which could be obsoleted.
217 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
218 // A map from the original to the newly allocated obsolete method for frames on this thread. The
219 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
220 // the redefined classes ClassExt as it is filled.
221 ObsoleteMap* obsolete_maps_;
222 };
223
IsModifiableClass(jvmtiEnv * env ATTRIBUTE_UNUSED,jclass klass,jboolean * is_redefinable)224 jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
225 jclass klass,
226 jboolean* is_redefinable) {
227 art::Thread* self = art::Thread::Current();
228 art::ScopedObjectAccess soa(self);
229 art::StackHandleScope<1> hs(self);
230 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
231 if (obj.IsNull()) {
232 return ERR(INVALID_CLASS);
233 }
234 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
235 std::string err_unused;
236 *is_redefinable =
237 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
238 ? JNI_TRUE : JNI_FALSE;
239 return OK;
240 }
241
GetClassRedefinitionError(jclass klass,std::string * error_msg)242 jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
243 art::Thread* self = art::Thread::Current();
244 art::ScopedObjectAccess soa(self);
245 art::StackHandleScope<1> hs(self);
246 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
247 if (obj.IsNull()) {
248 return ERR(INVALID_CLASS);
249 }
250 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
251 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
252 }
253
GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,std::string * error_msg)254 jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
255 /*out*/std::string* error_msg) {
256 if (!klass->IsResolved()) {
257 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
258 // the same thread as the class-linking process. If it's on another thread we will be able to
259 // wait for the preparation to finish and continue from there.
260 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
261 *error_msg = "Modification of class " + klass->PrettyClass() +
262 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
263 " Please use ClassFileLoadHook directly instead.";
264 return ERR(INTERNAL);
265 } else {
266 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
267 << "it could cause arbitrary length waits as the class is being resolved.";
268 }
269 }
270 if (klass->IsPrimitive()) {
271 *error_msg = "Modification of primitive classes is not supported";
272 return ERR(UNMODIFIABLE_CLASS);
273 } else if (klass->IsInterface()) {
274 *error_msg = "Modification of Interface classes is currently not supported";
275 return ERR(UNMODIFIABLE_CLASS);
276 } else if (klass->IsStringClass()) {
277 *error_msg = "Modification of String class is not supported";
278 return ERR(UNMODIFIABLE_CLASS);
279 } else if (klass->IsArrayClass()) {
280 *error_msg = "Modification of Array classes is not supported";
281 return ERR(UNMODIFIABLE_CLASS);
282 } else if (klass->IsProxyClass()) {
283 *error_msg = "Modification of proxy classes is not supported";
284 return ERR(UNMODIFIABLE_CLASS);
285 }
286
287 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
288 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
289 *error_msg = "Class might have stack frames that cannot be made obsolete";
290 return ERR(UNMODIFIABLE_CLASS);
291 }
292 }
293
294 return OK;
295 }
296
297 // Moves dex data to an anonymous, read-only mmap'd region.
MoveDataToMemMap(const std::string & original_location,art::ArrayRef<const unsigned char> data,std::string * error_msg)298 std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
299 art::ArrayRef<const unsigned char> data,
300 std::string* error_msg) {
301 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
302 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
303 nullptr,
304 data.size(),
305 PROT_READ|PROT_WRITE,
306 /*low_4gb*/false,
307 /*reuse*/false,
308 error_msg));
309 if (map == nullptr) {
310 return map;
311 }
312 memcpy(map->Begin(), data.data(), data.size());
313 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
314 // programs from corrupting it.
315 map->Protect(PROT_READ);
316 return map;
317 }
318
ClassRedefinition(Redefiner * driver,jclass klass,const art::DexFile * redefined_dex_file,const char * class_sig,art::ArrayRef<const unsigned char> orig_dex_file)319 Redefiner::ClassRedefinition::ClassRedefinition(
320 Redefiner* driver,
321 jclass klass,
322 const art::DexFile* redefined_dex_file,
323 const char* class_sig,
324 art::ArrayRef<const unsigned char> orig_dex_file) :
325 driver_(driver),
326 klass_(klass),
327 dex_file_(redefined_dex_file),
328 class_sig_(class_sig),
329 original_dex_file_(orig_dex_file) {
330 GetMirrorClass()->MonitorEnter(driver_->self_);
331 }
332
~ClassRedefinition()333 Redefiner::ClassRedefinition::~ClassRedefinition() {
334 if (driver_ != nullptr) {
335 GetMirrorClass()->MonitorExit(driver_->self_);
336 }
337 }
338
RedefineClasses(ArtJvmTiEnv * env,EventHandler * event_handler,art::Runtime * runtime,art::Thread * self,jint class_count,const jvmtiClassDefinition * definitions,std::string * error_msg)339 jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
340 EventHandler* event_handler,
341 art::Runtime* runtime,
342 art::Thread* self,
343 jint class_count,
344 const jvmtiClassDefinition* definitions,
345 /*out*/std::string* error_msg) {
346 if (env == nullptr) {
347 *error_msg = "env was null!";
348 return ERR(INVALID_ENVIRONMENT);
349 } else if (class_count < 0) {
350 *error_msg = "class_count was less then 0";
351 return ERR(ILLEGAL_ARGUMENT);
352 } else if (class_count == 0) {
353 // We don't actually need to do anything. Just return OK.
354 return OK;
355 } else if (definitions == nullptr) {
356 *error_msg = "null definitions!";
357 return ERR(NULL_POINTER);
358 }
359 std::vector<ArtClassDefinition> def_vector;
360 def_vector.reserve(class_count);
361 for (jint i = 0; i < class_count; i++) {
362 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
363 if (res != OK) {
364 return res;
365 }
366 // We make a copy of the class_bytes to pass into the retransformation.
367 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
368 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
369 // to get the passed in bytes.
370 unsigned char* class_bytes_copy = nullptr;
371 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
372 if (res != OK) {
373 return res;
374 }
375 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
376
377 ArtClassDefinition def;
378 res = def.Init(self, definitions[i]);
379 if (res != OK) {
380 return res;
381 }
382 def_vector.push_back(std::move(def));
383 }
384 // Call all the transformation events.
385 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
386 self,
387 &def_vector);
388 if (res != OK) {
389 // Something went wrong with transformation!
390 return res;
391 }
392 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
393 }
394
RedefineClassesDirect(ArtJvmTiEnv * env,art::Runtime * runtime,art::Thread * self,const std::vector<ArtClassDefinition> & definitions,std::string * error_msg)395 jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
396 art::Runtime* runtime,
397 art::Thread* self,
398 const std::vector<ArtClassDefinition>& definitions,
399 std::string* error_msg) {
400 DCHECK(env != nullptr);
401 if (definitions.size() == 0) {
402 // We don't actually need to do anything. Just return OK.
403 return OK;
404 }
405 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
406 // are going to redefine.
407 art::jit::ScopedJitSuspend suspend_jit;
408 // Get shared mutator lock so we can lock all the classes.
409 art::ScopedObjectAccess soa(self);
410 Redefiner r(env, runtime, self, error_msg);
411 for (const ArtClassDefinition& def : definitions) {
412 // Only try to transform classes that have been modified.
413 if (def.IsModified()) {
414 jvmtiError res = r.AddRedefinition(env, def);
415 if (res != OK) {
416 return res;
417 }
418 }
419 }
420 return r.Run();
421 }
422
AddRedefinition(ArtJvmTiEnv * env,const ArtClassDefinition & def)423 jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
424 std::string original_dex_location;
425 jvmtiError ret = OK;
426 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
427 *error_msg_ = "Unable to get original dex file location!";
428 return ret;
429 }
430 char* generic_ptr_unused = nullptr;
431 char* signature_ptr = nullptr;
432 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
433 *error_msg_ = "Unable to get class signature!";
434 return ret;
435 }
436 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
437 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
438 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
439 def.GetDexData(),
440 error_msg_));
441 std::ostringstream os;
442 if (map.get() == nullptr) {
443 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
444 << "in dex file " << original_dex_location << " because: " << *error_msg_;
445 *error_msg_ = os.str();
446 return ERR(OUT_OF_MEMORY);
447 }
448 if (map->Size() < sizeof(art::DexFile::Header)) {
449 *error_msg_ = "Could not read dex file header because dex_data was too short";
450 return ERR(INVALID_CLASS_FORMAT);
451 }
452 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
453 const art::ArtDexFileLoader dex_file_loader;
454 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map->GetName(),
455 checksum,
456 std::move(map),
457 /*verify*/true,
458 /*verify_checksum*/true,
459 error_msg_));
460 if (dex_file.get() == nullptr) {
461 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
462 *error_msg_ = os.str();
463 return ERR(INVALID_CLASS_FORMAT);
464 }
465 redefinitions_.push_back(
466 Redefiner::ClassRedefinition(this,
467 def.GetClass(),
468 dex_file.release(),
469 signature_ptr,
470 def.GetNewOriginalDexFile()));
471 return OK;
472 }
473
GetMirrorClass()474 art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
475 return driver_->self_->DecodeJObject(klass_)->AsClass();
476 }
477
GetClassLoader()478 art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
479 return GetMirrorClass()->GetClassLoader();
480 }
481
CreateNewDexCache(art::Handle<art::mirror::ClassLoader> loader)482 art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
483 art::Handle<art::mirror::ClassLoader> loader) {
484 art::StackHandleScope<2> hs(driver_->self_);
485 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
486 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
487 art::ObjPtr<art::mirror::DexCache>::DownCast(
488 cl->GetClassRoot(art::ClassLinker::kJavaLangDexCache)->AllocObject(driver_->self_))));
489 if (cache.IsNull()) {
490 driver_->self_->AssertPendingOOMException();
491 return nullptr;
492 }
493 art::Handle<art::mirror::String> location(hs.NewHandle(
494 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
495 if (location.IsNull()) {
496 driver_->self_->AssertPendingOOMException();
497 return nullptr;
498 }
499 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
500 art::mirror::DexCache::InitializeDexCache(driver_->self_,
501 cache.Get(),
502 location.Get(),
503 dex_file_.get(),
504 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
505 : loader->GetAllocator(),
506 art::kRuntimePointerSize);
507 return cache.Get();
508 }
509
RecordFailure(jvmtiError result,const std::string & class_sig,const std::string & error_msg)510 void Redefiner::RecordFailure(jvmtiError result,
511 const std::string& class_sig,
512 const std::string& error_msg) {
513 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
514 class_sig.c_str(),
515 error_msg.c_str());
516 result_ = result;
517 }
518
AllocateOrGetOriginalDexFile()519 art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
520 // If we have been specifically given a new set of bytes use that
521 if (original_dex_file_.size() != 0) {
522 return art::mirror::ByteArray::AllocateAndFill(
523 driver_->self_,
524 reinterpret_cast<const signed char*>(original_dex_file_.data()),
525 original_dex_file_.size());
526 }
527
528 // See if we already have one set.
529 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
530 if (!ext.IsNull()) {
531 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
532 if (!old_original_dex_file.IsNull()) {
533 // We do. Use it.
534 return old_original_dex_file.Ptr();
535 }
536 }
537
538 // return the current dex_cache which has the dex file in it.
539 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
540 // TODO Handle this or make it so it cannot happen.
541 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
542 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
543 << "on this class might fail if no transformations are applied to it!";
544 }
545 return current_dex_cache.Ptr();
546 }
547
548 struct CallbackCtx {
549 ObsoleteMap* obsolete_map;
550 art::LinearAlloc* allocator;
551 std::unordered_set<art::ArtMethod*> obsolete_methods;
552
CallbackCtxopenjdkjvmti::CallbackCtx553 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
554 : obsolete_map(map), allocator(alloc) {}
555 };
556
DoAllocateObsoleteMethodsCallback(art::Thread * t,void * vdata)557 void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
558 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
559 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
560 data->allocator,
561 data->obsolete_methods,
562 data->obsolete_map);
563 }
564
565 // This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
566 // updated so they will be run.
567 // TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
FindAndAllocateObsoleteMethods(art::mirror::Class * art_klass)568 void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
569 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
570 art::mirror::ClassExt* ext = art_klass->GetExtData();
571 CHECK(ext->GetObsoleteMethods() != nullptr);
572 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
573 // This holds pointers to the obsolete methods map fields which are updated as needed.
574 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
575 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
576 // Add all the declared methods to the map
577 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
578 if (m.IsIntrinsic()) {
579 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
580 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
581 << "methods that have already been compiled.";
582 }
583 // It is possible to simply filter out some methods where they cannot really become obsolete,
584 // such as native methods and keep their original (possibly optimized) implementations. We don't
585 // do this, however, since we would need to mark these functions (still in the classes
586 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
587 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
588 // error checking from the interpreter which ensure we don't try to start executing obsolete
589 // methods.
590 ctx.obsolete_methods.insert(&m);
591 }
592 {
593 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
594 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
595 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
596 }
597 }
598
599 // Try and get the declared method. First try to get a virtual method then a direct method if that's
600 // not found.
FindMethod(art::Handle<art::mirror::Class> klass,art::StringPiece name,art::Signature sig)601 static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
602 art::StringPiece name,
603 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
604 DCHECK(!klass->IsProxyClass());
605 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
606 if (m.GetName() == name && m.GetSignature() == sig) {
607 return &m;
608 }
609 }
610 return nullptr;
611 }
612
CheckSameMethods()613 bool Redefiner::ClassRedefinition::CheckSameMethods() {
614 art::StackHandleScope<1> hs(driver_->self_);
615 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
616 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
617
618 art::ClassDataItemIterator new_iter(*dex_file_,
619 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
620
621 // Make sure we have the same number of methods.
622 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
623 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
624 if (num_new_method != num_old_method) {
625 bool bigger = num_new_method > num_old_method;
626 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
627 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
628 StringPrintf("Total number of declared methods changed from %d to %d",
629 num_old_method, num_new_method));
630 return false;
631 }
632
633 // Skip all of the fields. We should have already checked this.
634 new_iter.SkipAllFields();
635 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
636 // files have the same number of methods, which means there must be an equal amount of additions
637 // and removals.
638 for (; new_iter.HasNextMethod(); new_iter.Next()) {
639 // Get the data on the method we are searching for
640 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
641 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
642 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
643 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
644 // If we got past the check for the same number of methods above that means there must be at
645 // least one added and one removed method. We will return the ADDED failure message since it is
646 // easier to get a useful error report for it.
647 if (old_method == nullptr) {
648 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
649 StringPrintf("Unknown method '%s' (sig: %s) was added!",
650 new_method_name,
651 new_method_signature.ToString().c_str()));
652 return false;
653 }
654 // Since direct methods have different flags than virtual ones (specifically direct methods must
655 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
656 // virtual to direct.
657 uint32_t new_flags = new_iter.GetMethodAccessFlags();
658 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
659 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
660 StringPrintf("method '%s' (sig: %s) had different access flags",
661 new_method_name,
662 new_method_signature.ToString().c_str()));
663 return false;
664 }
665 }
666 return true;
667 }
668
CheckSameFields()669 bool Redefiner::ClassRedefinition::CheckSameFields() {
670 art::StackHandleScope<1> hs(driver_->self_);
671 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
672 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
673 art::ClassDataItemIterator new_iter(*dex_file_,
674 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
675 const art::DexFile& old_dex_file = h_klass->GetDexFile();
676 art::ClassDataItemIterator old_iter(old_dex_file,
677 old_dex_file.GetClassData(*h_klass->GetClassDef()));
678 // Instance and static fields can be differentiated by their flags so no need to check them
679 // separately.
680 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
681 // Get the data on the method we are searching for
682 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
683 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
684 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
685
686 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
687 // We are missing the old version of this method!
688 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
689 StringPrintf("Unknown field '%s' (type: %s) added!",
690 new_field_name,
691 new_field_type));
692 return false;
693 }
694
695 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
696 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
697 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
698
699 // Check name and type.
700 if (strcmp(old_field_name, new_field_name) != 0 ||
701 strcmp(old_field_type, new_field_type) != 0) {
702 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
703 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
704 old_field_name,
705 old_field_type,
706 new_field_name,
707 new_field_type));
708 return false;
709 }
710
711 // Since static fields have different flags than instance ones (specifically static fields must
712 // have the kAccStatic flag) we can tell if a field changes from static to instance.
713 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
714 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
715 StringPrintf("Field '%s' (sig: %s) had different access flags",
716 new_field_name,
717 new_field_type));
718 return false;
719 }
720
721 new_iter.Next();
722 old_iter.Next();
723 }
724 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
725 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
726 StringPrintf("field '%s' (sig: %s) is missing!",
727 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
728 old_iter.GetMemberIndex())),
729 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
730 old_iter.GetMemberIndex()))));
731 return false;
732 }
733 return true;
734 }
735
CheckClass()736 bool Redefiner::ClassRedefinition::CheckClass() {
737 art::StackHandleScope<1> hs(driver_->self_);
738 // Easy check that only 1 class def is present.
739 if (dex_file_->NumClassDefs() != 1) {
740 RecordFailure(ERR(ILLEGAL_ARGUMENT),
741 StringPrintf("Expected 1 class def in dex file but found %d",
742 dex_file_->NumClassDefs()));
743 return false;
744 }
745 // Get the ClassDef from the new DexFile.
746 // Since the dex file has only a single class def the index is always 0.
747 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
748 // Get the class as it is now.
749 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
750
751 // Check the access flags didn't change.
752 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
753 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
754 "Cannot change modifiers of class by redefinition");
755 return false;
756 }
757
758 // Check class name.
759 // These should have been checked by the dexfile verifier on load.
760 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
761 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
762 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
763 if (!current_class->DescriptorEquals(descriptor)) {
764 std::string storage;
765 RecordFailure(ERR(NAMES_DONT_MATCH),
766 StringPrintf("expected file to contain class called '%s' but found '%s'!",
767 current_class->GetDescriptor(&storage),
768 descriptor));
769 return false;
770 }
771 if (current_class->IsObjectClass()) {
772 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
773 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
774 return false;
775 }
776 } else {
777 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
778 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
779 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
780 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
781 return false;
782 }
783 }
784 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
785 if (interfaces == nullptr) {
786 if (current_class->NumDirectInterfaces() != 0) {
787 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
788 return false;
789 }
790 } else {
791 DCHECK(!current_class->IsProxyClass());
792 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
793 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
794 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
795 return false;
796 }
797 // The order of interfaces is (barely) meaningful so we error if it changes.
798 const art::DexFile& orig_dex_file = current_class->GetDexFile();
799 for (uint32_t i = 0; i < interfaces->Size(); i++) {
800 if (strcmp(
801 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
802 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
803 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
804 "Interfaces changed or re-ordered");
805 return false;
806 }
807 }
808 }
809 return true;
810 }
811
CheckRedefinable()812 bool Redefiner::ClassRedefinition::CheckRedefinable() {
813 std::string err;
814 art::StackHandleScope<1> hs(driver_->self_);
815
816 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
817 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
818 if (res != OK) {
819 RecordFailure(res, err);
820 return false;
821 } else {
822 return true;
823 }
824 }
825
CheckRedefinitionIsValid()826 bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
827 return CheckRedefinable() &&
828 CheckClass() &&
829 CheckSameFields() &&
830 CheckSameMethods();
831 }
832
833 class RedefinitionDataIter;
834
835 // A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
836 // reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
837 // having to deal with the fact that we need to hold an arbitrary number of references live.
838 class RedefinitionDataHolder {
839 public:
840 enum DataSlot : int32_t {
841 kSlotSourceClassLoader = 0,
842 kSlotJavaDexFile = 1,
843 kSlotNewDexFileCookie = 2,
844 kSlotNewDexCache = 3,
845 kSlotMirrorClass = 4,
846 kSlotOrigDexFile = 5,
847 kSlotOldObsoleteMethods = 6,
848 kSlotOldDexCaches = 7,
849
850 // Must be last one.
851 kNumSlots = 8,
852 };
853
854 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
855 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
856 // the passed in handle-scope.
RedefinitionDataHolder(art::StackHandleScope<1> * hs,art::Runtime * runtime,art::Thread * self,std::vector<Redefiner::ClassRedefinition> * redefinitions)857 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
858 art::Runtime* runtime,
859 art::Thread* self,
860 std::vector<Redefiner::ClassRedefinition>* redefinitions)
861 REQUIRES_SHARED(art::Locks::mutator_lock_) :
862 arr_(
863 hs->NewHandle(
864 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
865 self,
866 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
867 redefinitions->size() * kNumSlots))),
868 redefinitions_(redefinitions) {}
869
IsNull() const870 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
871 return arr_.IsNull();
872 }
873
GetSourceClassLoader(jint klass_index) const874 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
875 REQUIRES_SHARED(art::Locks::mutator_lock_) {
876 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
877 }
GetJavaDexFile(jint klass_index) const878 art::mirror::Object* GetJavaDexFile(jint klass_index) const
879 REQUIRES_SHARED(art::Locks::mutator_lock_) {
880 return GetSlot(klass_index, kSlotJavaDexFile);
881 }
GetNewDexFileCookie(jint klass_index) const882 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
883 REQUIRES_SHARED(art::Locks::mutator_lock_) {
884 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
885 }
GetNewDexCache(jint klass_index) const886 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
887 REQUIRES_SHARED(art::Locks::mutator_lock_) {
888 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
889 }
GetMirrorClass(jint klass_index) const890 art::mirror::Class* GetMirrorClass(jint klass_index) const
891 REQUIRES_SHARED(art::Locks::mutator_lock_) {
892 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
893 }
894
GetOriginalDexFile(jint klass_index) const895 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
896 REQUIRES_SHARED(art::Locks::mutator_lock_) {
897 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
898 }
899
GetOldObsoleteMethods(jint klass_index) const900 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
901 REQUIRES_SHARED(art::Locks::mutator_lock_) {
902 return art::down_cast<art::mirror::PointerArray*>(
903 GetSlot(klass_index, kSlotOldObsoleteMethods));
904 }
905
GetOldDexCaches(jint klass_index) const906 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
907 REQUIRES_SHARED(art::Locks::mutator_lock_) {
908 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
909 GetSlot(klass_index, kSlotOldDexCaches));
910 }
911
SetSourceClassLoader(jint klass_index,art::mirror::ClassLoader * loader)912 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
913 REQUIRES_SHARED(art::Locks::mutator_lock_) {
914 SetSlot(klass_index, kSlotSourceClassLoader, loader);
915 }
SetJavaDexFile(jint klass_index,art::mirror::Object * dexfile)916 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
917 REQUIRES_SHARED(art::Locks::mutator_lock_) {
918 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
919 }
SetNewDexFileCookie(jint klass_index,art::mirror::LongArray * cookie)920 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
921 REQUIRES_SHARED(art::Locks::mutator_lock_) {
922 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
923 }
SetNewDexCache(jint klass_index,art::mirror::DexCache * cache)924 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
925 REQUIRES_SHARED(art::Locks::mutator_lock_) {
926 SetSlot(klass_index, kSlotNewDexCache, cache);
927 }
SetMirrorClass(jint klass_index,art::mirror::Class * klass)928 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
929 REQUIRES_SHARED(art::Locks::mutator_lock_) {
930 SetSlot(klass_index, kSlotMirrorClass, klass);
931 }
SetOriginalDexFile(jint klass_index,art::mirror::Object * bytes)932 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
933 REQUIRES_SHARED(art::Locks::mutator_lock_) {
934 SetSlot(klass_index, kSlotOrigDexFile, bytes);
935 }
SetOldObsoleteMethods(jint klass_index,art::mirror::PointerArray * methods)936 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
937 REQUIRES_SHARED(art::Locks::mutator_lock_) {
938 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
939 }
SetOldDexCaches(jint klass_index,art::mirror::ObjectArray<art::mirror::DexCache> * caches)940 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
941 REQUIRES_SHARED(art::Locks::mutator_lock_) {
942 SetSlot(klass_index, kSlotOldDexCaches, caches);
943 }
944
Length() const945 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
946 return arr_->GetLength() / kNumSlots;
947 }
948
GetRedefinitions()949 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
950 REQUIRES_SHARED(art::Locks::mutator_lock_) {
951 return redefinitions_;
952 }
953
operator ==(const RedefinitionDataHolder & other) const954 bool operator==(const RedefinitionDataHolder& other) const
955 REQUIRES_SHARED(art::Locks::mutator_lock_) {
956 return arr_.Get() == other.arr_.Get();
957 }
958
operator !=(const RedefinitionDataHolder & other) const959 bool operator!=(const RedefinitionDataHolder& other) const
960 REQUIRES_SHARED(art::Locks::mutator_lock_) {
961 return !(*this == other);
962 }
963
964 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
965 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
966
967 private:
968 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
969 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
970
GetSlot(jint klass_index,DataSlot slot) const971 art::mirror::Object* GetSlot(jint klass_index,
972 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
973 DCHECK_LT(klass_index, Length());
974 return arr_->Get((kNumSlots * klass_index) + slot);
975 }
976
SetSlot(jint klass_index,DataSlot slot,art::ObjPtr<art::mirror::Object> obj)977 void SetSlot(jint klass_index,
978 DataSlot slot,
979 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
980 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
981 DCHECK_LT(klass_index, Length());
982 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
983 }
984
985 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
986 };
987
988 class RedefinitionDataIter {
989 public:
RedefinitionDataIter(int32_t idx,RedefinitionDataHolder & holder)990 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
991
992 RedefinitionDataIter(const RedefinitionDataIter&) = default;
993 RedefinitionDataIter(RedefinitionDataIter&&) = default;
994 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
995 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
996
operator ==(const RedefinitionDataIter & other) const997 bool operator==(const RedefinitionDataIter& other) const
998 REQUIRES_SHARED(art::Locks::mutator_lock_) {
999 return idx_ == other.idx_ && holder_ == other.holder_;
1000 }
1001
operator !=(const RedefinitionDataIter & other) const1002 bool operator!=(const RedefinitionDataIter& other) const
1003 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1004 return !(*this == other);
1005 }
1006
operator ++()1007 RedefinitionDataIter operator++() { // Value after modification.
1008 idx_++;
1009 return *this;
1010 }
1011
operator ++(int)1012 RedefinitionDataIter operator++(int) {
1013 RedefinitionDataIter temp = *this;
1014 idx_++;
1015 return temp;
1016 }
1017
operator +(ssize_t delta) const1018 RedefinitionDataIter operator+(ssize_t delta) const {
1019 RedefinitionDataIter temp = *this;
1020 temp += delta;
1021 return temp;
1022 }
1023
operator +=(ssize_t delta)1024 RedefinitionDataIter& operator+=(ssize_t delta) {
1025 idx_ += delta;
1026 return *this;
1027 }
1028
GetRedefinition()1029 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1030 return (*holder_.GetRedefinitions())[idx_];
1031 }
1032
GetHolder()1033 RedefinitionDataHolder& GetHolder() {
1034 return holder_;
1035 }
1036
GetSourceClassLoader() const1037 art::mirror::ClassLoader* GetSourceClassLoader() const
1038 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1039 return holder_.GetSourceClassLoader(idx_);
1040 }
GetJavaDexFile() const1041 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1042 return holder_.GetJavaDexFile(idx_);
1043 }
GetNewDexFileCookie() const1044 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1045 return holder_.GetNewDexFileCookie(idx_);
1046 }
GetNewDexCache() const1047 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1048 return holder_.GetNewDexCache(idx_);
1049 }
GetMirrorClass() const1050 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1051 return holder_.GetMirrorClass(idx_);
1052 }
GetOriginalDexFile() const1053 art::mirror::Object* GetOriginalDexFile() const
1054 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1055 return holder_.GetOriginalDexFile(idx_);
1056 }
GetOldObsoleteMethods() const1057 art::mirror::PointerArray* GetOldObsoleteMethods() const
1058 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1059 return holder_.GetOldObsoleteMethods(idx_);
1060 }
GetOldDexCaches() const1061 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1062 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1063 return holder_.GetOldDexCaches(idx_);
1064 }
1065
GetIndex() const1066 int32_t GetIndex() const {
1067 return idx_;
1068 }
1069
SetSourceClassLoader(art::mirror::ClassLoader * loader)1070 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1071 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1072 holder_.SetSourceClassLoader(idx_, loader);
1073 }
SetJavaDexFile(art::mirror::Object * dexfile)1074 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1075 holder_.SetJavaDexFile(idx_, dexfile);
1076 }
SetNewDexFileCookie(art::mirror::LongArray * cookie)1077 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1078 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1079 holder_.SetNewDexFileCookie(idx_, cookie);
1080 }
SetNewDexCache(art::mirror::DexCache * cache)1081 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1082 holder_.SetNewDexCache(idx_, cache);
1083 }
SetMirrorClass(art::mirror::Class * klass)1084 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1085 holder_.SetMirrorClass(idx_, klass);
1086 }
SetOriginalDexFile(art::mirror::Object * bytes)1087 void SetOriginalDexFile(art::mirror::Object* bytes)
1088 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1089 holder_.SetOriginalDexFile(idx_, bytes);
1090 }
SetOldObsoleteMethods(art::mirror::PointerArray * methods)1091 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1092 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1093 holder_.SetOldObsoleteMethods(idx_, methods);
1094 }
SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache> * caches)1095 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1096 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1097 holder_.SetOldDexCaches(idx_, caches);
1098 }
1099
1100 private:
1101 int32_t idx_;
1102 RedefinitionDataHolder& holder_;
1103 };
1104
begin()1105 RedefinitionDataIter RedefinitionDataHolder::begin() {
1106 return RedefinitionDataIter(0, *this);
1107 }
1108
end()1109 RedefinitionDataIter RedefinitionDataHolder::end() {
1110 return RedefinitionDataIter(Length(), *this);
1111 }
1112
CheckVerification(const RedefinitionDataIter & iter)1113 bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
1114 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1115 art::StackHandleScope<2> hs(driver_->self_);
1116 std::string error;
1117 // TODO Make verification log level lower
1118 art::verifier::FailureKind failure =
1119 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1120 dex_file_.get(),
1121 hs.NewHandle(iter.GetNewDexCache()),
1122 hs.NewHandle(GetClassLoader()),
1123 dex_file_->GetClassDef(0), /*class_def*/
1124 nullptr, /*compiler_callbacks*/
1125 true, /*allow_soft_failures*/
1126 /*log_level*/
1127 art::verifier::HardFailLogMode::kLogWarning,
1128 &error);
1129 switch (failure) {
1130 case art::verifier::FailureKind::kNoFailure:
1131 case art::verifier::FailureKind::kSoftFailure:
1132 return true;
1133 case art::verifier::FailureKind::kHardFailure: {
1134 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1135 return false;
1136 }
1137 }
1138 }
1139
1140 // Looks through the previously allocated cookies to see if we need to update them with another new
1141 // dexfile. This is so that even if multiple classes with the same classloader are redefined at
1142 // once they are all added to the classloader.
AllocateAndRememberNewDexFileCookie(art::Handle<art::mirror::ClassLoader> source_class_loader,art::Handle<art::mirror::Object> dex_file_obj,RedefinitionDataIter * cur_data)1143 bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
1144 art::Handle<art::mirror::ClassLoader> source_class_loader,
1145 art::Handle<art::mirror::Object> dex_file_obj,
1146 /*out*/RedefinitionDataIter* cur_data) {
1147 art::StackHandleScope<2> hs(driver_->self_);
1148 art::MutableHandle<art::mirror::LongArray> old_cookie(
1149 hs.NewHandle<art::mirror::LongArray>(nullptr));
1150 bool has_older_cookie = false;
1151 // See if we already have a cookie that a previous redefinition got from the same classloader.
1152 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1153 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1154 // Since every instance of this classloader should have the same cookie associated with it we
1155 // can stop looking here.
1156 has_older_cookie = true;
1157 old_cookie.Assign(old_data.GetNewDexFileCookie());
1158 break;
1159 }
1160 }
1161 if (old_cookie.IsNull()) {
1162 // No older cookie. Get it directly from the dex_file_obj
1163 // We should not have seen this classloader elsewhere.
1164 CHECK(!has_older_cookie);
1165 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1166 }
1167 // Use the old cookie to generate the new one with the new DexFile* added in.
1168 art::Handle<art::mirror::LongArray>
1169 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1170 old_cookie,
1171 dex_file_.get())));
1172 // Make sure the allocation worked.
1173 if (new_cookie.IsNull()) {
1174 return false;
1175 }
1176
1177 // Save the cookie.
1178 cur_data->SetNewDexFileCookie(new_cookie.Get());
1179 // If there are other copies of this same classloader we need to make sure that we all have the
1180 // same cookie.
1181 if (has_older_cookie) {
1182 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1183 // We will let the GC take care of the cookie we allocated for this one.
1184 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1185 old_data.SetNewDexFileCookie(new_cookie.Get());
1186 }
1187 }
1188 }
1189
1190 return true;
1191 }
1192
FinishRemainingAllocations(RedefinitionDataIter * cur_data)1193 bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
1194 /*out*/RedefinitionDataIter* cur_data) {
1195 art::ScopedObjectAccessUnchecked soa(driver_->self_);
1196 art::StackHandleScope<2> hs(driver_->self_);
1197 cur_data->SetMirrorClass(GetMirrorClass());
1198 // This shouldn't allocate
1199 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
1200 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1201 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
1202 cur_data->SetSourceClassLoader(loader.Get());
1203 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1204 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
1205 cur_data->SetJavaDexFile(dex_file_obj.Get());
1206 if (dex_file_obj == nullptr) {
1207 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1208 return false;
1209 }
1210 // Allocate the new dex file cookie.
1211 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
1212 driver_->self_->AssertPendingOOMException();
1213 driver_->self_->ClearException();
1214 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1215 return false;
1216 }
1217 }
1218 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1219 if (cur_data->GetNewDexCache() == nullptr) {
1220 driver_->self_->AssertPendingException();
1221 driver_->self_->ClearException();
1222 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1223 return false;
1224 }
1225
1226 // We won't always need to set this field.
1227 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1228 if (cur_data->GetOriginalDexFile() == nullptr) {
1229 driver_->self_->AssertPendingOOMException();
1230 driver_->self_->ClearException();
1231 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1232 return false;
1233 }
1234 return true;
1235 }
1236
UnregisterJvmtiBreakpoints()1237 void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
1238 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass());
1239 }
1240
UnregisterBreakpoints()1241 void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1242 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1243 return;
1244 }
1245 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1246 if (state != nullptr) {
1247 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1248 }
1249 }
1250
UnregisterAllBreakpoints()1251 void Redefiner::UnregisterAllBreakpoints() {
1252 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1253 redef.UnregisterBreakpoints();
1254 redef.UnregisterJvmtiBreakpoints();
1255 }
1256 }
1257
CheckAllRedefinitionAreValid()1258 bool Redefiner::CheckAllRedefinitionAreValid() {
1259 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1260 if (!redef.CheckRedefinitionIsValid()) {
1261 return false;
1262 }
1263 }
1264 return true;
1265 }
1266
RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder & holder)1267 void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1268 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1269 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1270 }
1271 }
1272
EnsureAllClassAllocationsFinished(RedefinitionDataHolder & holder)1273 bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1274 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1275 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
1276 return false;
1277 }
1278 }
1279 return true;
1280 }
1281
FinishAllRemainingAllocations(RedefinitionDataHolder & holder)1282 bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
1283 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1284 // Allocate the data this redefinition requires.
1285 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
1286 return false;
1287 }
1288 }
1289 return true;
1290 }
1291
ReleaseDexFile()1292 void Redefiner::ClassRedefinition::ReleaseDexFile() {
1293 dex_file_.release();
1294 }
1295
ReleaseAllDexFiles()1296 void Redefiner::ReleaseAllDexFiles() {
1297 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1298 redef.ReleaseDexFile();
1299 }
1300 }
1301
CheckAllClassesAreVerified(RedefinitionDataHolder & holder)1302 bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1303 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1304 if (!data.GetRedefinition().CheckVerification(data)) {
1305 return false;
1306 }
1307 }
1308 return true;
1309 }
1310
1311 class ScopedDisableConcurrentAndMovingGc {
1312 public:
ScopedDisableConcurrentAndMovingGc(art::gc::Heap * heap,art::Thread * self)1313 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1314 : heap_(heap), self_(self) {
1315 if (heap_->IsGcConcurrentAndMoving()) {
1316 heap_->IncrementDisableMovingGC(self_);
1317 }
1318 }
1319
~ScopedDisableConcurrentAndMovingGc()1320 ~ScopedDisableConcurrentAndMovingGc() {
1321 if (heap_->IsGcConcurrentAndMoving()) {
1322 heap_->DecrementDisableMovingGC(self_);
1323 }
1324 }
1325 private:
1326 art::gc::Heap* heap_;
1327 art::Thread* self_;
1328 };
1329
Run()1330 jvmtiError Redefiner::Run() {
1331 art::StackHandleScope<1> hs(self_);
1332 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1333 // We will let this be collected after the end of this function.
1334 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
1335 if (holder.IsNull()) {
1336 self_->AssertPendingOOMException();
1337 self_->ClearException();
1338 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1339 return result_;
1340 }
1341
1342 // First we just allocate the ClassExt and its fields that we need. These can be updated
1343 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1344 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1345 // between allocating them and pausing all threads before we can update them so we need to do a
1346 // try loop.
1347 if (!CheckAllRedefinitionAreValid() ||
1348 !EnsureAllClassAllocationsFinished(holder) ||
1349 !FinishAllRemainingAllocations(holder) ||
1350 !CheckAllClassesAreVerified(holder)) {
1351 return result_;
1352 }
1353
1354 // At this point we can no longer fail without corrupting the runtime state.
1355 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1356 art::ClassLinker* cl = runtime_->GetClassLinker();
1357 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
1358 if (data.GetSourceClassLoader() == nullptr) {
1359 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
1360 }
1361 }
1362 UnregisterAllBreakpoints();
1363
1364 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1365 // allocating so no deadlocks.
1366 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1367
1368 // Do transition to final suspension
1369 // TODO We might want to give this its own suspended state!
1370 // TODO This isn't right. We need to change state without any chance of suspend ideally!
1371 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1372 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1373 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1374 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
1375 ClassRedefinition& redef = data.GetRedefinition();
1376 if (data.GetSourceClassLoader() != nullptr) {
1377 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
1378 }
1379 art::mirror::Class* klass = data.GetMirrorClass();
1380 // TODO Rewrite so we don't do a stack walk for each and every class.
1381 redef.FindAndAllocateObsoleteMethods(klass);
1382 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
1383 }
1384 RestoreObsoleteMethodMapsIfUnneeded(holder);
1385 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1386 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1387 // methods that have been jitted prior to the current redefinition being applied might continue
1388 // to use the old versions of the intrinsics!
1389 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1390 // owns the DexFile and when ownership is transferred.
1391 ReleaseAllDexFiles();
1392 return OK;
1393 }
1394
UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,const art::DexFile::ClassDef & class_def)1395 void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1396 const art::DexFile::ClassDef& class_def) {
1397 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
1398 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
1399 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
1400 const art::DexFile& old_dex_file = mclass->GetDexFile();
1401 // Update methods.
1402 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1403 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1404 art::dex::TypeIndex method_return_idx =
1405 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1406 const auto* old_type_list = method.GetParameterTypeList();
1407 std::vector<art::dex::TypeIndex> new_type_list;
1408 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1409 new_type_list.push_back(
1410 dex_file_->GetIndexForTypeId(
1411 *dex_file_->FindTypeId(
1412 old_dex_file.GetTypeDescriptor(
1413 old_dex_file.GetTypeId(
1414 old_type_list->GetTypeItem(i).type_idx_)))));
1415 }
1416 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1417 new_type_list);
1418 CHECK(proto_id != nullptr || old_type_list == nullptr);
1419 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1420 *new_name_id,
1421 *proto_id);
1422 CHECK(method_id != nullptr);
1423 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1424 method.SetDexMethodIndex(dex_method_idx);
1425 linker->SetEntryPointsToInterpreter(&method);
1426 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
1427 // Clear all the intrinsics related flags.
1428 method.SetNotIntrinsic();
1429 }
1430 }
1431
UpdateFields(art::ObjPtr<art::mirror::Class> mclass)1432 void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
1433 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1434 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1435 for (art::ArtField& field : fields_iter) {
1436 std::string declaring_class_name;
1437 const art::DexFile::TypeId* new_declaring_id =
1438 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1439 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1440 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1441 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1442 const art::DexFile::FieldId* new_field_id =
1443 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1444 CHECK(new_field_id != nullptr);
1445 // We only need to update the index since the other data in the ArtField cannot be updated.
1446 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1447 }
1448 }
1449 }
1450
1451 // Performs updates to class that will allow us to verify it.
UpdateClass(art::ObjPtr<art::mirror::Class> mclass,art::ObjPtr<art::mirror::DexCache> new_dex_cache,art::ObjPtr<art::mirror::Object> original_dex_file)1452 void Redefiner::ClassRedefinition::UpdateClass(
1453 art::ObjPtr<art::mirror::Class> mclass,
1454 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1455 art::ObjPtr<art::mirror::Object> original_dex_file) {
1456 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1457 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1458 UpdateMethods(mclass, class_def);
1459 UpdateFields(mclass);
1460
1461 // Update the class fields.
1462 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1463 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1464 mclass->SetDexCache(new_dex_cache.Ptr());
1465 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
1466 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
1467 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1468 CHECK(!ext.IsNull());
1469 ext->SetOriginalDexFile(original_dex_file);
1470
1471 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1472 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1473 // meta-data.
1474 art::jit::Jit* jit = driver_->runtime_->GetJit();
1475 if (jit != nullptr) {
1476 art::PointerSize image_pointer_size =
1477 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1478 auto code_cache = jit->GetCodeCache();
1479 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1480 // the jit about them.
1481 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1482 if (method.IsInvokable()) {
1483 code_cache->NotifyMethodRedefined(&method);
1484 }
1485 }
1486 }
1487 }
1488
1489 // Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1490 // obsolete methods).
RestoreObsoleteMethodMapsIfUnneeded(const RedefinitionDataIter * cur_data)1491 void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1492 const RedefinitionDataIter* cur_data) {
1493 art::mirror::Class* klass = GetMirrorClass();
1494 art::mirror::ClassExt* ext = klass->GetExtData();
1495 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
1496 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1497 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
1498 int32_t expected_length =
1499 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1500 // Check to make sure we are only undoing this one.
1501 if (expected_length == methods->GetLength()) {
1502 for (int32_t i = 0; i < expected_length; i++) {
1503 art::ArtMethod* expected = nullptr;
1504 if (i < old_length) {
1505 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1506 }
1507 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
1508 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1509 // obsolete methods array.
1510 return;
1511 }
1512 }
1513 // No new obsolete methods! We can get rid of the maps.
1514 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1515 }
1516 }
1517
1518 // This function does all (java) allocations we need to do for the Class being redefined.
1519 // TODO Change this name maybe?
EnsureClassAllocationsFinished(RedefinitionDataIter * cur_data)1520 bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1521 /*out*/RedefinitionDataIter* cur_data) {
1522 art::StackHandleScope<2> hs(driver_->self_);
1523 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1524 driver_->self_->DecodeJObject(klass_)->AsClass()));
1525 if (klass == nullptr) {
1526 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1527 return false;
1528 }
1529 // Allocate the classExt
1530 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
1531 if (ext == nullptr) {
1532 // No memory. Clear exception (it's not useful) and return error.
1533 driver_->self_->AssertPendingOOMException();
1534 driver_->self_->ClearException();
1535 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1536 return false;
1537 }
1538 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1539 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1540 // are only modified when all threads (other than the modifying one) are suspended we don't need
1541 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1542 // however, since that can happen at any time.
1543 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1544 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1545 if (!ext->ExtendObsoleteArrays(
1546 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1547 // OOM. Clear exception and return error.
1548 driver_->self_->AssertPendingOOMException();
1549 driver_->self_->ClearException();
1550 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1551 return false;
1552 }
1553 return true;
1554 }
1555
1556 } // namespace openjdkjvmti
1557