blob: eefd012d9abb4ebde6f37a6177098375ff375c90 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light5643caf2017-02-08 11:39:07 -080041#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000042#include "dex_file.h"
43#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080044#include "events-inl.h"
45#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080046#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "instrumentation.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "jdwp/jdwp.h"
49#include "jdwp/jdwp_constants.h"
50#include "jdwp/jdwp_event.h"
51#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080052#include "jit/jit.h"
53#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "jni_env_ext-inl.h"
55#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080056#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080057#include "mirror/class_ext.h"
58#include "mirror/object.h"
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 Light8c889d22017-02-06 13:58:27 -080064#include "verifier/method_verifier.h"
65#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080066
67namespace openjdkjvmti {
68
Andreas Gampe46ee31b2016-12-14 10:11:49 -080069using android::base::StringPrintf;
70
Alex Lighteee0bd42017-02-14 15:31:45 +000071// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
72// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
73// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
74class ObsoleteMap {
75 public:
76 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
77 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
78 auto method_pair = id_map_.find(original);
79 if (method_pair != id_map_.end()) {
80 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
81 method_pair->second, art::kRuntimePointerSize);
82 DCHECK(res != nullptr);
83 DCHECK_EQ(original, res->GetNonObsoleteMethod());
84 return res;
85 } else {
86 return nullptr;
87 }
88 }
89
90 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
91 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
92 DCHECK(original != nullptr);
93 DCHECK(obsolete != nullptr);
94 int32_t slot = next_free_slot_++;
95 DCHECK_LT(slot, obsolete_methods_->GetLength());
96 DCHECK(nullptr ==
97 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
98 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
99 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
100 obsolete_dex_caches_->Set(slot, original_dex_cache_);
101 id_map_.insert({original, slot});
102 }
103
104 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
105 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
106 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
107 : next_free_slot_(0),
108 obsolete_methods_(obsolete_methods),
109 obsolete_dex_caches_(obsolete_dex_caches),
110 original_dex_cache_(original_dex_cache) {
111 // Figure out where the first unused slot in the obsolete_methods_ array is.
112 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
113 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
114 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
115 next_free_slot_++;
116 }
117 // Sanity check that the same slot in obsolete_dex_caches_ is free.
118 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
119 }
120
121 private:
122 int32_t next_free_slot_;
123 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
124 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
125 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
126 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
127 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
128 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
129};
130
Alex Lightdba61482016-12-21 08:20:29 -0800131// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
132// some basic sanity checks that the obsolete method is sane.
133class ObsoleteMethodStackVisitor : public art::StackVisitor {
134 protected:
135 ObsoleteMethodStackVisitor(
136 art::Thread* thread,
137 art::LinearAlloc* allocator,
138 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000139 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800140 : StackVisitor(thread,
141 /*context*/nullptr,
142 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
143 allocator_(allocator),
144 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800145 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800146
147 ~ObsoleteMethodStackVisitor() OVERRIDE {}
148
149 public:
150 // Returns true if we successfully installed obsolete methods on this thread, filling
151 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
152 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800153 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800154 art::Thread* thread,
155 art::LinearAlloc* allocator,
156 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000157 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800158 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800159 ObsoleteMethodStackVisitor visitor(thread,
160 allocator,
161 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800162 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800163 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800164 }
165
166 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000167 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800168 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800169 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800170 // We cannot ensure that the right dex file is used in inlined frames so we don't support
171 // redefining them.
172 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000173 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
174 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800175 // Create a new Obsolete Method and put it in the list.
176 art::Runtime* runtime = art::Runtime::Current();
177 art::ClassLinker* cl = runtime->GetClassLinker();
178 auto ptr_size = cl->GetImagePointerSize();
179 const size_t method_size = art::ArtMethod::Size(ptr_size);
180 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800181 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
182 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800183 new_obsolete_method = new (method_storage) art::ArtMethod();
184 new_obsolete_method->CopyFrom(old_method, ptr_size);
185 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
186 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800187 new_obsolete_method->SetDontCompile();
Alex Lighteee0bd42017-02-14 15:31:45 +0000188 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800189 // Update JIT Data structures to point to the new method.
190 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
191 if (jit != nullptr) {
192 // Notify the JIT we are making this obsolete method. It will update the jit's internal
193 // structures to keep track of the new obsolete method.
194 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
195 }
Alex Lightdba61482016-12-21 08:20:29 -0800196 }
197 DCHECK(new_obsolete_method != nullptr);
198 SetMethod(new_obsolete_method);
199 }
200 return true;
201 }
202
203 private:
204 // The linear allocator we should use to make new methods.
205 art::LinearAlloc* allocator_;
206 // The set of all methods which could be obsoleted.
207 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
208 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000209 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
210 // the redefined classes ClassExt as it is filled.
211 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800212};
213
Alex Lighte4a88632017-01-10 07:41:24 -0800214jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
215 jclass klass,
216 jboolean* is_redefinable) {
217 // TODO Check for the appropriate feature flags once we have enabled them.
218 art::Thread* self = art::Thread::Current();
219 art::ScopedObjectAccess soa(self);
220 art::StackHandleScope<1> hs(self);
221 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
222 if (obj.IsNull()) {
223 return ERR(INVALID_CLASS);
224 }
225 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
226 std::string err_unused;
227 *is_redefinable =
228 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
229 return OK;
230}
231
232jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
233 /*out*/std::string* error_msg) {
234 if (klass->IsPrimitive()) {
235 *error_msg = "Modification of primitive classes is not supported";
236 return ERR(UNMODIFIABLE_CLASS);
237 } else if (klass->IsInterface()) {
238 *error_msg = "Modification of Interface classes is currently not supported";
239 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800240 } else if (klass->IsStringClass()) {
241 *error_msg = "Modification of String class is not supported";
242 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800243 } else if (klass->IsArrayClass()) {
244 *error_msg = "Modification of Array classes is not supported";
245 return ERR(UNMODIFIABLE_CLASS);
246 } else if (klass->IsProxyClass()) {
247 *error_msg = "Modification of proxy classes is not supported";
248 return ERR(UNMODIFIABLE_CLASS);
249 }
250
251 // TODO We should check if the class has non-obsoletable methods on the stack
252 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
253 return OK;
254}
255
Alex Lighta01de592016-11-15 10:43:06 -0800256// Moves dex data to an anonymous, read-only mmap'd region.
257std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
258 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800259 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800260 std::string* error_msg) {
261 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800262 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800263 nullptr,
264 data_len,
265 PROT_READ|PROT_WRITE,
266 /*low_4gb*/false,
267 /*reuse*/false,
268 error_msg));
269 if (map == nullptr) {
270 return map;
271 }
272 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800273 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
274 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800275 map->Protect(PROT_READ);
276 return map;
277}
278
Alex Lighta7e38d82017-01-19 14:57:28 -0800279Redefiner::ClassRedefinition::ClassRedefinition(
280 Redefiner* driver,
281 jclass klass,
282 const art::DexFile* redefined_dex_file,
283 const char* class_sig,
284 art::ArraySlice<const unsigned char> orig_dex_file) :
285 driver_(driver),
286 klass_(klass),
287 dex_file_(redefined_dex_file),
288 class_sig_(class_sig),
289 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800290 GetMirrorClass()->MonitorEnter(driver_->self_);
291}
292
293Redefiner::ClassRedefinition::~ClassRedefinition() {
294 if (driver_ != nullptr) {
295 GetMirrorClass()->MonitorExit(driver_->self_);
296 }
297}
298
Alex Light0e692732017-01-10 15:00:05 -0800299jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
300 art::Runtime* runtime,
301 art::Thread* self,
302 jint class_count,
303 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800304 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800305 if (env == nullptr) {
306 *error_msg = "env was null!";
307 return ERR(INVALID_ENVIRONMENT);
308 } else if (class_count < 0) {
309 *error_msg = "class_count was less then 0";
310 return ERR(ILLEGAL_ARGUMENT);
311 } else if (class_count == 0) {
312 // We don't actually need to do anything. Just return OK.
313 return OK;
314 } else if (definitions == nullptr) {
315 *error_msg = "null definitions!";
316 return ERR(NULL_POINTER);
317 }
Alex Light6ac57502017-01-19 15:05:06 -0800318 std::vector<ArtClassDefinition> def_vector;
319 def_vector.reserve(class_count);
320 for (jint i = 0; i < class_count; i++) {
321 // We make a copy of the class_bytes to pass into the retransformation.
322 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
323 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
324 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800325 unsigned char* class_bytes_copy = nullptr;
326 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
327 if (res != OK) {
328 return res;
329 }
330 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
331
332 ArtClassDefinition def;
333 def.dex_len = definitions[i].class_byte_count;
334 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
335 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800336 def.SetModified();
337 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
338 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800339 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
340 if (res != OK) {
341 return res;
342 }
343 def_vector.push_back(std::move(def));
344 }
345 // Call all the transformation events.
346 jvmtiError res = Transformer::RetransformClassesDirect(env,
347 self,
348 &def_vector);
349 if (res != OK) {
350 // Something went wrong with transformation!
351 return res;
352 }
353 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
354}
355
356jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
357 art::Runtime* runtime,
358 art::Thread* self,
359 const std::vector<ArtClassDefinition>& definitions,
360 std::string* error_msg) {
361 DCHECK(env != nullptr);
362 if (definitions.size() == 0) {
363 // We don't actually need to do anything. Just return OK.
364 return OK;
365 }
Alex Light0e692732017-01-10 15:00:05 -0800366 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
367 // are going to redefine.
368 art::jit::ScopedJitSuspend suspend_jit;
369 // Get shared mutator lock so we can lock all the classes.
370 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800371 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800372 for (const ArtClassDefinition& def : definitions) {
373 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800374 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800375 jvmtiError res = r.AddRedefinition(env, def);
376 if (res != OK) {
377 return res;
378 }
Alex Light0e692732017-01-10 15:00:05 -0800379 }
380 }
381 return r.Run();
382}
383
Alex Light6ac57502017-01-19 15:05:06 -0800384jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800385 std::string original_dex_location;
386 jvmtiError ret = OK;
387 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
388 *error_msg_ = "Unable to get original dex file location!";
389 return ret;
390 }
Alex Light52a2db52017-01-19 23:00:21 +0000391 char* generic_ptr_unused = nullptr;
392 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800393 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
394 *error_msg_ = "Unable to get class signature!";
395 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000396 }
Andreas Gampe54711412017-02-21 12:41:43 -0800397 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
398 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800399 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
400 def.dex_len,
401 def.dex_data.get(),
402 error_msg_));
403 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800404 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800405 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800406 << "in dex file " << original_dex_location << " because: " << *error_msg_;
407 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800408 return ERR(OUT_OF_MEMORY);
409 }
410 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800411 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800412 return ERR(INVALID_CLASS_FORMAT);
413 }
414 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
415 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
416 checksum,
417 std::move(map),
418 /*verify*/true,
419 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800420 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800421 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800422 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800423 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800424 return ERR(INVALID_CLASS_FORMAT);
425 }
Alex Light0e692732017-01-10 15:00:05 -0800426 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800427 Redefiner::ClassRedefinition(this,
428 def.klass,
429 dex_file.release(),
430 signature_ptr,
431 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800432 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800433}
434
Alex Light0e692732017-01-10 15:00:05 -0800435art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
436 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800437}
438
Alex Light0e692732017-01-10 15:00:05 -0800439art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800440 return GetMirrorClass()->GetClassLoader();
441}
442
Alex Light0e692732017-01-10 15:00:05 -0800443art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
444 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000445 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800446}
447
Alex Light0e692732017-01-10 15:00:05 -0800448void Redefiner::RecordFailure(jvmtiError result,
449 const std::string& class_sig,
450 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800451 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800452 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800453 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800454 result_ = result;
455}
456
Alex Lighta7e38d82017-01-19 14:57:28 -0800457art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
458 // If we have been specifically given a new set of bytes use that
459 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800460 return art::mirror::ByteArray::AllocateAndFill(
461 driver_->self_,
462 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
463 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800464 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800465
466 // See if we already have one set.
467 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
468 if (!ext.IsNull()) {
469 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
470 if (!old_original_bytes.IsNull()) {
471 // We do. Use it.
472 return old_original_bytes.Ptr();
473 }
Alex Lighta01de592016-11-15 10:43:06 -0800474 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800475
476 // Copy the current dex_file
477 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
478 // TODO Handle this or make it so it cannot happen.
479 if (current_dex_file.NumClassDefs() != 1) {
480 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
481 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800482 }
Alex Light440b5d92017-01-24 15:32:25 -0800483 return art::mirror::ByteArray::AllocateAndFill(
484 driver_->self_,
485 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
486 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800487}
488
Alex Lightdba61482016-12-21 08:20:29 -0800489struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000490 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800491 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800492 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800493
Alex Lighteee0bd42017-02-14 15:31:45 +0000494 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
495 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800496};
497
Alex Lightdba61482016-12-21 08:20:29 -0800498void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
499 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800500 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
501 data->allocator,
502 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000503 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800504}
505
506// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
507// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800508// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
509void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800510 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
511 art::mirror::ClassExt* ext = art_klass->GetExtData();
512 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800513 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000514 // This holds pointers to the obsolete methods map fields which are updated as needed.
515 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
516 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800517 // Add all the declared methods to the map
518 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800519 if (m.IsIntrinsic()) {
520 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
521 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
522 << "methods that have already been compiled.";
523 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000524 // It is possible to simply filter out some methods where they cannot really become obsolete,
525 // such as native methods and keep their original (possibly optimized) implementations. We don't
526 // do this, however, since we would need to mark these functions (still in the classes
527 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
528 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
529 // error checking from the interpreter which ensure we don't try to start executing obsolete
530 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000531 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800532 }
533 {
Alex Light0e692732017-01-10 15:00:05 -0800534 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800535 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
536 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800537 }
Alex Lightdba61482016-12-21 08:20:29 -0800538}
539
Alex Light6161f132017-01-25 10:30:20 -0800540// Try and get the declared method. First try to get a virtual method then a direct method if that's
541// not found.
542static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
543 const char* name,
544 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
545 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
546 if (m == nullptr) {
547 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
548 }
549 return m;
550}
551
552bool Redefiner::ClassRedefinition::CheckSameMethods() {
553 art::StackHandleScope<1> hs(driver_->self_);
554 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
555 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
556
557 art::ClassDataItemIterator new_iter(*dex_file_,
558 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
559
560 // Make sure we have the same number of methods.
561 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
562 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
563 if (num_new_method != num_old_method) {
564 bool bigger = num_new_method > num_old_method;
565 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
566 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
567 StringPrintf("Total number of declared methods changed from %d to %d",
568 num_old_method, num_new_method));
569 return false;
570 }
571
572 // Skip all of the fields. We should have already checked this.
573 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
574 new_iter.Next();
575 }
576 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
577 // files have the same number of methods, which means there must be an equal amount of additions
578 // and removals.
579 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
580 // Get the data on the method we are searching for
581 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
582 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
583 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
584 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
585 // If we got past the check for the same number of methods above that means there must be at
586 // least one added and one removed method. We will return the ADDED failure message since it is
587 // easier to get a useful error report for it.
588 if (old_method == nullptr) {
589 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
590 StringPrintf("Unknown method '%s' (sig: %s) was added!",
591 new_method_name,
592 new_method_signature.ToString().c_str()));
593 return false;
594 }
595 // Since direct methods have different flags than virtual ones (specifically direct methods must
596 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
597 // virtual to direct.
598 uint32_t new_flags = new_iter.GetMethodAccessFlags();
599 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
600 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
601 StringPrintf("method '%s' (sig: %s) had different access flags",
602 new_method_name,
603 new_method_signature.ToString().c_str()));
604 return false;
605 }
606 }
607 return true;
608}
609
610bool Redefiner::ClassRedefinition::CheckSameFields() {
611 art::StackHandleScope<1> hs(driver_->self_);
612 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
613 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
614 art::ClassDataItemIterator new_iter(*dex_file_,
615 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
616 const art::DexFile& old_dex_file = h_klass->GetDexFile();
617 art::ClassDataItemIterator old_iter(old_dex_file,
618 old_dex_file.GetClassData(*h_klass->GetClassDef()));
619 // Instance and static fields can be differentiated by their flags so no need to check them
620 // separately.
621 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
622 // Get the data on the method we are searching for
623 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
624 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
625 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
626
627 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
628 // We are missing the old version of this method!
629 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
630 StringPrintf("Unknown field '%s' (type: %s) added!",
631 new_field_name,
632 new_field_type));
633 return false;
634 }
635
636 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
637 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
638 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
639
640 // Check name and type.
641 if (strcmp(old_field_name, new_field_name) != 0 ||
642 strcmp(old_field_type, new_field_type) != 0) {
643 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
644 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
645 old_field_name,
646 old_field_type,
647 new_field_name,
648 new_field_type));
649 return false;
650 }
651
652 // Since static fields have different flags than instance ones (specifically static fields must
653 // have the kAccStatic flag) we can tell if a field changes from static to instance.
654 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
655 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
656 StringPrintf("Field '%s' (sig: %s) had different access flags",
657 new_field_name,
658 new_field_type));
659 return false;
660 }
661
662 new_iter.Next();
663 old_iter.Next();
664 }
665 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
666 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
667 StringPrintf("field '%s' (sig: %s) is missing!",
668 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
669 old_iter.GetMemberIndex())),
670 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
671 old_iter.GetMemberIndex()))));
672 return false;
673 }
674 return true;
675}
676
Alex Light0e692732017-01-10 15:00:05 -0800677bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800678 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000679 // Easy check that only 1 class def is present.
680 if (dex_file_->NumClassDefs() != 1) {
681 RecordFailure(ERR(ILLEGAL_ARGUMENT),
682 StringPrintf("Expected 1 class def in dex file but found %d",
683 dex_file_->NumClassDefs()));
684 return false;
685 }
686 // Get the ClassDef from the new DexFile.
687 // Since the dex file has only a single class def the index is always 0.
688 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
689 // Get the class as it is now.
690 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
691
692 // Check the access flags didn't change.
693 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
694 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
695 "Cannot change modifiers of class by redefinition");
696 return false;
697 }
698
699 // Check class name.
700 // These should have been checked by the dexfile verifier on load.
701 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
702 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
703 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
704 if (!current_class->DescriptorEquals(descriptor)) {
705 std::string storage;
706 RecordFailure(ERR(NAMES_DONT_MATCH),
707 StringPrintf("expected file to contain class called '%s' but found '%s'!",
708 current_class->GetDescriptor(&storage),
709 descriptor));
710 return false;
711 }
712 if (current_class->IsObjectClass()) {
713 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
714 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
715 return false;
716 }
717 } else {
718 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
719 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
720 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
721 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
722 return false;
723 }
724 }
725 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
726 if (interfaces == nullptr) {
727 if (current_class->NumDirectInterfaces() != 0) {
728 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
729 return false;
730 }
731 } else {
732 DCHECK(!current_class->IsProxyClass());
733 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
734 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
735 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
736 return false;
737 }
738 // The order of interfaces is (barely) meaningful so we error if it changes.
739 const art::DexFile& orig_dex_file = current_class->GetDexFile();
740 for (uint32_t i = 0; i < interfaces->Size(); i++) {
741 if (strcmp(
742 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
743 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
744 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
745 "Interfaces changed or re-ordered");
746 return false;
747 }
748 }
749 }
Alex Light460d1b42017-01-10 15:37:17 +0000750 return true;
751}
752
Alex Light0e692732017-01-10 15:00:05 -0800753bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800754 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800755 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000756
Alex Lighte4a88632017-01-10 07:41:24 -0800757 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
758 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
759 if (res != OK) {
760 RecordFailure(res, err);
761 return false;
762 } else {
763 return true;
764 }
Alex Light460d1b42017-01-10 15:37:17 +0000765}
766
Alex Light0e692732017-01-10 15:00:05 -0800767bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000768 return CheckRedefinable() &&
769 CheckClass() &&
770 CheckSameFields() &&
771 CheckSameMethods();
772}
773
Alex Light0e692732017-01-10 15:00:05 -0800774// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
775// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
776// having to deal with the fact that we need to hold an arbitrary number of references live.
777class RedefinitionDataHolder {
778 public:
779 enum DataSlot : int32_t {
780 kSlotSourceClassLoader = 0,
781 kSlotJavaDexFile = 1,
782 kSlotNewDexFileCookie = 2,
783 kSlotNewDexCache = 3,
784 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800785 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800786
787 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800788 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800789 };
790
791 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
792 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
793 // the passed in handle-scope.
794 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
795 art::Runtime* runtime,
796 art::Thread* self,
797 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
798 arr_(
799 hs->NewHandle(
800 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
801 self,
802 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
803 num_redefinitions * kNumSlots))) {}
804
805 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
806 return arr_.IsNull();
807 }
808
809 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800810 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800811 REQUIRES_SHARED(art::Locks::mutator_lock_) {
812 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
813 }
Alex Light8c889d22017-02-06 13:58:27 -0800814 art::mirror::Object* GetJavaDexFile(jint klass_index) const
815 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800816 return GetSlot(klass_index, kSlotJavaDexFile);
817 }
Alex Light8c889d22017-02-06 13:58:27 -0800818 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800819 REQUIRES_SHARED(art::Locks::mutator_lock_) {
820 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
821 }
Alex Light8c889d22017-02-06 13:58:27 -0800822 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800823 REQUIRES_SHARED(art::Locks::mutator_lock_) {
824 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
825 }
Alex Light8c889d22017-02-06 13:58:27 -0800826 art::mirror::Class* GetMirrorClass(jint klass_index) const
827 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800828 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
829 }
830
Alex Light8c889d22017-02-06 13:58:27 -0800831 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800832 REQUIRES_SHARED(art::Locks::mutator_lock_) {
833 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
834 }
835
Alex Light0e692732017-01-10 15:00:05 -0800836 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
837 REQUIRES_SHARED(art::Locks::mutator_lock_) {
838 SetSlot(klass_index, kSlotSourceClassLoader, loader);
839 }
840 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
841 REQUIRES_SHARED(art::Locks::mutator_lock_) {
842 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
843 }
844 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
845 REQUIRES_SHARED(art::Locks::mutator_lock_) {
846 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
847 }
848 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
849 REQUIRES_SHARED(art::Locks::mutator_lock_) {
850 SetSlot(klass_index, kSlotNewDexCache, cache);
851 }
852 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
853 REQUIRES_SHARED(art::Locks::mutator_lock_) {
854 SetSlot(klass_index, kSlotMirrorClass, klass);
855 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800856 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
857 REQUIRES_SHARED(art::Locks::mutator_lock_) {
858 SetSlot(klass_index, kSlotOrigDexFile, bytes);
859 }
Alex Light0e692732017-01-10 15:00:05 -0800860
Alex Light8c889d22017-02-06 13:58:27 -0800861 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800862 return arr_->GetLength() / kNumSlots;
863 }
864
865 private:
Alex Light8c889d22017-02-06 13:58:27 -0800866 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Light0e692732017-01-10 15:00:05 -0800867
868 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800869 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800870 DCHECK_LT(klass_index, Length());
871 return arr_->Get((kNumSlots * klass_index) + slot);
872 }
873
874 void SetSlot(jint klass_index,
875 DataSlot slot,
876 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
877 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
878 DCHECK_LT(klass_index, Length());
879 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
880 }
881
882 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
883};
884
Alex Light8c889d22017-02-06 13:58:27 -0800885bool Redefiner::ClassRedefinition::CheckVerification(int32_t klass_index,
886 const RedefinitionDataHolder& holder) {
887 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
888 art::StackHandleScope<2> hs(driver_->self_);
889 std::string error;
890 // TODO Make verification log level lower
891 art::verifier::MethodVerifier::FailureKind failure =
892 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
893 dex_file_.get(),
894 hs.NewHandle(holder.GetNewDexCache(klass_index)),
895 hs.NewHandle(GetClassLoader()),
896 dex_file_->GetClassDef(0), /*class_def*/
897 nullptr, /*compiler_callbacks*/
898 false, /*allow_soft_failures*/
899 /*log_level*/
900 art::verifier::HardFailLogMode::kLogWarning,
901 &error);
902 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
903 if (!passes) {
904 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
905 }
906 return passes;
907}
908
Alex Light1babae02017-02-01 15:35:34 -0800909// Looks through the previously allocated cookies to see if we need to update them with another new
910// dexfile. This is so that even if multiple classes with the same classloader are redefined at
911// once they are all added to the classloader.
912bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
913 int32_t klass_index,
914 art::Handle<art::mirror::ClassLoader> source_class_loader,
915 art::Handle<art::mirror::Object> dex_file_obj,
916 /*out*/RedefinitionDataHolder* holder) {
917 art::StackHandleScope<2> hs(driver_->self_);
918 art::MutableHandle<art::mirror::LongArray> old_cookie(
919 hs.NewHandle<art::mirror::LongArray>(nullptr));
920 bool has_older_cookie = false;
921 // See if we already have a cookie that a previous redefinition got from the same classloader.
922 for (int32_t i = 0; i < klass_index; i++) {
923 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
924 // Since every instance of this classloader should have the same cookie associated with it we
925 // can stop looking here.
926 has_older_cookie = true;
927 old_cookie.Assign(holder->GetNewDexFileCookie(i));
928 break;
929 }
930 }
931 if (old_cookie.IsNull()) {
932 // No older cookie. Get it directly from the dex_file_obj
933 // We should not have seen this classloader elsewhere.
934 CHECK(!has_older_cookie);
935 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
936 }
937 // Use the old cookie to generate the new one with the new DexFile* added in.
938 art::Handle<art::mirror::LongArray>
939 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
940 old_cookie,
941 dex_file_.get())));
942 // Make sure the allocation worked.
943 if (new_cookie.IsNull()) {
944 return false;
945 }
946
947 // Save the cookie.
948 holder->SetNewDexFileCookie(klass_index, new_cookie.Get());
949 // If there are other copies of this same classloader we need to make sure that we all have the
950 // same cookie.
951 if (has_older_cookie) {
952 for (int32_t i = 0; i < klass_index; i++) {
953 // We will let the GC take care of the cookie we allocated for this one.
954 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
955 holder->SetNewDexFileCookie(i, new_cookie.Get());
956 }
957 }
958 }
959
960 return true;
961}
962
Alex Lighta7e38d82017-01-19 14:57:28 -0800963bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
964 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800965 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800966 art::StackHandleScope<2> hs(driver_->self_);
967 holder->SetMirrorClass(klass_index, GetMirrorClass());
968 // This shouldn't allocate
969 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800970 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
971 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
972 holder->SetSourceClassLoader(klass_index, loader.Get());
973 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
974 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
975 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -0800976 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -0800977 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
978 return false;
979 }
Alex Light1babae02017-02-01 15:35:34 -0800980 // Allocate the new dex file cookie.
981 if (!AllocateAndRememberNewDexFileCookie(klass_index, loader, dex_file_obj, holder)) {
Alex Light7916f202017-01-27 09:00:15 -0800982 driver_->self_->AssertPendingOOMException();
983 driver_->self_->ClearException();
984 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
985 return false;
986 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800987 }
988 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
989 if (holder->GetNewDexCache(klass_index) == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000990 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -0800991 driver_->self_->ClearException();
992 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
993 return false;
994 }
995
996 // We won't always need to set this field.
997 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
998 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
999 driver_->self_->AssertPendingOOMException();
1000 driver_->self_->ClearException();
1001 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1002 return false;
1003 }
1004 return true;
1005}
1006
Alex Light5643caf2017-02-08 11:39:07 -08001007void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1008 DCHECK(art::Dbg::IsDebuggerActive());
1009 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1010 if (state != nullptr) {
1011 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1012 }
1013}
1014
1015void Redefiner::UnregisterAllBreakpoints() {
1016 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1017 return;
1018 }
1019 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1020 redef.UnregisterBreakpoints();
1021 }
1022}
1023
Alex Light0e692732017-01-10 15:00:05 -08001024bool Redefiner::CheckAllRedefinitionAreValid() {
1025 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1026 if (!redef.CheckRedefinitionIsValid()) {
1027 return false;
1028 }
1029 }
1030 return true;
1031}
1032
1033bool Redefiner::EnsureAllClassAllocationsFinished() {
1034 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1035 if (!redef.EnsureClassAllocationsFinished()) {
1036 return false;
1037 }
1038 }
1039 return true;
1040}
1041
1042bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
1043 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -08001044 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -08001045 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -08001046 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -08001047 return false;
1048 }
Alex Light0e692732017-01-10 15:00:05 -08001049 cnt++;
1050 }
1051 return true;
1052}
1053
1054void Redefiner::ClassRedefinition::ReleaseDexFile() {
1055 dex_file_.release();
1056}
1057
1058void Redefiner::ReleaseAllDexFiles() {
1059 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1060 redef.ReleaseDexFile();
1061 }
1062}
1063
Alex Light8c889d22017-02-06 13:58:27 -08001064bool Redefiner::CheckAllClassesAreVerified(const RedefinitionDataHolder& holder) {
1065 int32_t cnt = 0;
1066 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1067 if (!redef.CheckVerification(cnt, holder)) {
1068 return false;
1069 }
1070 cnt++;
1071 }
1072 return true;
1073}
1074
Alex Lighta01de592016-11-15 10:43:06 -08001075jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001076 art::StackHandleScope<1> hs(self_);
1077 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1078 // We will let this be collected after the end of this function.
1079 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
1080 if (holder.IsNull()) {
1081 self_->AssertPendingOOMException();
1082 self_->ClearException();
1083 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1084 return result_;
1085 }
1086
Alex Lighta01de592016-11-15 10:43:06 -08001087 // First we just allocate the ClassExt and its fields that we need. These can be updated
1088 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1089 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1090 // between allocating them and pausing all threads before we can update them so we need to do a
1091 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001092 if (!CheckAllRedefinitionAreValid() ||
1093 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001094 !FinishAllRemainingAllocations(holder) ||
1095 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001096 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1097 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001098 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1099 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001100 return result_;
1101 }
Alex Light5643caf2017-02-08 11:39:07 -08001102 // At this point we can no longer fail without corrupting the runtime state.
Alex Light7916f202017-01-27 09:00:15 -08001103 int32_t counter = 0;
1104 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1105 if (holder.GetSourceClassLoader(counter) == nullptr) {
1106 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
1107 }
1108 counter++;
1109 }
Alex Light5643caf2017-02-08 11:39:07 -08001110 UnregisterAllBreakpoints();
Alex Light6abd5392017-01-05 17:53:00 -08001111 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1112 // allocating so no deadlocks.
1113 art::gc::Heap* heap = runtime_->GetHeap();
1114 if (heap->IsGcConcurrentAndMoving()) {
1115 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
1116 heap->IncrementDisableMovingGC(self_);
1117 }
Alex Lighta01de592016-11-15 10:43:06 -08001118 // Do transition to final suspension
1119 // TODO We might want to give this its own suspended state!
1120 // TODO This isn't right. We need to change state without any chance of suspend ideally!
1121 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
1122 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -08001123 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Light7916f202017-01-27 09:00:15 -08001124 counter = 0;
Alex Light0e692732017-01-10 15:00:05 -08001125 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -08001126 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light7916f202017-01-27 09:00:15 -08001127 if (holder.GetSourceClassLoader(counter) != nullptr) {
1128 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(counter),
1129 holder.GetNewDexFileCookie(counter));
1130 }
1131 art::mirror::Class* klass = holder.GetMirrorClass(counter);
Alex Light0e692732017-01-10 15:00:05 -08001132 // TODO Rewrite so we don't do a stack walk for each and every class.
1133 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light7916f202017-01-27 09:00:15 -08001134 redef.UpdateClass(klass, holder.GetNewDexCache(counter),
1135 holder.GetOriginalDexFileBytes(counter));
1136 counter++;
Alex Light0e692732017-01-10 15:00:05 -08001137 }
Alex Light7532d582017-02-13 16:36:06 -08001138 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1139 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1140 // methods that have been jitted prior to the current redefinition being applied might continue
1141 // to use the old versions of the intrinsics!
Alex Lightdba61482016-12-21 08:20:29 -08001142 // TODO Shrink the obsolete method maps if possible?
Alex Lighta01de592016-11-15 10:43:06 -08001143 // TODO Put this into a scoped thing.
1144 runtime_->GetThreadList()->ResumeAll();
1145 // Get back shared mutator lock as expected for return.
1146 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -08001147 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1148 // owns the DexFile and when ownership is transferred.
1149 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001150 if (heap->IsGcConcurrentAndMoving()) {
1151 heap->DecrementDisableMovingGC(self_);
1152 }
Alex Lighta01de592016-11-15 10:43:06 -08001153 return OK;
1154}
1155
Alex Light0e692732017-01-10 15:00:05 -08001156void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1157 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1158 const art::DexFile::ClassDef& class_def) {
1159 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001160 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001161 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001162 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001163 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001164 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1165 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1166 art::dex::TypeIndex method_return_idx =
1167 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1168 const auto* old_type_list = method.GetParameterTypeList();
1169 std::vector<art::dex::TypeIndex> new_type_list;
1170 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1171 new_type_list.push_back(
1172 dex_file_->GetIndexForTypeId(
1173 *dex_file_->FindTypeId(
1174 old_dex_file.GetTypeDescriptor(
1175 old_dex_file.GetTypeId(
1176 old_type_list->GetTypeItem(i).type_idx_)))));
1177 }
1178 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1179 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001180 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001181 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1182 *new_name_id,
1183 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001184 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001185 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1186 method.SetDexMethodIndex(dex_method_idx);
1187 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001188 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001189 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001190 // Clear all the intrinsics related flags.
1191 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001192 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001193 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001194 if (jit != nullptr) {
1195 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1196 }
Alex Lighta01de592016-11-15 10:43:06 -08001197 }
Alex Light200b9d72016-12-15 11:34:13 -08001198}
1199
Alex Light0e692732017-01-10 15:00:05 -08001200void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001201 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1202 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1203 for (art::ArtField& field : fields_iter) {
1204 std::string declaring_class_name;
1205 const art::DexFile::TypeId* new_declaring_id =
1206 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1207 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1208 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001209 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1210 const art::DexFile::FieldId* new_field_id =
1211 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1212 CHECK(new_field_id != nullptr);
1213 // We only need to update the index since the other data in the ArtField cannot be updated.
1214 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1215 }
1216 }
Alex Light200b9d72016-12-15 11:34:13 -08001217}
1218
1219// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001220void Redefiner::ClassRedefinition::UpdateClass(
1221 art::ObjPtr<art::mirror::Class> mclass,
1222 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1223 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001224 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1225 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1226 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001227 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001228
Alex Lighta01de592016-11-15 10:43:06 -08001229 // Update the class fields.
1230 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1231 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1232 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001233 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001234 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001235 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1236 CHECK(!ext.IsNull());
1237 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001238}
1239
Alex Lighta01de592016-11-15 10:43:06 -08001240// This function does all (java) allocations we need to do for the Class being redefined.
1241// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001242bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1243 art::StackHandleScope<2> hs(driver_->self_);
1244 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1245 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001246 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001247 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1248 return false;
1249 }
1250 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001251 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001252 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001253 // No memory. Clear exception (it's not useful) and return error.
1254 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1255 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001256 driver_->self_->AssertPendingOOMException();
1257 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001258 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1259 return false;
1260 }
1261 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1262 // are only modified when all threads (other than the modifying one) are suspended we don't need
1263 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1264 // however, since that can happen at any time.
1265 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1266 // are no obsolete methods.
1267 {
Alex Light0e692732017-01-10 15:00:05 -08001268 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001269 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001270 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001271 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001272 driver_->self_->AssertPendingOOMException();
1273 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001274 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1275 return false;
1276 }
1277 }
1278 return true;
1279}
1280
1281} // namespace openjdkjvmti