blob: dcf999e8b6572d5ed186c1dfe6fc64d628899596 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light5643caf2017-02-08 11:39:07 -080041#include "debugger.h"
Alex Light460d1b42017-01-10 15:37:17 +000042#include "dex_file.h"
43#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080044#include "events-inl.h"
45#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080046#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080047#include "instrumentation.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "jdwp/jdwp.h"
49#include "jdwp/jdwp_constants.h"
50#include "jdwp/jdwp_event.h"
51#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080052#include "jit/jit.h"
53#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080054#include "jni_env_ext-inl.h"
55#include "jvmti_allocator.h"
Alex Light6161f132017-01-25 10:30:20 -080056#include "mirror/class-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080057#include "mirror/class_ext.h"
58#include "mirror/object.h"
59#include "object_lock.h"
60#include "runtime.h"
61#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080062#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080063#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080064#include "verifier/method_verifier.h"
65#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080066
67namespace openjdkjvmti {
68
Andreas Gampe46ee31b2016-12-14 10:11:49 -080069using android::base::StringPrintf;
70
Alex Lighteee0bd42017-02-14 15:31:45 +000071// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
72// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
73// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
74class ObsoleteMap {
75 public:
76 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
77 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
78 auto method_pair = id_map_.find(original);
79 if (method_pair != id_map_.end()) {
80 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
81 method_pair->second, art::kRuntimePointerSize);
82 DCHECK(res != nullptr);
83 DCHECK_EQ(original, res->GetNonObsoleteMethod());
84 return res;
85 } else {
86 return nullptr;
87 }
88 }
89
90 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
91 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
92 DCHECK(original != nullptr);
93 DCHECK(obsolete != nullptr);
94 int32_t slot = next_free_slot_++;
95 DCHECK_LT(slot, obsolete_methods_->GetLength());
96 DCHECK(nullptr ==
97 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
98 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
99 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
100 obsolete_dex_caches_->Set(slot, original_dex_cache_);
101 id_map_.insert({original, slot});
102 }
103
104 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
105 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
106 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
107 : next_free_slot_(0),
108 obsolete_methods_(obsolete_methods),
109 obsolete_dex_caches_(obsolete_dex_caches),
110 original_dex_cache_(original_dex_cache) {
111 // Figure out where the first unused slot in the obsolete_methods_ array is.
112 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
113 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
114 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
115 next_free_slot_++;
116 }
117 // Sanity check that the same slot in obsolete_dex_caches_ is free.
118 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
119 }
120
121 private:
122 int32_t next_free_slot_;
123 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
124 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
125 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
126 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
127 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
128 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
129};
130
Alex Lightdba61482016-12-21 08:20:29 -0800131// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
132// some basic sanity checks that the obsolete method is sane.
133class ObsoleteMethodStackVisitor : public art::StackVisitor {
134 protected:
135 ObsoleteMethodStackVisitor(
136 art::Thread* thread,
137 art::LinearAlloc* allocator,
138 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000139 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800140 : StackVisitor(thread,
141 /*context*/nullptr,
142 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
143 allocator_(allocator),
144 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800145 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800146
147 ~ObsoleteMethodStackVisitor() OVERRIDE {}
148
149 public:
150 // Returns true if we successfully installed obsolete methods on this thread, filling
151 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
152 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800153 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800154 art::Thread* thread,
155 art::LinearAlloc* allocator,
156 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000157 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800158 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800159 ObsoleteMethodStackVisitor visitor(thread,
160 allocator,
161 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800162 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800163 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800164 }
165
166 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000167 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800168 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800169 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800170 // We cannot ensure that the right dex file is used in inlined frames so we don't support
171 // redefining them.
172 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
173 // TODO We should really support intrinsic obsolete methods.
174 // TODO We should really support redefining intrinsics.
175 // We don't support intrinsics so check for them here.
176 DCHECK(!old_method->IsIntrinsic());
Alex Lighteee0bd42017-02-14 15:31:45 +0000177 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
178 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800179 // Create a new Obsolete Method and put it in the list.
180 art::Runtime* runtime = art::Runtime::Current();
181 art::ClassLinker* cl = runtime->GetClassLinker();
182 auto ptr_size = cl->GetImagePointerSize();
183 const size_t method_size = art::ArtMethod::Size(ptr_size);
184 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800185 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
186 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800187 new_obsolete_method = new (method_storage) art::ArtMethod();
188 new_obsolete_method->CopyFrom(old_method, ptr_size);
189 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
190 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800191 new_obsolete_method->SetDontCompile();
Alex Lighteee0bd42017-02-14 15:31:45 +0000192 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800193 // Update JIT Data structures to point to the new method.
194 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
195 if (jit != nullptr) {
196 // Notify the JIT we are making this obsolete method. It will update the jit's internal
197 // structures to keep track of the new obsolete method.
198 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
199 }
Alex Lightdba61482016-12-21 08:20:29 -0800200 }
201 DCHECK(new_obsolete_method != nullptr);
202 SetMethod(new_obsolete_method);
203 }
204 return true;
205 }
206
207 private:
208 // The linear allocator we should use to make new methods.
209 art::LinearAlloc* allocator_;
210 // The set of all methods which could be obsoleted.
211 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
212 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000213 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
214 // the redefined classes ClassExt as it is filled.
215 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800216};
217
Alex Lighte4a88632017-01-10 07:41:24 -0800218jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
219 jclass klass,
220 jboolean* is_redefinable) {
221 // TODO Check for the appropriate feature flags once we have enabled them.
222 art::Thread* self = art::Thread::Current();
223 art::ScopedObjectAccess soa(self);
224 art::StackHandleScope<1> hs(self);
225 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
226 if (obj.IsNull()) {
227 return ERR(INVALID_CLASS);
228 }
229 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
230 std::string err_unused;
231 *is_redefinable =
232 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
233 return OK;
234}
235
236jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
237 /*out*/std::string* error_msg) {
238 if (klass->IsPrimitive()) {
239 *error_msg = "Modification of primitive classes is not supported";
240 return ERR(UNMODIFIABLE_CLASS);
241 } else if (klass->IsInterface()) {
242 *error_msg = "Modification of Interface classes is currently not supported";
243 return ERR(UNMODIFIABLE_CLASS);
244 } else if (klass->IsArrayClass()) {
245 *error_msg = "Modification of Array classes is not supported";
246 return ERR(UNMODIFIABLE_CLASS);
247 } else if (klass->IsProxyClass()) {
248 *error_msg = "Modification of proxy classes is not supported";
249 return ERR(UNMODIFIABLE_CLASS);
250 }
251
252 // TODO We should check if the class has non-obsoletable methods on the stack
253 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
254 return OK;
255}
256
Alex Lighta01de592016-11-15 10:43:06 -0800257// Moves dex data to an anonymous, read-only mmap'd region.
258std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
259 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800260 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800261 std::string* error_msg) {
262 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800263 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800264 nullptr,
265 data_len,
266 PROT_READ|PROT_WRITE,
267 /*low_4gb*/false,
268 /*reuse*/false,
269 error_msg));
270 if (map == nullptr) {
271 return map;
272 }
273 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800274 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
275 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800276 map->Protect(PROT_READ);
277 return map;
278}
279
Alex Lighta7e38d82017-01-19 14:57:28 -0800280Redefiner::ClassRedefinition::ClassRedefinition(
281 Redefiner* driver,
282 jclass klass,
283 const art::DexFile* redefined_dex_file,
284 const char* class_sig,
285 art::ArraySlice<const unsigned char> orig_dex_file) :
286 driver_(driver),
287 klass_(klass),
288 dex_file_(redefined_dex_file),
289 class_sig_(class_sig),
290 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800291 GetMirrorClass()->MonitorEnter(driver_->self_);
292}
293
294Redefiner::ClassRedefinition::~ClassRedefinition() {
295 if (driver_ != nullptr) {
296 GetMirrorClass()->MonitorExit(driver_->self_);
297 }
298}
299
Alex Light0e692732017-01-10 15:00:05 -0800300jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
301 art::Runtime* runtime,
302 art::Thread* self,
303 jint class_count,
304 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800305 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800306 if (env == nullptr) {
307 *error_msg = "env was null!";
308 return ERR(INVALID_ENVIRONMENT);
309 } else if (class_count < 0) {
310 *error_msg = "class_count was less then 0";
311 return ERR(ILLEGAL_ARGUMENT);
312 } else if (class_count == 0) {
313 // We don't actually need to do anything. Just return OK.
314 return OK;
315 } else if (definitions == nullptr) {
316 *error_msg = "null definitions!";
317 return ERR(NULL_POINTER);
318 }
Alex Light6ac57502017-01-19 15:05:06 -0800319 std::vector<ArtClassDefinition> def_vector;
320 def_vector.reserve(class_count);
321 for (jint i = 0; i < class_count; i++) {
322 // We make a copy of the class_bytes to pass into the retransformation.
323 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
324 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
325 // to get the passed in bytes.
326 // TODO Implement saving the original bytes.
327 unsigned char* class_bytes_copy = nullptr;
328 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
329 if (res != OK) {
330 return res;
331 }
332 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
333
334 ArtClassDefinition def;
335 def.dex_len = definitions[i].class_byte_count;
336 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
337 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800338 def.SetModified();
339 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
340 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800341 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
342 if (res != OK) {
343 return res;
344 }
345 def_vector.push_back(std::move(def));
346 }
347 // Call all the transformation events.
348 jvmtiError res = Transformer::RetransformClassesDirect(env,
349 self,
350 &def_vector);
351 if (res != OK) {
352 // Something went wrong with transformation!
353 return res;
354 }
355 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
356}
357
358jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
359 art::Runtime* runtime,
360 art::Thread* self,
361 const std::vector<ArtClassDefinition>& definitions,
362 std::string* error_msg) {
363 DCHECK(env != nullptr);
364 if (definitions.size() == 0) {
365 // We don't actually need to do anything. Just return OK.
366 return OK;
367 }
Alex Light0e692732017-01-10 15:00:05 -0800368 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
369 // are going to redefine.
370 art::jit::ScopedJitSuspend suspend_jit;
371 // Get shared mutator lock so we can lock all the classes.
372 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800373 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800374 for (const ArtClassDefinition& def : definitions) {
375 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800376 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800377 jvmtiError res = r.AddRedefinition(env, def);
378 if (res != OK) {
379 return res;
380 }
Alex Light0e692732017-01-10 15:00:05 -0800381 }
382 }
383 return r.Run();
384}
385
Alex Light6ac57502017-01-19 15:05:06 -0800386jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800387 std::string original_dex_location;
388 jvmtiError ret = OK;
389 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
390 *error_msg_ = "Unable to get original dex file location!";
391 return ret;
392 }
Alex Light52a2db52017-01-19 23:00:21 +0000393 char* generic_ptr_unused = nullptr;
394 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800395 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
396 *error_msg_ = "Unable to get class signature!";
397 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000398 }
Andreas Gampe54711412017-02-21 12:41:43 -0800399 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
400 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800401 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
402 def.dex_len,
403 def.dex_data.get(),
404 error_msg_));
405 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800406 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800407 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800408 << "in dex file " << original_dex_location << " because: " << *error_msg_;
409 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800410 return ERR(OUT_OF_MEMORY);
411 }
412 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800413 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800414 return ERR(INVALID_CLASS_FORMAT);
415 }
416 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
417 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
418 checksum,
419 std::move(map),
420 /*verify*/true,
421 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800422 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800423 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800424 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800425 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800426 return ERR(INVALID_CLASS_FORMAT);
427 }
Alex Light0e692732017-01-10 15:00:05 -0800428 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800429 Redefiner::ClassRedefinition(this,
430 def.klass,
431 dex_file.release(),
432 signature_ptr,
433 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800434 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800435}
436
Alex Light0e692732017-01-10 15:00:05 -0800437art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
438 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800439}
440
Alex Light0e692732017-01-10 15:00:05 -0800441art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800442 return GetMirrorClass()->GetClassLoader();
443}
444
Alex Light0e692732017-01-10 15:00:05 -0800445art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
446 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000447 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800448}
449
Alex Light0e692732017-01-10 15:00:05 -0800450void Redefiner::RecordFailure(jvmtiError result,
451 const std::string& class_sig,
452 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800453 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800454 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800455 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800456 result_ = result;
457}
458
Alex Lighta7e38d82017-01-19 14:57:28 -0800459art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
460 // If we have been specifically given a new set of bytes use that
461 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800462 return art::mirror::ByteArray::AllocateAndFill(
463 driver_->self_,
464 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
465 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800466 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800467
468 // See if we already have one set.
469 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
470 if (!ext.IsNull()) {
471 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
472 if (!old_original_bytes.IsNull()) {
473 // We do. Use it.
474 return old_original_bytes.Ptr();
475 }
Alex Lighta01de592016-11-15 10:43:06 -0800476 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800477
478 // Copy the current dex_file
479 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
480 // TODO Handle this or make it so it cannot happen.
481 if (current_dex_file.NumClassDefs() != 1) {
482 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
483 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800484 }
Alex Light440b5d92017-01-24 15:32:25 -0800485 return art::mirror::ByteArray::AllocateAndFill(
486 driver_->self_,
487 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
488 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800489}
490
Alex Lightdba61482016-12-21 08:20:29 -0800491struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000492 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800493 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800494 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800495
Alex Lighteee0bd42017-02-14 15:31:45 +0000496 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
497 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800498};
499
Alex Lightdba61482016-12-21 08:20:29 -0800500void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
501 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800502 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
503 data->allocator,
504 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000505 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800506}
507
508// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
509// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800510// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
511void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800512 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
513 art::mirror::ClassExt* ext = art_klass->GetExtData();
514 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800515 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000516 // This holds pointers to the obsolete methods map fields which are updated as needed.
517 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
518 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800519 // Add all the declared methods to the map
520 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000521 // It is possible to simply filter out some methods where they cannot really become obsolete,
522 // such as native methods and keep their original (possibly optimized) implementations. We don't
523 // do this, however, since we would need to mark these functions (still in the classes
524 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
525 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
526 // error checking from the interpreter which ensure we don't try to start executing obsolete
527 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000528 ctx.obsolete_methods.insert(&m);
529 // TODO Allow this or check in IsModifiableClass.
530 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800531 }
532 {
Alex Light0e692732017-01-10 15:00:05 -0800533 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800534 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
535 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800536 }
Alex Lightdba61482016-12-21 08:20:29 -0800537}
538
Alex Light6161f132017-01-25 10:30:20 -0800539// Try and get the declared method. First try to get a virtual method then a direct method if that's
540// not found.
541static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
542 const char* name,
543 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
544 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
545 if (m == nullptr) {
546 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
547 }
548 return m;
549}
550
551bool Redefiner::ClassRedefinition::CheckSameMethods() {
552 art::StackHandleScope<1> hs(driver_->self_);
553 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
554 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
555
556 art::ClassDataItemIterator new_iter(*dex_file_,
557 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
558
559 // Make sure we have the same number of methods.
560 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
561 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
562 if (num_new_method != num_old_method) {
563 bool bigger = num_new_method > num_old_method;
564 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
565 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
566 StringPrintf("Total number of declared methods changed from %d to %d",
567 num_old_method, num_new_method));
568 return false;
569 }
570
571 // Skip all of the fields. We should have already checked this.
572 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
573 new_iter.Next();
574 }
575 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
576 // files have the same number of methods, which means there must be an equal amount of additions
577 // and removals.
578 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
579 // Get the data on the method we are searching for
580 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
581 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
582 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
583 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
584 // If we got past the check for the same number of methods above that means there must be at
585 // least one added and one removed method. We will return the ADDED failure message since it is
586 // easier to get a useful error report for it.
587 if (old_method == nullptr) {
588 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
589 StringPrintf("Unknown method '%s' (sig: %s) was added!",
590 new_method_name,
591 new_method_signature.ToString().c_str()));
592 return false;
593 }
594 // Since direct methods have different flags than virtual ones (specifically direct methods must
595 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
596 // virtual to direct.
597 uint32_t new_flags = new_iter.GetMethodAccessFlags();
598 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
599 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
600 StringPrintf("method '%s' (sig: %s) had different access flags",
601 new_method_name,
602 new_method_signature.ToString().c_str()));
603 return false;
604 }
605 }
606 return true;
607}
608
609bool Redefiner::ClassRedefinition::CheckSameFields() {
610 art::StackHandleScope<1> hs(driver_->self_);
611 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
612 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
613 art::ClassDataItemIterator new_iter(*dex_file_,
614 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
615 const art::DexFile& old_dex_file = h_klass->GetDexFile();
616 art::ClassDataItemIterator old_iter(old_dex_file,
617 old_dex_file.GetClassData(*h_klass->GetClassDef()));
618 // Instance and static fields can be differentiated by their flags so no need to check them
619 // separately.
620 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
621 // Get the data on the method we are searching for
622 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
623 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
624 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
625
626 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
627 // We are missing the old version of this method!
628 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
629 StringPrintf("Unknown field '%s' (type: %s) added!",
630 new_field_name,
631 new_field_type));
632 return false;
633 }
634
635 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
636 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
637 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
638
639 // Check name and type.
640 if (strcmp(old_field_name, new_field_name) != 0 ||
641 strcmp(old_field_type, new_field_type) != 0) {
642 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
643 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
644 old_field_name,
645 old_field_type,
646 new_field_name,
647 new_field_type));
648 return false;
649 }
650
651 // Since static fields have different flags than instance ones (specifically static fields must
652 // have the kAccStatic flag) we can tell if a field changes from static to instance.
653 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
654 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
655 StringPrintf("Field '%s' (sig: %s) had different access flags",
656 new_field_name,
657 new_field_type));
658 return false;
659 }
660
661 new_iter.Next();
662 old_iter.Next();
663 }
664 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
665 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
666 StringPrintf("field '%s' (sig: %s) is missing!",
667 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
668 old_iter.GetMemberIndex())),
669 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
670 old_iter.GetMemberIndex()))));
671 return false;
672 }
673 return true;
674}
675
Alex Light0e692732017-01-10 15:00:05 -0800676bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000677 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800678 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000679 // Easy check that only 1 class def is present.
680 if (dex_file_->NumClassDefs() != 1) {
681 RecordFailure(ERR(ILLEGAL_ARGUMENT),
682 StringPrintf("Expected 1 class def in dex file but found %d",
683 dex_file_->NumClassDefs()));
684 return false;
685 }
686 // Get the ClassDef from the new DexFile.
687 // Since the dex file has only a single class def the index is always 0.
688 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
689 // Get the class as it is now.
690 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
691
692 // Check the access flags didn't change.
693 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
694 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
695 "Cannot change modifiers of class by redefinition");
696 return false;
697 }
698
699 // Check class name.
700 // These should have been checked by the dexfile verifier on load.
701 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
702 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
703 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
704 if (!current_class->DescriptorEquals(descriptor)) {
705 std::string storage;
706 RecordFailure(ERR(NAMES_DONT_MATCH),
707 StringPrintf("expected file to contain class called '%s' but found '%s'!",
708 current_class->GetDescriptor(&storage),
709 descriptor));
710 return false;
711 }
712 if (current_class->IsObjectClass()) {
713 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
714 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
715 return false;
716 }
717 } else {
718 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
719 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
720 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
721 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
722 return false;
723 }
724 }
725 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
726 if (interfaces == nullptr) {
727 if (current_class->NumDirectInterfaces() != 0) {
728 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
729 return false;
730 }
731 } else {
732 DCHECK(!current_class->IsProxyClass());
733 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
734 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
735 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
736 return false;
737 }
738 // The order of interfaces is (barely) meaningful so we error if it changes.
739 const art::DexFile& orig_dex_file = current_class->GetDexFile();
740 for (uint32_t i = 0; i < interfaces->Size(); i++) {
741 if (strcmp(
742 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
743 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
744 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
745 "Interfaces changed or re-ordered");
746 return false;
747 }
748 }
749 }
Alex Light460d1b42017-01-10 15:37:17 +0000750 return true;
751}
752
753// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800754bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800755 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800756 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000757
Alex Lighte4a88632017-01-10 07:41:24 -0800758 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
759 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
760 if (res != OK) {
761 RecordFailure(res, err);
762 return false;
763 } else {
764 return true;
765 }
Alex Light460d1b42017-01-10 15:37:17 +0000766}
767
Alex Light0e692732017-01-10 15:00:05 -0800768bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000769 return CheckRedefinable() &&
770 CheckClass() &&
771 CheckSameFields() &&
772 CheckSameMethods();
773}
774
Alex Light0e692732017-01-10 15:00:05 -0800775// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
776// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
777// having to deal with the fact that we need to hold an arbitrary number of references live.
778class RedefinitionDataHolder {
779 public:
780 enum DataSlot : int32_t {
781 kSlotSourceClassLoader = 0,
782 kSlotJavaDexFile = 1,
783 kSlotNewDexFileCookie = 2,
784 kSlotNewDexCache = 3,
785 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800786 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800787
788 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800789 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800790 };
791
792 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
793 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
794 // the passed in handle-scope.
795 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
796 art::Runtime* runtime,
797 art::Thread* self,
798 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
799 arr_(
800 hs->NewHandle(
801 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
802 self,
803 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
804 num_redefinitions * kNumSlots))) {}
805
806 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
807 return arr_.IsNull();
808 }
809
810 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800811 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800812 REQUIRES_SHARED(art::Locks::mutator_lock_) {
813 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
814 }
Alex Light8c889d22017-02-06 13:58:27 -0800815 art::mirror::Object* GetJavaDexFile(jint klass_index) const
816 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800817 return GetSlot(klass_index, kSlotJavaDexFile);
818 }
Alex Light8c889d22017-02-06 13:58:27 -0800819 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800820 REQUIRES_SHARED(art::Locks::mutator_lock_) {
821 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
822 }
Alex Light8c889d22017-02-06 13:58:27 -0800823 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800824 REQUIRES_SHARED(art::Locks::mutator_lock_) {
825 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
826 }
Alex Light8c889d22017-02-06 13:58:27 -0800827 art::mirror::Class* GetMirrorClass(jint klass_index) const
828 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800829 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
830 }
831
Alex Light8c889d22017-02-06 13:58:27 -0800832 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800833 REQUIRES_SHARED(art::Locks::mutator_lock_) {
834 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
835 }
836
Alex Light0e692732017-01-10 15:00:05 -0800837 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
838 REQUIRES_SHARED(art::Locks::mutator_lock_) {
839 SetSlot(klass_index, kSlotSourceClassLoader, loader);
840 }
841 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
842 REQUIRES_SHARED(art::Locks::mutator_lock_) {
843 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
844 }
845 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
846 REQUIRES_SHARED(art::Locks::mutator_lock_) {
847 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
848 }
849 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
850 REQUIRES_SHARED(art::Locks::mutator_lock_) {
851 SetSlot(klass_index, kSlotNewDexCache, cache);
852 }
853 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
854 REQUIRES_SHARED(art::Locks::mutator_lock_) {
855 SetSlot(klass_index, kSlotMirrorClass, klass);
856 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800857 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
858 REQUIRES_SHARED(art::Locks::mutator_lock_) {
859 SetSlot(klass_index, kSlotOrigDexFile, bytes);
860 }
Alex Light0e692732017-01-10 15:00:05 -0800861
Alex Light8c889d22017-02-06 13:58:27 -0800862 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800863 return arr_->GetLength() / kNumSlots;
864 }
865
866 private:
Alex Light8c889d22017-02-06 13:58:27 -0800867 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Light0e692732017-01-10 15:00:05 -0800868
869 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800870 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800871 DCHECK_LT(klass_index, Length());
872 return arr_->Get((kNumSlots * klass_index) + slot);
873 }
874
875 void SetSlot(jint klass_index,
876 DataSlot slot,
877 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
878 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
879 DCHECK_LT(klass_index, Length());
880 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
881 }
882
883 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
884};
885
Alex Light8c889d22017-02-06 13:58:27 -0800886// TODO Stash and update soft failure state
887bool Redefiner::ClassRedefinition::CheckVerification(int32_t klass_index,
888 const RedefinitionDataHolder& holder) {
889 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
890 art::StackHandleScope<2> hs(driver_->self_);
891 std::string error;
892 // TODO Make verification log level lower
893 art::verifier::MethodVerifier::FailureKind failure =
894 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
895 dex_file_.get(),
896 hs.NewHandle(holder.GetNewDexCache(klass_index)),
897 hs.NewHandle(GetClassLoader()),
898 dex_file_->GetClassDef(0), /*class_def*/
899 nullptr, /*compiler_callbacks*/
900 false, /*allow_soft_failures*/
901 /*log_level*/
902 art::verifier::HardFailLogMode::kLogWarning,
903 &error);
904 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
905 if (!passes) {
906 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
907 }
908 return passes;
909}
910
Alex Light1babae02017-02-01 15:35:34 -0800911// Looks through the previously allocated cookies to see if we need to update them with another new
912// dexfile. This is so that even if multiple classes with the same classloader are redefined at
913// once they are all added to the classloader.
914bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
915 int32_t klass_index,
916 art::Handle<art::mirror::ClassLoader> source_class_loader,
917 art::Handle<art::mirror::Object> dex_file_obj,
918 /*out*/RedefinitionDataHolder* holder) {
919 art::StackHandleScope<2> hs(driver_->self_);
920 art::MutableHandle<art::mirror::LongArray> old_cookie(
921 hs.NewHandle<art::mirror::LongArray>(nullptr));
922 bool has_older_cookie = false;
923 // See if we already have a cookie that a previous redefinition got from the same classloader.
924 for (int32_t i = 0; i < klass_index; i++) {
925 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
926 // Since every instance of this classloader should have the same cookie associated with it we
927 // can stop looking here.
928 has_older_cookie = true;
929 old_cookie.Assign(holder->GetNewDexFileCookie(i));
930 break;
931 }
932 }
933 if (old_cookie.IsNull()) {
934 // No older cookie. Get it directly from the dex_file_obj
935 // We should not have seen this classloader elsewhere.
936 CHECK(!has_older_cookie);
937 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
938 }
939 // Use the old cookie to generate the new one with the new DexFile* added in.
940 art::Handle<art::mirror::LongArray>
941 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
942 old_cookie,
943 dex_file_.get())));
944 // Make sure the allocation worked.
945 if (new_cookie.IsNull()) {
946 return false;
947 }
948
949 // Save the cookie.
950 holder->SetNewDexFileCookie(klass_index, new_cookie.Get());
951 // If there are other copies of this same classloader we need to make sure that we all have the
952 // same cookie.
953 if (has_older_cookie) {
954 for (int32_t i = 0; i < klass_index; i++) {
955 // We will let the GC take care of the cookie we allocated for this one.
956 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
957 holder->SetNewDexFileCookie(i, new_cookie.Get());
958 }
959 }
960 }
961
962 return true;
963}
964
Alex Lighta7e38d82017-01-19 14:57:28 -0800965bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
966 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800967 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800968 art::StackHandleScope<2> hs(driver_->self_);
969 holder->SetMirrorClass(klass_index, GetMirrorClass());
970 // This shouldn't allocate
971 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800972 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
973 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
974 holder->SetSourceClassLoader(klass_index, loader.Get());
975 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
976 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
977 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -0800978 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -0800979 // TODO Better error msg.
980 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
981 return false;
982 }
Alex Light1babae02017-02-01 15:35:34 -0800983 // Allocate the new dex file cookie.
984 if (!AllocateAndRememberNewDexFileCookie(klass_index, loader, dex_file_obj, holder)) {
Alex Light7916f202017-01-27 09:00:15 -0800985 driver_->self_->AssertPendingOOMException();
986 driver_->self_->ClearException();
987 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
988 return false;
989 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800990 }
991 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
992 if (holder->GetNewDexCache(klass_index) == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000993 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -0800994 driver_->self_->ClearException();
995 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
996 return false;
997 }
998
999 // We won't always need to set this field.
1000 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
1001 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
1002 driver_->self_->AssertPendingOOMException();
1003 driver_->self_->ClearException();
1004 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1005 return false;
1006 }
1007 return true;
1008}
1009
Alex Light5643caf2017-02-08 11:39:07 -08001010void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1011 DCHECK(art::Dbg::IsDebuggerActive());
1012 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1013 if (state != nullptr) {
1014 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1015 }
1016}
1017
1018void Redefiner::UnregisterAllBreakpoints() {
1019 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1020 return;
1021 }
1022 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1023 redef.UnregisterBreakpoints();
1024 }
1025}
1026
Alex Light0e692732017-01-10 15:00:05 -08001027bool Redefiner::CheckAllRedefinitionAreValid() {
1028 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1029 if (!redef.CheckRedefinitionIsValid()) {
1030 return false;
1031 }
1032 }
1033 return true;
1034}
1035
1036bool Redefiner::EnsureAllClassAllocationsFinished() {
1037 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1038 if (!redef.EnsureClassAllocationsFinished()) {
1039 return false;
1040 }
1041 }
1042 return true;
1043}
1044
1045bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
1046 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -08001047 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -08001048 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -08001049 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -08001050 return false;
1051 }
Alex Light0e692732017-01-10 15:00:05 -08001052 cnt++;
1053 }
1054 return true;
1055}
1056
1057void Redefiner::ClassRedefinition::ReleaseDexFile() {
1058 dex_file_.release();
1059}
1060
1061void Redefiner::ReleaseAllDexFiles() {
1062 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1063 redef.ReleaseDexFile();
1064 }
1065}
1066
Alex Light8c889d22017-02-06 13:58:27 -08001067bool Redefiner::CheckAllClassesAreVerified(const RedefinitionDataHolder& holder) {
1068 int32_t cnt = 0;
1069 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1070 if (!redef.CheckVerification(cnt, holder)) {
1071 return false;
1072 }
1073 cnt++;
1074 }
1075 return true;
1076}
1077
Alex Lighta01de592016-11-15 10:43:06 -08001078jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001079 art::StackHandleScope<1> hs(self_);
1080 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1081 // We will let this be collected after the end of this function.
1082 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
1083 if (holder.IsNull()) {
1084 self_->AssertPendingOOMException();
1085 self_->ClearException();
1086 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1087 return result_;
1088 }
1089
Alex Lighta01de592016-11-15 10:43:06 -08001090 // First we just allocate the ClassExt and its fields that we need. These can be updated
1091 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1092 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1093 // between allocating them and pausing all threads before we can update them so we need to do a
1094 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001095 if (!CheckAllRedefinitionAreValid() ||
1096 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001097 !FinishAllRemainingAllocations(holder) ||
1098 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001099 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1100 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001101 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1102 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001103 return result_;
1104 }
Alex Light5643caf2017-02-08 11:39:07 -08001105 // At this point we can no longer fail without corrupting the runtime state.
Alex Light7916f202017-01-27 09:00:15 -08001106 int32_t counter = 0;
1107 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1108 if (holder.GetSourceClassLoader(counter) == nullptr) {
1109 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
1110 }
1111 counter++;
1112 }
Alex Light5643caf2017-02-08 11:39:07 -08001113 UnregisterAllBreakpoints();
Alex Light6abd5392017-01-05 17:53:00 -08001114 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1115 // allocating so no deadlocks.
1116 art::gc::Heap* heap = runtime_->GetHeap();
1117 if (heap->IsGcConcurrentAndMoving()) {
1118 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
1119 heap->IncrementDisableMovingGC(self_);
1120 }
Alex Lighta01de592016-11-15 10:43:06 -08001121 // Do transition to final suspension
1122 // TODO We might want to give this its own suspended state!
1123 // TODO This isn't right. We need to change state without any chance of suspend ideally!
1124 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
1125 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -08001126 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -08001127 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
1128 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
1129 // TODO We need to update all debugger MethodIDs so they note the method they point to is
1130 // obsolete or implement some other well defined semantics.
1131 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light7916f202017-01-27 09:00:15 -08001132 counter = 0;
Alex Light0e692732017-01-10 15:00:05 -08001133 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighteb98b082017-01-25 13:02:32 -08001134 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Light7916f202017-01-27 09:00:15 -08001135 if (holder.GetSourceClassLoader(counter) != nullptr) {
1136 ClassLoaderHelper::UpdateJavaDexFile(holder.GetJavaDexFile(counter),
1137 holder.GetNewDexFileCookie(counter));
1138 }
1139 art::mirror::Class* klass = holder.GetMirrorClass(counter);
Alex Light0e692732017-01-10 15:00:05 -08001140 // TODO Rewrite so we don't do a stack walk for each and every class.
1141 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light7916f202017-01-27 09:00:15 -08001142 redef.UpdateClass(klass, holder.GetNewDexCache(counter),
1143 holder.GetOriginalDexFileBytes(counter));
1144 counter++;
Alex Light0e692732017-01-10 15:00:05 -08001145 }
Alex Lightdba61482016-12-21 08:20:29 -08001146 // TODO Shrink the obsolete method maps if possible?
Alex Lighta01de592016-11-15 10:43:06 -08001147 // TODO Put this into a scoped thing.
1148 runtime_->GetThreadList()->ResumeAll();
1149 // Get back shared mutator lock as expected for return.
1150 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -08001151 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1152 // owns the DexFile and when ownership is transferred.
1153 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001154 if (heap->IsGcConcurrentAndMoving()) {
1155 heap->DecrementDisableMovingGC(self_);
1156 }
Alex Lighta01de592016-11-15 10:43:06 -08001157 return OK;
1158}
1159
Alex Light0e692732017-01-10 15:00:05 -08001160void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1161 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1162 const art::DexFile::ClassDef& class_def) {
1163 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001164 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001165 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001166 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001167 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001168 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1169 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1170 art::dex::TypeIndex method_return_idx =
1171 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1172 const auto* old_type_list = method.GetParameterTypeList();
1173 std::vector<art::dex::TypeIndex> new_type_list;
1174 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1175 new_type_list.push_back(
1176 dex_file_->GetIndexForTypeId(
1177 *dex_file_->FindTypeId(
1178 old_dex_file.GetTypeDescriptor(
1179 old_dex_file.GetTypeId(
1180 old_type_list->GetTypeItem(i).type_idx_)))));
1181 }
1182 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1183 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001184 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001185 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001186 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1187 *new_name_id,
1188 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001189 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001190 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001191 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1192 method.SetDexMethodIndex(dex_method_idx);
1193 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001194 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001195 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -08001196 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001197 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001198 if (jit != nullptr) {
1199 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1200 }
Alex Lighta01de592016-11-15 10:43:06 -08001201 }
Alex Light200b9d72016-12-15 11:34:13 -08001202}
1203
Alex Light0e692732017-01-10 15:00:05 -08001204void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001205 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1206 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1207 for (art::ArtField& field : fields_iter) {
1208 std::string declaring_class_name;
1209 const art::DexFile::TypeId* new_declaring_id =
1210 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1211 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1212 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1213 // TODO Handle error, cleanup.
1214 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1215 const art::DexFile::FieldId* new_field_id =
1216 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1217 CHECK(new_field_id != nullptr);
1218 // We only need to update the index since the other data in the ArtField cannot be updated.
1219 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1220 }
1221 }
Alex Light200b9d72016-12-15 11:34:13 -08001222}
1223
1224// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001225void Redefiner::ClassRedefinition::UpdateClass(
1226 art::ObjPtr<art::mirror::Class> mclass,
1227 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1228 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001229 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1230 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1231 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001232 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001233
Alex Lighta01de592016-11-15 10:43:06 -08001234 // Update the class fields.
1235 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1236 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1237 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001238 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001239 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001240 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1241 CHECK(!ext.IsNull());
1242 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001243}
1244
Alex Lighta01de592016-11-15 10:43:06 -08001245// This function does all (java) allocations we need to do for the Class being redefined.
1246// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001247bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1248 art::StackHandleScope<2> hs(driver_->self_);
1249 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1250 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001251 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001252 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1253 return false;
1254 }
1255 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001256 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001257 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001258 // No memory. Clear exception (it's not useful) and return error.
1259 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1260 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001261 driver_->self_->AssertPendingOOMException();
1262 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001263 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1264 return false;
1265 }
1266 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1267 // are only modified when all threads (other than the modifying one) are suspended we don't need
1268 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1269 // however, since that can happen at any time.
1270 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1271 // are no obsolete methods.
1272 {
Alex Light0e692732017-01-10 15:00:05 -08001273 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001274 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001275 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001276 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001277 driver_->self_->AssertPendingOOMException();
1278 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001279 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1280 return false;
1281 }
1282 }
1283 return true;
1284}
1285
1286} // namespace openjdkjvmti