blob: b76d74ae79e438f954254b129f141ad201260271 [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 Light460d1b42017-01-10 15:37:17 +000041#include "dex_file.h"
42#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080043#include "events-inl.h"
44#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080045#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080046#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080047#include "jit/jit.h"
48#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080049#include "jni_env_ext-inl.h"
50#include "jvmti_allocator.h"
51#include "mirror/class.h"
52#include "mirror/class_ext.h"
53#include "mirror/object.h"
54#include "object_lock.h"
55#include "runtime.h"
56#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080057#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080058#include "transform.h"
Alex Lighta01de592016-11-15 10:43:06 -080059
60namespace openjdkjvmti {
61
Andreas Gampe46ee31b2016-12-14 10:11:49 -080062using android::base::StringPrintf;
63
Alex Lightdba61482016-12-21 08:20:29 -080064// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
65// some basic sanity checks that the obsolete method is sane.
66class ObsoleteMethodStackVisitor : public art::StackVisitor {
67 protected:
68 ObsoleteMethodStackVisitor(
69 art::Thread* thread,
70 art::LinearAlloc* allocator,
71 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080072 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -080073 : StackVisitor(thread,
74 /*context*/nullptr,
75 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
76 allocator_(allocator),
77 obsoleted_methods_(obsoleted_methods),
78 obsolete_maps_(obsolete_maps),
Alex Light007ada22017-01-10 13:33:56 -080079 is_runtime_frame_(false) {
Alex Lightdba61482016-12-21 08:20:29 -080080 }
81
82 ~ObsoleteMethodStackVisitor() OVERRIDE {}
83
84 public:
85 // Returns true if we successfully installed obsolete methods on this thread, filling
86 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
87 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080088 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080089 art::Thread* thread,
90 art::LinearAlloc* allocator,
91 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080092 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
93 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080094 ObsoleteMethodStackVisitor visitor(thread,
95 allocator,
96 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080097 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -080098 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -080099 }
100
101 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
102 art::ArtMethod* old_method = GetMethod();
103 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
104 // works through runtime methods.
105 bool prev_was_runtime_frame_ = is_runtime_frame_;
106 is_runtime_frame_ = old_method->IsRuntimeMethod();
107 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
108 // The check below works since when we deoptimize we set shadow frames for all frames until a
109 // native/runtime transition and for those set the return PC to a function that will complete
110 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
111 // below runtime frames cannot be deoptimized at the moment.
112 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
113 // works through runtime methods.
114 // TODO b/33616143
115 if (!IsShadowFrame() && prev_was_runtime_frame_) {
Alex Light007ada22017-01-10 13:33:56 -0800116 LOG(FATAL) << "Deoptimization failed due to runtime method in stack. See b/33616143";
Alex Lightdba61482016-12-21 08:20:29 -0800117 }
118 // We cannot ensure that the right dex file is used in inlined frames so we don't support
119 // redefining them.
120 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
121 // TODO We should really support intrinsic obsolete methods.
122 // TODO We should really support redefining intrinsics.
123 // We don't support intrinsics so check for them here.
124 DCHECK(!old_method->IsIntrinsic());
125 art::ArtMethod* new_obsolete_method = nullptr;
126 auto obsolete_method_pair = obsolete_maps_->find(old_method);
127 if (obsolete_method_pair == obsolete_maps_->end()) {
128 // Create a new Obsolete Method and put it in the list.
129 art::Runtime* runtime = art::Runtime::Current();
130 art::ClassLinker* cl = runtime->GetClassLinker();
131 auto ptr_size = cl->GetImagePointerSize();
132 const size_t method_size = art::ArtMethod::Size(ptr_size);
133 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800134 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
135 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800136 new_obsolete_method = new (method_storage) art::ArtMethod();
137 new_obsolete_method->CopyFrom(old_method, ptr_size);
138 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
139 new_obsolete_method->SetIsObsolete();
140 obsolete_maps_->insert({old_method, new_obsolete_method});
141 // Update JIT Data structures to point to the new method.
142 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
143 if (jit != nullptr) {
144 // Notify the JIT we are making this obsolete method. It will update the jit's internal
145 // structures to keep track of the new obsolete method.
146 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
147 }
148 } else {
149 new_obsolete_method = obsolete_method_pair->second;
150 }
151 DCHECK(new_obsolete_method != nullptr);
152 SetMethod(new_obsolete_method);
153 }
154 return true;
155 }
156
157 private:
158 // The linear allocator we should use to make new methods.
159 art::LinearAlloc* allocator_;
160 // The set of all methods which could be obsoleted.
161 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
162 // A map from the original to the newly allocated obsolete method for frames on this thread. The
163 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
164 // the redefined classes ClassExt by the caller.
165 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800166 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
167 // works through runtime methods.
168 bool is_runtime_frame_;
Alex Lightdba61482016-12-21 08:20:29 -0800169};
170
Alex Lighte4a88632017-01-10 07:41:24 -0800171jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
172 jclass klass,
173 jboolean* is_redefinable) {
174 // TODO Check for the appropriate feature flags once we have enabled them.
175 art::Thread* self = art::Thread::Current();
176 art::ScopedObjectAccess soa(self);
177 art::StackHandleScope<1> hs(self);
178 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
179 if (obj.IsNull()) {
180 return ERR(INVALID_CLASS);
181 }
182 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
183 std::string err_unused;
184 *is_redefinable =
185 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
186 return OK;
187}
188
189jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
190 /*out*/std::string* error_msg) {
191 if (klass->IsPrimitive()) {
192 *error_msg = "Modification of primitive classes is not supported";
193 return ERR(UNMODIFIABLE_CLASS);
194 } else if (klass->IsInterface()) {
195 *error_msg = "Modification of Interface classes is currently not supported";
196 return ERR(UNMODIFIABLE_CLASS);
197 } else if (klass->IsArrayClass()) {
198 *error_msg = "Modification of Array classes is not supported";
199 return ERR(UNMODIFIABLE_CLASS);
200 } else if (klass->IsProxyClass()) {
201 *error_msg = "Modification of proxy classes is not supported";
202 return ERR(UNMODIFIABLE_CLASS);
203 }
204
205 // TODO We should check if the class has non-obsoletable methods on the stack
206 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
207 return OK;
208}
209
Alex Lighta01de592016-11-15 10:43:06 -0800210// Moves dex data to an anonymous, read-only mmap'd region.
211std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
212 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800213 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800214 std::string* error_msg) {
215 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800216 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800217 nullptr,
218 data_len,
219 PROT_READ|PROT_WRITE,
220 /*low_4gb*/false,
221 /*reuse*/false,
222 error_msg));
223 if (map == nullptr) {
224 return map;
225 }
226 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800227 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
228 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800229 map->Protect(PROT_READ);
230 return map;
231}
232
Alex Lighta7e38d82017-01-19 14:57:28 -0800233Redefiner::ClassRedefinition::ClassRedefinition(
234 Redefiner* driver,
235 jclass klass,
236 const art::DexFile* redefined_dex_file,
237 const char* class_sig,
238 art::ArraySlice<const unsigned char> orig_dex_file) :
239 driver_(driver),
240 klass_(klass),
241 dex_file_(redefined_dex_file),
242 class_sig_(class_sig),
243 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800244 GetMirrorClass()->MonitorEnter(driver_->self_);
245}
246
247Redefiner::ClassRedefinition::~ClassRedefinition() {
248 if (driver_ != nullptr) {
249 GetMirrorClass()->MonitorExit(driver_->self_);
250 }
251}
252
Alex Light0e692732017-01-10 15:00:05 -0800253jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
254 art::Runtime* runtime,
255 art::Thread* self,
256 jint class_count,
257 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800258 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800259 if (env == nullptr) {
260 *error_msg = "env was null!";
261 return ERR(INVALID_ENVIRONMENT);
262 } else if (class_count < 0) {
263 *error_msg = "class_count was less then 0";
264 return ERR(ILLEGAL_ARGUMENT);
265 } else if (class_count == 0) {
266 // We don't actually need to do anything. Just return OK.
267 return OK;
268 } else if (definitions == nullptr) {
269 *error_msg = "null definitions!";
270 return ERR(NULL_POINTER);
271 }
Alex Light6ac57502017-01-19 15:05:06 -0800272 std::vector<ArtClassDefinition> def_vector;
273 def_vector.reserve(class_count);
274 for (jint i = 0; i < class_count; i++) {
275 // We make a copy of the class_bytes to pass into the retransformation.
276 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
277 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
278 // to get the passed in bytes.
279 // TODO Implement saving the original bytes.
280 unsigned char* class_bytes_copy = nullptr;
281 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
282 if (res != OK) {
283 return res;
284 }
285 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
286
287 ArtClassDefinition def;
288 def.dex_len = definitions[i].class_byte_count;
289 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
290 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800291 def.SetModified();
292 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
293 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800294 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
295 if (res != OK) {
296 return res;
297 }
298 def_vector.push_back(std::move(def));
299 }
300 // Call all the transformation events.
301 jvmtiError res = Transformer::RetransformClassesDirect(env,
302 self,
303 &def_vector);
304 if (res != OK) {
305 // Something went wrong with transformation!
306 return res;
307 }
308 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
309}
310
311jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
312 art::Runtime* runtime,
313 art::Thread* self,
314 const std::vector<ArtClassDefinition>& definitions,
315 std::string* error_msg) {
316 DCHECK(env != nullptr);
317 if (definitions.size() == 0) {
318 // We don't actually need to do anything. Just return OK.
319 return OK;
320 }
Alex Light0e692732017-01-10 15:00:05 -0800321 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
322 // are going to redefine.
323 art::jit::ScopedJitSuspend suspend_jit;
324 // Get shared mutator lock so we can lock all the classes.
325 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800326 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800327 for (const ArtClassDefinition& def : definitions) {
328 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800329 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800330 jvmtiError res = r.AddRedefinition(env, def);
331 if (res != OK) {
332 return res;
333 }
Alex Light0e692732017-01-10 15:00:05 -0800334 }
335 }
336 return r.Run();
337}
338
Alex Light6ac57502017-01-19 15:05:06 -0800339jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800340 std::string original_dex_location;
341 jvmtiError ret = OK;
342 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
343 *error_msg_ = "Unable to get original dex file location!";
344 return ret;
345 }
Alex Light52a2db52017-01-19 23:00:21 +0000346 char* generic_ptr_unused = nullptr;
347 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800348 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
349 *error_msg_ = "Unable to get class signature!";
350 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000351 }
Alex Light52a2db52017-01-19 23:00:21 +0000352 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800353 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
354 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
355 def.dex_len,
356 def.dex_data.get(),
357 error_msg_));
358 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800359 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800360 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800361 << "in dex file " << original_dex_location << " because: " << *error_msg_;
362 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800363 return ERR(OUT_OF_MEMORY);
364 }
365 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800366 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800367 return ERR(INVALID_CLASS_FORMAT);
368 }
369 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
370 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
371 checksum,
372 std::move(map),
373 /*verify*/true,
374 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800375 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800376 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800377 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800378 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800379 return ERR(INVALID_CLASS_FORMAT);
380 }
Alex Light0e692732017-01-10 15:00:05 -0800381 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800382 Redefiner::ClassRedefinition(this,
383 def.klass,
384 dex_file.release(),
385 signature_ptr,
386 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800387 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800388}
389
Alex Light0e692732017-01-10 15:00:05 -0800390art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
391 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800392}
393
Alex Light0e692732017-01-10 15:00:05 -0800394art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800395 return GetMirrorClass()->GetClassLoader();
396}
397
Alex Light0e692732017-01-10 15:00:05 -0800398art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
399 art::Handle<art::mirror::ClassLoader> loader) {
400 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800401}
402
Alex Light0e692732017-01-10 15:00:05 -0800403void Redefiner::RecordFailure(jvmtiError result,
404 const std::string& class_sig,
405 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800406 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800407 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800408 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800409 result_ = result;
410}
411
Alex Lighta7e38d82017-01-19 14:57:28 -0800412art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
413 // If we have been specifically given a new set of bytes use that
414 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800415 return art::mirror::ByteArray::AllocateAndFill(
416 driver_->self_,
417 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
418 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800419 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800420
421 // See if we already have one set.
422 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
423 if (!ext.IsNull()) {
424 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
425 if (!old_original_bytes.IsNull()) {
426 // We do. Use it.
427 return old_original_bytes.Ptr();
428 }
Alex Lighta01de592016-11-15 10:43:06 -0800429 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800430
431 // Copy the current dex_file
432 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
433 // TODO Handle this or make it so it cannot happen.
434 if (current_dex_file.NumClassDefs() != 1) {
435 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
436 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800437 }
Alex Light440b5d92017-01-24 15:32:25 -0800438 return art::mirror::ByteArray::AllocateAndFill(
439 driver_->self_,
440 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
441 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800442}
443
Alex Lightdba61482016-12-21 08:20:29 -0800444struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800445 art::LinearAlloc* allocator;
446 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
447 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800448
Alex Light0e692732017-01-10 15:00:05 -0800449 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800450};
451
Alex Lightdba61482016-12-21 08:20:29 -0800452void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
453 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800454 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
455 data->allocator,
456 data->obsolete_methods,
457 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800458}
459
460// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
461// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800462// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
463void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800464 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
465 art::mirror::ClassExt* ext = art_klass->GetExtData();
466 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800467 CallbackCtx ctx(art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800468 // Add all the declared methods to the map
469 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
470 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800471 // TODO Allow this or check in IsModifiableClass.
472 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800473 }
474 {
Alex Light0e692732017-01-10 15:00:05 -0800475 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800476 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
477 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800478 }
479 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800480}
481
482// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
483// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800484void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800485 art::mirror::Class* art_klass,
486 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
487 int32_t index = 0;
488 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
489 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
490 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
491 ext_data->GetObsoleteDexCaches();
492 int32_t num_method_slots = obsolete_methods->GetLength();
493 // Find the first empty index.
494 for (; index < num_method_slots; index++) {
495 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
496 index, art::kRuntimePointerSize) == nullptr) {
497 break;
498 }
499 }
500 // Make sure we have enough space.
501 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
502 CHECK(obsolete_dex_caches->Get(index) == nullptr);
503 // Fill in the map.
504 for (auto& obs : obsoletes) {
505 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
506 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
507 index++;
508 }
509}
510
511// TODO It should be possible to only deoptimize the specific obsolete methods.
512// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
513// If one of these frames is an obsolete method we have a problem. b/33616143
514// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
515// registers across suspend points.
516// TODO Pending b/33630159
517void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
518 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
519 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
520 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
521}
522
Alex Light0e692732017-01-10 15:00:05 -0800523bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000524 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800525 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000526 // Easy check that only 1 class def is present.
527 if (dex_file_->NumClassDefs() != 1) {
528 RecordFailure(ERR(ILLEGAL_ARGUMENT),
529 StringPrintf("Expected 1 class def in dex file but found %d",
530 dex_file_->NumClassDefs()));
531 return false;
532 }
533 // Get the ClassDef from the new DexFile.
534 // Since the dex file has only a single class def the index is always 0.
535 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
536 // Get the class as it is now.
537 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
538
539 // Check the access flags didn't change.
540 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
541 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
542 "Cannot change modifiers of class by redefinition");
543 return false;
544 }
545
546 // Check class name.
547 // These should have been checked by the dexfile verifier on load.
548 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
549 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
550 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
551 if (!current_class->DescriptorEquals(descriptor)) {
552 std::string storage;
553 RecordFailure(ERR(NAMES_DONT_MATCH),
554 StringPrintf("expected file to contain class called '%s' but found '%s'!",
555 current_class->GetDescriptor(&storage),
556 descriptor));
557 return false;
558 }
559 if (current_class->IsObjectClass()) {
560 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
561 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
562 return false;
563 }
564 } else {
565 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
566 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
567 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
568 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
569 return false;
570 }
571 }
572 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
573 if (interfaces == nullptr) {
574 if (current_class->NumDirectInterfaces() != 0) {
575 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
576 return false;
577 }
578 } else {
579 DCHECK(!current_class->IsProxyClass());
580 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
581 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
582 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
583 return false;
584 }
585 // The order of interfaces is (barely) meaningful so we error if it changes.
586 const art::DexFile& orig_dex_file = current_class->GetDexFile();
587 for (uint32_t i = 0; i < interfaces->Size(); i++) {
588 if (strcmp(
589 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
590 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
591 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
592 "Interfaces changed or re-ordered");
593 return false;
594 }
595 }
596 }
597 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800598 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000599
600 return true;
601}
602
603// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800604bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800605 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800606 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000607
Alex Lighte4a88632017-01-10 07:41:24 -0800608 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
609 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
610 if (res != OK) {
611 RecordFailure(res, err);
612 return false;
613 } else {
614 return true;
615 }
Alex Light460d1b42017-01-10 15:37:17 +0000616}
617
Alex Light0e692732017-01-10 15:00:05 -0800618bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000619 return CheckRedefinable() &&
620 CheckClass() &&
621 CheckSameFields() &&
622 CheckSameMethods();
623}
624
Alex Light0e692732017-01-10 15:00:05 -0800625// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
626// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
627// having to deal with the fact that we need to hold an arbitrary number of references live.
628class RedefinitionDataHolder {
629 public:
630 enum DataSlot : int32_t {
631 kSlotSourceClassLoader = 0,
632 kSlotJavaDexFile = 1,
633 kSlotNewDexFileCookie = 2,
634 kSlotNewDexCache = 3,
635 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800636 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800637
638 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800639 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800640 };
641
642 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
643 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
644 // the passed in handle-scope.
645 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
646 art::Runtime* runtime,
647 art::Thread* self,
648 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
649 arr_(
650 hs->NewHandle(
651 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
652 self,
653 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
654 num_redefinitions * kNumSlots))) {}
655
656 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
657 return arr_.IsNull();
658 }
659
660 // TODO Maybe make an iterable view type to simplify using this.
661 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
662 REQUIRES_SHARED(art::Locks::mutator_lock_) {
663 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
664 }
665 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
666 return GetSlot(klass_index, kSlotJavaDexFile);
667 }
668 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
669 REQUIRES_SHARED(art::Locks::mutator_lock_) {
670 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
671 }
672 art::mirror::DexCache* GetNewDexCache(jint klass_index)
673 REQUIRES_SHARED(art::Locks::mutator_lock_) {
674 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
675 }
676 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
677 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
678 }
679
Alex Lighta7e38d82017-01-19 14:57:28 -0800680 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index)
681 REQUIRES_SHARED(art::Locks::mutator_lock_) {
682 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
683 }
684
Alex Light0e692732017-01-10 15:00:05 -0800685 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
686 REQUIRES_SHARED(art::Locks::mutator_lock_) {
687 SetSlot(klass_index, kSlotSourceClassLoader, loader);
688 }
689 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
690 REQUIRES_SHARED(art::Locks::mutator_lock_) {
691 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
692 }
693 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
694 REQUIRES_SHARED(art::Locks::mutator_lock_) {
695 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
696 }
697 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
698 REQUIRES_SHARED(art::Locks::mutator_lock_) {
699 SetSlot(klass_index, kSlotNewDexCache, cache);
700 }
701 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
702 REQUIRES_SHARED(art::Locks::mutator_lock_) {
703 SetSlot(klass_index, kSlotMirrorClass, klass);
704 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800705 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
706 REQUIRES_SHARED(art::Locks::mutator_lock_) {
707 SetSlot(klass_index, kSlotOrigDexFile, bytes);
708 }
Alex Light0e692732017-01-10 15:00:05 -0800709
710 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
711 return arr_->GetLength() / kNumSlots;
712 }
713
714 private:
715 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
716
717 art::mirror::Object* GetSlot(jint klass_index,
718 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
719 DCHECK_LT(klass_index, Length());
720 return arr_->Get((kNumSlots * klass_index) + slot);
721 }
722
723 void SetSlot(jint klass_index,
724 DataSlot slot,
725 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
726 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
727 DCHECK_LT(klass_index, Length());
728 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
729 }
730
731 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
732};
733
Alex Lighta7e38d82017-01-19 14:57:28 -0800734bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
735 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
736 art::StackHandleScope<2> hs(driver_->self_);
737 holder->SetMirrorClass(klass_index, GetMirrorClass());
738 // This shouldn't allocate
739 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
740 holder->SetSourceClassLoader(klass_index, loader.Get());
741 if (loader.Get() == nullptr) {
742 // TODO Better error msg.
743 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
744 return false;
745 }
Alex Lighteb98b082017-01-25 13:02:32 -0800746 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
747 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lighta7e38d82017-01-19 14:57:28 -0800748 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
749 if (dex_file_obj.Get() == nullptr) {
750 // TODO Better error msg.
751 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
752 return false;
753 }
Alex Lighteb98b082017-01-25 13:02:32 -0800754 holder->SetNewDexFileCookie(klass_index,
755 ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
756 dex_file_obj,
757 dex_file_.get()).Ptr());
Alex Lighta7e38d82017-01-19 14:57:28 -0800758 if (holder->GetNewDexFileCookie(klass_index) == nullptr) {
759 driver_->self_->AssertPendingOOMException();
760 driver_->self_->ClearException();
761 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
762 return false;
763 }
764 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
765 if (holder->GetNewDexCache(klass_index) == nullptr) {
766 driver_->self_->AssertPendingOOMException();
767 driver_->self_->ClearException();
768 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
769 return false;
770 }
771
772 // We won't always need to set this field.
773 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
774 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
775 driver_->self_->AssertPendingOOMException();
776 driver_->self_->ClearException();
777 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
778 return false;
779 }
780 return true;
781}
782
Alex Light0e692732017-01-10 15:00:05 -0800783bool Redefiner::CheckAllRedefinitionAreValid() {
784 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
785 if (!redef.CheckRedefinitionIsValid()) {
786 return false;
787 }
788 }
789 return true;
790}
791
792bool Redefiner::EnsureAllClassAllocationsFinished() {
793 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
794 if (!redef.EnsureClassAllocationsFinished()) {
795 return false;
796 }
797 }
798 return true;
799}
800
801bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
802 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -0800803 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -0800804 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -0800805 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -0800806 return false;
807 }
Alex Light0e692732017-01-10 15:00:05 -0800808 cnt++;
809 }
810 return true;
811}
812
813void Redefiner::ClassRedefinition::ReleaseDexFile() {
814 dex_file_.release();
815}
816
817void Redefiner::ReleaseAllDexFiles() {
818 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
819 redef.ReleaseDexFile();
820 }
821}
822
Alex Lighta01de592016-11-15 10:43:06 -0800823jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800824 art::StackHandleScope<1> hs(self_);
825 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
826 // We will let this be collected after the end of this function.
827 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
828 if (holder.IsNull()) {
829 self_->AssertPendingOOMException();
830 self_->ClearException();
831 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
832 return result_;
833 }
834
Alex Lighta01de592016-11-15 10:43:06 -0800835 // First we just allocate the ClassExt and its fields that we need. These can be updated
836 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
837 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
838 // between allocating them and pausing all threads before we can update them so we need to do a
839 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800840 if (!CheckAllRedefinitionAreValid() ||
841 !EnsureAllClassAllocationsFinished() ||
842 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800843 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
844 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800845 // declared_methods_.length) but would be good to get rid of. All other allocations should be
846 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800847 return result_;
848 }
Alex Light6abd5392017-01-05 17:53:00 -0800849 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
850 // allocating so no deadlocks.
851 art::gc::Heap* heap = runtime_->GetHeap();
852 if (heap->IsGcConcurrentAndMoving()) {
853 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
854 heap->IncrementDisableMovingGC(self_);
855 }
Alex Lighta01de592016-11-15 10:43:06 -0800856 // Do transition to final suspension
857 // TODO We might want to give this its own suspended state!
858 // TODO This isn't right. We need to change state without any chance of suspend ideally!
859 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
860 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800861 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800862 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
863 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
864 // TODO We need to update all debugger MethodIDs so they note the method they point to is
865 // obsolete or implement some other well defined semantics.
866 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light0e692732017-01-10 15:00:05 -0800867 int32_t cnt = 0;
868 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -0800869 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light0e692732017-01-10 15:00:05 -0800870 art::mirror::Class* klass = holder.GetMirrorClass(cnt);
Alex Lighteb98b082017-01-25 13:02:32 -0800871 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(cnt),
872 holder.GetNewDexFileCookie(cnt));
Alex Light0e692732017-01-10 15:00:05 -0800873 // TODO Rewrite so we don't do a stack walk for each and every class.
874 redef.FindAndAllocateObsoleteMethods(klass);
Alex Lighta7e38d82017-01-19 14:57:28 -0800875 redef.UpdateClass(klass, holder.GetNewDexCache(cnt), holder.GetOriginalDexFileBytes(cnt));
Alex Light0e692732017-01-10 15:00:05 -0800876 cnt++;
877 }
Alex Lightdba61482016-12-21 08:20:29 -0800878 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
879 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
Alex Light0e692732017-01-10 15:00:05 -0800880 // DexCache. (b/33630159)
Alex Lightdba61482016-12-21 08:20:29 -0800881 // TODO This can fail (leave some methods optimized) near runtime methods (including
882 // quick-to-interpreter transition function).
883 // TODO We probably don't need this at all once we have a way to ensure that the
884 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
885 // stack-walker.
886 EnsureObsoleteMethodsAreDeoptimized();
887 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -0800888 // TODO Shrink the obsolete method maps if possible?
889 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800890 // TODO Put this into a scoped thing.
891 runtime_->GetThreadList()->ResumeAll();
892 // Get back shared mutator lock as expected for return.
893 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800894 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
895 // owns the DexFile and when ownership is transferred.
896 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -0800897 if (heap->IsGcConcurrentAndMoving()) {
898 heap->DecrementDisableMovingGC(self_);
899 }
Alex Lighta01de592016-11-15 10:43:06 -0800900 return OK;
901}
902
Alex Light0e692732017-01-10 15:00:05 -0800903void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
904 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
905 const art::DexFile::ClassDef& class_def) {
906 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800907 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800908 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800909 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800910 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800911 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
912 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
913 art::dex::TypeIndex method_return_idx =
914 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
915 const auto* old_type_list = method.GetParameterTypeList();
916 std::vector<art::dex::TypeIndex> new_type_list;
917 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
918 new_type_list.push_back(
919 dex_file_->GetIndexForTypeId(
920 *dex_file_->FindTypeId(
921 old_dex_file.GetTypeDescriptor(
922 old_dex_file.GetTypeId(
923 old_type_list->GetTypeItem(i).type_idx_)))));
924 }
925 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
926 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000927 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800928 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800929 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
930 *new_name_id,
931 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000932 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800933 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800934 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
935 method.SetDexMethodIndex(dex_method_idx);
936 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800937 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800938 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800939 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -0800940 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -0800941 if (jit != nullptr) {
942 jit->GetCodeCache()->NotifyMethodRedefined(&method);
943 }
Alex Lighta01de592016-11-15 10:43:06 -0800944 }
Alex Light200b9d72016-12-15 11:34:13 -0800945}
946
Alex Light0e692732017-01-10 15:00:05 -0800947void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -0800948 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
949 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
950 for (art::ArtField& field : fields_iter) {
951 std::string declaring_class_name;
952 const art::DexFile::TypeId* new_declaring_id =
953 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
954 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
955 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
956 // TODO Handle error, cleanup.
957 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
958 const art::DexFile::FieldId* new_field_id =
959 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
960 CHECK(new_field_id != nullptr);
961 // We only need to update the index since the other data in the ArtField cannot be updated.
962 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
963 }
964 }
Alex Light200b9d72016-12-15 11:34:13 -0800965}
966
967// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -0800968void Redefiner::ClassRedefinition::UpdateClass(
969 art::ObjPtr<art::mirror::Class> mclass,
970 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
971 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -0800972 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
973 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
974 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -0800975 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -0800976
Alex Lighta01de592016-11-15 10:43:06 -0800977 // Update the class fields.
978 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
979 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
980 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -0800981 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -0800982 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -0800983 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
984 CHECK(!ext.IsNull());
985 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -0800986}
987
Alex Lighta01de592016-11-15 10:43:06 -0800988// This function does all (java) allocations we need to do for the Class being redefined.
989// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -0800990bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
991 art::StackHandleScope<2> hs(driver_->self_);
992 art::Handle<art::mirror::Class> klass(hs.NewHandle(
993 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -0800994 if (klass.Get() == nullptr) {
995 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
996 return false;
997 }
998 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -0800999 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001000 if (ext.Get() == nullptr) {
1001 // No memory. Clear exception (it's not useful) and return error.
1002 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1003 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001004 driver_->self_->AssertPendingOOMException();
1005 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001006 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1007 return false;
1008 }
1009 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1010 // are only modified when all threads (other than the modifying one) are suspended we don't need
1011 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1012 // however, since that can happen at any time.
1013 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1014 // are no obsolete methods.
1015 {
Alex Light0e692732017-01-10 15:00:05 -08001016 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001017 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001018 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001019 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001020 driver_->self_->AssertPendingOOMException();
1021 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001022 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1023 return false;
1024 }
1025 }
1026 return true;
1027}
1028
1029} // namespace openjdkjvmti