blob: 3aad8412711730c799d942b7fb45e48b1ef0f169 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light460d1b42017-01-10 15:37:17 +000041#include "dex_file.h"
42#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080043#include "events-inl.h"
44#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080045#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080046#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080047#include "jit/jit.h"
48#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080049#include "jni_env_ext-inl.h"
50#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080051#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080052#include "mirror/class_ext.h"
53#include "mirror/object.h"
54#include "object_lock.h"
55#include "runtime.h"
56#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080057#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080058#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080059#include "verifier/method_verifier.h"
60#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080061
62namespace openjdkjvmti {
63
Andreas Gampe46ee31b2016-12-14 10:11:49 -080064using android::base::StringPrintf;
65
Alex Lighteee0bd42017-02-14 15:31:45 +000066// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
67// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
68// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
69class ObsoleteMap {
70 public:
71 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
72 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
73 auto method_pair = id_map_.find(original);
74 if (method_pair != id_map_.end()) {
75 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
76 method_pair->second, art::kRuntimePointerSize);
77 DCHECK(res != nullptr);
78 DCHECK_EQ(original, res->GetNonObsoleteMethod());
79 return res;
80 } else {
81 return nullptr;
82 }
83 }
84
85 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
86 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
87 DCHECK(original != nullptr);
88 DCHECK(obsolete != nullptr);
89 int32_t slot = next_free_slot_++;
90 DCHECK_LT(slot, obsolete_methods_->GetLength());
91 DCHECK(nullptr ==
92 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
93 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
94 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
95 obsolete_dex_caches_->Set(slot, original_dex_cache_);
96 id_map_.insert({original, slot});
97 }
98
99 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
100 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
101 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
102 : next_free_slot_(0),
103 obsolete_methods_(obsolete_methods),
104 obsolete_dex_caches_(obsolete_dex_caches),
105 original_dex_cache_(original_dex_cache) {
106 // Figure out where the first unused slot in the obsolete_methods_ array is.
107 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
108 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
109 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
110 next_free_slot_++;
111 }
112 // Sanity check that the same slot in obsolete_dex_caches_ is free.
113 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
114 }
115
116 private:
117 int32_t next_free_slot_;
118 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
119 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
120 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
121 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
122 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
123 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
124};
125
Alex Lightdba61482016-12-21 08:20:29 -0800126// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
127// some basic sanity checks that the obsolete method is sane.
128class ObsoleteMethodStackVisitor : public art::StackVisitor {
129 protected:
130 ObsoleteMethodStackVisitor(
131 art::Thread* thread,
132 art::LinearAlloc* allocator,
133 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000134 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800135 : StackVisitor(thread,
136 /*context*/nullptr,
137 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
138 allocator_(allocator),
139 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800140 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800141
142 ~ObsoleteMethodStackVisitor() OVERRIDE {}
143
144 public:
145 // Returns true if we successfully installed obsolete methods on this thread, filling
146 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
147 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800148 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800149 art::Thread* thread,
150 art::LinearAlloc* allocator,
151 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000152 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800153 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800154 ObsoleteMethodStackVisitor visitor(thread,
155 allocator,
156 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800157 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800158 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800159 }
160
161 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000162 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800163 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800164 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800165 // We cannot ensure that the right dex file is used in inlined frames so we don't support
166 // redefining them.
167 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
168 // TODO We should really support intrinsic obsolete methods.
169 // TODO We should really support redefining intrinsics.
170 // We don't support intrinsics so check for them here.
171 DCHECK(!old_method->IsIntrinsic());
Alex Lighteee0bd42017-02-14 15:31:45 +0000172 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
173 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800174 // Create a new Obsolete Method and put it in the list.
175 art::Runtime* runtime = art::Runtime::Current();
176 art::ClassLinker* cl = runtime->GetClassLinker();
177 auto ptr_size = cl->GetImagePointerSize();
178 const size_t method_size = art::ArtMethod::Size(ptr_size);
179 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800180 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
181 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800182 new_obsolete_method = new (method_storage) art::ArtMethod();
183 new_obsolete_method->CopyFrom(old_method, ptr_size);
184 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
185 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800186 new_obsolete_method->SetDontCompile();
Alex Lighteee0bd42017-02-14 15:31:45 +0000187 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800188 // Update JIT Data structures to point to the new method.
189 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
190 if (jit != nullptr) {
191 // Notify the JIT we are making this obsolete method. It will update the jit's internal
192 // structures to keep track of the new obsolete method.
193 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
194 }
Alex Lightdba61482016-12-21 08:20:29 -0800195 }
196 DCHECK(new_obsolete_method != nullptr);
197 SetMethod(new_obsolete_method);
198 }
199 return true;
200 }
201
202 private:
203 // The linear allocator we should use to make new methods.
204 art::LinearAlloc* allocator_;
205 // The set of all methods which could be obsoleted.
206 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
207 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000208 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
209 // the redefined classes ClassExt as it is filled.
210 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800211};
212
Alex Lighte4a88632017-01-10 07:41:24 -0800213jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
214 jclass klass,
215 jboolean* is_redefinable) {
216 // TODO Check for the appropriate feature flags once we have enabled them.
217 art::Thread* self = art::Thread::Current();
218 art::ScopedObjectAccess soa(self);
219 art::StackHandleScope<1> hs(self);
220 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
221 if (obj.IsNull()) {
222 return ERR(INVALID_CLASS);
223 }
224 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
225 std::string err_unused;
226 *is_redefinable =
227 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
228 return OK;
229}
230
231jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
232 /*out*/std::string* error_msg) {
233 if (klass->IsPrimitive()) {
234 *error_msg = "Modification of primitive classes is not supported";
235 return ERR(UNMODIFIABLE_CLASS);
236 } else if (klass->IsInterface()) {
237 *error_msg = "Modification of Interface classes is currently not supported";
238 return ERR(UNMODIFIABLE_CLASS);
239 } else if (klass->IsArrayClass()) {
240 *error_msg = "Modification of Array classes is not supported";
241 return ERR(UNMODIFIABLE_CLASS);
242 } else if (klass->IsProxyClass()) {
243 *error_msg = "Modification of proxy classes is not supported";
244 return ERR(UNMODIFIABLE_CLASS);
245 }
246
247 // TODO We should check if the class has non-obsoletable methods on the stack
248 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
249 return OK;
250}
251
Alex Lighta01de592016-11-15 10:43:06 -0800252// Moves dex data to an anonymous, read-only mmap'd region.
253std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
254 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800255 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800256 std::string* error_msg) {
257 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800258 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800259 nullptr,
260 data_len,
261 PROT_READ|PROT_WRITE,
262 /*low_4gb*/false,
263 /*reuse*/false,
264 error_msg));
265 if (map == nullptr) {
266 return map;
267 }
268 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800269 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
270 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800271 map->Protect(PROT_READ);
272 return map;
273}
274
Alex Lighta7e38d82017-01-19 14:57:28 -0800275Redefiner::ClassRedefinition::ClassRedefinition(
276 Redefiner* driver,
277 jclass klass,
278 const art::DexFile* redefined_dex_file,
279 const char* class_sig,
280 art::ArraySlice<const unsigned char> orig_dex_file) :
281 driver_(driver),
282 klass_(klass),
283 dex_file_(redefined_dex_file),
284 class_sig_(class_sig),
285 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800286 GetMirrorClass()->MonitorEnter(driver_->self_);
287}
288
289Redefiner::ClassRedefinition::~ClassRedefinition() {
290 if (driver_ != nullptr) {
291 GetMirrorClass()->MonitorExit(driver_->self_);
292 }
293}
294
Alex Light0e692732017-01-10 15:00:05 -0800295jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
296 art::Runtime* runtime,
297 art::Thread* self,
298 jint class_count,
299 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800300 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800301 if (env == nullptr) {
302 *error_msg = "env was null!";
303 return ERR(INVALID_ENVIRONMENT);
304 } else if (class_count < 0) {
305 *error_msg = "class_count was less then 0";
306 return ERR(ILLEGAL_ARGUMENT);
307 } else if (class_count == 0) {
308 // We don't actually need to do anything. Just return OK.
309 return OK;
310 } else if (definitions == nullptr) {
311 *error_msg = "null definitions!";
312 return ERR(NULL_POINTER);
313 }
Alex Light6ac57502017-01-19 15:05:06 -0800314 std::vector<ArtClassDefinition> def_vector;
315 def_vector.reserve(class_count);
316 for (jint i = 0; i < class_count; i++) {
317 // We make a copy of the class_bytes to pass into the retransformation.
318 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
319 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
320 // to get the passed in bytes.
321 // TODO Implement saving the original bytes.
322 unsigned char* class_bytes_copy = nullptr;
323 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
324 if (res != OK) {
325 return res;
326 }
327 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
328
329 ArtClassDefinition def;
330 def.dex_len = definitions[i].class_byte_count;
331 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
332 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800333 def.SetModified();
334 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
335 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800336 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
337 if (res != OK) {
338 return res;
339 }
340 def_vector.push_back(std::move(def));
341 }
342 // Call all the transformation events.
343 jvmtiError res = Transformer::RetransformClassesDirect(env,
344 self,
345 &def_vector);
346 if (res != OK) {
347 // Something went wrong with transformation!
348 return res;
349 }
350 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
351}
352
353jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
354 art::Runtime* runtime,
355 art::Thread* self,
356 const std::vector<ArtClassDefinition>& definitions,
357 std::string* error_msg) {
358 DCHECK(env != nullptr);
359 if (definitions.size() == 0) {
360 // We don't actually need to do anything. Just return OK.
361 return OK;
362 }
Alex Light0e692732017-01-10 15:00:05 -0800363 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
364 // are going to redefine.
365 art::jit::ScopedJitSuspend suspend_jit;
366 // Get shared mutator lock so we can lock all the classes.
367 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800368 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800369 for (const ArtClassDefinition& def : definitions) {
370 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800371 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800372 jvmtiError res = r.AddRedefinition(env, def);
373 if (res != OK) {
374 return res;
375 }
Alex Light0e692732017-01-10 15:00:05 -0800376 }
377 }
378 return r.Run();
379}
380
Alex Light6ac57502017-01-19 15:05:06 -0800381jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800382 std::string original_dex_location;
383 jvmtiError ret = OK;
384 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
385 *error_msg_ = "Unable to get original dex file location!";
386 return ret;
387 }
Alex Light52a2db52017-01-19 23:00:21 +0000388 char* generic_ptr_unused = nullptr;
389 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800390 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
391 *error_msg_ = "Unable to get class signature!";
392 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000393 }
Alex Light52a2db52017-01-19 23:00:21 +0000394 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800395 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
396 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
397 def.dex_len,
398 def.dex_data.get(),
399 error_msg_));
400 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800401 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800402 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800403 << "in dex file " << original_dex_location << " because: " << *error_msg_;
404 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800405 return ERR(OUT_OF_MEMORY);
406 }
407 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800408 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800409 return ERR(INVALID_CLASS_FORMAT);
410 }
411 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
412 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
413 checksum,
414 std::move(map),
415 /*verify*/true,
416 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800417 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800418 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800419 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800420 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800421 return ERR(INVALID_CLASS_FORMAT);
422 }
Alex Light0e692732017-01-10 15:00:05 -0800423 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800424 Redefiner::ClassRedefinition(this,
425 def.klass,
426 dex_file.release(),
427 signature_ptr,
428 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800429 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800430}
431
Alex Light0e692732017-01-10 15:00:05 -0800432art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
433 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800434}
435
Alex Light0e692732017-01-10 15:00:05 -0800436art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800437 return GetMirrorClass()->GetClassLoader();
438}
439
Alex Light0e692732017-01-10 15:00:05 -0800440art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
441 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000442 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800443}
444
Alex Light0e692732017-01-10 15:00:05 -0800445void Redefiner::RecordFailure(jvmtiError result,
446 const std::string& class_sig,
447 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800448 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800449 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800450 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800451 result_ = result;
452}
453
Alex Lighta7e38d82017-01-19 14:57:28 -0800454art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
455 // If we have been specifically given a new set of bytes use that
456 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800457 return art::mirror::ByteArray::AllocateAndFill(
458 driver_->self_,
459 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
460 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800461 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800462
463 // See if we already have one set.
464 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
465 if (!ext.IsNull()) {
466 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
467 if (!old_original_bytes.IsNull()) {
468 // We do. Use it.
469 return old_original_bytes.Ptr();
470 }
Alex Lighta01de592016-11-15 10:43:06 -0800471 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800472
473 // Copy the current dex_file
474 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
475 // TODO Handle this or make it so it cannot happen.
476 if (current_dex_file.NumClassDefs() != 1) {
477 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
478 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800479 }
Alex Light440b5d92017-01-24 15:32:25 -0800480 return art::mirror::ByteArray::AllocateAndFill(
481 driver_->self_,
482 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
483 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800484}
485
Alex Lightdba61482016-12-21 08:20:29 -0800486struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000487 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800488 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800489 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800490
Alex Lighteee0bd42017-02-14 15:31:45 +0000491 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
492 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800493};
494
Alex Lightdba61482016-12-21 08:20:29 -0800495void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
496 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800497 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
498 data->allocator,
499 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000500 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800501}
502
503// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
504// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800505// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
506void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800507 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
508 art::mirror::ClassExt* ext = art_klass->GetExtData();
509 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800510 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000511 // This holds pointers to the obsolete methods map fields which are updated as needed.
512 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
513 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800514 // Add all the declared methods to the map
515 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000516 // It is possible to simply filter out some methods where they cannot really become obsolete,
517 // such as native methods and keep their original (possibly optimized) implementations. We don't
518 // do this, however, since we would need to mark these functions (still in the classes
519 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
520 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
521 // error checking from the interpreter which ensure we don't try to start executing obsolete
522 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000523 ctx.obsolete_methods.insert(&m);
524 // TODO Allow this or check in IsModifiableClass.
525 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800526 }
527 {
Alex Light0e692732017-01-10 15:00:05 -0800528 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800529 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
530 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800531 }
Alex Lightdba61482016-12-21 08:20:29 -0800532}
533
Alex Light6161f132017-01-25 10:30:20 -0800534// Try and get the declared method. First try to get a virtual method then a direct method if that's
535// not found.
536static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
537 const char* name,
538 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
539 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
540 if (m == nullptr) {
541 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
542 }
543 return m;
544}
545
546bool Redefiner::ClassRedefinition::CheckSameMethods() {
547 art::StackHandleScope<1> hs(driver_->self_);
548 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
549 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
550
551 art::ClassDataItemIterator new_iter(*dex_file_,
552 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
553
554 // Make sure we have the same number of methods.
555 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
556 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
557 if (num_new_method != num_old_method) {
558 bool bigger = num_new_method > num_old_method;
559 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
560 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
561 StringPrintf("Total number of declared methods changed from %d to %d",
562 num_old_method, num_new_method));
563 return false;
564 }
565
566 // Skip all of the fields. We should have already checked this.
567 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
568 new_iter.Next();
569 }
570 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
571 // files have the same number of methods, which means there must be an equal amount of additions
572 // and removals.
573 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
574 // Get the data on the method we are searching for
575 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
576 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
577 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
578 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
579 // If we got past the check for the same number of methods above that means there must be at
580 // least one added and one removed method. We will return the ADDED failure message since it is
581 // easier to get a useful error report for it.
582 if (old_method == nullptr) {
583 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
584 StringPrintf("Unknown method '%s' (sig: %s) was added!",
585 new_method_name,
586 new_method_signature.ToString().c_str()));
587 return false;
588 }
589 // Since direct methods have different flags than virtual ones (specifically direct methods must
590 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
591 // virtual to direct.
592 uint32_t new_flags = new_iter.GetMethodAccessFlags();
593 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
594 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
595 StringPrintf("method '%s' (sig: %s) had different access flags",
596 new_method_name,
597 new_method_signature.ToString().c_str()));
598 return false;
599 }
600 }
601 return true;
602}
603
604bool Redefiner::ClassRedefinition::CheckSameFields() {
605 art::StackHandleScope<1> hs(driver_->self_);
606 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
607 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
608 art::ClassDataItemIterator new_iter(*dex_file_,
609 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
610 const art::DexFile& old_dex_file = h_klass->GetDexFile();
611 art::ClassDataItemIterator old_iter(old_dex_file,
612 old_dex_file.GetClassData(*h_klass->GetClassDef()));
613 // Instance and static fields can be differentiated by their flags so no need to check them
614 // separately.
615 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
616 // Get the data on the method we are searching for
617 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
618 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
619 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
620
621 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
622 // We are missing the old version of this method!
623 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
624 StringPrintf("Unknown field '%s' (type: %s) added!",
625 new_field_name,
626 new_field_type));
627 return false;
628 }
629
630 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
631 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
632 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
633
634 // Check name and type.
635 if (strcmp(old_field_name, new_field_name) != 0 ||
636 strcmp(old_field_type, new_field_type) != 0) {
637 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
638 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
639 old_field_name,
640 old_field_type,
641 new_field_name,
642 new_field_type));
643 return false;
644 }
645
646 // Since static fields have different flags than instance ones (specifically static fields must
647 // have the kAccStatic flag) we can tell if a field changes from static to instance.
648 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
649 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
650 StringPrintf("Field '%s' (sig: %s) had different access flags",
651 new_field_name,
652 new_field_type));
653 return false;
654 }
655
656 new_iter.Next();
657 old_iter.Next();
658 }
659 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
660 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
661 StringPrintf("field '%s' (sig: %s) is missing!",
662 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
663 old_iter.GetMemberIndex())),
664 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
665 old_iter.GetMemberIndex()))));
666 return false;
667 }
668 return true;
669}
670
Alex Light0e692732017-01-10 15:00:05 -0800671bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000672 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800673 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000674 // Easy check that only 1 class def is present.
675 if (dex_file_->NumClassDefs() != 1) {
676 RecordFailure(ERR(ILLEGAL_ARGUMENT),
677 StringPrintf("Expected 1 class def in dex file but found %d",
678 dex_file_->NumClassDefs()));
679 return false;
680 }
681 // Get the ClassDef from the new DexFile.
682 // Since the dex file has only a single class def the index is always 0.
683 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
684 // Get the class as it is now.
685 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
686
687 // Check the access flags didn't change.
688 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
689 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
690 "Cannot change modifiers of class by redefinition");
691 return false;
692 }
693
694 // Check class name.
695 // These should have been checked by the dexfile verifier on load.
696 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
697 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
698 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
699 if (!current_class->DescriptorEquals(descriptor)) {
700 std::string storage;
701 RecordFailure(ERR(NAMES_DONT_MATCH),
702 StringPrintf("expected file to contain class called '%s' but found '%s'!",
703 current_class->GetDescriptor(&storage),
704 descriptor));
705 return false;
706 }
707 if (current_class->IsObjectClass()) {
708 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
709 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
710 return false;
711 }
712 } else {
713 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
714 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
715 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
716 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
717 return false;
718 }
719 }
720 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
721 if (interfaces == nullptr) {
722 if (current_class->NumDirectInterfaces() != 0) {
723 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
724 return false;
725 }
726 } else {
727 DCHECK(!current_class->IsProxyClass());
728 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
729 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
730 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
731 return false;
732 }
733 // The order of interfaces is (barely) meaningful so we error if it changes.
734 const art::DexFile& orig_dex_file = current_class->GetDexFile();
735 for (uint32_t i = 0; i < interfaces->Size(); i++) {
736 if (strcmp(
737 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
738 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
739 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
740 "Interfaces changed or re-ordered");
741 return false;
742 }
743 }
744 }
745 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
746
747 return true;
748}
749
750// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800751bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800752 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800753 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000754
Alex Lighte4a88632017-01-10 07:41:24 -0800755 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
756 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
757 if (res != OK) {
758 RecordFailure(res, err);
759 return false;
760 } else {
761 return true;
762 }
Alex Light460d1b42017-01-10 15:37:17 +0000763}
764
Alex Light0e692732017-01-10 15:00:05 -0800765bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000766 return CheckRedefinable() &&
767 CheckClass() &&
768 CheckSameFields() &&
769 CheckSameMethods();
770}
771
Alex Light0e692732017-01-10 15:00:05 -0800772// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
773// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
774// having to deal with the fact that we need to hold an arbitrary number of references live.
775class RedefinitionDataHolder {
776 public:
777 enum DataSlot : int32_t {
778 kSlotSourceClassLoader = 0,
779 kSlotJavaDexFile = 1,
780 kSlotNewDexFileCookie = 2,
781 kSlotNewDexCache = 3,
782 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800783 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800784
785 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800786 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800787 };
788
789 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
790 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
791 // the passed in handle-scope.
792 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
793 art::Runtime* runtime,
794 art::Thread* self,
795 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
796 arr_(
797 hs->NewHandle(
798 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
799 self,
800 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
801 num_redefinitions * kNumSlots))) {}
802
803 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
804 return arr_.IsNull();
805 }
806
807 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800808 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800809 REQUIRES_SHARED(art::Locks::mutator_lock_) {
810 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
811 }
Alex Light8c889d22017-02-06 13:58:27 -0800812 art::mirror::Object* GetJavaDexFile(jint klass_index) const
813 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800814 return GetSlot(klass_index, kSlotJavaDexFile);
815 }
Alex Light8c889d22017-02-06 13:58:27 -0800816 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800817 REQUIRES_SHARED(art::Locks::mutator_lock_) {
818 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
819 }
Alex Light8c889d22017-02-06 13:58:27 -0800820 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800821 REQUIRES_SHARED(art::Locks::mutator_lock_) {
822 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
823 }
Alex Light8c889d22017-02-06 13:58:27 -0800824 art::mirror::Class* GetMirrorClass(jint klass_index) const
825 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800826 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
827 }
828
Alex Light8c889d22017-02-06 13:58:27 -0800829 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800830 REQUIRES_SHARED(art::Locks::mutator_lock_) {
831 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
832 }
833
Alex Light0e692732017-01-10 15:00:05 -0800834 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
835 REQUIRES_SHARED(art::Locks::mutator_lock_) {
836 SetSlot(klass_index, kSlotSourceClassLoader, loader);
837 }
838 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
839 REQUIRES_SHARED(art::Locks::mutator_lock_) {
840 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
841 }
842 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
843 REQUIRES_SHARED(art::Locks::mutator_lock_) {
844 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
845 }
846 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
847 REQUIRES_SHARED(art::Locks::mutator_lock_) {
848 SetSlot(klass_index, kSlotNewDexCache, cache);
849 }
850 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
851 REQUIRES_SHARED(art::Locks::mutator_lock_) {
852 SetSlot(klass_index, kSlotMirrorClass, klass);
853 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800854 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
855 REQUIRES_SHARED(art::Locks::mutator_lock_) {
856 SetSlot(klass_index, kSlotOrigDexFile, bytes);
857 }
Alex Light0e692732017-01-10 15:00:05 -0800858
Alex Light8c889d22017-02-06 13:58:27 -0800859 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800860 return arr_->GetLength() / kNumSlots;
861 }
862
863 private:
Alex Light8c889d22017-02-06 13:58:27 -0800864 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Light0e692732017-01-10 15:00:05 -0800865
866 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800867 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800868 DCHECK_LT(klass_index, Length());
869 return arr_->Get((kNumSlots * klass_index) + slot);
870 }
871
872 void SetSlot(jint klass_index,
873 DataSlot slot,
874 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
875 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
876 DCHECK_LT(klass_index, Length());
877 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
878 }
879
880 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
881};
882
Alex Light8c889d22017-02-06 13:58:27 -0800883// TODO Stash and update soft failure state
884bool Redefiner::ClassRedefinition::CheckVerification(int32_t klass_index,
885 const RedefinitionDataHolder& holder) {
886 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
887 art::StackHandleScope<2> hs(driver_->self_);
888 std::string error;
889 // TODO Make verification log level lower
890 art::verifier::MethodVerifier::FailureKind failure =
891 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
892 dex_file_.get(),
893 hs.NewHandle(holder.GetNewDexCache(klass_index)),
894 hs.NewHandle(GetClassLoader()),
895 dex_file_->GetClassDef(0), /*class_def*/
896 nullptr, /*compiler_callbacks*/
897 false, /*allow_soft_failures*/
898 /*log_level*/
899 art::verifier::HardFailLogMode::kLogWarning,
900 &error);
901 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
902 if (!passes) {
903 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
904 }
905 return passes;
906}
907
Alex Light1babae02017-02-01 15:35:34 -0800908// Looks through the previously allocated cookies to see if we need to update them with another new
909// dexfile. This is so that even if multiple classes with the same classloader are redefined at
910// once they are all added to the classloader.
911bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
912 int32_t klass_index,
913 art::Handle<art::mirror::ClassLoader> source_class_loader,
914 art::Handle<art::mirror::Object> dex_file_obj,
915 /*out*/RedefinitionDataHolder* holder) {
916 art::StackHandleScope<2> hs(driver_->self_);
917 art::MutableHandle<art::mirror::LongArray> old_cookie(
918 hs.NewHandle<art::mirror::LongArray>(nullptr));
919 bool has_older_cookie = false;
920 // See if we already have a cookie that a previous redefinition got from the same classloader.
921 for (int32_t i = 0; i < klass_index; i++) {
922 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
923 // Since every instance of this classloader should have the same cookie associated with it we
924 // can stop looking here.
925 has_older_cookie = true;
926 old_cookie.Assign(holder->GetNewDexFileCookie(i));
927 break;
928 }
929 }
930 if (old_cookie.IsNull()) {
931 // No older cookie. Get it directly from the dex_file_obj
932 // We should not have seen this classloader elsewhere.
933 CHECK(!has_older_cookie);
934 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
935 }
936 // Use the old cookie to generate the new one with the new DexFile* added in.
937 art::Handle<art::mirror::LongArray>
938 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
939 old_cookie,
940 dex_file_.get())));
941 // Make sure the allocation worked.
942 if (new_cookie.IsNull()) {
943 return false;
944 }
945
946 // Save the cookie.
947 holder->SetNewDexFileCookie(klass_index, new_cookie.Get());
948 // If there are other copies of this same classloader we need to make sure that we all have the
949 // same cookie.
950 if (has_older_cookie) {
951 for (int32_t i = 0; i < klass_index; i++) {
952 // We will let the GC take care of the cookie we allocated for this one.
953 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
954 holder->SetNewDexFileCookie(i, new_cookie.Get());
955 }
956 }
957 }
958
959 return true;
960}
961
Alex Lighta7e38d82017-01-19 14:57:28 -0800962bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
963 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800964 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800965 art::StackHandleScope<2> hs(driver_->self_);
966 holder->SetMirrorClass(klass_index, GetMirrorClass());
967 // This shouldn't allocate
968 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800969 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
970 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
971 holder->SetSourceClassLoader(klass_index, loader.Get());
972 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
973 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
974 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
975 if (dex_file_obj.Get() == nullptr) {
976 // TODO Better error msg.
977 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 Light0e692732017-01-10 15:00:05 -08001007bool Redefiner::CheckAllRedefinitionAreValid() {
1008 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1009 if (!redef.CheckRedefinitionIsValid()) {
1010 return false;
1011 }
1012 }
1013 return true;
1014}
1015
1016bool Redefiner::EnsureAllClassAllocationsFinished() {
1017 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1018 if (!redef.EnsureClassAllocationsFinished()) {
1019 return false;
1020 }
1021 }
1022 return true;
1023}
1024
1025bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
1026 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -08001027 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -08001028 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -08001029 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -08001030 return false;
1031 }
Alex Light0e692732017-01-10 15:00:05 -08001032 cnt++;
1033 }
1034 return true;
1035}
1036
1037void Redefiner::ClassRedefinition::ReleaseDexFile() {
1038 dex_file_.release();
1039}
1040
1041void Redefiner::ReleaseAllDexFiles() {
1042 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1043 redef.ReleaseDexFile();
1044 }
1045}
1046
Alex Light8c889d22017-02-06 13:58:27 -08001047bool Redefiner::CheckAllClassesAreVerified(const RedefinitionDataHolder& holder) {
1048 int32_t cnt = 0;
1049 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1050 if (!redef.CheckVerification(cnt, holder)) {
1051 return false;
1052 }
1053 cnt++;
1054 }
1055 return true;
1056}
1057
Alex Lighta01de592016-11-15 10:43:06 -08001058jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001059 art::StackHandleScope<1> hs(self_);
1060 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1061 // We will let this be collected after the end of this function.
1062 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
1063 if (holder.IsNull()) {
1064 self_->AssertPendingOOMException();
1065 self_->ClearException();
1066 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1067 return result_;
1068 }
1069
Alex Lighta01de592016-11-15 10:43:06 -08001070 // First we just allocate the ClassExt and its fields that we need. These can be updated
1071 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1072 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1073 // between allocating them and pausing all threads before we can update them so we need to do a
1074 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001075 if (!CheckAllRedefinitionAreValid() ||
1076 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001077 !FinishAllRemainingAllocations(holder) ||
1078 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001079 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1080 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001081 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1082 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001083 return result_;
1084 }
Alex Light7916f202017-01-27 09:00:15 -08001085 int32_t counter = 0;
1086 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1087 if (holder.GetSourceClassLoader(counter) == nullptr) {
1088 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
1089 }
1090 counter++;
1091 }
Alex Light6abd5392017-01-05 17:53:00 -08001092 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1093 // allocating so no deadlocks.
1094 art::gc::Heap* heap = runtime_->GetHeap();
1095 if (heap->IsGcConcurrentAndMoving()) {
1096 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
1097 heap->IncrementDisableMovingGC(self_);
1098 }
Alex Lighta01de592016-11-15 10:43:06 -08001099 // Do transition to final suspension
1100 // TODO We might want to give this its own suspended state!
1101 // TODO This isn't right. We need to change state without any chance of suspend ideally!
1102 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
1103 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -08001104 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -08001105 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
1106 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
1107 // TODO We need to update all debugger MethodIDs so they note the method they point to is
1108 // obsolete or implement some other well defined semantics.
1109 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light7916f202017-01-27 09:00:15 -08001110 counter = 0;
Alex Light0e692732017-01-10 15:00:05 -08001111 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -08001112 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light7916f202017-01-27 09:00:15 -08001113 if (holder.GetSourceClassLoader(counter) != nullptr) {
1114 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(counter),
1115 holder.GetNewDexFileCookie(counter));
1116 }
1117 art::mirror::Class* klass = holder.GetMirrorClass(counter);
Alex Light0e692732017-01-10 15:00:05 -08001118 // TODO Rewrite so we don't do a stack walk for each and every class.
1119 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light7916f202017-01-27 09:00:15 -08001120 redef.UpdateClass(klass, holder.GetNewDexCache(counter),
1121 holder.GetOriginalDexFileBytes(counter));
1122 counter++;
Alex Light0e692732017-01-10 15:00:05 -08001123 }
Alex Lightdba61482016-12-21 08:20:29 -08001124 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -08001125 // TODO Shrink the obsolete method maps if possible?
1126 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -08001127 // TODO Put this into a scoped thing.
1128 runtime_->GetThreadList()->ResumeAll();
1129 // Get back shared mutator lock as expected for return.
1130 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -08001131 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1132 // owns the DexFile and when ownership is transferred.
1133 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001134 if (heap->IsGcConcurrentAndMoving()) {
1135 heap->DecrementDisableMovingGC(self_);
1136 }
Alex Lighta01de592016-11-15 10:43:06 -08001137 return OK;
1138}
1139
Alex Light0e692732017-01-10 15:00:05 -08001140void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1141 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1142 const art::DexFile::ClassDef& class_def) {
1143 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001144 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001145 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001146 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001147 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001148 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1149 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1150 art::dex::TypeIndex method_return_idx =
1151 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1152 const auto* old_type_list = method.GetParameterTypeList();
1153 std::vector<art::dex::TypeIndex> new_type_list;
1154 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1155 new_type_list.push_back(
1156 dex_file_->GetIndexForTypeId(
1157 *dex_file_->FindTypeId(
1158 old_dex_file.GetTypeDescriptor(
1159 old_dex_file.GetTypeId(
1160 old_type_list->GetTypeItem(i).type_idx_)))));
1161 }
1162 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1163 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001164 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001165 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001166 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1167 *new_name_id,
1168 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001169 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001170 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001171 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1172 method.SetDexMethodIndex(dex_method_idx);
1173 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001174 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001175 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -08001176 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001177 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001178 if (jit != nullptr) {
1179 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1180 }
Alex Lighta01de592016-11-15 10:43:06 -08001181 }
Alex Light200b9d72016-12-15 11:34:13 -08001182}
1183
Alex Light0e692732017-01-10 15:00:05 -08001184void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001185 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1186 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1187 for (art::ArtField& field : fields_iter) {
1188 std::string declaring_class_name;
1189 const art::DexFile::TypeId* new_declaring_id =
1190 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1191 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1192 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1193 // TODO Handle error, cleanup.
1194 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1195 const art::DexFile::FieldId* new_field_id =
1196 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1197 CHECK(new_field_id != nullptr);
1198 // We only need to update the index since the other data in the ArtField cannot be updated.
1199 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1200 }
1201 }
Alex Light200b9d72016-12-15 11:34:13 -08001202}
1203
1204// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001205void Redefiner::ClassRedefinition::UpdateClass(
1206 art::ObjPtr<art::mirror::Class> mclass,
1207 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1208 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001209 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1210 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1211 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001212 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001213
Alex Lighta01de592016-11-15 10:43:06 -08001214 // Update the class fields.
1215 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1216 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1217 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001218 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001219 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001220 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1221 CHECK(!ext.IsNull());
1222 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001223}
1224
Alex Lighta01de592016-11-15 10:43:06 -08001225// This function does all (java) allocations we need to do for the Class being redefined.
1226// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001227bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1228 art::StackHandleScope<2> hs(driver_->self_);
1229 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1230 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001231 if (klass.Get() == nullptr) {
1232 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1233 return false;
1234 }
1235 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001236 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001237 if (ext.Get() == nullptr) {
1238 // No memory. Clear exception (it's not useful) and return error.
1239 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1240 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001241 driver_->self_->AssertPendingOOMException();
1242 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001243 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1244 return false;
1245 }
1246 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1247 // are only modified when all threads (other than the modifying one) are suspended we don't need
1248 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1249 // however, since that can happen at any time.
1250 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1251 // are no obsolete methods.
1252 {
Alex Light0e692732017-01-10 15:00:05 -08001253 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001254 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001255 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001256 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001257 driver_->self_->AssertPendingOOMException();
1258 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001259 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1260 return false;
1261 }
1262 }
1263 return true;
1264}
1265
1266} // namespace openjdkjvmti