blob: c0dc16a3963b06cc21a42abce421cc12b6dd4141 [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);
181 auto* method_storage = allocator_->Alloc(GetThread(), 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);
241 } else if (klass->IsArrayClass()) {
242 *error_msg = "Modification of Array classes is not supported";
243 return ERR(UNMODIFIABLE_CLASS);
244 } else if (klass->IsProxyClass()) {
245 *error_msg = "Modification of proxy classes is not supported";
246 return ERR(UNMODIFIABLE_CLASS);
247 }
248
Alex Lighte77b48b2017-02-22 11:08:06 -0800249 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
250 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
251 *error_msg = "Class might have stack frames that cannot be made obsolete";
252 return ERR(UNMODIFIABLE_CLASS);
253 }
254 }
255
Alex Lighte4a88632017-01-10 07:41:24 -0800256 return OK;
257}
258
Alex Lighta01de592016-11-15 10:43:06 -0800259// Moves dex data to an anonymous, read-only mmap'd region.
260std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
261 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800262 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800263 std::string* error_msg) {
264 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800265 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800266 nullptr,
267 data_len,
268 PROT_READ|PROT_WRITE,
269 /*low_4gb*/false,
270 /*reuse*/false,
271 error_msg));
272 if (map == nullptr) {
273 return map;
274 }
275 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800276 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
277 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800278 map->Protect(PROT_READ);
279 return map;
280}
281
Alex Lighta7e38d82017-01-19 14:57:28 -0800282Redefiner::ClassRedefinition::ClassRedefinition(
283 Redefiner* driver,
284 jclass klass,
285 const art::DexFile* redefined_dex_file,
286 const char* class_sig,
287 art::ArraySlice<const unsigned char> orig_dex_file) :
288 driver_(driver),
289 klass_(klass),
290 dex_file_(redefined_dex_file),
291 class_sig_(class_sig),
292 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800293 GetMirrorClass()->MonitorEnter(driver_->self_);
294}
295
296Redefiner::ClassRedefinition::~ClassRedefinition() {
297 if (driver_ != nullptr) {
298 GetMirrorClass()->MonitorExit(driver_->self_);
299 }
300}
301
Alex Light0e692732017-01-10 15:00:05 -0800302jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
303 art::Runtime* runtime,
304 art::Thread* self,
305 jint class_count,
306 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800307 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800308 if (env == nullptr) {
309 *error_msg = "env was null!";
310 return ERR(INVALID_ENVIRONMENT);
311 } else if (class_count < 0) {
312 *error_msg = "class_count was less then 0";
313 return ERR(ILLEGAL_ARGUMENT);
314 } else if (class_count == 0) {
315 // We don't actually need to do anything. Just return OK.
316 return OK;
317 } else if (definitions == nullptr) {
318 *error_msg = "null definitions!";
319 return ERR(NULL_POINTER);
320 }
Alex Light6ac57502017-01-19 15:05:06 -0800321 std::vector<ArtClassDefinition> def_vector;
322 def_vector.reserve(class_count);
323 for (jint i = 0; i < class_count; i++) {
324 // We make a copy of the class_bytes to pass into the retransformation.
325 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
326 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
327 // to get the passed in bytes.
328 // TODO Implement saving the original bytes.
329 unsigned char* class_bytes_copy = nullptr;
330 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
331 if (res != OK) {
332 return res;
333 }
334 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
335
336 ArtClassDefinition def;
337 def.dex_len = definitions[i].class_byte_count;
338 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
339 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800340 def.SetModified();
341 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
342 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800343 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
344 if (res != OK) {
345 return res;
346 }
347 def_vector.push_back(std::move(def));
348 }
349 // Call all the transformation events.
350 jvmtiError res = Transformer::RetransformClassesDirect(env,
351 self,
352 &def_vector);
353 if (res != OK) {
354 // Something went wrong with transformation!
355 return res;
356 }
357 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
358}
359
360jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
361 art::Runtime* runtime,
362 art::Thread* self,
363 const std::vector<ArtClassDefinition>& definitions,
364 std::string* error_msg) {
365 DCHECK(env != nullptr);
366 if (definitions.size() == 0) {
367 // We don't actually need to do anything. Just return OK.
368 return OK;
369 }
Alex Light0e692732017-01-10 15:00:05 -0800370 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
371 // are going to redefine.
372 art::jit::ScopedJitSuspend suspend_jit;
373 // Get shared mutator lock so we can lock all the classes.
374 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800375 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800376 for (const ArtClassDefinition& def : definitions) {
377 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800378 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800379 jvmtiError res = r.AddRedefinition(env, def);
380 if (res != OK) {
381 return res;
382 }
Alex Light0e692732017-01-10 15:00:05 -0800383 }
384 }
385 return r.Run();
386}
387
Alex Light6ac57502017-01-19 15:05:06 -0800388jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800389 std::string original_dex_location;
390 jvmtiError ret = OK;
391 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
392 *error_msg_ = "Unable to get original dex file location!";
393 return ret;
394 }
Alex Light52a2db52017-01-19 23:00:21 +0000395 char* generic_ptr_unused = nullptr;
396 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800397 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
398 *error_msg_ = "Unable to get class signature!";
399 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000400 }
Alex Light52a2db52017-01-19 23:00:21 +0000401 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800402 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
403 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
404 def.dex_len,
405 def.dex_data.get(),
406 error_msg_));
407 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800408 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800409 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800410 << "in dex file " << original_dex_location << " because: " << *error_msg_;
411 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800412 return ERR(OUT_OF_MEMORY);
413 }
414 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800415 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800416 return ERR(INVALID_CLASS_FORMAT);
417 }
418 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
419 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
420 checksum,
421 std::move(map),
422 /*verify*/true,
423 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800424 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800425 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800426 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800427 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800428 return ERR(INVALID_CLASS_FORMAT);
429 }
Alex Light0e692732017-01-10 15:00:05 -0800430 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800431 Redefiner::ClassRedefinition(this,
432 def.klass,
433 dex_file.release(),
434 signature_ptr,
435 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800436 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800437}
438
Alex Light0e692732017-01-10 15:00:05 -0800439art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
440 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800441}
442
Alex Light0e692732017-01-10 15:00:05 -0800443art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800444 return GetMirrorClass()->GetClassLoader();
445}
446
Alex Light0e692732017-01-10 15:00:05 -0800447art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
448 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000449 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800450}
451
Alex Light0e692732017-01-10 15:00:05 -0800452void Redefiner::RecordFailure(jvmtiError result,
453 const std::string& class_sig,
454 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800455 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800456 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800457 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800458 result_ = result;
459}
460
Alex Lighta7e38d82017-01-19 14:57:28 -0800461art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
462 // If we have been specifically given a new set of bytes use that
463 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800464 return art::mirror::ByteArray::AllocateAndFill(
465 driver_->self_,
466 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
467 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800468 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800469
470 // See if we already have one set.
471 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
472 if (!ext.IsNull()) {
473 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
474 if (!old_original_bytes.IsNull()) {
475 // We do. Use it.
476 return old_original_bytes.Ptr();
477 }
Alex Lighta01de592016-11-15 10:43:06 -0800478 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800479
480 // Copy the current dex_file
481 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
482 // TODO Handle this or make it so it cannot happen.
483 if (current_dex_file.NumClassDefs() != 1) {
484 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
485 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800486 }
Alex Light440b5d92017-01-24 15:32:25 -0800487 return art::mirror::ByteArray::AllocateAndFill(
488 driver_->self_,
489 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
490 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800491}
492
Alex Lightdba61482016-12-21 08:20:29 -0800493struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000494 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800495 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800496 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800497
Alex Lighteee0bd42017-02-14 15:31:45 +0000498 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
499 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800500};
501
Alex Lightdba61482016-12-21 08:20:29 -0800502void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
503 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800504 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
505 data->allocator,
506 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000507 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800508}
509
510// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
511// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800512// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
513void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800514 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
515 art::mirror::ClassExt* ext = art_klass->GetExtData();
516 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800517 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000518 // This holds pointers to the obsolete methods map fields which are updated as needed.
519 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
520 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800521 // Add all the declared methods to the map
522 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800523 if (m.IsIntrinsic()) {
524 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
525 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
526 << "methods that have already been compiled.";
527 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000528 // It is possible to simply filter out some methods where they cannot really become obsolete,
529 // such as native methods and keep their original (possibly optimized) implementations. We don't
530 // do this, however, since we would need to mark these functions (still in the classes
531 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
532 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
533 // error checking from the interpreter which ensure we don't try to start executing obsolete
534 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000535 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800536 }
537 {
Alex Light0e692732017-01-10 15:00:05 -0800538 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800539 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
540 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800541 }
Alex Lightdba61482016-12-21 08:20:29 -0800542}
543
Alex Light6161f132017-01-25 10:30:20 -0800544// Try and get the declared method. First try to get a virtual method then a direct method if that's
545// not found.
546static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
547 const char* name,
548 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
549 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
550 if (m == nullptr) {
551 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
552 }
553 return m;
554}
555
556bool Redefiner::ClassRedefinition::CheckSameMethods() {
557 art::StackHandleScope<1> hs(driver_->self_);
558 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
559 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
560
561 art::ClassDataItemIterator new_iter(*dex_file_,
562 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
563
564 // Make sure we have the same number of methods.
565 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
566 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
567 if (num_new_method != num_old_method) {
568 bool bigger = num_new_method > num_old_method;
569 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
570 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
571 StringPrintf("Total number of declared methods changed from %d to %d",
572 num_old_method, num_new_method));
573 return false;
574 }
575
576 // Skip all of the fields. We should have already checked this.
577 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
578 new_iter.Next();
579 }
580 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
581 // files have the same number of methods, which means there must be an equal amount of additions
582 // and removals.
583 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
584 // Get the data on the method we are searching for
585 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
586 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
587 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
588 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
589 // If we got past the check for the same number of methods above that means there must be at
590 // least one added and one removed method. We will return the ADDED failure message since it is
591 // easier to get a useful error report for it.
592 if (old_method == nullptr) {
593 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
594 StringPrintf("Unknown method '%s' (sig: %s) was added!",
595 new_method_name,
596 new_method_signature.ToString().c_str()));
597 return false;
598 }
599 // Since direct methods have different flags than virtual ones (specifically direct methods must
600 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
601 // virtual to direct.
602 uint32_t new_flags = new_iter.GetMethodAccessFlags();
603 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
604 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
605 StringPrintf("method '%s' (sig: %s) had different access flags",
606 new_method_name,
607 new_method_signature.ToString().c_str()));
608 return false;
609 }
610 }
611 return true;
612}
613
614bool Redefiner::ClassRedefinition::CheckSameFields() {
615 art::StackHandleScope<1> hs(driver_->self_);
616 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
617 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
618 art::ClassDataItemIterator new_iter(*dex_file_,
619 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
620 const art::DexFile& old_dex_file = h_klass->GetDexFile();
621 art::ClassDataItemIterator old_iter(old_dex_file,
622 old_dex_file.GetClassData(*h_klass->GetClassDef()));
623 // Instance and static fields can be differentiated by their flags so no need to check them
624 // separately.
625 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
626 // Get the data on the method we are searching for
627 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
628 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
629 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
630
631 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
632 // We are missing the old version of this method!
633 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
634 StringPrintf("Unknown field '%s' (type: %s) added!",
635 new_field_name,
636 new_field_type));
637 return false;
638 }
639
640 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
641 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
642 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
643
644 // Check name and type.
645 if (strcmp(old_field_name, new_field_name) != 0 ||
646 strcmp(old_field_type, new_field_type) != 0) {
647 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
648 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
649 old_field_name,
650 old_field_type,
651 new_field_name,
652 new_field_type));
653 return false;
654 }
655
656 // Since static fields have different flags than instance ones (specifically static fields must
657 // have the kAccStatic flag) we can tell if a field changes from static to instance.
658 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
659 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
660 StringPrintf("Field '%s' (sig: %s) had different access flags",
661 new_field_name,
662 new_field_type));
663 return false;
664 }
665
666 new_iter.Next();
667 old_iter.Next();
668 }
669 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
670 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
671 StringPrintf("field '%s' (sig: %s) is missing!",
672 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
673 old_iter.GetMemberIndex())),
674 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
675 old_iter.GetMemberIndex()))));
676 return false;
677 }
678 return true;
679}
680
Alex Light0e692732017-01-10 15:00:05 -0800681bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000682 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800683 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000684 // Easy check that only 1 class def is present.
685 if (dex_file_->NumClassDefs() != 1) {
686 RecordFailure(ERR(ILLEGAL_ARGUMENT),
687 StringPrintf("Expected 1 class def in dex file but found %d",
688 dex_file_->NumClassDefs()));
689 return false;
690 }
691 // Get the ClassDef from the new DexFile.
692 // Since the dex file has only a single class def the index is always 0.
693 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
694 // Get the class as it is now.
695 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
696
697 // Check the access flags didn't change.
698 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
699 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
700 "Cannot change modifiers of class by redefinition");
701 return false;
702 }
703
704 // Check class name.
705 // These should have been checked by the dexfile verifier on load.
706 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
707 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
708 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
709 if (!current_class->DescriptorEquals(descriptor)) {
710 std::string storage;
711 RecordFailure(ERR(NAMES_DONT_MATCH),
712 StringPrintf("expected file to contain class called '%s' but found '%s'!",
713 current_class->GetDescriptor(&storage),
714 descriptor));
715 return false;
716 }
717 if (current_class->IsObjectClass()) {
718 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
719 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
720 return false;
721 }
722 } else {
723 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
724 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
725 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
726 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
727 return false;
728 }
729 }
730 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
731 if (interfaces == nullptr) {
732 if (current_class->NumDirectInterfaces() != 0) {
733 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
734 return false;
735 }
736 } else {
737 DCHECK(!current_class->IsProxyClass());
738 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
739 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
740 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
741 return false;
742 }
743 // The order of interfaces is (barely) meaningful so we error if it changes.
744 const art::DexFile& orig_dex_file = current_class->GetDexFile();
745 for (uint32_t i = 0; i < interfaces->Size(); i++) {
746 if (strcmp(
747 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
748 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
749 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
750 "Interfaces changed or re-ordered");
751 return false;
752 }
753 }
754 }
Alex Light460d1b42017-01-10 15:37:17 +0000755 return true;
756}
757
758// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800759bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800760 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800761 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000762
Alex Lighte4a88632017-01-10 07:41:24 -0800763 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
764 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
765 if (res != OK) {
766 RecordFailure(res, err);
767 return false;
768 } else {
769 return true;
770 }
Alex Light460d1b42017-01-10 15:37:17 +0000771}
772
Alex Light0e692732017-01-10 15:00:05 -0800773bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000774 return CheckRedefinable() &&
775 CheckClass() &&
776 CheckSameFields() &&
777 CheckSameMethods();
778}
779
Alex Light0e692732017-01-10 15:00:05 -0800780// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
781// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
782// having to deal with the fact that we need to hold an arbitrary number of references live.
783class RedefinitionDataHolder {
784 public:
785 enum DataSlot : int32_t {
786 kSlotSourceClassLoader = 0,
787 kSlotJavaDexFile = 1,
788 kSlotNewDexFileCookie = 2,
789 kSlotNewDexCache = 3,
790 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800791 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800792
793 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800794 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800795 };
796
797 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
798 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
799 // the passed in handle-scope.
800 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
801 art::Runtime* runtime,
802 art::Thread* self,
803 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
804 arr_(
805 hs->NewHandle(
806 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
807 self,
808 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
809 num_redefinitions * kNumSlots))) {}
810
811 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
812 return arr_.IsNull();
813 }
814
815 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800816 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800817 REQUIRES_SHARED(art::Locks::mutator_lock_) {
818 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
819 }
Alex Light8c889d22017-02-06 13:58:27 -0800820 art::mirror::Object* GetJavaDexFile(jint klass_index) const
821 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800822 return GetSlot(klass_index, kSlotJavaDexFile);
823 }
Alex Light8c889d22017-02-06 13:58:27 -0800824 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800825 REQUIRES_SHARED(art::Locks::mutator_lock_) {
826 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
827 }
Alex Light8c889d22017-02-06 13:58:27 -0800828 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800829 REQUIRES_SHARED(art::Locks::mutator_lock_) {
830 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
831 }
Alex Light8c889d22017-02-06 13:58:27 -0800832 art::mirror::Class* GetMirrorClass(jint klass_index) const
833 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800834 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
835 }
836
Alex Light8c889d22017-02-06 13:58:27 -0800837 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800838 REQUIRES_SHARED(art::Locks::mutator_lock_) {
839 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
840 }
841
Alex Light0e692732017-01-10 15:00:05 -0800842 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
843 REQUIRES_SHARED(art::Locks::mutator_lock_) {
844 SetSlot(klass_index, kSlotSourceClassLoader, loader);
845 }
846 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
847 REQUIRES_SHARED(art::Locks::mutator_lock_) {
848 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
849 }
850 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
851 REQUIRES_SHARED(art::Locks::mutator_lock_) {
852 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
853 }
854 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
855 REQUIRES_SHARED(art::Locks::mutator_lock_) {
856 SetSlot(klass_index, kSlotNewDexCache, cache);
857 }
858 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
859 REQUIRES_SHARED(art::Locks::mutator_lock_) {
860 SetSlot(klass_index, kSlotMirrorClass, klass);
861 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800862 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
863 REQUIRES_SHARED(art::Locks::mutator_lock_) {
864 SetSlot(klass_index, kSlotOrigDexFile, bytes);
865 }
Alex Light0e692732017-01-10 15:00:05 -0800866
Alex Light8c889d22017-02-06 13:58:27 -0800867 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800868 return arr_->GetLength() / kNumSlots;
869 }
870
871 private:
Alex Light8c889d22017-02-06 13:58:27 -0800872 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Light0e692732017-01-10 15:00:05 -0800873
874 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800875 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800876 DCHECK_LT(klass_index, Length());
877 return arr_->Get((kNumSlots * klass_index) + slot);
878 }
879
880 void SetSlot(jint klass_index,
881 DataSlot slot,
882 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
883 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
884 DCHECK_LT(klass_index, Length());
885 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
886 }
887
888 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
889};
890
Alex Light8c889d22017-02-06 13:58:27 -0800891// TODO Stash and update soft failure state
892bool Redefiner::ClassRedefinition::CheckVerification(int32_t klass_index,
893 const RedefinitionDataHolder& holder) {
894 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
895 art::StackHandleScope<2> hs(driver_->self_);
896 std::string error;
897 // TODO Make verification log level lower
898 art::verifier::MethodVerifier::FailureKind failure =
899 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
900 dex_file_.get(),
901 hs.NewHandle(holder.GetNewDexCache(klass_index)),
902 hs.NewHandle(GetClassLoader()),
903 dex_file_->GetClassDef(0), /*class_def*/
904 nullptr, /*compiler_callbacks*/
905 false, /*allow_soft_failures*/
906 /*log_level*/
907 art::verifier::HardFailLogMode::kLogWarning,
908 &error);
909 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
910 if (!passes) {
911 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
912 }
913 return passes;
914}
915
Alex Light1babae02017-02-01 15:35:34 -0800916// Looks through the previously allocated cookies to see if we need to update them with another new
917// dexfile. This is so that even if multiple classes with the same classloader are redefined at
918// once they are all added to the classloader.
919bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
920 int32_t klass_index,
921 art::Handle<art::mirror::ClassLoader> source_class_loader,
922 art::Handle<art::mirror::Object> dex_file_obj,
923 /*out*/RedefinitionDataHolder* holder) {
924 art::StackHandleScope<2> hs(driver_->self_);
925 art::MutableHandle<art::mirror::LongArray> old_cookie(
926 hs.NewHandle<art::mirror::LongArray>(nullptr));
927 bool has_older_cookie = false;
928 // See if we already have a cookie that a previous redefinition got from the same classloader.
929 for (int32_t i = 0; i < klass_index; i++) {
930 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
931 // Since every instance of this classloader should have the same cookie associated with it we
932 // can stop looking here.
933 has_older_cookie = true;
934 old_cookie.Assign(holder->GetNewDexFileCookie(i));
935 break;
936 }
937 }
938 if (old_cookie.IsNull()) {
939 // No older cookie. Get it directly from the dex_file_obj
940 // We should not have seen this classloader elsewhere.
941 CHECK(!has_older_cookie);
942 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
943 }
944 // Use the old cookie to generate the new one with the new DexFile* added in.
945 art::Handle<art::mirror::LongArray>
946 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
947 old_cookie,
948 dex_file_.get())));
949 // Make sure the allocation worked.
950 if (new_cookie.IsNull()) {
951 return false;
952 }
953
954 // Save the cookie.
955 holder->SetNewDexFileCookie(klass_index, new_cookie.Get());
956 // If there are other copies of this same classloader we need to make sure that we all have the
957 // same cookie.
958 if (has_older_cookie) {
959 for (int32_t i = 0; i < klass_index; i++) {
960 // We will let the GC take care of the cookie we allocated for this one.
961 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
962 holder->SetNewDexFileCookie(i, new_cookie.Get());
963 }
964 }
965 }
966
967 return true;
968}
969
Alex Lighta7e38d82017-01-19 14:57:28 -0800970bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
971 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800972 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800973 art::StackHandleScope<2> hs(driver_->self_);
974 holder->SetMirrorClass(klass_index, GetMirrorClass());
975 // This shouldn't allocate
976 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800977 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
978 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
979 holder->SetSourceClassLoader(klass_index, loader.Get());
980 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
981 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
982 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -0800983 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -0800984 // TODO Better error msg.
985 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
986 return false;
987 }
Alex Light1babae02017-02-01 15:35:34 -0800988 // Allocate the new dex file cookie.
989 if (!AllocateAndRememberNewDexFileCookie(klass_index, loader, dex_file_obj, holder)) {
Alex Light7916f202017-01-27 09:00:15 -0800990 driver_->self_->AssertPendingOOMException();
991 driver_->self_->ClearException();
992 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
993 return false;
994 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800995 }
996 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
997 if (holder->GetNewDexCache(klass_index) == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000998 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -0800999 driver_->self_->ClearException();
1000 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1001 return false;
1002 }
1003
1004 // We won't always need to set this field.
1005 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
1006 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
1007 driver_->self_->AssertPendingOOMException();
1008 driver_->self_->ClearException();
1009 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1010 return false;
1011 }
1012 return true;
1013}
1014
Alex Light5643caf2017-02-08 11:39:07 -08001015void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1016 DCHECK(art::Dbg::IsDebuggerActive());
1017 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1018 if (state != nullptr) {
1019 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1020 }
1021}
1022
1023void Redefiner::UnregisterAllBreakpoints() {
1024 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1025 return;
1026 }
1027 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1028 redef.UnregisterBreakpoints();
1029 }
1030}
1031
Alex Light0e692732017-01-10 15:00:05 -08001032bool Redefiner::CheckAllRedefinitionAreValid() {
1033 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1034 if (!redef.CheckRedefinitionIsValid()) {
1035 return false;
1036 }
1037 }
1038 return true;
1039}
1040
1041bool Redefiner::EnsureAllClassAllocationsFinished() {
1042 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1043 if (!redef.EnsureClassAllocationsFinished()) {
1044 return false;
1045 }
1046 }
1047 return true;
1048}
1049
1050bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
1051 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -08001052 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -08001053 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -08001054 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -08001055 return false;
1056 }
Alex Light0e692732017-01-10 15:00:05 -08001057 cnt++;
1058 }
1059 return true;
1060}
1061
1062void Redefiner::ClassRedefinition::ReleaseDexFile() {
1063 dex_file_.release();
1064}
1065
1066void Redefiner::ReleaseAllDexFiles() {
1067 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1068 redef.ReleaseDexFile();
1069 }
1070}
1071
Alex Light8c889d22017-02-06 13:58:27 -08001072bool Redefiner::CheckAllClassesAreVerified(const RedefinitionDataHolder& holder) {
1073 int32_t cnt = 0;
1074 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1075 if (!redef.CheckVerification(cnt, holder)) {
1076 return false;
1077 }
1078 cnt++;
1079 }
1080 return true;
1081}
1082
Alex Lighta01de592016-11-15 10:43:06 -08001083jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001084 art::StackHandleScope<1> hs(self_);
1085 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1086 // We will let this be collected after the end of this function.
1087 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
1088 if (holder.IsNull()) {
1089 self_->AssertPendingOOMException();
1090 self_->ClearException();
1091 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1092 return result_;
1093 }
1094
Alex Lighta01de592016-11-15 10:43:06 -08001095 // First we just allocate the ClassExt and its fields that we need. These can be updated
1096 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1097 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1098 // between allocating them and pausing all threads before we can update them so we need to do a
1099 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001100 if (!CheckAllRedefinitionAreValid() ||
1101 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001102 !FinishAllRemainingAllocations(holder) ||
1103 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001104 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1105 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001106 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1107 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001108 return result_;
1109 }
Alex Light5643caf2017-02-08 11:39:07 -08001110 // At this point we can no longer fail without corrupting the runtime state.
Alex Light7916f202017-01-27 09:00:15 -08001111 int32_t counter = 0;
1112 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1113 if (holder.GetSourceClassLoader(counter) == nullptr) {
1114 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
1115 }
1116 counter++;
1117 }
Alex Light5643caf2017-02-08 11:39:07 -08001118 UnregisterAllBreakpoints();
Alex Light6abd5392017-01-05 17:53:00 -08001119 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1120 // allocating so no deadlocks.
1121 art::gc::Heap* heap = runtime_->GetHeap();
1122 if (heap->IsGcConcurrentAndMoving()) {
1123 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
1124 heap->IncrementDisableMovingGC(self_);
1125 }
Alex Lighta01de592016-11-15 10:43:06 -08001126 // Do transition to final suspension
1127 // TODO We might want to give this its own suspended state!
1128 // TODO This isn't right. We need to change state without any chance of suspend ideally!
1129 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
1130 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -08001131 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -08001132 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
1133 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
1134 // TODO We need to update all debugger MethodIDs so they note the method they point to is
1135 // obsolete or implement some other well defined semantics.
1136 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light7916f202017-01-27 09:00:15 -08001137 counter = 0;
Alex Light0e692732017-01-10 15:00:05 -08001138 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -08001139 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light7916f202017-01-27 09:00:15 -08001140 if (holder.GetSourceClassLoader(counter) != nullptr) {
1141 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(counter),
1142 holder.GetNewDexFileCookie(counter));
1143 }
1144 art::mirror::Class* klass = holder.GetMirrorClass(counter);
Alex Light0e692732017-01-10 15:00:05 -08001145 // TODO Rewrite so we don't do a stack walk for each and every class.
1146 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light7916f202017-01-27 09:00:15 -08001147 redef.UpdateClass(klass, holder.GetNewDexCache(counter),
1148 holder.GetOriginalDexFileBytes(counter));
1149 counter++;
Alex Light0e692732017-01-10 15:00:05 -08001150 }
Alex Light7532d582017-02-13 16:36:06 -08001151 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1152 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1153 // methods that have been jitted prior to the current redefinition being applied might continue
1154 // to use the old versions of the intrinsics!
Alex Lightdba61482016-12-21 08:20:29 -08001155 // TODO Shrink the obsolete method maps if possible?
Alex Lighta01de592016-11-15 10:43:06 -08001156 // TODO Put this into a scoped thing.
1157 runtime_->GetThreadList()->ResumeAll();
1158 // Get back shared mutator lock as expected for return.
1159 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -08001160 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1161 // owns the DexFile and when ownership is transferred.
1162 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001163 if (heap->IsGcConcurrentAndMoving()) {
1164 heap->DecrementDisableMovingGC(self_);
1165 }
Alex Lighta01de592016-11-15 10:43:06 -08001166 return OK;
1167}
1168
Alex Light0e692732017-01-10 15:00:05 -08001169void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1170 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1171 const art::DexFile::ClassDef& class_def) {
1172 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001173 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001174 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001175 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001176 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001177 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1178 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1179 art::dex::TypeIndex method_return_idx =
1180 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1181 const auto* old_type_list = method.GetParameterTypeList();
1182 std::vector<art::dex::TypeIndex> new_type_list;
1183 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1184 new_type_list.push_back(
1185 dex_file_->GetIndexForTypeId(
1186 *dex_file_->FindTypeId(
1187 old_dex_file.GetTypeDescriptor(
1188 old_dex_file.GetTypeId(
1189 old_type_list->GetTypeItem(i).type_idx_)))));
1190 }
1191 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1192 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001193 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001194 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001195 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1196 *new_name_id,
1197 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001198 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001199 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001200 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1201 method.SetDexMethodIndex(dex_method_idx);
1202 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001203 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001204 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001205 // Clear all the intrinsics related flags.
1206 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001207 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001208 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001209 if (jit != nullptr) {
1210 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1211 }
Alex Lighta01de592016-11-15 10:43:06 -08001212 }
Alex Light200b9d72016-12-15 11:34:13 -08001213}
1214
Alex Light0e692732017-01-10 15:00:05 -08001215void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001216 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1217 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1218 for (art::ArtField& field : fields_iter) {
1219 std::string declaring_class_name;
1220 const art::DexFile::TypeId* new_declaring_id =
1221 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1222 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1223 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1224 // TODO Handle error, cleanup.
1225 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1226 const art::DexFile::FieldId* new_field_id =
1227 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1228 CHECK(new_field_id != nullptr);
1229 // We only need to update the index since the other data in the ArtField cannot be updated.
1230 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1231 }
1232 }
Alex Light200b9d72016-12-15 11:34:13 -08001233}
1234
1235// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001236void Redefiner::ClassRedefinition::UpdateClass(
1237 art::ObjPtr<art::mirror::Class> mclass,
1238 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1239 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001240 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1241 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1242 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001243 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001244
Alex Lighta01de592016-11-15 10:43:06 -08001245 // Update the class fields.
1246 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1247 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1248 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001249 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001250 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001251 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1252 CHECK(!ext.IsNull());
1253 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001254}
1255
Alex Lighta01de592016-11-15 10:43:06 -08001256// This function does all (java) allocations we need to do for the Class being redefined.
1257// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001258bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1259 art::StackHandleScope<2> hs(driver_->self_);
1260 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1261 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001262 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001263 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1264 return false;
1265 }
1266 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001267 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001268 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001269 // No memory. Clear exception (it's not useful) and return error.
1270 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1271 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001272 driver_->self_->AssertPendingOOMException();
1273 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001274 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1275 return false;
1276 }
1277 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1278 // are only modified when all threads (other than the modifying one) are suspended we don't need
1279 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1280 // however, since that can happen at any time.
1281 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1282 // are no obsolete methods.
1283 {
Alex Light0e692732017-01-10 15:00:05 -08001284 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001285 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001286 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001287 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001288 driver_->self_->AssertPendingOOMException();
1289 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001290 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1291 return false;
1292 }
1293 }
1294 return true;
1295}
1296
1297} // namespace openjdkjvmti