blob: a23baa5095b37b148a1119f53e8d836602ff82ff [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 Gampe57943812017-12-06 21:39:13 -080036#include <android-base/logging.h>
37#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080038
Andreas Gampea1d2f952017-04-20 22:53:58 -070039#include "art_field-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "art_jvmti.h"
Steven Morelande431e272017-07-18 16:53:49 -070041#include "art_method-inl.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010042#include "base/array_ref.h"
Vladimir Markoba118822017-06-12 15:41:56 +010043#include "base/stringpiece.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080044#include "class_linker-inl.h"
Alex Light5643caf2017-02-08 11:39:07 -080045#include "debugger.h"
David Sehr013fd802018-01-11 22:55:24 -080046#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080047#include "dex/dex_file.h"
48#include "dex/dex_file_loader.h"
49#include "dex/dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080050#include "events-inl.h"
51#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080052#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080053#include "instrumentation.h"
Alex Light07f06212017-06-01 14:01:43 -070054#include "intern_table.h"
Alex Light5643caf2017-02-08 11:39:07 -080055#include "jdwp/jdwp.h"
56#include "jdwp/jdwp_constants.h"
57#include "jdwp/jdwp_event.h"
58#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080059#include "jit/jit.h"
60#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080061#include "jni_env_ext-inl.h"
62#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080063#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080064#include "mirror/class_ext.h"
65#include "mirror/object.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070066#include "nativehelper/scoped_local_ref.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080067#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080068#include "object_lock.h"
69#include "runtime.h"
Alex Lighta26e3492017-06-27 17:55:37 -070070#include "ti_breakpoint.h"
Alex Lighteb98b082017-01-25 13:02:32 -080071#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080072#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080073#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070074#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080075
76namespace openjdkjvmti {
77
Andreas Gampe46ee31b2016-12-14 10:11:49 -080078using android::base::StringPrintf;
79
Alex Lighteee0bd42017-02-14 15:31:45 +000080// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
81// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
82// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
83class ObsoleteMap {
84 public:
85 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
86 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
87 auto method_pair = id_map_.find(original);
88 if (method_pair != id_map_.end()) {
89 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
90 method_pair->second, art::kRuntimePointerSize);
91 DCHECK(res != nullptr);
92 DCHECK_EQ(original, res->GetNonObsoleteMethod());
93 return res;
94 } else {
95 return nullptr;
96 }
97 }
98
99 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
100 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
101 DCHECK(original != nullptr);
102 DCHECK(obsolete != nullptr);
103 int32_t slot = next_free_slot_++;
104 DCHECK_LT(slot, obsolete_methods_->GetLength());
105 DCHECK(nullptr ==
106 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
107 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
108 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
109 obsolete_dex_caches_->Set(slot, original_dex_cache_);
110 id_map_.insert({original, slot});
111 }
112
113 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
114 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
115 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
116 : next_free_slot_(0),
117 obsolete_methods_(obsolete_methods),
118 obsolete_dex_caches_(obsolete_dex_caches),
119 original_dex_cache_(original_dex_cache) {
120 // Figure out where the first unused slot in the obsolete_methods_ array is.
121 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
122 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
123 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
124 next_free_slot_++;
125 }
126 // Sanity check that the same slot in obsolete_dex_caches_ is free.
127 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
128 }
129
130 private:
131 int32_t next_free_slot_;
132 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
133 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
134 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
135 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
136 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
137 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
138};
139
Alex Lightdba61482016-12-21 08:20:29 -0800140// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
141// some basic sanity checks that the obsolete method is sane.
142class ObsoleteMethodStackVisitor : public art::StackVisitor {
143 protected:
144 ObsoleteMethodStackVisitor(
145 art::Thread* thread,
146 art::LinearAlloc* allocator,
147 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000148 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800149 : StackVisitor(thread,
150 /*context*/nullptr,
151 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
152 allocator_(allocator),
153 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800154 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800155
156 ~ObsoleteMethodStackVisitor() OVERRIDE {}
157
158 public:
159 // Returns true if we successfully installed obsolete methods on this thread, filling
160 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
161 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800162 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800163 art::Thread* thread,
164 art::LinearAlloc* allocator,
165 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000166 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800167 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800168 ObsoleteMethodStackVisitor visitor(thread,
169 allocator,
170 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800171 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800172 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800173 }
174
175 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000176 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800177 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800178 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800179 // We cannot ensure that the right dex file is used in inlined frames so we don't support
180 // redefining them.
181 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000182 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
183 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800184 // Create a new Obsolete Method and put it in the list.
185 art::Runtime* runtime = art::Runtime::Current();
186 art::ClassLinker* cl = runtime->GetClassLinker();
187 auto ptr_size = cl->GetImagePointerSize();
188 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800189 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800190 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
191 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800192 new_obsolete_method = new (method_storage) art::ArtMethod();
193 new_obsolete_method->CopyFrom(old_method, ptr_size);
194 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
195 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800196 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700197 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000198 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800199 // Update JIT Data structures to point to the new method.
200 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
201 if (jit != nullptr) {
202 // Notify the JIT we are making this obsolete method. It will update the jit's internal
203 // structures to keep track of the new obsolete method.
204 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
205 }
Alex Lightdba61482016-12-21 08:20:29 -0800206 }
207 DCHECK(new_obsolete_method != nullptr);
208 SetMethod(new_obsolete_method);
209 }
210 return true;
211 }
212
213 private:
214 // The linear allocator we should use to make new methods.
215 art::LinearAlloc* allocator_;
216 // The set of all methods which could be obsoleted.
217 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
218 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000219 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
220 // the redefined classes ClassExt as it is filled.
221 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800222};
223
Alex Lighte4a88632017-01-10 07:41:24 -0800224jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
225 jclass klass,
226 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800227 art::Thread* self = art::Thread::Current();
228 art::ScopedObjectAccess soa(self);
229 art::StackHandleScope<1> hs(self);
230 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
231 if (obj.IsNull()) {
232 return ERR(INVALID_CLASS);
233 }
234 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
235 std::string err_unused;
236 *is_redefinable =
Alex Lightd3782f32018-04-05 13:49:43 -0700237 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
238 ? JNI_TRUE : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800239 return OK;
240}
241
Alex Lightd3782f32018-04-05 13:49:43 -0700242jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
243 art::Thread* self = art::Thread::Current();
244 art::ScopedObjectAccess soa(self);
245 art::StackHandleScope<1> hs(self);
246 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
247 if (obj.IsNull()) {
248 return ERR(INVALID_CLASS);
249 }
250 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
251 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
252}
253
Alex Lighte4a88632017-01-10 07:41:24 -0800254jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
255 /*out*/std::string* error_msg) {
Alex Lightd3782f32018-04-05 13:49:43 -0700256 if (!klass->IsResolved()) {
257 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
258 // the same thread as the class-linking process. If it's on another thread we will be able to
259 // wait for the preparation to finish and continue from there.
260 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
261 *error_msg = "Modification of class " + klass->PrettyClass() +
262 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
263 " Please use ClassFileLoadHook directly instead.";
264 return ERR(INTERNAL);
265 } else {
266 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
267 << "it could cause arbitrary length waits as the class is being resolved.";
268 }
269 }
Alex Lighte4a88632017-01-10 07:41:24 -0800270 if (klass->IsPrimitive()) {
271 *error_msg = "Modification of primitive classes is not supported";
272 return ERR(UNMODIFIABLE_CLASS);
273 } else if (klass->IsInterface()) {
274 *error_msg = "Modification of Interface classes is currently not supported";
275 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800276 } else if (klass->IsStringClass()) {
277 *error_msg = "Modification of String class is not supported";
278 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800279 } else if (klass->IsArrayClass()) {
280 *error_msg = "Modification of Array classes is not supported";
281 return ERR(UNMODIFIABLE_CLASS);
282 } else if (klass->IsProxyClass()) {
283 *error_msg = "Modification of proxy classes is not supported";
284 return ERR(UNMODIFIABLE_CLASS);
285 }
286
Alex Lighte77b48b2017-02-22 11:08:06 -0800287 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
288 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
289 *error_msg = "Class might have stack frames that cannot be made obsolete";
290 return ERR(UNMODIFIABLE_CLASS);
291 }
292 }
293
Alex Lighte4a88632017-01-10 07:41:24 -0800294 return OK;
295}
296
Alex Lighta01de592016-11-15 10:43:06 -0800297// Moves dex data to an anonymous, read-only mmap'd region.
298std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100299 art::ArrayRef<const unsigned char> data,
Alex Lighta01de592016-11-15 10:43:06 -0800300 std::string* error_msg) {
301 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800302 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800303 nullptr,
Alex Lightb7354d52017-03-30 15:17:01 -0700304 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800305 PROT_READ|PROT_WRITE,
306 /*low_4gb*/false,
307 /*reuse*/false,
308 error_msg));
309 if (map == nullptr) {
310 return map;
311 }
Vladimir Markoe1993c72017-06-14 17:01:38 +0100312 memcpy(map->Begin(), data.data(), data.size());
Alex Light0b772572016-12-02 17:27:31 -0800313 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
314 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800315 map->Protect(PROT_READ);
316 return map;
317}
318
Alex Lighta7e38d82017-01-19 14:57:28 -0800319Redefiner::ClassRedefinition::ClassRedefinition(
320 Redefiner* driver,
321 jclass klass,
322 const art::DexFile* redefined_dex_file,
323 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100324 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800325 driver_(driver),
326 klass_(klass),
327 dex_file_(redefined_dex_file),
328 class_sig_(class_sig),
329 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800330 GetMirrorClass()->MonitorEnter(driver_->self_);
331}
332
333Redefiner::ClassRedefinition::~ClassRedefinition() {
334 if (driver_ != nullptr) {
335 GetMirrorClass()->MonitorExit(driver_->self_);
336 }
337}
338
Alex Light0e692732017-01-10 15:00:05 -0800339jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800340 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800341 art::Runtime* runtime,
342 art::Thread* self,
343 jint class_count,
344 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800345 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800346 if (env == nullptr) {
347 *error_msg = "env was null!";
348 return ERR(INVALID_ENVIRONMENT);
349 } else if (class_count < 0) {
350 *error_msg = "class_count was less then 0";
351 return ERR(ILLEGAL_ARGUMENT);
352 } else if (class_count == 0) {
353 // We don't actually need to do anything. Just return OK.
354 return OK;
355 } else if (definitions == nullptr) {
356 *error_msg = "null definitions!";
357 return ERR(NULL_POINTER);
358 }
Alex Light6ac57502017-01-19 15:05:06 -0800359 std::vector<ArtClassDefinition> def_vector;
360 def_vector.reserve(class_count);
361 for (jint i = 0; i < class_count; i++) {
Alex Lightd3782f32018-04-05 13:49:43 -0700362 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800363 if (res != OK) {
364 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800365 }
Alex Light6ac57502017-01-19 15:05:06 -0800366 // We make a copy of the class_bytes to pass into the retransformation.
367 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
368 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
369 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800370 unsigned char* class_bytes_copy = nullptr;
Alex Lightce6ee702017-03-06 15:46:43 -0800371 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
Alex Light6ac57502017-01-19 15:05:06 -0800372 if (res != OK) {
373 return res;
374 }
375 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
376
377 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800378 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800379 if (res != OK) {
380 return res;
381 }
382 def_vector.push_back(std::move(def));
383 }
384 // Call all the transformation events.
Alex Light64e4c142018-01-30 13:46:37 -0800385 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800386 self,
387 &def_vector);
388 if (res != OK) {
389 // Something went wrong with transformation!
390 return res;
391 }
392 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
393}
394
395jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
396 art::Runtime* runtime,
397 art::Thread* self,
398 const std::vector<ArtClassDefinition>& definitions,
399 std::string* error_msg) {
400 DCHECK(env != nullptr);
401 if (definitions.size() == 0) {
402 // We don't actually need to do anything. Just return OK.
403 return OK;
404 }
Alex Light0e692732017-01-10 15:00:05 -0800405 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
406 // are going to redefine.
407 art::jit::ScopedJitSuspend suspend_jit;
408 // Get shared mutator lock so we can lock all the classes.
409 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700410 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800411 for (const ArtClassDefinition& def : definitions) {
412 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700413 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800414 jvmtiError res = r.AddRedefinition(env, def);
415 if (res != OK) {
416 return res;
417 }
Alex Light0e692732017-01-10 15:00:05 -0800418 }
419 }
420 return r.Run();
421}
422
Alex Light6ac57502017-01-19 15:05:06 -0800423jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800424 std::string original_dex_location;
425 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700426 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800427 *error_msg_ = "Unable to get original dex file location!";
428 return ret;
429 }
Alex Light52a2db52017-01-19 23:00:21 +0000430 char* generic_ptr_unused = nullptr;
431 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700432 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800433 *error_msg_ = "Unable to get class signature!";
434 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000435 }
Andreas Gampe54711412017-02-21 12:41:43 -0800436 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
437 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800438 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Lightb7354d52017-03-30 15:17:01 -0700439 def.GetDexData(),
Alex Light6ac57502017-01-19 15:05:06 -0800440 error_msg_));
441 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800442 if (map.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700443 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800444 << "in dex file " << original_dex_location << " because: " << *error_msg_;
445 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800446 return ERR(OUT_OF_MEMORY);
447 }
448 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800449 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800450 return ERR(INVALID_CLASS_FORMAT);
451 }
452 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800453 const art::ArtDexFileLoader dex_file_loader;
454 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(map->GetName(),
455 checksum,
456 std::move(map),
457 /*verify*/true,
458 /*verify_checksum*/true,
459 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800460 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700461 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800462 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800463 return ERR(INVALID_CLASS_FORMAT);
464 }
Alex Light0e692732017-01-10 15:00:05 -0800465 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800466 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700467 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800468 dex_file.release(),
469 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700470 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800471 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800472}
473
Alex Light0e692732017-01-10 15:00:05 -0800474art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
475 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800476}
477
Alex Light0e692732017-01-10 15:00:05 -0800478art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800479 return GetMirrorClass()->GetClassLoader();
480}
481
Alex Light0e692732017-01-10 15:00:05 -0800482art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
483 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700484 art::StackHandleScope<2> hs(driver_->self_);
485 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
486 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
487 art::ObjPtr<art::mirror::DexCache>::DownCast(
488 cl->GetClassRoot(art::ClassLinker::kJavaLangDexCache)->AllocObject(driver_->self_))));
489 if (cache.IsNull()) {
490 driver_->self_->AssertPendingOOMException();
491 return nullptr;
492 }
493 art::Handle<art::mirror::String> location(hs.NewHandle(
494 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
495 if (location.IsNull()) {
496 driver_->self_->AssertPendingOOMException();
497 return nullptr;
498 }
499 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
500 art::mirror::DexCache::InitializeDexCache(driver_->self_,
501 cache.Get(),
502 location.Get(),
503 dex_file_.get(),
504 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
505 : loader->GetAllocator(),
506 art::kRuntimePointerSize);
507 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800508}
509
Alex Light0e692732017-01-10 15:00:05 -0800510void Redefiner::RecordFailure(jvmtiError result,
511 const std::string& class_sig,
512 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800513 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800514 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800515 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800516 result_ = result;
517}
518
Alex Light2f814aa2017-03-24 15:21:34 +0000519art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800520 // If we have been specifically given a new set of bytes use that
521 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800522 return art::mirror::ByteArray::AllocateAndFill(
523 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100524 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Alex Light440b5d92017-01-24 15:32:25 -0800525 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800526 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800527
528 // See if we already have one set.
529 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
530 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000531 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
532 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800533 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000534 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800535 }
Alex Lighta01de592016-11-15 10:43:06 -0800536 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800537
Alex Light2f814aa2017-03-24 15:21:34 +0000538 // return the current dex_cache which has the dex file in it.
539 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800540 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000541 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800542 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
543 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800544 }
Alex Light2f814aa2017-03-24 15:21:34 +0000545 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800546}
547
Alex Lightdba61482016-12-21 08:20:29 -0800548struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000549 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800550 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800551 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800552
Alex Lighteee0bd42017-02-14 15:31:45 +0000553 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
554 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800555};
556
Alex Lightdba61482016-12-21 08:20:29 -0800557void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
558 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800559 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
560 data->allocator,
561 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000562 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800563}
564
565// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
566// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800567// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
568void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800569 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
570 art::mirror::ClassExt* ext = art_klass->GetExtData();
571 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800572 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000573 // This holds pointers to the obsolete methods map fields which are updated as needed.
574 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
575 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800576 // Add all the declared methods to the map
577 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800578 if (m.IsIntrinsic()) {
579 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
580 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
581 << "methods that have already been compiled.";
582 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000583 // It is possible to simply filter out some methods where they cannot really become obsolete,
584 // such as native methods and keep their original (possibly optimized) implementations. We don't
585 // do this, however, since we would need to mark these functions (still in the classes
586 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
587 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
588 // error checking from the interpreter which ensure we don't try to start executing obsolete
589 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000590 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800591 }
592 {
Alex Light0e692732017-01-10 15:00:05 -0800593 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800594 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
595 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800596 }
Alex Lightdba61482016-12-21 08:20:29 -0800597}
598
Alex Light6161f132017-01-25 10:30:20 -0800599// Try and get the declared method. First try to get a virtual method then a direct method if that's
600// not found.
601static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
Vladimir Markoba118822017-06-12 15:41:56 +0100602 art::StringPiece name,
Alex Light6161f132017-01-25 10:30:20 -0800603 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markoba118822017-06-12 15:41:56 +0100604 DCHECK(!klass->IsProxyClass());
605 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
606 if (m.GetName() == name && m.GetSignature() == sig) {
607 return &m;
608 }
Alex Light6161f132017-01-25 10:30:20 -0800609 }
Vladimir Markoba118822017-06-12 15:41:56 +0100610 return nullptr;
Alex Light6161f132017-01-25 10:30:20 -0800611}
612
613bool Redefiner::ClassRedefinition::CheckSameMethods() {
614 art::StackHandleScope<1> hs(driver_->self_);
615 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
616 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
617
618 art::ClassDataItemIterator new_iter(*dex_file_,
619 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
620
621 // Make sure we have the same number of methods.
622 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
623 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
624 if (num_new_method != num_old_method) {
625 bool bigger = num_new_method > num_old_method;
626 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
627 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
628 StringPrintf("Total number of declared methods changed from %d to %d",
629 num_old_method, num_new_method));
630 return false;
631 }
632
633 // Skip all of the fields. We should have already checked this.
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700634 new_iter.SkipAllFields();
Alex Light6161f132017-01-25 10:30:20 -0800635 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
636 // files have the same number of methods, which means there must be an equal amount of additions
637 // and removals.
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800638 for (; new_iter.HasNextMethod(); new_iter.Next()) {
Alex Light6161f132017-01-25 10:30:20 -0800639 // Get the data on the method we are searching for
640 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
641 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
642 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
643 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
644 // If we got past the check for the same number of methods above that means there must be at
645 // least one added and one removed method. We will return the ADDED failure message since it is
646 // easier to get a useful error report for it.
647 if (old_method == nullptr) {
648 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
649 StringPrintf("Unknown method '%s' (sig: %s) was added!",
650 new_method_name,
651 new_method_signature.ToString().c_str()));
652 return false;
653 }
654 // Since direct methods have different flags than virtual ones (specifically direct methods must
655 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
656 // virtual to direct.
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100657 uint32_t new_flags = new_iter.GetMethodAccessFlags();
658 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
Alex Light6161f132017-01-25 10:30:20 -0800659 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
660 StringPrintf("method '%s' (sig: %s) had different access flags",
661 new_method_name,
662 new_method_signature.ToString().c_str()));
663 return false;
664 }
665 }
666 return true;
667}
668
669bool Redefiner::ClassRedefinition::CheckSameFields() {
670 art::StackHandleScope<1> hs(driver_->self_);
671 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
672 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
673 art::ClassDataItemIterator new_iter(*dex_file_,
674 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
675 const art::DexFile& old_dex_file = h_klass->GetDexFile();
676 art::ClassDataItemIterator old_iter(old_dex_file,
677 old_dex_file.GetClassData(*h_klass->GetClassDef()));
678 // Instance and static fields can be differentiated by their flags so no need to check them
679 // separately.
680 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
681 // Get the data on the method we are searching for
682 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
683 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
684 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
685
686 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
687 // We are missing the old version of this method!
688 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
689 StringPrintf("Unknown field '%s' (type: %s) added!",
690 new_field_name,
691 new_field_type));
692 return false;
693 }
694
695 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
696 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
697 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
698
699 // Check name and type.
700 if (strcmp(old_field_name, new_field_name) != 0 ||
701 strcmp(old_field_type, new_field_type) != 0) {
702 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
703 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
704 old_field_name,
705 old_field_type,
706 new_field_name,
707 new_field_type));
708 return false;
709 }
710
711 // Since static fields have different flags than instance ones (specifically static fields must
712 // have the kAccStatic flag) we can tell if a field changes from static to instance.
713 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
714 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
715 StringPrintf("Field '%s' (sig: %s) had different access flags",
716 new_field_name,
717 new_field_type));
718 return false;
719 }
720
721 new_iter.Next();
722 old_iter.Next();
723 }
724 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
725 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
726 StringPrintf("field '%s' (sig: %s) is missing!",
727 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
728 old_iter.GetMemberIndex())),
729 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
730 old_iter.GetMemberIndex()))));
731 return false;
732 }
733 return true;
734}
735
Alex Light0e692732017-01-10 15:00:05 -0800736bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800737 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000738 // Easy check that only 1 class def is present.
739 if (dex_file_->NumClassDefs() != 1) {
740 RecordFailure(ERR(ILLEGAL_ARGUMENT),
741 StringPrintf("Expected 1 class def in dex file but found %d",
742 dex_file_->NumClassDefs()));
743 return false;
744 }
745 // Get the ClassDef from the new DexFile.
746 // Since the dex file has only a single class def the index is always 0.
747 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
748 // Get the class as it is now.
749 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
750
751 // Check the access flags didn't change.
752 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
753 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
754 "Cannot change modifiers of class by redefinition");
755 return false;
756 }
757
758 // Check class name.
759 // These should have been checked by the dexfile verifier on load.
760 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
761 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
762 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
763 if (!current_class->DescriptorEquals(descriptor)) {
764 std::string storage;
765 RecordFailure(ERR(NAMES_DONT_MATCH),
766 StringPrintf("expected file to contain class called '%s' but found '%s'!",
767 current_class->GetDescriptor(&storage),
768 descriptor));
769 return false;
770 }
771 if (current_class->IsObjectClass()) {
772 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
773 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
774 return false;
775 }
776 } else {
777 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
778 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
779 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
780 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
781 return false;
782 }
783 }
784 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
785 if (interfaces == nullptr) {
786 if (current_class->NumDirectInterfaces() != 0) {
787 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
788 return false;
789 }
790 } else {
791 DCHECK(!current_class->IsProxyClass());
792 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
793 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
794 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
795 return false;
796 }
797 // The order of interfaces is (barely) meaningful so we error if it changes.
798 const art::DexFile& orig_dex_file = current_class->GetDexFile();
799 for (uint32_t i = 0; i < interfaces->Size(); i++) {
800 if (strcmp(
801 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
802 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
803 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
804 "Interfaces changed or re-ordered");
805 return false;
806 }
807 }
808 }
Alex Light460d1b42017-01-10 15:37:17 +0000809 return true;
810}
811
Alex Light0e692732017-01-10 15:00:05 -0800812bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800813 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800814 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000815
Alex Lighte4a88632017-01-10 07:41:24 -0800816 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
817 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
818 if (res != OK) {
819 RecordFailure(res, err);
820 return false;
821 } else {
822 return true;
823 }
Alex Light460d1b42017-01-10 15:37:17 +0000824}
825
Alex Light0e692732017-01-10 15:00:05 -0800826bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000827 return CheckRedefinable() &&
828 CheckClass() &&
829 CheckSameFields() &&
830 CheckSameMethods();
831}
832
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800833class RedefinitionDataIter;
834
Alex Light0e692732017-01-10 15:00:05 -0800835// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
836// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
837// having to deal with the fact that we need to hold an arbitrary number of references live.
838class RedefinitionDataHolder {
839 public:
840 enum DataSlot : int32_t {
841 kSlotSourceClassLoader = 0,
842 kSlotJavaDexFile = 1,
843 kSlotNewDexFileCookie = 2,
844 kSlotNewDexCache = 3,
845 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800846 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700847 kSlotOldObsoleteMethods = 6,
848 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800849
850 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700851 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800852 };
853
854 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
855 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
856 // the passed in handle-scope.
857 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
858 art::Runtime* runtime,
859 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800860 std::vector<Redefiner::ClassRedefinition>* redefinitions)
861 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Alex Light0e692732017-01-10 15:00:05 -0800862 arr_(
863 hs->NewHandle(
864 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
865 self,
866 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800867 redefinitions->size() * kNumSlots))),
868 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800869
870 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
871 return arr_.IsNull();
872 }
873
Alex Light8c889d22017-02-06 13:58:27 -0800874 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800875 REQUIRES_SHARED(art::Locks::mutator_lock_) {
876 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
877 }
Alex Light8c889d22017-02-06 13:58:27 -0800878 art::mirror::Object* GetJavaDexFile(jint klass_index) const
879 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800880 return GetSlot(klass_index, kSlotJavaDexFile);
881 }
Alex Light8c889d22017-02-06 13:58:27 -0800882 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800883 REQUIRES_SHARED(art::Locks::mutator_lock_) {
884 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
885 }
Alex Light8c889d22017-02-06 13:58:27 -0800886 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800887 REQUIRES_SHARED(art::Locks::mutator_lock_) {
888 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
889 }
Alex Light8c889d22017-02-06 13:58:27 -0800890 art::mirror::Class* GetMirrorClass(jint klass_index) const
891 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800892 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
893 }
894
Alex Light2f814aa2017-03-24 15:21:34 +0000895 art::mirror::Object* GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800896 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +0000897 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800898 }
899
Alex Light1e3926a2017-04-07 10:38:06 -0700900 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const
901 REQUIRES_SHARED(art::Locks::mutator_lock_) {
902 return art::down_cast<art::mirror::PointerArray*>(
903 GetSlot(klass_index, kSlotOldObsoleteMethods));
904 }
905
906 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const
907 REQUIRES_SHARED(art::Locks::mutator_lock_) {
908 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>(
909 GetSlot(klass_index, kSlotOldDexCaches));
910 }
911
Alex Light0e692732017-01-10 15:00:05 -0800912 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
913 REQUIRES_SHARED(art::Locks::mutator_lock_) {
914 SetSlot(klass_index, kSlotSourceClassLoader, loader);
915 }
916 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
917 REQUIRES_SHARED(art::Locks::mutator_lock_) {
918 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
919 }
920 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
921 REQUIRES_SHARED(art::Locks::mutator_lock_) {
922 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
923 }
924 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
925 REQUIRES_SHARED(art::Locks::mutator_lock_) {
926 SetSlot(klass_index, kSlotNewDexCache, cache);
927 }
928 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
929 REQUIRES_SHARED(art::Locks::mutator_lock_) {
930 SetSlot(klass_index, kSlotMirrorClass, klass);
931 }
Alex Light2f814aa2017-03-24 15:21:34 +0000932 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800933 REQUIRES_SHARED(art::Locks::mutator_lock_) {
934 SetSlot(klass_index, kSlotOrigDexFile, bytes);
935 }
Alex Light1e3926a2017-04-07 10:38:06 -0700936 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods)
937 REQUIRES_SHARED(art::Locks::mutator_lock_) {
938 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
939 }
940 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches)
941 REQUIRES_SHARED(art::Locks::mutator_lock_) {
942 SetSlot(klass_index, kSlotOldDexCaches, caches);
943 }
Alex Light0e692732017-01-10 15:00:05 -0800944
Alex Light8c889d22017-02-06 13:58:27 -0800945 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800946 return arr_->GetLength() / kNumSlots;
947 }
948
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800949 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
950 REQUIRES_SHARED(art::Locks::mutator_lock_) {
951 return redefinitions_;
952 }
953
954 bool operator==(const RedefinitionDataHolder& other) const
955 REQUIRES_SHARED(art::Locks::mutator_lock_) {
956 return arr_.Get() == other.arr_.Get();
957 }
958
959 bool operator!=(const RedefinitionDataHolder& other) const
960 REQUIRES_SHARED(art::Locks::mutator_lock_) {
961 return !(*this == other);
962 }
963
964 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
965 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
966
Alex Light0e692732017-01-10 15:00:05 -0800967 private:
Alex Light8c889d22017-02-06 13:58:27 -0800968 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800969 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -0800970
971 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800972 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800973 DCHECK_LT(klass_index, Length());
974 return arr_->Get((kNumSlots * klass_index) + slot);
975 }
976
977 void SetSlot(jint klass_index,
978 DataSlot slot,
979 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
980 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
981 DCHECK_LT(klass_index, Length());
982 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
983 }
984
985 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
986};
987
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800988class RedefinitionDataIter {
989 public:
990 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
991
992 RedefinitionDataIter(const RedefinitionDataIter&) = default;
993 RedefinitionDataIter(RedefinitionDataIter&&) = default;
994 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
995 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
996
997 bool operator==(const RedefinitionDataIter& other) const
998 REQUIRES_SHARED(art::Locks::mutator_lock_) {
999 return idx_ == other.idx_ && holder_ == other.holder_;
1000 }
1001
1002 bool operator!=(const RedefinitionDataIter& other) const
1003 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1004 return !(*this == other);
1005 }
1006
1007 RedefinitionDataIter operator++() { // Value after modification.
1008 idx_++;
1009 return *this;
1010 }
1011
1012 RedefinitionDataIter operator++(int) {
1013 RedefinitionDataIter temp = *this;
1014 idx_++;
1015 return temp;
1016 }
1017
1018 RedefinitionDataIter operator+(ssize_t delta) const {
1019 RedefinitionDataIter temp = *this;
1020 temp += delta;
1021 return temp;
1022 }
1023
1024 RedefinitionDataIter& operator+=(ssize_t delta) {
1025 idx_ += delta;
1026 return *this;
1027 }
1028
1029 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1030 return (*holder_.GetRedefinitions())[idx_];
1031 }
1032
1033 RedefinitionDataHolder& GetHolder() {
1034 return holder_;
1035 }
1036
1037 art::mirror::ClassLoader* GetSourceClassLoader() const
1038 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1039 return holder_.GetSourceClassLoader(idx_);
1040 }
1041 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1042 return holder_.GetJavaDexFile(idx_);
1043 }
1044 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1045 return holder_.GetNewDexFileCookie(idx_);
1046 }
1047 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1048 return holder_.GetNewDexCache(idx_);
1049 }
1050 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1051 return holder_.GetMirrorClass(idx_);
1052 }
Alex Light2f814aa2017-03-24 15:21:34 +00001053 art::mirror::Object* GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001054 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001055 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001056 }
Alex Light1e3926a2017-04-07 10:38:06 -07001057 art::mirror::PointerArray* GetOldObsoleteMethods() const
1058 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1059 return holder_.GetOldObsoleteMethods(idx_);
1060 }
1061 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const
1062 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1063 return holder_.GetOldDexCaches(idx_);
1064 }
1065
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001066 int32_t GetIndex() const {
1067 return idx_;
1068 }
1069
1070 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1071 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1072 holder_.SetSourceClassLoader(idx_, loader);
1073 }
1074 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1075 holder_.SetJavaDexFile(idx_, dexfile);
1076 }
1077 void SetNewDexFileCookie(art::mirror::LongArray* cookie)
1078 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1079 holder_.SetNewDexFileCookie(idx_, cookie);
1080 }
1081 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1082 holder_.SetNewDexCache(idx_, cache);
1083 }
1084 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1085 holder_.SetMirrorClass(idx_, klass);
1086 }
Alex Light2f814aa2017-03-24 15:21:34 +00001087 void SetOriginalDexFile(art::mirror::Object* bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001088 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001089 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001090 }
Alex Light1e3926a2017-04-07 10:38:06 -07001091 void SetOldObsoleteMethods(art::mirror::PointerArray* methods)
1092 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1093 holder_.SetOldObsoleteMethods(idx_, methods);
1094 }
1095 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches)
1096 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1097 holder_.SetOldDexCaches(idx_, caches);
1098 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001099
1100 private:
1101 int32_t idx_;
1102 RedefinitionDataHolder& holder_;
1103};
1104
1105RedefinitionDataIter RedefinitionDataHolder::begin() {
1106 return RedefinitionDataIter(0, *this);
1107}
1108
1109RedefinitionDataIter RedefinitionDataHolder::end() {
1110 return RedefinitionDataIter(Length(), *this);
1111}
1112
1113bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001114 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1115 art::StackHandleScope<2> hs(driver_->self_);
1116 std::string error;
1117 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001118 art::verifier::FailureKind failure =
Alex Light8c889d22017-02-06 13:58:27 -08001119 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
1120 dex_file_.get(),
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001121 hs.NewHandle(iter.GetNewDexCache()),
Alex Light8c889d22017-02-06 13:58:27 -08001122 hs.NewHandle(GetClassLoader()),
1123 dex_file_->GetClassDef(0), /*class_def*/
1124 nullptr, /*compiler_callbacks*/
Alex Light53330612017-10-04 15:29:53 -07001125 true, /*allow_soft_failures*/
Alex Light8c889d22017-02-06 13:58:27 -08001126 /*log_level*/
1127 art::verifier::HardFailLogMode::kLogWarning,
1128 &error);
Alex Light53330612017-10-04 15:29:53 -07001129 switch (failure) {
1130 case art::verifier::FailureKind::kNoFailure:
1131 case art::verifier::FailureKind::kSoftFailure:
1132 return true;
1133 case art::verifier::FailureKind::kHardFailure: {
1134 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1135 return false;
1136 }
Alex Light8c889d22017-02-06 13:58:27 -08001137 }
Alex Light8c889d22017-02-06 13:58:27 -08001138}
1139
Alex Light1babae02017-02-01 15:35:34 -08001140// Looks through the previously allocated cookies to see if we need to update them with another new
1141// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1142// once they are all added to the classloader.
1143bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001144 art::Handle<art::mirror::ClassLoader> source_class_loader,
1145 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001146 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001147 art::StackHandleScope<2> hs(driver_->self_);
1148 art::MutableHandle<art::mirror::LongArray> old_cookie(
1149 hs.NewHandle<art::mirror::LongArray>(nullptr));
1150 bool has_older_cookie = false;
1151 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001152 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1153 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001154 // Since every instance of this classloader should have the same cookie associated with it we
1155 // can stop looking here.
1156 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001157 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001158 break;
1159 }
1160 }
1161 if (old_cookie.IsNull()) {
1162 // No older cookie. Get it directly from the dex_file_obj
1163 // We should not have seen this classloader elsewhere.
1164 CHECK(!has_older_cookie);
1165 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1166 }
1167 // Use the old cookie to generate the new one with the new DexFile* added in.
1168 art::Handle<art::mirror::LongArray>
1169 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1170 old_cookie,
1171 dex_file_.get())));
1172 // Make sure the allocation worked.
1173 if (new_cookie.IsNull()) {
1174 return false;
1175 }
1176
1177 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001178 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001179 // If there are other copies of this same classloader we need to make sure that we all have the
1180 // same cookie.
1181 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001182 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001183 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001184 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1185 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001186 }
1187 }
1188 }
1189
1190 return true;
1191}
1192
Alex Lighta7e38d82017-01-19 14:57:28 -08001193bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001194 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001195 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001196 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001197 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001198 // This shouldn't allocate
1199 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001200 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1201 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001202 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001203 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1204 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001205 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001206 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001207 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1208 return false;
1209 }
Alex Light1babae02017-02-01 15:35:34 -08001210 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001211 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001212 driver_->self_->AssertPendingOOMException();
1213 driver_->self_->ClearException();
1214 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1215 return false;
1216 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001217 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001218 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1219 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001220 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001221 driver_->self_->ClearException();
1222 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1223 return false;
1224 }
1225
1226 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001227 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1228 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001229 driver_->self_->AssertPendingOOMException();
1230 driver_->self_->ClearException();
1231 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1232 return false;
1233 }
1234 return true;
1235}
1236
Alex Lighta26e3492017-06-27 17:55:37 -07001237void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
1238 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass());
1239}
1240
Alex Light5643caf2017-02-08 11:39:07 -08001241void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
Alex Lighte34fe442018-02-21 17:35:55 -08001242 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1243 return;
1244 }
Alex Light5643caf2017-02-08 11:39:07 -08001245 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1246 if (state != nullptr) {
1247 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1248 }
1249}
1250
1251void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08001252 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1253 redef.UnregisterBreakpoints();
Alex Lighte34fe442018-02-21 17:35:55 -08001254 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08001255 }
1256}
1257
Alex Light0e692732017-01-10 15:00:05 -08001258bool Redefiner::CheckAllRedefinitionAreValid() {
1259 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1260 if (!redef.CheckRedefinitionIsValid()) {
1261 return false;
1262 }
1263 }
1264 return true;
1265}
1266
Alex Light1e3926a2017-04-07 10:38:06 -07001267void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1268 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1269 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1270 }
1271}
1272
1273bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1274 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1275 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001276 return false;
1277 }
1278 }
1279 return true;
1280}
1281
1282bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001283 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001284 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001285 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001286 return false;
1287 }
Alex Light0e692732017-01-10 15:00:05 -08001288 }
1289 return true;
1290}
1291
1292void Redefiner::ClassRedefinition::ReleaseDexFile() {
1293 dex_file_.release();
1294}
1295
1296void Redefiner::ReleaseAllDexFiles() {
1297 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1298 redef.ReleaseDexFile();
1299 }
1300}
1301
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001302bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1303 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1304 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001305 return false;
1306 }
Alex Light8c889d22017-02-06 13:58:27 -08001307 }
1308 return true;
1309}
1310
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001311class ScopedDisableConcurrentAndMovingGc {
1312 public:
1313 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1314 : heap_(heap), self_(self) {
1315 if (heap_->IsGcConcurrentAndMoving()) {
1316 heap_->IncrementDisableMovingGC(self_);
1317 }
1318 }
1319
1320 ~ScopedDisableConcurrentAndMovingGc() {
1321 if (heap_->IsGcConcurrentAndMoving()) {
1322 heap_->DecrementDisableMovingGC(self_);
1323 }
1324 }
1325 private:
1326 art::gc::Heap* heap_;
1327 art::Thread* self_;
1328};
1329
Alex Lighta01de592016-11-15 10:43:06 -08001330jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001331 art::StackHandleScope<1> hs(self_);
1332 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1333 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001334 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001335 if (holder.IsNull()) {
1336 self_->AssertPendingOOMException();
1337 self_->ClearException();
1338 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1339 return result_;
1340 }
1341
Alex Lighta01de592016-11-15 10:43:06 -08001342 // First we just allocate the ClassExt and its fields that we need. These can be updated
1343 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1344 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1345 // between allocating them and pausing all threads before we can update them so we need to do a
1346 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001347 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001348 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001349 !FinishAllRemainingAllocations(holder) ||
1350 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001351 return result_;
1352 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001353
Alex Light5643caf2017-02-08 11:39:07 -08001354 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001355 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001356 art::ClassLinker* cl = runtime_->GetClassLinker();
1357 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001358 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001359 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001360 }
Alex Light7916f202017-01-27 09:00:15 -08001361 }
Alex Light5643caf2017-02-08 11:39:07 -08001362 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001363
Alex Light6abd5392017-01-05 17:53:00 -08001364 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1365 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001366 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1367
Alex Lighta01de592016-11-15 10:43:06 -08001368 // Do transition to final suspension
1369 // TODO We might want to give this its own suspended state!
1370 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001371 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
1372 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true);
1373 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001374 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001375 ClassRedefinition& redef = data.GetRedefinition();
1376 if (data.GetSourceClassLoader() != nullptr) {
1377 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001378 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001379 art::mirror::Class* klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001380 // TODO Rewrite so we don't do a stack walk for each and every class.
1381 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001382 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001383 }
Alex Light1e3926a2017-04-07 10:38:06 -07001384 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001385 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1386 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1387 // methods that have been jitted prior to the current redefinition being applied might continue
1388 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001389 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1390 // owns the DexFile and when ownership is transferred.
1391 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001392 return OK;
1393}
1394
Alex Light0e692732017-01-10 15:00:05 -08001395void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Alex Light0e692732017-01-10 15:00:05 -08001396 const art::DexFile::ClassDef& class_def) {
1397 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001398 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001399 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001400 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001401 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07001402 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Alex Lighta01de592016-11-15 10:43:06 -08001403 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1404 art::dex::TypeIndex method_return_idx =
1405 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1406 const auto* old_type_list = method.GetParameterTypeList();
1407 std::vector<art::dex::TypeIndex> new_type_list;
1408 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1409 new_type_list.push_back(
1410 dex_file_->GetIndexForTypeId(
1411 *dex_file_->FindTypeId(
1412 old_dex_file.GetTypeDescriptor(
1413 old_dex_file.GetTypeId(
1414 old_type_list->GetTypeItem(i).type_idx_)))));
1415 }
1416 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1417 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001418 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001419 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1420 *new_name_id,
1421 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001422 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001423 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1424 method.SetDexMethodIndex(dex_method_idx);
1425 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001426 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Light7532d582017-02-13 16:36:06 -08001427 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01001428 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08001429 }
Alex Light200b9d72016-12-15 11:34:13 -08001430}
1431
Alex Light0e692732017-01-10 15:00:05 -08001432void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001433 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1434 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1435 for (art::ArtField& field : fields_iter) {
1436 std::string declaring_class_name;
1437 const art::DexFile::TypeId* new_declaring_id =
1438 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1439 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1440 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001441 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1442 const art::DexFile::FieldId* new_field_id =
1443 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1444 CHECK(new_field_id != nullptr);
1445 // We only need to update the index since the other data in the ArtField cannot be updated.
1446 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1447 }
1448 }
Alex Light200b9d72016-12-15 11:34:13 -08001449}
1450
1451// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001452void Redefiner::ClassRedefinition::UpdateClass(
1453 art::ObjPtr<art::mirror::Class> mclass,
1454 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001455 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001456 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1457 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001458 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001459 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001460
Alex Lighta01de592016-11-15 10:43:06 -08001461 // Update the class fields.
1462 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1463 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1464 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001465 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001466 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001467 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1468 CHECK(!ext.IsNull());
Alex Light2f814aa2017-03-24 15:21:34 +00001469 ext->SetOriginalDexFile(original_dex_file);
Alex Light18e14b52018-03-05 17:48:48 -08001470
1471 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1472 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1473 // meta-data.
1474 art::jit::Jit* jit = driver_->runtime_->GetJit();
1475 if (jit != nullptr) {
1476 art::PointerSize image_pointer_size =
1477 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1478 auto code_cache = jit->GetCodeCache();
1479 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1480 // the jit about them.
1481 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1482 if (method.IsInvokable()) {
1483 code_cache->NotifyMethodRedefined(&method);
1484 }
1485 }
1486 }
Alex Lighta01de592016-11-15 10:43:06 -08001487}
1488
Alex Light1e3926a2017-04-07 10:38:06 -07001489// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1490// obsolete methods).
1491void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1492 const RedefinitionDataIter* cur_data) {
1493 art::mirror::Class* klass = GetMirrorClass();
1494 art::mirror::ClassExt* ext = klass->GetExtData();
1495 art::mirror::PointerArray* methods = ext->GetObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001496 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods();
1497 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001498 int32_t expected_length =
1499 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1500 // Check to make sure we are only undoing this one.
1501 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001502 for (int32_t i = 0; i < expected_length; i++) {
1503 art::ArtMethod* expected = nullptr;
1504 if (i < old_length) {
1505 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1506 }
1507 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001508 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1509 // obsolete methods array.
1510 return;
1511 }
1512 }
1513 // No new obsolete methods! We can get rid of the maps.
1514 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1515 }
1516}
1517
Alex Lighta01de592016-11-15 10:43:06 -08001518// This function does all (java) allocations we need to do for the Class being redefined.
1519// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001520bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1521 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001522 art::StackHandleScope<2> hs(driver_->self_);
1523 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1524 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001525 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001526 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1527 return false;
1528 }
1529 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001530 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001531 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001532 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001533 driver_->self_->AssertPendingOOMException();
1534 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001535 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1536 return false;
1537 }
Alex Light1e3926a2017-04-07 10:38:06 -07001538 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1539 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001540 // are only modified when all threads (other than the modifying one) are suspended we don't need
1541 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1542 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001543 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1544 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1545 if (!ext->ExtendObsoleteArrays(
1546 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1547 // OOM. Clear exception and return error.
1548 driver_->self_->AssertPendingOOMException();
1549 driver_->self_->ClearException();
1550 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1551 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001552 }
1553 return true;
1554}
1555
1556} // namespace openjdkjvmti