blob: eb4c2f9f211680dfa0bafbf9b500f6d4e8499990 [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),
Alex Light4ba388a2017-01-27 10:26:49 -080078 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -080079
80 ~ObsoleteMethodStackVisitor() OVERRIDE {}
81
82 public:
83 // Returns true if we successfully installed obsolete methods on this thread, filling
84 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
85 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080086 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080087 art::Thread* thread,
88 art::LinearAlloc* allocator,
89 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080090 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
91 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080092 ObsoleteMethodStackVisitor visitor(thread,
93 allocator,
94 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080095 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -080096 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -080097 }
98
99 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
100 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800101 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800102 // We cannot ensure that the right dex file is used in inlined frames so we don't support
103 // redefining them.
104 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
105 // TODO We should really support intrinsic obsolete methods.
106 // TODO We should really support redefining intrinsics.
107 // We don't support intrinsics so check for them here.
108 DCHECK(!old_method->IsIntrinsic());
109 art::ArtMethod* new_obsolete_method = nullptr;
110 auto obsolete_method_pair = obsolete_maps_->find(old_method);
111 if (obsolete_method_pair == obsolete_maps_->end()) {
112 // Create a new Obsolete Method and put it in the list.
113 art::Runtime* runtime = art::Runtime::Current();
114 art::ClassLinker* cl = runtime->GetClassLinker();
115 auto ptr_size = cl->GetImagePointerSize();
116 const size_t method_size = art::ArtMethod::Size(ptr_size);
117 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800118 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
119 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800120 new_obsolete_method = new (method_storage) art::ArtMethod();
121 new_obsolete_method->CopyFrom(old_method, ptr_size);
122 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
123 new_obsolete_method->SetIsObsolete();
124 obsolete_maps_->insert({old_method, new_obsolete_method});
125 // Update JIT Data structures to point to the new method.
126 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
127 if (jit != nullptr) {
128 // Notify the JIT we are making this obsolete method. It will update the jit's internal
129 // structures to keep track of the new obsolete method.
130 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
131 }
132 } else {
133 new_obsolete_method = obsolete_method_pair->second;
134 }
135 DCHECK(new_obsolete_method != nullptr);
136 SetMethod(new_obsolete_method);
137 }
138 return true;
139 }
140
141 private:
142 // The linear allocator we should use to make new methods.
143 art::LinearAlloc* allocator_;
144 // The set of all methods which could be obsoleted.
145 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
146 // A map from the original to the newly allocated obsolete method for frames on this thread. The
147 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
148 // the redefined classes ClassExt by the caller.
149 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800150};
151
Alex Lighte4a88632017-01-10 07:41:24 -0800152jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
153 jclass klass,
154 jboolean* is_redefinable) {
155 // TODO Check for the appropriate feature flags once we have enabled them.
156 art::Thread* self = art::Thread::Current();
157 art::ScopedObjectAccess soa(self);
158 art::StackHandleScope<1> hs(self);
159 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
160 if (obj.IsNull()) {
161 return ERR(INVALID_CLASS);
162 }
163 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
164 std::string err_unused;
165 *is_redefinable =
166 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
167 return OK;
168}
169
170jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
171 /*out*/std::string* error_msg) {
172 if (klass->IsPrimitive()) {
173 *error_msg = "Modification of primitive classes is not supported";
174 return ERR(UNMODIFIABLE_CLASS);
175 } else if (klass->IsInterface()) {
176 *error_msg = "Modification of Interface classes is currently not supported";
177 return ERR(UNMODIFIABLE_CLASS);
178 } else if (klass->IsArrayClass()) {
179 *error_msg = "Modification of Array classes is not supported";
180 return ERR(UNMODIFIABLE_CLASS);
181 } else if (klass->IsProxyClass()) {
182 *error_msg = "Modification of proxy classes is not supported";
183 return ERR(UNMODIFIABLE_CLASS);
184 }
185
186 // TODO We should check if the class has non-obsoletable methods on the stack
187 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
188 return OK;
189}
190
Alex Lighta01de592016-11-15 10:43:06 -0800191// Moves dex data to an anonymous, read-only mmap'd region.
192std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
193 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800194 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800195 std::string* error_msg) {
196 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800197 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800198 nullptr,
199 data_len,
200 PROT_READ|PROT_WRITE,
201 /*low_4gb*/false,
202 /*reuse*/false,
203 error_msg));
204 if (map == nullptr) {
205 return map;
206 }
207 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800208 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
209 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800210 map->Protect(PROT_READ);
211 return map;
212}
213
Alex Lighta7e38d82017-01-19 14:57:28 -0800214Redefiner::ClassRedefinition::ClassRedefinition(
215 Redefiner* driver,
216 jclass klass,
217 const art::DexFile* redefined_dex_file,
218 const char* class_sig,
219 art::ArraySlice<const unsigned char> orig_dex_file) :
220 driver_(driver),
221 klass_(klass),
222 dex_file_(redefined_dex_file),
223 class_sig_(class_sig),
224 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800225 GetMirrorClass()->MonitorEnter(driver_->self_);
226}
227
228Redefiner::ClassRedefinition::~ClassRedefinition() {
229 if (driver_ != nullptr) {
230 GetMirrorClass()->MonitorExit(driver_->self_);
231 }
232}
233
Alex Light0e692732017-01-10 15:00:05 -0800234jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
235 art::Runtime* runtime,
236 art::Thread* self,
237 jint class_count,
238 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800239 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800240 if (env == nullptr) {
241 *error_msg = "env was null!";
242 return ERR(INVALID_ENVIRONMENT);
243 } else if (class_count < 0) {
244 *error_msg = "class_count was less then 0";
245 return ERR(ILLEGAL_ARGUMENT);
246 } else if (class_count == 0) {
247 // We don't actually need to do anything. Just return OK.
248 return OK;
249 } else if (definitions == nullptr) {
250 *error_msg = "null definitions!";
251 return ERR(NULL_POINTER);
252 }
Alex Light6ac57502017-01-19 15:05:06 -0800253 std::vector<ArtClassDefinition> def_vector;
254 def_vector.reserve(class_count);
255 for (jint i = 0; i < class_count; i++) {
256 // We make a copy of the class_bytes to pass into the retransformation.
257 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
258 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
259 // to get the passed in bytes.
260 // TODO Implement saving the original bytes.
261 unsigned char* class_bytes_copy = nullptr;
262 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
263 if (res != OK) {
264 return res;
265 }
266 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
267
268 ArtClassDefinition def;
269 def.dex_len = definitions[i].class_byte_count;
270 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
271 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800272 def.SetModified();
273 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
274 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800275 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
276 if (res != OK) {
277 return res;
278 }
279 def_vector.push_back(std::move(def));
280 }
281 // Call all the transformation events.
282 jvmtiError res = Transformer::RetransformClassesDirect(env,
283 self,
284 &def_vector);
285 if (res != OK) {
286 // Something went wrong with transformation!
287 return res;
288 }
289 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
290}
291
292jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
293 art::Runtime* runtime,
294 art::Thread* self,
295 const std::vector<ArtClassDefinition>& definitions,
296 std::string* error_msg) {
297 DCHECK(env != nullptr);
298 if (definitions.size() == 0) {
299 // We don't actually need to do anything. Just return OK.
300 return OK;
301 }
Alex Light0e692732017-01-10 15:00:05 -0800302 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
303 // are going to redefine.
304 art::jit::ScopedJitSuspend suspend_jit;
305 // Get shared mutator lock so we can lock all the classes.
306 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800307 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800308 for (const ArtClassDefinition& def : definitions) {
309 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800310 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800311 jvmtiError res = r.AddRedefinition(env, def);
312 if (res != OK) {
313 return res;
314 }
Alex Light0e692732017-01-10 15:00:05 -0800315 }
316 }
317 return r.Run();
318}
319
Alex Light6ac57502017-01-19 15:05:06 -0800320jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800321 std::string original_dex_location;
322 jvmtiError ret = OK;
323 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
324 *error_msg_ = "Unable to get original dex file location!";
325 return ret;
326 }
Alex Light52a2db52017-01-19 23:00:21 +0000327 char* generic_ptr_unused = nullptr;
328 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800329 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
330 *error_msg_ = "Unable to get class signature!";
331 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000332 }
Alex Light52a2db52017-01-19 23:00:21 +0000333 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800334 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
335 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
336 def.dex_len,
337 def.dex_data.get(),
338 error_msg_));
339 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800340 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800341 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800342 << "in dex file " << original_dex_location << " because: " << *error_msg_;
343 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800344 return ERR(OUT_OF_MEMORY);
345 }
346 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800347 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800348 return ERR(INVALID_CLASS_FORMAT);
349 }
350 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
351 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
352 checksum,
353 std::move(map),
354 /*verify*/true,
355 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800356 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800357 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800358 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800359 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800360 return ERR(INVALID_CLASS_FORMAT);
361 }
Alex Light0e692732017-01-10 15:00:05 -0800362 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800363 Redefiner::ClassRedefinition(this,
364 def.klass,
365 dex_file.release(),
366 signature_ptr,
367 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800368 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800369}
370
Alex Light0e692732017-01-10 15:00:05 -0800371art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
372 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800373}
374
Alex Light0e692732017-01-10 15:00:05 -0800375art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800376 return GetMirrorClass()->GetClassLoader();
377}
378
Alex Light0e692732017-01-10 15:00:05 -0800379art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
380 art::Handle<art::mirror::ClassLoader> loader) {
381 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800382}
383
Alex Light0e692732017-01-10 15:00:05 -0800384void Redefiner::RecordFailure(jvmtiError result,
385 const std::string& class_sig,
386 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800387 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800388 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800389 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800390 result_ = result;
391}
392
Alex Lighta7e38d82017-01-19 14:57:28 -0800393art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
394 // If we have been specifically given a new set of bytes use that
395 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800396 return art::mirror::ByteArray::AllocateAndFill(
397 driver_->self_,
398 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
399 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800400 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800401
402 // See if we already have one set.
403 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
404 if (!ext.IsNull()) {
405 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
406 if (!old_original_bytes.IsNull()) {
407 // We do. Use it.
408 return old_original_bytes.Ptr();
409 }
Alex Lighta01de592016-11-15 10:43:06 -0800410 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800411
412 // Copy the current dex_file
413 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
414 // TODO Handle this or make it so it cannot happen.
415 if (current_dex_file.NumClassDefs() != 1) {
416 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
417 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800418 }
Alex Light440b5d92017-01-24 15:32:25 -0800419 return art::mirror::ByteArray::AllocateAndFill(
420 driver_->self_,
421 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
422 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800423}
424
Alex Lightdba61482016-12-21 08:20:29 -0800425struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800426 art::LinearAlloc* allocator;
427 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
428 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800429
Alex Light0e692732017-01-10 15:00:05 -0800430 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800431};
432
Alex Lightdba61482016-12-21 08:20:29 -0800433void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
434 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800435 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
436 data->allocator,
437 data->obsolete_methods,
438 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800439}
440
441// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
442// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800443// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
444void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800445 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
446 art::mirror::ClassExt* ext = art_klass->GetExtData();
447 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800448 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
449 CallbackCtx ctx(linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800450 // Add all the declared methods to the map
451 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
452 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800453 // TODO Allow this or check in IsModifiableClass.
454 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800455 }
456 {
Alex Light0e692732017-01-10 15:00:05 -0800457 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800458 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
459 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800460 }
461 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800462}
463
464// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
465// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800466void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800467 art::mirror::Class* art_klass,
468 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
469 int32_t index = 0;
470 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
471 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
472 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
473 ext_data->GetObsoleteDexCaches();
474 int32_t num_method_slots = obsolete_methods->GetLength();
475 // Find the first empty index.
476 for (; index < num_method_slots; index++) {
477 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
478 index, art::kRuntimePointerSize) == nullptr) {
479 break;
480 }
481 }
482 // Make sure we have enough space.
483 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
484 CHECK(obsolete_dex_caches->Get(index) == nullptr);
485 // Fill in the map.
486 for (auto& obs : obsoletes) {
487 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
488 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
489 index++;
490 }
491}
492
Alex Light0e692732017-01-10 15:00:05 -0800493bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000494 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800495 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000496 // Easy check that only 1 class def is present.
497 if (dex_file_->NumClassDefs() != 1) {
498 RecordFailure(ERR(ILLEGAL_ARGUMENT),
499 StringPrintf("Expected 1 class def in dex file but found %d",
500 dex_file_->NumClassDefs()));
501 return false;
502 }
503 // Get the ClassDef from the new DexFile.
504 // Since the dex file has only a single class def the index is always 0.
505 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
506 // Get the class as it is now.
507 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
508
509 // Check the access flags didn't change.
510 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
511 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
512 "Cannot change modifiers of class by redefinition");
513 return false;
514 }
515
516 // Check class name.
517 // These should have been checked by the dexfile verifier on load.
518 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
519 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
520 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
521 if (!current_class->DescriptorEquals(descriptor)) {
522 std::string storage;
523 RecordFailure(ERR(NAMES_DONT_MATCH),
524 StringPrintf("expected file to contain class called '%s' but found '%s'!",
525 current_class->GetDescriptor(&storage),
526 descriptor));
527 return false;
528 }
529 if (current_class->IsObjectClass()) {
530 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
531 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
532 return false;
533 }
534 } else {
535 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
536 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
537 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
538 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
539 return false;
540 }
541 }
542 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
543 if (interfaces == nullptr) {
544 if (current_class->NumDirectInterfaces() != 0) {
545 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
546 return false;
547 }
548 } else {
549 DCHECK(!current_class->IsProxyClass());
550 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
551 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
552 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
553 return false;
554 }
555 // The order of interfaces is (barely) meaningful so we error if it changes.
556 const art::DexFile& orig_dex_file = current_class->GetDexFile();
557 for (uint32_t i = 0; i < interfaces->Size(); i++) {
558 if (strcmp(
559 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
560 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
561 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
562 "Interfaces changed or re-ordered");
563 return false;
564 }
565 }
566 }
567 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800568 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000569
570 return true;
571}
572
573// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800574bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800575 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800576 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000577
Alex Lighte4a88632017-01-10 07:41:24 -0800578 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
579 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
580 if (res != OK) {
581 RecordFailure(res, err);
582 return false;
583 } else {
584 return true;
585 }
Alex Light460d1b42017-01-10 15:37:17 +0000586}
587
Alex Light0e692732017-01-10 15:00:05 -0800588bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000589 return CheckRedefinable() &&
590 CheckClass() &&
591 CheckSameFields() &&
592 CheckSameMethods();
593}
594
Alex Light0e692732017-01-10 15:00:05 -0800595// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
596// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
597// having to deal with the fact that we need to hold an arbitrary number of references live.
598class RedefinitionDataHolder {
599 public:
600 enum DataSlot : int32_t {
601 kSlotSourceClassLoader = 0,
602 kSlotJavaDexFile = 1,
603 kSlotNewDexFileCookie = 2,
604 kSlotNewDexCache = 3,
605 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800606 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800607
608 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800609 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800610 };
611
612 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
613 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
614 // the passed in handle-scope.
615 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
616 art::Runtime* runtime,
617 art::Thread* self,
618 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
619 arr_(
620 hs->NewHandle(
621 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
622 self,
623 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
624 num_redefinitions * kNumSlots))) {}
625
626 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
627 return arr_.IsNull();
628 }
629
630 // TODO Maybe make an iterable view type to simplify using this.
631 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
632 REQUIRES_SHARED(art::Locks::mutator_lock_) {
633 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
634 }
635 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
636 return GetSlot(klass_index, kSlotJavaDexFile);
637 }
638 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
639 REQUIRES_SHARED(art::Locks::mutator_lock_) {
640 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
641 }
642 art::mirror::DexCache* GetNewDexCache(jint klass_index)
643 REQUIRES_SHARED(art::Locks::mutator_lock_) {
644 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
645 }
646 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
647 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
648 }
649
Alex Lighta7e38d82017-01-19 14:57:28 -0800650 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index)
651 REQUIRES_SHARED(art::Locks::mutator_lock_) {
652 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
653 }
654
Alex Light0e692732017-01-10 15:00:05 -0800655 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
656 REQUIRES_SHARED(art::Locks::mutator_lock_) {
657 SetSlot(klass_index, kSlotSourceClassLoader, loader);
658 }
659 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
660 REQUIRES_SHARED(art::Locks::mutator_lock_) {
661 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
662 }
663 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
664 REQUIRES_SHARED(art::Locks::mutator_lock_) {
665 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
666 }
667 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
668 REQUIRES_SHARED(art::Locks::mutator_lock_) {
669 SetSlot(klass_index, kSlotNewDexCache, cache);
670 }
671 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
672 REQUIRES_SHARED(art::Locks::mutator_lock_) {
673 SetSlot(klass_index, kSlotMirrorClass, klass);
674 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800675 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
676 REQUIRES_SHARED(art::Locks::mutator_lock_) {
677 SetSlot(klass_index, kSlotOrigDexFile, bytes);
678 }
Alex Light0e692732017-01-10 15:00:05 -0800679
680 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
681 return arr_->GetLength() / kNumSlots;
682 }
683
684 private:
685 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
686
687 art::mirror::Object* GetSlot(jint klass_index,
688 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
689 DCHECK_LT(klass_index, Length());
690 return arr_->Get((kNumSlots * klass_index) + slot);
691 }
692
693 void SetSlot(jint klass_index,
694 DataSlot slot,
695 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
696 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
697 DCHECK_LT(klass_index, Length());
698 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
699 }
700
701 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
702};
703
Alex Light1babae02017-02-01 15:35:34 -0800704// Looks through the previously allocated cookies to see if we need to update them with another new
705// dexfile. This is so that even if multiple classes with the same classloader are redefined at
706// once they are all added to the classloader.
707bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
708 int32_t klass_index,
709 art::Handle<art::mirror::ClassLoader> source_class_loader,
710 art::Handle<art::mirror::Object> dex_file_obj,
711 /*out*/RedefinitionDataHolder* holder) {
712 art::StackHandleScope<2> hs(driver_->self_);
713 art::MutableHandle<art::mirror::LongArray> old_cookie(
714 hs.NewHandle<art::mirror::LongArray>(nullptr));
715 bool has_older_cookie = false;
716 // See if we already have a cookie that a previous redefinition got from the same classloader.
717 for (int32_t i = 0; i < klass_index; i++) {
718 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
719 // Since every instance of this classloader should have the same cookie associated with it we
720 // can stop looking here.
721 has_older_cookie = true;
722 old_cookie.Assign(holder->GetNewDexFileCookie(i));
723 break;
724 }
725 }
726 if (old_cookie.IsNull()) {
727 // No older cookie. Get it directly from the dex_file_obj
728 // We should not have seen this classloader elsewhere.
729 CHECK(!has_older_cookie);
730 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
731 }
732 // Use the old cookie to generate the new one with the new DexFile* added in.
733 art::Handle<art::mirror::LongArray>
734 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
735 old_cookie,
736 dex_file_.get())));
737 // Make sure the allocation worked.
738 if (new_cookie.IsNull()) {
739 return false;
740 }
741
742 // Save the cookie.
743 holder->SetNewDexFileCookie(klass_index, new_cookie.Get());
744 // If there are other copies of this same classloader we need to make sure that we all have the
745 // same cookie.
746 if (has_older_cookie) {
747 for (int32_t i = 0; i < klass_index; i++) {
748 // We will let the GC take care of the cookie we allocated for this one.
749 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
750 holder->SetNewDexFileCookie(i, new_cookie.Get());
751 }
752 }
753 }
754
755 return true;
756}
757
Alex Lighta7e38d82017-01-19 14:57:28 -0800758bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
759 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800760 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800761 art::StackHandleScope<2> hs(driver_->self_);
762 holder->SetMirrorClass(klass_index, GetMirrorClass());
763 // This shouldn't allocate
764 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800765 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
766 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
767 holder->SetSourceClassLoader(klass_index, loader.Get());
768 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
769 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
770 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
771 if (dex_file_obj.Get() == nullptr) {
772 // TODO Better error msg.
773 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
774 return false;
775 }
Alex Light1babae02017-02-01 15:35:34 -0800776 // Allocate the new dex file cookie.
777 if (!AllocateAndRememberNewDexFileCookie(klass_index, loader, dex_file_obj, holder)) {
Alex Light7916f202017-01-27 09:00:15 -0800778 driver_->self_->AssertPendingOOMException();
779 driver_->self_->ClearException();
780 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
781 return false;
782 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800783 }
784 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
785 if (holder->GetNewDexCache(klass_index) == nullptr) {
786 driver_->self_->AssertPendingOOMException();
787 driver_->self_->ClearException();
788 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
789 return false;
790 }
791
792 // We won't always need to set this field.
793 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
794 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
795 driver_->self_->AssertPendingOOMException();
796 driver_->self_->ClearException();
797 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
798 return false;
799 }
800 return true;
801}
802
Alex Light0e692732017-01-10 15:00:05 -0800803bool Redefiner::CheckAllRedefinitionAreValid() {
804 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
805 if (!redef.CheckRedefinitionIsValid()) {
806 return false;
807 }
808 }
809 return true;
810}
811
812bool Redefiner::EnsureAllClassAllocationsFinished() {
813 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
814 if (!redef.EnsureClassAllocationsFinished()) {
815 return false;
816 }
817 }
818 return true;
819}
820
821bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
822 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -0800823 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -0800824 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -0800825 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -0800826 return false;
827 }
Alex Light0e692732017-01-10 15:00:05 -0800828 cnt++;
829 }
830 return true;
831}
832
833void Redefiner::ClassRedefinition::ReleaseDexFile() {
834 dex_file_.release();
835}
836
837void Redefiner::ReleaseAllDexFiles() {
838 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
839 redef.ReleaseDexFile();
840 }
841}
842
Alex Lighta01de592016-11-15 10:43:06 -0800843jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800844 art::StackHandleScope<1> hs(self_);
845 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
846 // We will let this be collected after the end of this function.
847 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
848 if (holder.IsNull()) {
849 self_->AssertPendingOOMException();
850 self_->ClearException();
851 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
852 return result_;
853 }
854
Alex Lighta01de592016-11-15 10:43:06 -0800855 // First we just allocate the ClassExt and its fields that we need. These can be updated
856 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
857 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
858 // between allocating them and pausing all threads before we can update them so we need to do a
859 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800860 if (!CheckAllRedefinitionAreValid() ||
861 !EnsureAllClassAllocationsFinished() ||
862 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800863 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
864 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800865 // declared_methods_.length) but would be good to get rid of. All other allocations should be
866 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800867 return result_;
868 }
Alex Light7916f202017-01-27 09:00:15 -0800869 int32_t counter = 0;
870 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
871 if (holder.GetSourceClassLoader(counter) == nullptr) {
872 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
873 }
874 counter++;
875 }
Alex Light6abd5392017-01-05 17:53:00 -0800876 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
877 // allocating so no deadlocks.
878 art::gc::Heap* heap = runtime_->GetHeap();
879 if (heap->IsGcConcurrentAndMoving()) {
880 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
881 heap->IncrementDisableMovingGC(self_);
882 }
Alex Lighta01de592016-11-15 10:43:06 -0800883 // Do transition to final suspension
884 // TODO We might want to give this its own suspended state!
885 // TODO This isn't right. We need to change state without any chance of suspend ideally!
886 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
887 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800888 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800889 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
890 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
891 // TODO We need to update all debugger MethodIDs so they note the method they point to is
892 // obsolete or implement some other well defined semantics.
893 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light7916f202017-01-27 09:00:15 -0800894 counter = 0;
Alex Light0e692732017-01-10 15:00:05 -0800895 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -0800896 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light7916f202017-01-27 09:00:15 -0800897 if (holder.GetSourceClassLoader(counter) != nullptr) {
898 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(counter),
899 holder.GetNewDexFileCookie(counter));
900 }
901 art::mirror::Class* klass = holder.GetMirrorClass(counter);
Alex Light0e692732017-01-10 15:00:05 -0800902 // TODO Rewrite so we don't do a stack walk for each and every class.
903 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light7916f202017-01-27 09:00:15 -0800904 redef.UpdateClass(klass, holder.GetNewDexCache(counter),
905 holder.GetOriginalDexFileBytes(counter));
906 counter++;
Alex Light0e692732017-01-10 15:00:05 -0800907 }
Alex Lightdba61482016-12-21 08:20:29 -0800908 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -0800909 // TODO Shrink the obsolete method maps if possible?
910 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800911 // TODO Put this into a scoped thing.
912 runtime_->GetThreadList()->ResumeAll();
913 // Get back shared mutator lock as expected for return.
914 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800915 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
916 // owns the DexFile and when ownership is transferred.
917 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -0800918 if (heap->IsGcConcurrentAndMoving()) {
919 heap->DecrementDisableMovingGC(self_);
920 }
Alex Lighta01de592016-11-15 10:43:06 -0800921 return OK;
922}
923
Alex Light0e692732017-01-10 15:00:05 -0800924void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
925 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
926 const art::DexFile::ClassDef& class_def) {
927 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800928 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800929 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800930 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800931 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800932 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
933 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
934 art::dex::TypeIndex method_return_idx =
935 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
936 const auto* old_type_list = method.GetParameterTypeList();
937 std::vector<art::dex::TypeIndex> new_type_list;
938 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
939 new_type_list.push_back(
940 dex_file_->GetIndexForTypeId(
941 *dex_file_->FindTypeId(
942 old_dex_file.GetTypeDescriptor(
943 old_dex_file.GetTypeId(
944 old_type_list->GetTypeItem(i).type_idx_)))));
945 }
946 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
947 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000948 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800949 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800950 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
951 *new_name_id,
952 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000953 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800954 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800955 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
956 method.SetDexMethodIndex(dex_method_idx);
957 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800958 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800959 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800960 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -0800961 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -0800962 if (jit != nullptr) {
963 jit->GetCodeCache()->NotifyMethodRedefined(&method);
964 }
Alex Lighta01de592016-11-15 10:43:06 -0800965 }
Alex Light200b9d72016-12-15 11:34:13 -0800966}
967
Alex Light0e692732017-01-10 15:00:05 -0800968void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -0800969 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
970 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
971 for (art::ArtField& field : fields_iter) {
972 std::string declaring_class_name;
973 const art::DexFile::TypeId* new_declaring_id =
974 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
975 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
976 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
977 // TODO Handle error, cleanup.
978 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
979 const art::DexFile::FieldId* new_field_id =
980 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
981 CHECK(new_field_id != nullptr);
982 // We only need to update the index since the other data in the ArtField cannot be updated.
983 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
984 }
985 }
Alex Light200b9d72016-12-15 11:34:13 -0800986}
987
988// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -0800989void Redefiner::ClassRedefinition::UpdateClass(
990 art::ObjPtr<art::mirror::Class> mclass,
991 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
992 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -0800993 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
994 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
995 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -0800996 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -0800997
Alex Lighta01de592016-11-15 10:43:06 -0800998 // Update the class fields.
999 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1000 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1001 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001002 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001003 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001004 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1005 CHECK(!ext.IsNull());
1006 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001007}
1008
Alex Lighta01de592016-11-15 10:43:06 -08001009// This function does all (java) allocations we need to do for the Class being redefined.
1010// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001011bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1012 art::StackHandleScope<2> hs(driver_->self_);
1013 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1014 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001015 if (klass.Get() == nullptr) {
1016 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1017 return false;
1018 }
1019 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001020 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001021 if (ext.Get() == nullptr) {
1022 // No memory. Clear exception (it's not useful) and return error.
1023 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1024 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001025 driver_->self_->AssertPendingOOMException();
1026 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001027 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1028 return false;
1029 }
1030 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1031 // are only modified when all threads (other than the modifying one) are suspended we don't need
1032 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1033 // however, since that can happen at any time.
1034 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1035 // are no obsolete methods.
1036 {
Alex Light0e692732017-01-10 15:00:05 -08001037 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001038 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001039 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001040 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001041 driver_->self_->AssertPendingOOMException();
1042 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001043 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1044 return false;
1045 }
1046 }
1047 return true;
1048}
1049
1050} // namespace openjdkjvmti