blob: baa3b4ad02a683b966796c6eb8e04255d0b206bc [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light5643caf2017-02-08 11:39:07 -080041#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000042#include "dex_file.h"
43#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080044#include "events-inl.h"
45#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080046#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "instrumentation.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "jdwp/jdwp.h"
49#include "jdwp/jdwp_constants.h"
50#include "jdwp/jdwp_event.h"
51#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080052#include "jit/jit.h"
53#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "jni_env_ext-inl.h"
55#include "jvmti_allocator.h"
56#include "mirror/class.h"
57#include "mirror/class_ext.h"
58#include "mirror/object.h"
59#include "object_lock.h"
60#include "runtime.h"
61#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080062#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080063#include "transform.h"
Alex Lighta01de592016-11-15 10:43:06 -080064
65namespace openjdkjvmti {
66
Andreas Gampe46ee31b2016-12-14 10:11:49 -080067using android::base::StringPrintf;
68
Alex Lightdba61482016-12-21 08:20:29 -080069// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
70// some basic sanity checks that the obsolete method is sane.
71class ObsoleteMethodStackVisitor : public art::StackVisitor {
72 protected:
73 ObsoleteMethodStackVisitor(
74 art::Thread* thread,
75 art::LinearAlloc* allocator,
76 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080077 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -080078 : StackVisitor(thread,
79 /*context*/nullptr,
80 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
81 allocator_(allocator),
82 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -080083 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -080084
85 ~ObsoleteMethodStackVisitor() OVERRIDE {}
86
87 public:
88 // Returns true if we successfully installed obsolete methods on this thread, filling
89 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
90 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080091 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080092 art::Thread* thread,
93 art::LinearAlloc* allocator,
94 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080095 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
96 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080097 ObsoleteMethodStackVisitor visitor(thread,
98 allocator,
99 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800100 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800101 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800102 }
103
104 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
105 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800106 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800107 // We cannot ensure that the right dex file is used in inlined frames so we don't support
108 // redefining them.
109 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
110 // TODO We should really support intrinsic obsolete methods.
111 // TODO We should really support redefining intrinsics.
112 // We don't support intrinsics so check for them here.
113 DCHECK(!old_method->IsIntrinsic());
114 art::ArtMethod* new_obsolete_method = nullptr;
115 auto obsolete_method_pair = obsolete_maps_->find(old_method);
116 if (obsolete_method_pair == obsolete_maps_->end()) {
117 // Create a new Obsolete Method and put it in the list.
118 art::Runtime* runtime = art::Runtime::Current();
119 art::ClassLinker* cl = runtime->GetClassLinker();
120 auto ptr_size = cl->GetImagePointerSize();
121 const size_t method_size = art::ArtMethod::Size(ptr_size);
122 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800123 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
124 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800125 new_obsolete_method = new (method_storage) art::ArtMethod();
126 new_obsolete_method->CopyFrom(old_method, ptr_size);
127 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
128 new_obsolete_method->SetIsObsolete();
129 obsolete_maps_->insert({old_method, new_obsolete_method});
130 // Update JIT Data structures to point to the new method.
131 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
132 if (jit != nullptr) {
133 // Notify the JIT we are making this obsolete method. It will update the jit's internal
134 // structures to keep track of the new obsolete method.
135 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
136 }
137 } else {
138 new_obsolete_method = obsolete_method_pair->second;
139 }
140 DCHECK(new_obsolete_method != nullptr);
141 SetMethod(new_obsolete_method);
142 }
143 return true;
144 }
145
146 private:
147 // The linear allocator we should use to make new methods.
148 art::LinearAlloc* allocator_;
149 // The set of all methods which could be obsoleted.
150 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
151 // A map from the original to the newly allocated obsolete method for frames on this thread. The
152 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
153 // the redefined classes ClassExt by the caller.
154 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800155};
156
Alex Lighte4a88632017-01-10 07:41:24 -0800157jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
158 jclass klass,
159 jboolean* is_redefinable) {
160 // TODO Check for the appropriate feature flags once we have enabled them.
161 art::Thread* self = art::Thread::Current();
162 art::ScopedObjectAccess soa(self);
163 art::StackHandleScope<1> hs(self);
164 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
165 if (obj.IsNull()) {
166 return ERR(INVALID_CLASS);
167 }
168 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
169 std::string err_unused;
170 *is_redefinable =
171 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
172 return OK;
173}
174
175jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
176 /*out*/std::string* error_msg) {
177 if (klass->IsPrimitive()) {
178 *error_msg = "Modification of primitive classes is not supported";
179 return ERR(UNMODIFIABLE_CLASS);
180 } else if (klass->IsInterface()) {
181 *error_msg = "Modification of Interface classes is currently not supported";
182 return ERR(UNMODIFIABLE_CLASS);
183 } else if (klass->IsArrayClass()) {
184 *error_msg = "Modification of Array classes is not supported";
185 return ERR(UNMODIFIABLE_CLASS);
186 } else if (klass->IsProxyClass()) {
187 *error_msg = "Modification of proxy classes is not supported";
188 return ERR(UNMODIFIABLE_CLASS);
189 }
190
191 // TODO We should check if the class has non-obsoletable methods on the stack
192 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
193 return OK;
194}
195
Alex Lighta01de592016-11-15 10:43:06 -0800196// Moves dex data to an anonymous, read-only mmap'd region.
197std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
198 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800199 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800200 std::string* error_msg) {
201 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800202 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800203 nullptr,
204 data_len,
205 PROT_READ|PROT_WRITE,
206 /*low_4gb*/false,
207 /*reuse*/false,
208 error_msg));
209 if (map == nullptr) {
210 return map;
211 }
212 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800213 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
214 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800215 map->Protect(PROT_READ);
216 return map;
217}
218
Alex Lighta7e38d82017-01-19 14:57:28 -0800219Redefiner::ClassRedefinition::ClassRedefinition(
220 Redefiner* driver,
221 jclass klass,
222 const art::DexFile* redefined_dex_file,
223 const char* class_sig,
224 art::ArraySlice<const unsigned char> orig_dex_file) :
225 driver_(driver),
226 klass_(klass),
227 dex_file_(redefined_dex_file),
228 class_sig_(class_sig),
229 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800230 GetMirrorClass()->MonitorEnter(driver_->self_);
231}
232
233Redefiner::ClassRedefinition::~ClassRedefinition() {
234 if (driver_ != nullptr) {
235 GetMirrorClass()->MonitorExit(driver_->self_);
236 }
237}
238
Alex Light0e692732017-01-10 15:00:05 -0800239jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
240 art::Runtime* runtime,
241 art::Thread* self,
242 jint class_count,
243 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800244 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800245 if (env == nullptr) {
246 *error_msg = "env was null!";
247 return ERR(INVALID_ENVIRONMENT);
248 } else if (class_count < 0) {
249 *error_msg = "class_count was less then 0";
250 return ERR(ILLEGAL_ARGUMENT);
251 } else if (class_count == 0) {
252 // We don't actually need to do anything. Just return OK.
253 return OK;
254 } else if (definitions == nullptr) {
255 *error_msg = "null definitions!";
256 return ERR(NULL_POINTER);
257 }
Alex Light6ac57502017-01-19 15:05:06 -0800258 std::vector<ArtClassDefinition> def_vector;
259 def_vector.reserve(class_count);
260 for (jint i = 0; i < class_count; i++) {
261 // We make a copy of the class_bytes to pass into the retransformation.
262 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
263 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
264 // to get the passed in bytes.
265 // TODO Implement saving the original bytes.
266 unsigned char* class_bytes_copy = nullptr;
267 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
268 if (res != OK) {
269 return res;
270 }
271 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
272
273 ArtClassDefinition def;
274 def.dex_len = definitions[i].class_byte_count;
275 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
276 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800277 def.SetModified();
278 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
279 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800280 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
281 if (res != OK) {
282 return res;
283 }
284 def_vector.push_back(std::move(def));
285 }
286 // Call all the transformation events.
287 jvmtiError res = Transformer::RetransformClassesDirect(env,
288 self,
289 &def_vector);
290 if (res != OK) {
291 // Something went wrong with transformation!
292 return res;
293 }
294 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
295}
296
297jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
298 art::Runtime* runtime,
299 art::Thread* self,
300 const std::vector<ArtClassDefinition>& definitions,
301 std::string* error_msg) {
302 DCHECK(env != nullptr);
303 if (definitions.size() == 0) {
304 // We don't actually need to do anything. Just return OK.
305 return OK;
306 }
Alex Light0e692732017-01-10 15:00:05 -0800307 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
308 // are going to redefine.
309 art::jit::ScopedJitSuspend suspend_jit;
310 // Get shared mutator lock so we can lock all the classes.
311 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800312 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800313 for (const ArtClassDefinition& def : definitions) {
314 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800315 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800316 jvmtiError res = r.AddRedefinition(env, def);
317 if (res != OK) {
318 return res;
319 }
Alex Light0e692732017-01-10 15:00:05 -0800320 }
321 }
322 return r.Run();
323}
324
Alex Light6ac57502017-01-19 15:05:06 -0800325jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800326 std::string original_dex_location;
327 jvmtiError ret = OK;
328 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
329 *error_msg_ = "Unable to get original dex file location!";
330 return ret;
331 }
Alex Light52a2db52017-01-19 23:00:21 +0000332 char* generic_ptr_unused = nullptr;
333 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800334 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
335 *error_msg_ = "Unable to get class signature!";
336 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000337 }
Alex Light52a2db52017-01-19 23:00:21 +0000338 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800339 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
340 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
341 def.dex_len,
342 def.dex_data.get(),
343 error_msg_));
344 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800345 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800346 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800347 << "in dex file " << original_dex_location << " because: " << *error_msg_;
348 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800349 return ERR(OUT_OF_MEMORY);
350 }
351 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800352 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800353 return ERR(INVALID_CLASS_FORMAT);
354 }
355 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
356 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
357 checksum,
358 std::move(map),
359 /*verify*/true,
360 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800361 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800362 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800363 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800364 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800365 return ERR(INVALID_CLASS_FORMAT);
366 }
Alex Light0e692732017-01-10 15:00:05 -0800367 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800368 Redefiner::ClassRedefinition(this,
369 def.klass,
370 dex_file.release(),
371 signature_ptr,
372 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800373 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800374}
375
Alex Light0e692732017-01-10 15:00:05 -0800376art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
377 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800378}
379
Alex Light0e692732017-01-10 15:00:05 -0800380art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800381 return GetMirrorClass()->GetClassLoader();
382}
383
Alex Light0e692732017-01-10 15:00:05 -0800384art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
385 art::Handle<art::mirror::ClassLoader> loader) {
386 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800387}
388
Alex Light0e692732017-01-10 15:00:05 -0800389void Redefiner::RecordFailure(jvmtiError result,
390 const std::string& class_sig,
391 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800392 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800393 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800394 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800395 result_ = result;
396}
397
Alex Lighta7e38d82017-01-19 14:57:28 -0800398art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
399 // If we have been specifically given a new set of bytes use that
400 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800401 return art::mirror::ByteArray::AllocateAndFill(
402 driver_->self_,
403 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
404 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800405 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800406
407 // See if we already have one set.
408 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
409 if (!ext.IsNull()) {
410 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
411 if (!old_original_bytes.IsNull()) {
412 // We do. Use it.
413 return old_original_bytes.Ptr();
414 }
Alex Lighta01de592016-11-15 10:43:06 -0800415 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800416
417 // Copy the current dex_file
418 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
419 // TODO Handle this or make it so it cannot happen.
420 if (current_dex_file.NumClassDefs() != 1) {
421 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
422 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800423 }
Alex Light440b5d92017-01-24 15:32:25 -0800424 return art::mirror::ByteArray::AllocateAndFill(
425 driver_->self_,
426 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
427 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800428}
429
Alex Lightdba61482016-12-21 08:20:29 -0800430struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800431 art::LinearAlloc* allocator;
432 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
433 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800434
Alex Light0e692732017-01-10 15:00:05 -0800435 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800436};
437
Alex Lightdba61482016-12-21 08:20:29 -0800438void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
439 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800440 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
441 data->allocator,
442 data->obsolete_methods,
443 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800444}
445
446// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
447// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800448// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
449void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800450 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
451 art::mirror::ClassExt* ext = art_klass->GetExtData();
452 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800453 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
454 CallbackCtx ctx(linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800455 // Add all the declared methods to the map
456 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
457 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800458 // TODO Allow this or check in IsModifiableClass.
459 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800460 }
461 {
Alex Light0e692732017-01-10 15:00:05 -0800462 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800463 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
464 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800465 }
466 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800467}
468
469// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
470// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800471void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800472 art::mirror::Class* art_klass,
473 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
474 int32_t index = 0;
475 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
476 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
477 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
478 ext_data->GetObsoleteDexCaches();
479 int32_t num_method_slots = obsolete_methods->GetLength();
480 // Find the first empty index.
481 for (; index < num_method_slots; index++) {
482 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
483 index, art::kRuntimePointerSize) == nullptr) {
484 break;
485 }
486 }
487 // Make sure we have enough space.
488 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
489 CHECK(obsolete_dex_caches->Get(index) == nullptr);
490 // Fill in the map.
491 for (auto& obs : obsoletes) {
492 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
493 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
494 index++;
495 }
496}
497
Alex Light0e692732017-01-10 15:00:05 -0800498bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000499 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800500 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000501 // Easy check that only 1 class def is present.
502 if (dex_file_->NumClassDefs() != 1) {
503 RecordFailure(ERR(ILLEGAL_ARGUMENT),
504 StringPrintf("Expected 1 class def in dex file but found %d",
505 dex_file_->NumClassDefs()));
506 return false;
507 }
508 // Get the ClassDef from the new DexFile.
509 // Since the dex file has only a single class def the index is always 0.
510 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
511 // Get the class as it is now.
512 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
513
514 // Check the access flags didn't change.
515 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
516 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
517 "Cannot change modifiers of class by redefinition");
518 return false;
519 }
520
521 // Check class name.
522 // These should have been checked by the dexfile verifier on load.
523 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
524 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
525 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
526 if (!current_class->DescriptorEquals(descriptor)) {
527 std::string storage;
528 RecordFailure(ERR(NAMES_DONT_MATCH),
529 StringPrintf("expected file to contain class called '%s' but found '%s'!",
530 current_class->GetDescriptor(&storage),
531 descriptor));
532 return false;
533 }
534 if (current_class->IsObjectClass()) {
535 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
536 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
537 return false;
538 }
539 } else {
540 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
541 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
542 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
543 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
544 return false;
545 }
546 }
547 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
548 if (interfaces == nullptr) {
549 if (current_class->NumDirectInterfaces() != 0) {
550 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
551 return false;
552 }
553 } else {
554 DCHECK(!current_class->IsProxyClass());
555 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
556 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
557 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
558 return false;
559 }
560 // The order of interfaces is (barely) meaningful so we error if it changes.
561 const art::DexFile& orig_dex_file = current_class->GetDexFile();
562 for (uint32_t i = 0; i < interfaces->Size(); i++) {
563 if (strcmp(
564 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
565 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
566 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
567 "Interfaces changed or re-ordered");
568 return false;
569 }
570 }
571 }
572 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800573 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000574
575 return true;
576}
577
578// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800579bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800580 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800581 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000582
Alex Lighte4a88632017-01-10 07:41:24 -0800583 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
584 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
585 if (res != OK) {
586 RecordFailure(res, err);
587 return false;
588 } else {
589 return true;
590 }
Alex Light460d1b42017-01-10 15:37:17 +0000591}
592
Alex Light0e692732017-01-10 15:00:05 -0800593bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000594 return CheckRedefinable() &&
595 CheckClass() &&
596 CheckSameFields() &&
597 CheckSameMethods();
598}
599
Alex Light0e692732017-01-10 15:00:05 -0800600// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
601// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
602// having to deal with the fact that we need to hold an arbitrary number of references live.
603class RedefinitionDataHolder {
604 public:
605 enum DataSlot : int32_t {
606 kSlotSourceClassLoader = 0,
607 kSlotJavaDexFile = 1,
608 kSlotNewDexFileCookie = 2,
609 kSlotNewDexCache = 3,
610 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800611 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800612
613 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800614 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800615 };
616
617 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
618 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
619 // the passed in handle-scope.
620 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
621 art::Runtime* runtime,
622 art::Thread* self,
623 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
624 arr_(
625 hs->NewHandle(
626 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
627 self,
628 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
629 num_redefinitions * kNumSlots))) {}
630
631 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
632 return arr_.IsNull();
633 }
634
635 // TODO Maybe make an iterable view type to simplify using this.
636 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
637 REQUIRES_SHARED(art::Locks::mutator_lock_) {
638 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
639 }
640 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
641 return GetSlot(klass_index, kSlotJavaDexFile);
642 }
643 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
644 REQUIRES_SHARED(art::Locks::mutator_lock_) {
645 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
646 }
647 art::mirror::DexCache* GetNewDexCache(jint klass_index)
648 REQUIRES_SHARED(art::Locks::mutator_lock_) {
649 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
650 }
651 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
652 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
653 }
654
Alex Lighta7e38d82017-01-19 14:57:28 -0800655 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index)
656 REQUIRES_SHARED(art::Locks::mutator_lock_) {
657 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
658 }
659
Alex Light0e692732017-01-10 15:00:05 -0800660 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
661 REQUIRES_SHARED(art::Locks::mutator_lock_) {
662 SetSlot(klass_index, kSlotSourceClassLoader, loader);
663 }
664 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
665 REQUIRES_SHARED(art::Locks::mutator_lock_) {
666 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
667 }
668 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
669 REQUIRES_SHARED(art::Locks::mutator_lock_) {
670 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
671 }
672 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
673 REQUIRES_SHARED(art::Locks::mutator_lock_) {
674 SetSlot(klass_index, kSlotNewDexCache, cache);
675 }
676 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
677 REQUIRES_SHARED(art::Locks::mutator_lock_) {
678 SetSlot(klass_index, kSlotMirrorClass, klass);
679 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800680 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
681 REQUIRES_SHARED(art::Locks::mutator_lock_) {
682 SetSlot(klass_index, kSlotOrigDexFile, bytes);
683 }
Alex Light0e692732017-01-10 15:00:05 -0800684
685 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
686 return arr_->GetLength() / kNumSlots;
687 }
688
689 private:
690 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
691
692 art::mirror::Object* GetSlot(jint klass_index,
693 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
694 DCHECK_LT(klass_index, Length());
695 return arr_->Get((kNumSlots * klass_index) + slot);
696 }
697
698 void SetSlot(jint klass_index,
699 DataSlot slot,
700 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
701 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
702 DCHECK_LT(klass_index, Length());
703 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
704 }
705
706 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
707};
708
Alex Lighta7e38d82017-01-19 14:57:28 -0800709bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
710 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800711 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800712 art::StackHandleScope<2> hs(driver_->self_);
713 holder->SetMirrorClass(klass_index, GetMirrorClass());
714 // This shouldn't allocate
715 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800716 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
717 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
718 holder->SetSourceClassLoader(klass_index, loader.Get());
719 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
720 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
721 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
722 if (dex_file_obj.Get() == nullptr) {
723 // TODO Better error msg.
724 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
725 return false;
726 }
727 holder->SetNewDexFileCookie(klass_index,
728 ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
729 dex_file_obj,
730 dex_file_.get()).Ptr());
731 if (holder->GetNewDexFileCookie(klass_index) == nullptr) {
732 driver_->self_->AssertPendingOOMException();
733 driver_->self_->ClearException();
734 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
735 return false;
736 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800737 }
738 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
739 if (holder->GetNewDexCache(klass_index) == nullptr) {
740 driver_->self_->AssertPendingOOMException();
741 driver_->self_->ClearException();
742 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
743 return false;
744 }
745
746 // We won't always need to set this field.
747 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
748 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
749 driver_->self_->AssertPendingOOMException();
750 driver_->self_->ClearException();
751 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
752 return false;
753 }
754 return true;
755}
756
Alex Light5643caf2017-02-08 11:39:07 -0800757void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
758 DCHECK(art::Dbg::IsDebuggerActive());
759 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
760 if (state != nullptr) {
761 state->UnregisterLocationEventsOnClass(GetMirrorClass());
762 }
763}
764
765void Redefiner::UnregisterAllBreakpoints() {
766 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
767 return;
768 }
769 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
770 redef.UnregisterBreakpoints();
771 }
772}
773
Alex Light0e692732017-01-10 15:00:05 -0800774bool Redefiner::CheckAllRedefinitionAreValid() {
775 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
776 if (!redef.CheckRedefinitionIsValid()) {
777 return false;
778 }
779 }
780 return true;
781}
782
783bool Redefiner::EnsureAllClassAllocationsFinished() {
784 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
785 if (!redef.EnsureClassAllocationsFinished()) {
786 return false;
787 }
788 }
789 return true;
790}
791
792bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
793 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -0800794 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -0800795 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -0800796 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -0800797 return false;
798 }
Alex Light0e692732017-01-10 15:00:05 -0800799 cnt++;
800 }
801 return true;
802}
803
804void Redefiner::ClassRedefinition::ReleaseDexFile() {
805 dex_file_.release();
806}
807
808void Redefiner::ReleaseAllDexFiles() {
809 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
810 redef.ReleaseDexFile();
811 }
812}
813
Alex Lighta01de592016-11-15 10:43:06 -0800814jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800815 art::StackHandleScope<1> hs(self_);
816 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
817 // We will let this be collected after the end of this function.
818 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
819 if (holder.IsNull()) {
820 self_->AssertPendingOOMException();
821 self_->ClearException();
822 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
823 return result_;
824 }
825
Alex Lighta01de592016-11-15 10:43:06 -0800826 // First we just allocate the ClassExt and its fields that we need. These can be updated
827 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
828 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
829 // between allocating them and pausing all threads before we can update them so we need to do a
830 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800831 if (!CheckAllRedefinitionAreValid() ||
832 !EnsureAllClassAllocationsFinished() ||
833 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800834 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
835 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800836 // declared_methods_.length) but would be good to get rid of. All other allocations should be
837 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800838 return result_;
839 }
Alex Light5643caf2017-02-08 11:39:07 -0800840 // At this point we can no longer fail without corrupting the runtime state.
Alex Light7916f202017-01-27 09:00:15 -0800841 int32_t counter = 0;
842 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
843 if (holder.GetSourceClassLoader(counter) == nullptr) {
844 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
845 }
846 counter++;
847 }
Alex Light5643caf2017-02-08 11:39:07 -0800848 UnregisterAllBreakpoints();
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 Light7916f202017-01-27 09:00:15 -0800867 counter = 0;
Alex Light0e692732017-01-10 15:00:05 -0800868 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -0800869 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light7916f202017-01-27 09:00:15 -0800870 if (holder.GetSourceClassLoader(counter) != nullptr) {
871 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(counter),
872 holder.GetNewDexFileCookie(counter));
873 }
874 art::mirror::Class* klass = holder.GetMirrorClass(counter);
Alex Light0e692732017-01-10 15:00:05 -0800875 // TODO Rewrite so we don't do a stack walk for each and every class.
876 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light7916f202017-01-27 09:00:15 -0800877 redef.UpdateClass(klass, holder.GetNewDexCache(counter),
878 holder.GetOriginalDexFileBytes(counter));
879 counter++;
Alex Light0e692732017-01-10 15:00:05 -0800880 }
Alex Lightdba61482016-12-21 08:20:29 -0800881 // TODO Shrink the obsolete method maps if possible?
Alex Lighta01de592016-11-15 10:43:06 -0800882 // TODO Put this into a scoped thing.
883 runtime_->GetThreadList()->ResumeAll();
884 // Get back shared mutator lock as expected for return.
885 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800886 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
887 // owns the DexFile and when ownership is transferred.
888 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -0800889 if (heap->IsGcConcurrentAndMoving()) {
890 heap->DecrementDisableMovingGC(self_);
891 }
Alex Lighta01de592016-11-15 10:43:06 -0800892 return OK;
893}
894
Alex Light0e692732017-01-10 15:00:05 -0800895void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
896 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
897 const art::DexFile::ClassDef& class_def) {
898 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800899 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800900 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800901 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800902 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800903 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
904 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
905 art::dex::TypeIndex method_return_idx =
906 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
907 const auto* old_type_list = method.GetParameterTypeList();
908 std::vector<art::dex::TypeIndex> new_type_list;
909 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
910 new_type_list.push_back(
911 dex_file_->GetIndexForTypeId(
912 *dex_file_->FindTypeId(
913 old_dex_file.GetTypeDescriptor(
914 old_dex_file.GetTypeId(
915 old_type_list->GetTypeItem(i).type_idx_)))));
916 }
917 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
918 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000919 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800920 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800921 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
922 *new_name_id,
923 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000924 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800925 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800926 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
927 method.SetDexMethodIndex(dex_method_idx);
928 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800929 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800930 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800931 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -0800932 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -0800933 if (jit != nullptr) {
934 jit->GetCodeCache()->NotifyMethodRedefined(&method);
935 }
Alex Lighta01de592016-11-15 10:43:06 -0800936 }
Alex Light200b9d72016-12-15 11:34:13 -0800937}
938
Alex Light0e692732017-01-10 15:00:05 -0800939void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -0800940 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
941 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
942 for (art::ArtField& field : fields_iter) {
943 std::string declaring_class_name;
944 const art::DexFile::TypeId* new_declaring_id =
945 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
946 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
947 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
948 // TODO Handle error, cleanup.
949 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
950 const art::DexFile::FieldId* new_field_id =
951 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
952 CHECK(new_field_id != nullptr);
953 // We only need to update the index since the other data in the ArtField cannot be updated.
954 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
955 }
956 }
Alex Light200b9d72016-12-15 11:34:13 -0800957}
958
959// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -0800960void Redefiner::ClassRedefinition::UpdateClass(
961 art::ObjPtr<art::mirror::Class> mclass,
962 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
963 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -0800964 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
965 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
966 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -0800967 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -0800968
Alex Lighta01de592016-11-15 10:43:06 -0800969 // Update the class fields.
970 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
971 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
972 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -0800973 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -0800974 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -0800975 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
976 CHECK(!ext.IsNull());
977 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -0800978}
979
Alex Lighta01de592016-11-15 10:43:06 -0800980// This function does all (java) allocations we need to do for the Class being redefined.
981// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -0800982bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
983 art::StackHandleScope<2> hs(driver_->self_);
984 art::Handle<art::mirror::Class> klass(hs.NewHandle(
985 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -0800986 if (klass.Get() == nullptr) {
987 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
988 return false;
989 }
990 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -0800991 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -0800992 if (ext.Get() == nullptr) {
993 // No memory. Clear exception (it's not useful) and return error.
994 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
995 // this case.
Alex Light0e692732017-01-10 15:00:05 -0800996 driver_->self_->AssertPendingOOMException();
997 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800998 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
999 return false;
1000 }
1001 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1002 // are only modified when all threads (other than the modifying one) are suspended we don't need
1003 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1004 // however, since that can happen at any time.
1005 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1006 // are no obsolete methods.
1007 {
Alex Light0e692732017-01-10 15:00:05 -08001008 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001009 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001010 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001011 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001012 driver_->self_->AssertPendingOOMException();
1013 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001014 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1015 return false;
1016 }
1017 }
1018 return true;
1019}
1020
1021} // namespace openjdkjvmti