blob: c4d20c007eb4c733122f048cd9877d260ea162d9 [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"
Alex Lighte77b48b2017-02-22 11:08:06 -080059#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080060#include "object_lock.h"
61#include "runtime.h"
62#include "ScopedLocalRef.h"
Alex Lighteb98b082017-01-25 13:02:32 -080063#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080064#include "transform.h"
Alex Light8c889d22017-02-06 13:58:27 -080065#include "verifier/method_verifier.h"
66#include "verifier/verifier_log_mode.h"
Alex Lighta01de592016-11-15 10:43:06 -080067
68namespace openjdkjvmti {
69
Andreas Gampe46ee31b2016-12-14 10:11:49 -080070using android::base::StringPrintf;
71
Alex Lighteee0bd42017-02-14 15:31:45 +000072// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
73// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
74// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
75class ObsoleteMap {
76 public:
77 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original)
78 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
79 auto method_pair = id_map_.find(original);
80 if (method_pair != id_map_.end()) {
81 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
82 method_pair->second, art::kRuntimePointerSize);
83 DCHECK(res != nullptr);
84 DCHECK_EQ(original, res->GetNonObsoleteMethod());
85 return res;
86 } else {
87 return nullptr;
88 }
89 }
90
91 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
92 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
93 DCHECK(original != nullptr);
94 DCHECK(obsolete != nullptr);
95 int32_t slot = next_free_slot_++;
96 DCHECK_LT(slot, obsolete_methods_->GetLength());
97 DCHECK(nullptr ==
98 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
99 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
100 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
101 obsolete_dex_caches_->Set(slot, original_dex_cache_);
102 id_map_.insert({original, slot});
103 }
104
105 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
106 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
107 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
108 : next_free_slot_(0),
109 obsolete_methods_(obsolete_methods),
110 obsolete_dex_caches_(obsolete_dex_caches),
111 original_dex_cache_(original_dex_cache) {
112 // Figure out where the first unused slot in the obsolete_methods_ array is.
113 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
114 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
115 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
116 next_free_slot_++;
117 }
118 // Sanity check that the same slot in obsolete_dex_caches_ is free.
119 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
120 }
121
122 private:
123 int32_t next_free_slot_;
124 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
125 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
126 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
127 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
128 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
129 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
130};
131
Alex Lightdba61482016-12-21 08:20:29 -0800132// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
133// some basic sanity checks that the obsolete method is sane.
134class ObsoleteMethodStackVisitor : public art::StackVisitor {
135 protected:
136 ObsoleteMethodStackVisitor(
137 art::Thread* thread,
138 art::LinearAlloc* allocator,
139 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000140 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800141 : StackVisitor(thread,
142 /*context*/nullptr,
143 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
144 allocator_(allocator),
145 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800146 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800147
148 ~ObsoleteMethodStackVisitor() OVERRIDE {}
149
150 public:
151 // Returns true if we successfully installed obsolete methods on this thread, filling
152 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
153 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800154 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800155 art::Thread* thread,
156 art::LinearAlloc* allocator,
157 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000158 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800159 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800160 ObsoleteMethodStackVisitor visitor(thread,
161 allocator,
162 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800163 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800164 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800165 }
166
167 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000168 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800169 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800170 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800171 // We cannot ensure that the right dex file is used in inlined frames so we don't support
172 // redefining them.
173 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
Alex Lighteee0bd42017-02-14 15:31:45 +0000174 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
175 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800176 // Create a new Obsolete Method and put it in the list.
177 art::Runtime* runtime = art::Runtime::Current();
178 art::ClassLinker* cl = runtime->GetClassLinker();
179 auto ptr_size = cl->GetImagePointerSize();
180 const size_t method_size = art::ArtMethod::Size(ptr_size);
181 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800182 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
183 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800184 new_obsolete_method = new (method_storage) art::ArtMethod();
185 new_obsolete_method->CopyFrom(old_method, ptr_size);
186 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
187 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800188 new_obsolete_method->SetDontCompile();
Alex Lighteee0bd42017-02-14 15:31:45 +0000189 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800190 // Update JIT Data structures to point to the new method.
191 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
192 if (jit != nullptr) {
193 // Notify the JIT we are making this obsolete method. It will update the jit's internal
194 // structures to keep track of the new obsolete method.
195 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
196 }
Alex Lightdba61482016-12-21 08:20:29 -0800197 }
198 DCHECK(new_obsolete_method != nullptr);
199 SetMethod(new_obsolete_method);
200 }
201 return true;
202 }
203
204 private:
205 // The linear allocator we should use to make new methods.
206 art::LinearAlloc* allocator_;
207 // The set of all methods which could be obsoleted.
208 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
209 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000210 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
211 // the redefined classes ClassExt as it is filled.
212 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800213};
214
Alex Lighte4a88632017-01-10 07:41:24 -0800215jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
216 jclass klass,
217 jboolean* is_redefinable) {
218 // TODO Check for the appropriate feature flags once we have enabled them.
219 art::Thread* self = art::Thread::Current();
220 art::ScopedObjectAccess soa(self);
221 art::StackHandleScope<1> hs(self);
222 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
223 if (obj.IsNull()) {
224 return ERR(INVALID_CLASS);
225 }
226 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
227 std::string err_unused;
228 *is_redefinable =
229 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
230 return OK;
231}
232
233jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
234 /*out*/std::string* error_msg) {
235 if (klass->IsPrimitive()) {
236 *error_msg = "Modification of primitive classes is not supported";
237 return ERR(UNMODIFIABLE_CLASS);
238 } else if (klass->IsInterface()) {
239 *error_msg = "Modification of Interface classes is currently not supported";
240 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800241 } else if (klass->IsStringClass()) {
242 *error_msg = "Modification of String class is not supported";
243 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800244 } 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
Alex Lighte77b48b2017-02-22 11:08:06 -0800252 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
253 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
254 *error_msg = "Class might have stack frames that cannot be made obsolete";
255 return ERR(UNMODIFIABLE_CLASS);
256 }
257 }
258
Alex Lighte4a88632017-01-10 07:41:24 -0800259 return OK;
260}
261
Alex Lighta01de592016-11-15 10:43:06 -0800262// Moves dex data to an anonymous, read-only mmap'd region.
263std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
264 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800265 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800266 std::string* error_msg) {
267 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800268 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800269 nullptr,
270 data_len,
271 PROT_READ|PROT_WRITE,
272 /*low_4gb*/false,
273 /*reuse*/false,
274 error_msg));
275 if (map == nullptr) {
276 return map;
277 }
278 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800279 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
280 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800281 map->Protect(PROT_READ);
282 return map;
283}
284
Alex Lighta7e38d82017-01-19 14:57:28 -0800285Redefiner::ClassRedefinition::ClassRedefinition(
286 Redefiner* driver,
287 jclass klass,
288 const art::DexFile* redefined_dex_file,
289 const char* class_sig,
290 art::ArraySlice<const unsigned char> orig_dex_file) :
291 driver_(driver),
292 klass_(klass),
293 dex_file_(redefined_dex_file),
294 class_sig_(class_sig),
295 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800296 GetMirrorClass()->MonitorEnter(driver_->self_);
297}
298
299Redefiner::ClassRedefinition::~ClassRedefinition() {
300 if (driver_ != nullptr) {
301 GetMirrorClass()->MonitorExit(driver_->self_);
302 }
303}
304
Alex Light0e692732017-01-10 15:00:05 -0800305jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800306 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800307 art::Runtime* runtime,
308 art::Thread* self,
309 jint class_count,
310 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800311 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800312 if (env == nullptr) {
313 *error_msg = "env was null!";
314 return ERR(INVALID_ENVIRONMENT);
315 } else if (class_count < 0) {
316 *error_msg = "class_count was less then 0";
317 return ERR(ILLEGAL_ARGUMENT);
318 } else if (class_count == 0) {
319 // We don't actually need to do anything. Just return OK.
320 return OK;
321 } else if (definitions == nullptr) {
322 *error_msg = "null definitions!";
323 return ERR(NULL_POINTER);
324 }
Alex Light6ac57502017-01-19 15:05:06 -0800325 std::vector<ArtClassDefinition> def_vector;
326 def_vector.reserve(class_count);
327 for (jint i = 0; i < class_count; i++) {
328 // We make a copy of the class_bytes to pass into the retransformation.
329 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
330 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
331 // to get the passed in bytes.
Alex Light6ac57502017-01-19 15:05:06 -0800332 unsigned char* class_bytes_copy = nullptr;
333 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
334 if (res != OK) {
335 return res;
336 }
337 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
338
339 ArtClassDefinition def;
340 def.dex_len = definitions[i].class_byte_count;
341 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
342 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800343 def.SetModified();
344 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
345 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800346 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
347 if (res != OK) {
348 return res;
349 }
350 def_vector.push_back(std::move(def));
351 }
352 // Call all the transformation events.
353 jvmtiError res = Transformer::RetransformClassesDirect(env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800354 event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800355 self,
356 &def_vector);
357 if (res != OK) {
358 // Something went wrong with transformation!
359 return res;
360 }
361 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
362}
363
364jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
365 art::Runtime* runtime,
366 art::Thread* self,
367 const std::vector<ArtClassDefinition>& definitions,
368 std::string* error_msg) {
369 DCHECK(env != nullptr);
370 if (definitions.size() == 0) {
371 // We don't actually need to do anything. Just return OK.
372 return OK;
373 }
Alex Light0e692732017-01-10 15:00:05 -0800374 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
375 // are going to redefine.
376 art::jit::ScopedJitSuspend suspend_jit;
377 // Get shared mutator lock so we can lock all the classes.
378 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800379 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800380 for (const ArtClassDefinition& def : definitions) {
381 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800382 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800383 jvmtiError res = r.AddRedefinition(env, def);
384 if (res != OK) {
385 return res;
386 }
Alex Light0e692732017-01-10 15:00:05 -0800387 }
388 }
389 return r.Run();
390}
391
Alex Light6ac57502017-01-19 15:05:06 -0800392jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800393 std::string original_dex_location;
394 jvmtiError ret = OK;
395 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
396 *error_msg_ = "Unable to get original dex file location!";
397 return ret;
398 }
Alex Light52a2db52017-01-19 23:00:21 +0000399 char* generic_ptr_unused = nullptr;
400 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800401 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
402 *error_msg_ = "Unable to get class signature!";
403 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000404 }
Andreas Gampe54711412017-02-21 12:41:43 -0800405 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
406 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Alex Light6ac57502017-01-19 15:05:06 -0800407 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
408 def.dex_len,
409 def.dex_data.get(),
410 error_msg_));
411 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800412 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800413 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800414 << "in dex file " << original_dex_location << " because: " << *error_msg_;
415 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800416 return ERR(OUT_OF_MEMORY);
417 }
418 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800419 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800420 return ERR(INVALID_CLASS_FORMAT);
421 }
422 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
423 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
424 checksum,
425 std::move(map),
426 /*verify*/true,
427 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800428 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800429 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800430 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800431 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800432 return ERR(INVALID_CLASS_FORMAT);
433 }
Alex Light0e692732017-01-10 15:00:05 -0800434 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800435 Redefiner::ClassRedefinition(this,
436 def.klass,
437 dex_file.release(),
438 signature_ptr,
439 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800440 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800441}
442
Alex Light0e692732017-01-10 15:00:05 -0800443art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
444 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800445}
446
Alex Light0e692732017-01-10 15:00:05 -0800447art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800448 return GetMirrorClass()->GetClassLoader();
449}
450
Alex Light0e692732017-01-10 15:00:05 -0800451art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
452 art::Handle<art::mirror::ClassLoader> loader) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000453 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800454}
455
Alex Light0e692732017-01-10 15:00:05 -0800456void Redefiner::RecordFailure(jvmtiError result,
457 const std::string& class_sig,
458 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800459 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800460 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800461 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800462 result_ = result;
463}
464
Alex Lighta7e38d82017-01-19 14:57:28 -0800465art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
466 // If we have been specifically given a new set of bytes use that
467 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800468 return art::mirror::ByteArray::AllocateAndFill(
469 driver_->self_,
470 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
471 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800472 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800473
474 // See if we already have one set.
475 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
476 if (!ext.IsNull()) {
477 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
478 if (!old_original_bytes.IsNull()) {
479 // We do. Use it.
480 return old_original_bytes.Ptr();
481 }
Alex Lighta01de592016-11-15 10:43:06 -0800482 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800483
484 // Copy the current dex_file
485 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
486 // TODO Handle this or make it so it cannot happen.
487 if (current_dex_file.NumClassDefs() != 1) {
488 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
489 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800490 }
Alex Light440b5d92017-01-24 15:32:25 -0800491 return art::mirror::ByteArray::AllocateAndFill(
492 driver_->self_,
493 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
494 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800495}
496
Alex Lightdba61482016-12-21 08:20:29 -0800497struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000498 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800499 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800500 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800501
Alex Lighteee0bd42017-02-14 15:31:45 +0000502 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
503 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800504};
505
Alex Lightdba61482016-12-21 08:20:29 -0800506void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
507 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800508 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
509 data->allocator,
510 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000511 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800512}
513
514// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
515// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800516// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
517void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800518 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
519 art::mirror::ClassExt* ext = art_klass->GetExtData();
520 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800521 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000522 // This holds pointers to the obsolete methods map fields which are updated as needed.
523 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
524 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800525 // Add all the declared methods to the map
526 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800527 if (m.IsIntrinsic()) {
528 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
529 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
530 << "methods that have already been compiled.";
531 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000532 // It is possible to simply filter out some methods where they cannot really become obsolete,
533 // such as native methods and keep their original (possibly optimized) implementations. We don't
534 // do this, however, since we would need to mark these functions (still in the classes
535 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
536 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
537 // error checking from the interpreter which ensure we don't try to start executing obsolete
538 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000539 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800540 }
541 {
Alex Light0e692732017-01-10 15:00:05 -0800542 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800543 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
544 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800545 }
Alex Lightdba61482016-12-21 08:20:29 -0800546}
547
Alex Light6161f132017-01-25 10:30:20 -0800548// Try and get the declared method. First try to get a virtual method then a direct method if that's
549// not found.
550static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
551 const char* name,
552 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
553 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize);
554 if (m == nullptr) {
555 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize);
556 }
557 return m;
558}
559
560bool Redefiner::ClassRedefinition::CheckSameMethods() {
561 art::StackHandleScope<1> hs(driver_->self_);
562 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
563 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
564
565 art::ClassDataItemIterator new_iter(*dex_file_,
566 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
567
568 // Make sure we have the same number of methods.
569 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods();
570 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
571 if (num_new_method != num_old_method) {
572 bool bigger = num_new_method > num_old_method;
573 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
574 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
575 StringPrintf("Total number of declared methods changed from %d to %d",
576 num_old_method, num_new_method));
577 return false;
578 }
579
580 // Skip all of the fields. We should have already checked this.
581 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) {
582 new_iter.Next();
583 }
584 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
585 // files have the same number of methods, which means there must be an equal amount of additions
586 // and removals.
587 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) {
588 // Get the data on the method we are searching for
589 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex());
590 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
591 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
592 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
593 // If we got past the check for the same number of methods above that means there must be at
594 // least one added and one removed method. We will return the ADDED failure message since it is
595 // easier to get a useful error report for it.
596 if (old_method == nullptr) {
597 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
598 StringPrintf("Unknown method '%s' (sig: %s) was added!",
599 new_method_name,
600 new_method_signature.ToString().c_str()));
601 return false;
602 }
603 // Since direct methods have different flags than virtual ones (specifically direct methods must
604 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
605 // virtual to direct.
606 uint32_t new_flags = new_iter.GetMethodAccessFlags();
607 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
608 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
609 StringPrintf("method '%s' (sig: %s) had different access flags",
610 new_method_name,
611 new_method_signature.ToString().c_str()));
612 return false;
613 }
614 }
615 return true;
616}
617
618bool Redefiner::ClassRedefinition::CheckSameFields() {
619 art::StackHandleScope<1> hs(driver_->self_);
620 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
621 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
622 art::ClassDataItemIterator new_iter(*dex_file_,
623 dex_file_->GetClassData(dex_file_->GetClassDef(0)));
624 const art::DexFile& old_dex_file = h_klass->GetDexFile();
625 art::ClassDataItemIterator old_iter(old_dex_file,
626 old_dex_file.GetClassData(*h_klass->GetClassDef()));
627 // Instance and static fields can be differentiated by their flags so no need to check them
628 // separately.
629 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) {
630 // Get the data on the method we are searching for
631 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex());
632 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
633 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
634
635 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) {
636 // We are missing the old version of this method!
637 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
638 StringPrintf("Unknown field '%s' (type: %s) added!",
639 new_field_name,
640 new_field_type));
641 return false;
642 }
643
644 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex());
645 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
646 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
647
648 // Check name and type.
649 if (strcmp(old_field_name, new_field_name) != 0 ||
650 strcmp(old_field_type, new_field_type) != 0) {
651 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
652 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
653 old_field_name,
654 old_field_type,
655 new_field_name,
656 new_field_type));
657 return false;
658 }
659
660 // Since static fields have different flags than instance ones (specifically static fields must
661 // have the kAccStatic flag) we can tell if a field changes from static to instance.
662 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) {
663 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
664 StringPrintf("Field '%s' (sig: %s) had different access flags",
665 new_field_name,
666 new_field_type));
667 return false;
668 }
669
670 new_iter.Next();
671 old_iter.Next();
672 }
673 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) {
674 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
675 StringPrintf("field '%s' (sig: %s) is missing!",
676 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
677 old_iter.GetMemberIndex())),
678 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
679 old_iter.GetMemberIndex()))));
680 return false;
681 }
682 return true;
683}
684
Alex Light0e692732017-01-10 15:00:05 -0800685bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800686 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000687 // Easy check that only 1 class def is present.
688 if (dex_file_->NumClassDefs() != 1) {
689 RecordFailure(ERR(ILLEGAL_ARGUMENT),
690 StringPrintf("Expected 1 class def in dex file but found %d",
691 dex_file_->NumClassDefs()));
692 return false;
693 }
694 // Get the ClassDef from the new DexFile.
695 // Since the dex file has only a single class def the index is always 0.
696 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
697 // Get the class as it is now.
698 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
699
700 // Check the access flags didn't change.
701 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
702 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
703 "Cannot change modifiers of class by redefinition");
704 return false;
705 }
706
707 // Check class name.
708 // These should have been checked by the dexfile verifier on load.
709 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
710 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
711 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
712 if (!current_class->DescriptorEquals(descriptor)) {
713 std::string storage;
714 RecordFailure(ERR(NAMES_DONT_MATCH),
715 StringPrintf("expected file to contain class called '%s' but found '%s'!",
716 current_class->GetDescriptor(&storage),
717 descriptor));
718 return false;
719 }
720 if (current_class->IsObjectClass()) {
721 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
722 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
723 return false;
724 }
725 } else {
726 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
727 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
728 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
729 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
730 return false;
731 }
732 }
733 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
734 if (interfaces == nullptr) {
735 if (current_class->NumDirectInterfaces() != 0) {
736 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
737 return false;
738 }
739 } else {
740 DCHECK(!current_class->IsProxyClass());
741 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
742 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
743 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
744 return false;
745 }
746 // The order of interfaces is (barely) meaningful so we error if it changes.
747 const art::DexFile& orig_dex_file = current_class->GetDexFile();
748 for (uint32_t i = 0; i < interfaces->Size(); i++) {
749 if (strcmp(
750 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
751 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
752 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
753 "Interfaces changed or re-ordered");
754 return false;
755 }
756 }
757 }
Alex Light460d1b42017-01-10 15:37:17 +0000758 return true;
759}
760
Alex Light0e692732017-01-10 15:00:05 -0800761bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800762 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800763 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000764
Alex Lighte4a88632017-01-10 07:41:24 -0800765 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
766 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
767 if (res != OK) {
768 RecordFailure(res, err);
769 return false;
770 } else {
771 return true;
772 }
Alex Light460d1b42017-01-10 15:37:17 +0000773}
774
Alex Light0e692732017-01-10 15:00:05 -0800775bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000776 return CheckRedefinable() &&
777 CheckClass() &&
778 CheckSameFields() &&
779 CheckSameMethods();
780}
781
Alex Light0e692732017-01-10 15:00:05 -0800782// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
783// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
784// having to deal with the fact that we need to hold an arbitrary number of references live.
785class RedefinitionDataHolder {
786 public:
787 enum DataSlot : int32_t {
788 kSlotSourceClassLoader = 0,
789 kSlotJavaDexFile = 1,
790 kSlotNewDexFileCookie = 2,
791 kSlotNewDexCache = 3,
792 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800793 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800794
795 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800796 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800797 };
798
799 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
800 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
801 // the passed in handle-scope.
802 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
803 art::Runtime* runtime,
804 art::Thread* self,
805 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
806 arr_(
807 hs->NewHandle(
808 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
809 self,
810 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
811 num_redefinitions * kNumSlots))) {}
812
813 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
814 return arr_.IsNull();
815 }
816
817 // TODO Maybe make an iterable view type to simplify using this.
Alex Light8c889d22017-02-06 13:58:27 -0800818 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800819 REQUIRES_SHARED(art::Locks::mutator_lock_) {
820 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
821 }
Alex Light8c889d22017-02-06 13:58:27 -0800822 art::mirror::Object* GetJavaDexFile(jint klass_index) const
823 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800824 return GetSlot(klass_index, kSlotJavaDexFile);
825 }
Alex Light8c889d22017-02-06 13:58:27 -0800826 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800827 REQUIRES_SHARED(art::Locks::mutator_lock_) {
828 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
829 }
Alex Light8c889d22017-02-06 13:58:27 -0800830 art::mirror::DexCache* GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800831 REQUIRES_SHARED(art::Locks::mutator_lock_) {
832 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
833 }
Alex Light8c889d22017-02-06 13:58:27 -0800834 art::mirror::Class* GetMirrorClass(jint klass_index) const
835 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800836 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
837 }
838
Alex Light8c889d22017-02-06 13:58:27 -0800839 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800840 REQUIRES_SHARED(art::Locks::mutator_lock_) {
841 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
842 }
843
Alex Light0e692732017-01-10 15:00:05 -0800844 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
845 REQUIRES_SHARED(art::Locks::mutator_lock_) {
846 SetSlot(klass_index, kSlotSourceClassLoader, loader);
847 }
848 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
849 REQUIRES_SHARED(art::Locks::mutator_lock_) {
850 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
851 }
852 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
853 REQUIRES_SHARED(art::Locks::mutator_lock_) {
854 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
855 }
856 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
857 REQUIRES_SHARED(art::Locks::mutator_lock_) {
858 SetSlot(klass_index, kSlotNewDexCache, cache);
859 }
860 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
861 REQUIRES_SHARED(art::Locks::mutator_lock_) {
862 SetSlot(klass_index, kSlotMirrorClass, klass);
863 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800864 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
865 REQUIRES_SHARED(art::Locks::mutator_lock_) {
866 SetSlot(klass_index, kSlotOrigDexFile, bytes);
867 }
Alex Light0e692732017-01-10 15:00:05 -0800868
Alex Light8c889d22017-02-06 13:58:27 -0800869 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800870 return arr_->GetLength() / kNumSlots;
871 }
872
873 private:
Alex Light8c889d22017-02-06 13:58:27 -0800874 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Light0e692732017-01-10 15:00:05 -0800875
876 art::mirror::Object* GetSlot(jint klass_index,
Alex Light8c889d22017-02-06 13:58:27 -0800877 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800878 DCHECK_LT(klass_index, Length());
879 return arr_->Get((kNumSlots * klass_index) + slot);
880 }
881
882 void SetSlot(jint klass_index,
883 DataSlot slot,
884 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
885 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
886 DCHECK_LT(klass_index, Length());
887 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
888 }
889
890 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
891};
892
Alex Light8c889d22017-02-06 13:58:27 -0800893bool Redefiner::ClassRedefinition::CheckVerification(int32_t klass_index,
894 const RedefinitionDataHolder& holder) {
895 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
896 art::StackHandleScope<2> hs(driver_->self_);
897 std::string error;
898 // TODO Make verification log level lower
899 art::verifier::MethodVerifier::FailureKind failure =
900 art::verifier::MethodVerifier::VerifyClass(driver_->self_,
901 dex_file_.get(),
902 hs.NewHandle(holder.GetNewDexCache(klass_index)),
903 hs.NewHandle(GetClassLoader()),
904 dex_file_->GetClassDef(0), /*class_def*/
905 nullptr, /*compiler_callbacks*/
906 false, /*allow_soft_failures*/
907 /*log_level*/
908 art::verifier::HardFailLogMode::kLogWarning,
909 &error);
910 bool passes = failure == art::verifier::MethodVerifier::kNoFailure;
911 if (!passes) {
912 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
913 }
914 return passes;
915}
916
Alex Light1babae02017-02-01 15:35:34 -0800917// Looks through the previously allocated cookies to see if we need to update them with another new
918// dexfile. This is so that even if multiple classes with the same classloader are redefined at
919// once they are all added to the classloader.
920bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
921 int32_t klass_index,
922 art::Handle<art::mirror::ClassLoader> source_class_loader,
923 art::Handle<art::mirror::Object> dex_file_obj,
924 /*out*/RedefinitionDataHolder* holder) {
925 art::StackHandleScope<2> hs(driver_->self_);
926 art::MutableHandle<art::mirror::LongArray> old_cookie(
927 hs.NewHandle<art::mirror::LongArray>(nullptr));
928 bool has_older_cookie = false;
929 // See if we already have a cookie that a previous redefinition got from the same classloader.
930 for (int32_t i = 0; i < klass_index; i++) {
931 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
932 // Since every instance of this classloader should have the same cookie associated with it we
933 // can stop looking here.
934 has_older_cookie = true;
935 old_cookie.Assign(holder->GetNewDexFileCookie(i));
936 break;
937 }
938 }
939 if (old_cookie.IsNull()) {
940 // No older cookie. Get it directly from the dex_file_obj
941 // We should not have seen this classloader elsewhere.
942 CHECK(!has_older_cookie);
943 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
944 }
945 // Use the old cookie to generate the new one with the new DexFile* added in.
946 art::Handle<art::mirror::LongArray>
947 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
948 old_cookie,
949 dex_file_.get())));
950 // Make sure the allocation worked.
951 if (new_cookie.IsNull()) {
952 return false;
953 }
954
955 // Save the cookie.
956 holder->SetNewDexFileCookie(klass_index, new_cookie.Get());
957 // If there are other copies of this same classloader we need to make sure that we all have the
958 // same cookie.
959 if (has_older_cookie) {
960 for (int32_t i = 0; i < klass_index; i++) {
961 // We will let the GC take care of the cookie we allocated for this one.
962 if (holder->GetSourceClassLoader(i) == source_class_loader.Get()) {
963 holder->SetNewDexFileCookie(i, new_cookie.Get());
964 }
965 }
966 }
967
968 return true;
969}
970
Alex Lighta7e38d82017-01-19 14:57:28 -0800971bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
972 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
Alex Light7916f202017-01-27 09:00:15 -0800973 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -0800974 art::StackHandleScope<2> hs(driver_->self_);
975 holder->SetMirrorClass(klass_index, GetMirrorClass());
976 // This shouldn't allocate
977 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -0800978 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
979 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
980 holder->SetSourceClassLoader(klass_index, loader.Get());
981 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
982 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
983 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -0800984 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -0800985 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
986 return false;
987 }
Alex Light1babae02017-02-01 15:35:34 -0800988 // Allocate the new dex file cookie.
989 if (!AllocateAndRememberNewDexFileCookie(klass_index, loader, dex_file_obj, holder)) {
Alex Light7916f202017-01-27 09:00:15 -0800990 driver_->self_->AssertPendingOOMException();
991 driver_->self_->ClearException();
992 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
993 return false;
994 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800995 }
996 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
997 if (holder->GetNewDexCache(klass_index) == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000998 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -0800999 driver_->self_->ClearException();
1000 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1001 return false;
1002 }
1003
1004 // We won't always need to set this field.
1005 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
1006 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
1007 driver_->self_->AssertPendingOOMException();
1008 driver_->self_->ClearException();
1009 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1010 return false;
1011 }
1012 return true;
1013}
1014
Alex Light5643caf2017-02-08 11:39:07 -08001015void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
1016 DCHECK(art::Dbg::IsDebuggerActive());
1017 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1018 if (state != nullptr) {
1019 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1020 }
1021}
1022
1023void Redefiner::UnregisterAllBreakpoints() {
1024 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1025 return;
1026 }
1027 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1028 redef.UnregisterBreakpoints();
1029 }
1030}
1031
Alex Light0e692732017-01-10 15:00:05 -08001032bool Redefiner::CheckAllRedefinitionAreValid() {
1033 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1034 if (!redef.CheckRedefinitionIsValid()) {
1035 return false;
1036 }
1037 }
1038 return true;
1039}
1040
1041bool Redefiner::EnsureAllClassAllocationsFinished() {
1042 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1043 if (!redef.EnsureClassAllocationsFinished()) {
1044 return false;
1045 }
1046 }
1047 return true;
1048}
1049
1050bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
1051 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -08001052 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -08001053 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -08001054 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -08001055 return false;
1056 }
Alex Light0e692732017-01-10 15:00:05 -08001057 cnt++;
1058 }
1059 return true;
1060}
1061
1062void Redefiner::ClassRedefinition::ReleaseDexFile() {
1063 dex_file_.release();
1064}
1065
1066void Redefiner::ReleaseAllDexFiles() {
1067 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1068 redef.ReleaseDexFile();
1069 }
1070}
1071
Alex Light8c889d22017-02-06 13:58:27 -08001072bool Redefiner::CheckAllClassesAreVerified(const RedefinitionDataHolder& holder) {
1073 int32_t cnt = 0;
1074 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1075 if (!redef.CheckVerification(cnt, holder)) {
1076 return false;
1077 }
1078 cnt++;
1079 }
1080 return true;
1081}
1082
Alex Lighta01de592016-11-15 10:43:06 -08001083jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001084 art::StackHandleScope<1> hs(self_);
1085 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1086 // We will let this be collected after the end of this function.
1087 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
1088 if (holder.IsNull()) {
1089 self_->AssertPendingOOMException();
1090 self_->ClearException();
1091 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1092 return result_;
1093 }
1094
Alex Lighta01de592016-11-15 10:43:06 -08001095 // First we just allocate the ClassExt and its fields that we need. These can be updated
1096 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1097 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1098 // between allocating them and pausing all threads before we can update them so we need to do a
1099 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001100 if (!CheckAllRedefinitionAreValid() ||
1101 !EnsureAllClassAllocationsFinished() ||
Alex Light8c889d22017-02-06 13:58:27 -08001102 !FinishAllRemainingAllocations(holder) ||
1103 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001104 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
1105 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -08001106 // declared_methods_.length) but would be good to get rid of. All other allocations should be
1107 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -08001108 return result_;
1109 }
Alex Light5643caf2017-02-08 11:39:07 -08001110 // At this point we can no longer fail without corrupting the runtime state.
Alex Light7916f202017-01-27 09:00:15 -08001111 int32_t counter = 0;
1112 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1113 if (holder.GetSourceClassLoader(counter) == nullptr) {
1114 runtime_->GetClassLinker()->AppendToBootClassPath(self_, redef.GetDexFile());
1115 }
1116 counter++;
1117 }
Alex Light5643caf2017-02-08 11:39:07 -08001118 UnregisterAllBreakpoints();
Alex Light6abd5392017-01-05 17:53:00 -08001119 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1120 // allocating so no deadlocks.
1121 art::gc::Heap* heap = runtime_->GetHeap();
1122 if (heap->IsGcConcurrentAndMoving()) {
1123 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
1124 heap->IncrementDisableMovingGC(self_);
1125 }
Alex Lighta01de592016-11-15 10:43:06 -08001126 // Do transition to final suspension
1127 // TODO We might want to give this its own suspended state!
1128 // TODO This isn't right. We need to change state without any chance of suspend ideally!
1129 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
1130 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -08001131 "Final installation of redefined Classes!", /*long_suspend*/true);
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 Light7532d582017-02-13 16:36:06 -08001146 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1147 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1148 // methods that have been jitted prior to the current redefinition being applied might continue
1149 // to use the old versions of the intrinsics!
Alex Lightdba61482016-12-21 08:20:29 -08001150 // TODO Shrink the obsolete method maps if possible?
Alex Lighta01de592016-11-15 10:43:06 -08001151 // TODO Put this into a scoped thing.
1152 runtime_->GetThreadList()->ResumeAll();
1153 // Get back shared mutator lock as expected for return.
1154 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -08001155 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1156 // owns the DexFile and when ownership is transferred.
1157 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001158 if (heap->IsGcConcurrentAndMoving()) {
1159 heap->DecrementDisableMovingGC(self_);
1160 }
Alex Lighta01de592016-11-15 10:43:06 -08001161 return OK;
1162}
1163
Alex Light0e692732017-01-10 15:00:05 -08001164void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1165 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1166 const art::DexFile::ClassDef& class_def) {
1167 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001168 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001169 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001170 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001171 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001172 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1173 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1174 art::dex::TypeIndex method_return_idx =
1175 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1176 const auto* old_type_list = method.GetParameterTypeList();
1177 std::vector<art::dex::TypeIndex> new_type_list;
1178 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1179 new_type_list.push_back(
1180 dex_file_->GetIndexForTypeId(
1181 *dex_file_->FindTypeId(
1182 old_dex_file.GetTypeDescriptor(
1183 old_dex_file.GetTypeId(
1184 old_type_list->GetTypeItem(i).type_idx_)))));
1185 }
1186 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1187 new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001188 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001189 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1190 *new_name_id,
1191 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001192 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001193 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1194 method.SetDexMethodIndex(dex_method_idx);
1195 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001196 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001197 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Light7532d582017-02-13 16:36:06 -08001198 // Clear all the intrinsics related flags.
1199 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic));
Alex Lightdba61482016-12-21 08:20:29 -08001200 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001201 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001202 if (jit != nullptr) {
1203 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1204 }
Alex Lighta01de592016-11-15 10:43:06 -08001205 }
Alex Light200b9d72016-12-15 11:34:13 -08001206}
1207
Alex Light0e692732017-01-10 15:00:05 -08001208void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001209 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1210 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1211 for (art::ArtField& field : fields_iter) {
1212 std::string declaring_class_name;
1213 const art::DexFile::TypeId* new_declaring_id =
1214 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1215 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1216 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001217 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1218 const art::DexFile::FieldId* new_field_id =
1219 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1220 CHECK(new_field_id != nullptr);
1221 // We only need to update the index since the other data in the ArtField cannot be updated.
1222 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1223 }
1224 }
Alex Light200b9d72016-12-15 11:34:13 -08001225}
1226
1227// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001228void Redefiner::ClassRedefinition::UpdateClass(
1229 art::ObjPtr<art::mirror::Class> mclass,
1230 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1231 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001232 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1233 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1234 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001235 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001236
Alex Lighta01de592016-11-15 10:43:06 -08001237 // Update the class fields.
1238 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1239 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1240 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001241 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001242 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001243 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1244 CHECK(!ext.IsNull());
1245 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001246}
1247
Alex Lighta01de592016-11-15 10:43:06 -08001248// This function does all (java) allocations we need to do for the Class being redefined.
1249// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001250bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1251 art::StackHandleScope<2> hs(driver_->self_);
1252 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1253 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001254 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001255 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1256 return false;
1257 }
1258 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001259 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001260 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001261 // No memory. Clear exception (it's not useful) and return error.
1262 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1263 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001264 driver_->self_->AssertPendingOOMException();
1265 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001266 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1267 return false;
1268 }
1269 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1270 // are only modified when all threads (other than the modifying one) are suspended we don't need
1271 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1272 // however, since that can happen at any time.
1273 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1274 // are no obsolete methods.
1275 {
Alex Light0e692732017-01-10 15:00:05 -08001276 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001277 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001278 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001279 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001280 driver_->self_->AssertPendingOOMException();
1281 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001282 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1283 return false;
1284 }
1285 }
1286 return true;
1287}
1288
1289} // namespace openjdkjvmti