blob: 6af51c4c6cdc6fadab7489e8cba05f827e9a5ba7 [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"
39#include "base/logging.h"
Alex Light460d1b42017-01-10 15:37:17 +000040#include "dex_file.h"
41#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080042#include "events-inl.h"
43#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080044#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080045#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080048#include "jni_env_ext-inl.h"
49#include "jvmti_allocator.h"
50#include "mirror/class.h"
51#include "mirror/class_ext.h"
52#include "mirror/object.h"
53#include "object_lock.h"
54#include "runtime.h"
55#include "ScopedLocalRef.h"
Alex Light0e692732017-01-10 15:00:05 -080056#include "transform.h"
Alex Lighta01de592016-11-15 10:43:06 -080057
58namespace openjdkjvmti {
59
Andreas Gampe46ee31b2016-12-14 10:11:49 -080060using android::base::StringPrintf;
61
Alex Lightdba61482016-12-21 08:20:29 -080062// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
63// some basic sanity checks that the obsolete method is sane.
64class ObsoleteMethodStackVisitor : public art::StackVisitor {
65 protected:
66 ObsoleteMethodStackVisitor(
67 art::Thread* thread,
68 art::LinearAlloc* allocator,
69 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080070 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -080071 : StackVisitor(thread,
72 /*context*/nullptr,
73 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
74 allocator_(allocator),
75 obsoleted_methods_(obsoleted_methods),
76 obsolete_maps_(obsolete_maps),
Alex Light007ada22017-01-10 13:33:56 -080077 is_runtime_frame_(false) {
Alex Lightdba61482016-12-21 08:20:29 -080078 }
79
80 ~ObsoleteMethodStackVisitor() OVERRIDE {}
81
82 public:
83 // Returns true if we successfully installed obsolete methods on this thread, filling
84 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
85 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080086 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080087 art::Thread* thread,
88 art::LinearAlloc* allocator,
89 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080090 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
91 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080092 ObsoleteMethodStackVisitor visitor(thread,
93 allocator,
94 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080095 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -080096 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -080097 }
98
99 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
100 art::ArtMethod* old_method = GetMethod();
101 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
102 // works through runtime methods.
103 bool prev_was_runtime_frame_ = is_runtime_frame_;
104 is_runtime_frame_ = old_method->IsRuntimeMethod();
105 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
106 // The check below works since when we deoptimize we set shadow frames for all frames until a
107 // native/runtime transition and for those set the return PC to a function that will complete
108 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
109 // below runtime frames cannot be deoptimized at the moment.
110 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
111 // works through runtime methods.
112 // TODO b/33616143
113 if (!IsShadowFrame() && prev_was_runtime_frame_) {
Alex Light007ada22017-01-10 13:33:56 -0800114 LOG(FATAL) << "Deoptimization failed due to runtime method in stack. See b/33616143";
Alex Lightdba61482016-12-21 08:20:29 -0800115 }
116 // We cannot ensure that the right dex file is used in inlined frames so we don't support
117 // redefining them.
118 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
119 // TODO We should really support intrinsic obsolete methods.
120 // TODO We should really support redefining intrinsics.
121 // We don't support intrinsics so check for them here.
122 DCHECK(!old_method->IsIntrinsic());
123 art::ArtMethod* new_obsolete_method = nullptr;
124 auto obsolete_method_pair = obsolete_maps_->find(old_method);
125 if (obsolete_method_pair == obsolete_maps_->end()) {
126 // Create a new Obsolete Method and put it in the list.
127 art::Runtime* runtime = art::Runtime::Current();
128 art::ClassLinker* cl = runtime->GetClassLinker();
129 auto ptr_size = cl->GetImagePointerSize();
130 const size_t method_size = art::ArtMethod::Size(ptr_size);
131 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800132 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
133 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800134 new_obsolete_method = new (method_storage) art::ArtMethod();
135 new_obsolete_method->CopyFrom(old_method, ptr_size);
136 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
137 new_obsolete_method->SetIsObsolete();
138 obsolete_maps_->insert({old_method, new_obsolete_method});
139 // Update JIT Data structures to point to the new method.
140 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
141 if (jit != nullptr) {
142 // Notify the JIT we are making this obsolete method. It will update the jit's internal
143 // structures to keep track of the new obsolete method.
144 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
145 }
146 } else {
147 new_obsolete_method = obsolete_method_pair->second;
148 }
149 DCHECK(new_obsolete_method != nullptr);
150 SetMethod(new_obsolete_method);
151 }
152 return true;
153 }
154
155 private:
156 // The linear allocator we should use to make new methods.
157 art::LinearAlloc* allocator_;
158 // The set of all methods which could be obsoleted.
159 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
160 // A map from the original to the newly allocated obsolete method for frames on this thread. The
161 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
162 // the redefined classes ClassExt by the caller.
163 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800164 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
165 // works through runtime methods.
166 bool is_runtime_frame_;
Alex Lightdba61482016-12-21 08:20:29 -0800167};
168
Alex Lighte4a88632017-01-10 07:41:24 -0800169jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
170 jclass klass,
171 jboolean* is_redefinable) {
172 // TODO Check for the appropriate feature flags once we have enabled them.
173 art::Thread* self = art::Thread::Current();
174 art::ScopedObjectAccess soa(self);
175 art::StackHandleScope<1> hs(self);
176 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
177 if (obj.IsNull()) {
178 return ERR(INVALID_CLASS);
179 }
180 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
181 std::string err_unused;
182 *is_redefinable =
183 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
184 return OK;
185}
186
187jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
188 /*out*/std::string* error_msg) {
189 if (klass->IsPrimitive()) {
190 *error_msg = "Modification of primitive classes is not supported";
191 return ERR(UNMODIFIABLE_CLASS);
192 } else if (klass->IsInterface()) {
193 *error_msg = "Modification of Interface classes is currently not supported";
194 return ERR(UNMODIFIABLE_CLASS);
195 } else if (klass->IsArrayClass()) {
196 *error_msg = "Modification of Array classes is not supported";
197 return ERR(UNMODIFIABLE_CLASS);
198 } else if (klass->IsProxyClass()) {
199 *error_msg = "Modification of proxy classes is not supported";
200 return ERR(UNMODIFIABLE_CLASS);
201 }
202
203 // TODO We should check if the class has non-obsoletable methods on the stack
204 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
205 return OK;
206}
207
Alex Lighta01de592016-11-15 10:43:06 -0800208// Moves dex data to an anonymous, read-only mmap'd region.
209std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
210 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800211 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800212 std::string* error_msg) {
213 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800214 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800215 nullptr,
216 data_len,
217 PROT_READ|PROT_WRITE,
218 /*low_4gb*/false,
219 /*reuse*/false,
220 error_msg));
221 if (map == nullptr) {
222 return map;
223 }
224 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800225 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
226 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800227 map->Protect(PROT_READ);
228 return map;
229}
230
Alex Light0e692732017-01-10 15:00:05 -0800231Redefiner::ClassRedefinition::ClassRedefinition(Redefiner* driver,
232 jclass klass,
233 const art::DexFile* redefined_dex_file,
234 const char* class_sig) :
235 driver_(driver), klass_(klass), dex_file_(redefined_dex_file), class_sig_(class_sig) {
236 GetMirrorClass()->MonitorEnter(driver_->self_);
237}
238
239Redefiner::ClassRedefinition::~ClassRedefinition() {
240 if (driver_ != nullptr) {
241 GetMirrorClass()->MonitorExit(driver_->self_);
242 }
243}
244
Alex Light52a2db52017-01-19 23:00:21 +0000245// TODO This should handle doing multiple classes at once so we need to do less cleanup when things
246// go wrong.
Alex Light0e692732017-01-10 15:00:05 -0800247jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
248 art::Runtime* runtime,
249 art::Thread* self,
250 jint class_count,
251 const jvmtiClassDefinition* definitions,
Alex Light52a2db52017-01-19 23:00:21 +0000252 std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800253 if (env == nullptr) {
254 *error_msg = "env was null!";
255 return ERR(INVALID_ENVIRONMENT);
256 } else if (class_count < 0) {
257 *error_msg = "class_count was less then 0";
258 return ERR(ILLEGAL_ARGUMENT);
259 } else if (class_count == 0) {
260 // We don't actually need to do anything. Just return OK.
261 return OK;
262 } else if (definitions == nullptr) {
263 *error_msg = "null definitions!";
264 return ERR(NULL_POINTER);
265 }
266 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
267 // are going to redefine.
268 art::jit::ScopedJitSuspend suspend_jit;
269 // Get shared mutator lock so we can lock all the classes.
270 art::ScopedObjectAccess soa(self);
271 std::vector<Redefiner::ClassRedefinition> redefinitions;
Alex Light52a2db52017-01-19 23:00:21 +0000272 redefinitions.reserve(class_count);
Alex Light0e692732017-01-10 15:00:05 -0800273 Redefiner r(runtime, self, error_msg);
Alex Light52a2db52017-01-19 23:00:21 +0000274 for (jint i = 0; i < class_count; i++) {
275 jvmtiError res = r.AddRedefinition(env, definitions[i]);
276 if (res != OK) {
277 return res;
Alex Light0e692732017-01-10 15:00:05 -0800278 }
279 }
280 return r.Run();
281}
282
Alex Light52a2db52017-01-19 23:00:21 +0000283jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const jvmtiClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800284 std::string original_dex_location;
285 jvmtiError ret = OK;
286 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
287 *error_msg_ = "Unable to get original dex file location!";
288 return ret;
289 }
Alex Lighta6c5e972017-01-13 14:15:41 -0800290 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
Alex Light52a2db52017-01-19 23:00:21 +0000291 def.class_byte_count,
292 def.class_bytes,
Alex Lighta6c5e972017-01-13 14:15:41 -0800293 error_msg_));
294 std::ostringstream os;
Alex Light52a2db52017-01-19 23:00:21 +0000295 char* generic_ptr_unused = nullptr;
296 char* signature_ptr = nullptr;
297 if (env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused) != OK) {
298 *error_msg_ = "A jclass passed in does not seem to be valid";
299 return ERR(INVALID_CLASS);
300 }
301 // These will make sure we deallocate the signature.
302 JvmtiUniquePtr sig_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
303 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Lighta01de592016-11-15 10:43:06 -0800304 if (map.get() == nullptr) {
Alex Light52a2db52017-01-19 23:00:21 +0000305 os << "Failed to create anonymous mmap for modified dex file of class " << signature_ptr
Alex Light0e692732017-01-10 15:00:05 -0800306 << "in dex file " << original_dex_location << " because: " << *error_msg_;
307 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800308 return ERR(OUT_OF_MEMORY);
309 }
310 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800311 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800312 return ERR(INVALID_CLASS_FORMAT);
313 }
314 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
315 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
316 checksum,
317 std::move(map),
318 /*verify*/true,
319 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800320 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800321 if (dex_file.get() == nullptr) {
Alex Light52a2db52017-01-19 23:00:21 +0000322 os << "Unable to load modified dex file for " << signature_ptr << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800323 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800324 return ERR(INVALID_CLASS_FORMAT);
325 }
Alex Light0e692732017-01-10 15:00:05 -0800326 redefinitions_.push_back(
327 Redefiner::ClassRedefinition(this, def.klass, dex_file.release(), signature_ptr));
328 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800329}
330
331// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
332// TODO Make mirror of DexFile and associated types to make this less hellish.
333// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
Alex Light0e692732017-01-10 15:00:05 -0800334art::mirror::Object* Redefiner::ClassRedefinition::FindSourceDexFileObject(
Alex Lighta01de592016-11-15 10:43:06 -0800335 art::Handle<art::mirror::ClassLoader> loader) {
336 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
337 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
338 const char* dex_file_name = "Ldalvik/system/DexFile;";
339 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
340 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
341
Alex Light0e692732017-01-10 15:00:05 -0800342 CHECK(!driver_->self_->IsExceptionPending());
343 art::StackHandleScope<11> hs(driver_->self_);
344 art::ClassLinker* class_linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800345
346 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
347 nullptr));
348 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
Alex Light0e692732017-01-10 15:00:05 -0800349 driver_->self_, dex_class_loader_name, null_loader)));
Alex Lighta01de592016-11-15 10:43:06 -0800350
351 // Get all the ArtFields so we can look in the BaseDexClassLoader
352 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
353 "pathList", dex_path_list_name);
354 CHECK(path_list_field != nullptr);
355
356 art::ArtField* dex_path_list_element_field =
Alex Light0e692732017-01-10 15:00:05 -0800357 class_linker->FindClass(driver_->self_, dex_path_list_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800358 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
359 CHECK(dex_path_list_element_field != nullptr);
360
361 art::ArtField* element_dex_file_field =
Alex Light0e692732017-01-10 15:00:05 -0800362 class_linker->FindClass(driver_->self_, dex_path_list_element_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800363 ->FindDeclaredInstanceField("dexFile", dex_file_name);
364 CHECK(element_dex_file_field != nullptr);
365
366 // Check if loader is a BaseDexClassLoader
367 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
368 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
369 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
370 << "supported class loader type!";
371 return nullptr;
372 }
373 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
374 art::Handle<art::mirror::Object> path_list(
375 hs.NewHandle(path_list_field->GetObject(loader.Get())));
376 CHECK(path_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800377 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800378 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
379 dex_path_list_element_field->GetObject(path_list.Get())->
380 AsObjectArray<art::mirror::Object>()));
Alex Light0e692732017-01-10 15:00:05 -0800381 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800382 CHECK(dex_elements_list.Get() != nullptr);
383 size_t num_elements = dex_elements_list->GetLength();
384 art::MutableHandle<art::mirror::Object> current_element(
385 hs.NewHandle<art::mirror::Object>(nullptr));
386 art::MutableHandle<art::mirror::Object> first_dex_file(
387 hs.NewHandle<art::mirror::Object>(nullptr));
388 // Iterate over the DexPathList$Element to find the right one
389 // TODO Or not ATM just return the first one.
390 for (size_t i = 0; i < num_elements; i++) {
391 current_element.Assign(dex_elements_list->Get(i));
392 CHECK(current_element.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800393 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800394 CHECK(dex_elements_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800395 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(driver_->self_,
Alex Lighta01de592016-11-15 10:43:06 -0800396 dex_path_list_element_name,
397 null_loader));
398 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
399 // comes from but it is more annoying because we would need to find this class. It is not
400 // necessary for proper function since we just need to be in front of the classes old dex file
401 // in the path.
402 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
403 if (first_dex_file.Get() != nullptr) {
404 return first_dex_file.Get();
405 }
406 }
407 return nullptr;
408}
409
Alex Light0e692732017-01-10 15:00:05 -0800410art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
411 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800412}
413
Alex Light0e692732017-01-10 15:00:05 -0800414art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800415 return GetMirrorClass()->GetClassLoader();
416}
417
Alex Light0e692732017-01-10 15:00:05 -0800418art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
419 art::Handle<art::mirror::ClassLoader> loader) {
420 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800421}
422
423// TODO Really wishing I had that mirror of java.lang.DexFile now.
Alex Light0e692732017-01-10 15:00:05 -0800424art::mirror::LongArray* Redefiner::ClassRedefinition::AllocateDexFileCookie(
Alex Lighta01de592016-11-15 10:43:06 -0800425 art::Handle<art::mirror::Object> java_dex_file_obj) {
Alex Light0e692732017-01-10 15:00:05 -0800426 art::StackHandleScope<2> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800427 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
428 // the object is finalized. Since they always point to the same array if mCookie is not null we
429 // just use the mInternalCookie field. We will update one or both of these fields later.
430 // TODO Should I get the class from the classloader or directly?
431 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
432 "mInternalCookie", "Ljava/lang/Object;");
433 // TODO Add check that mCookie is either null or same as mInternalCookie
434 CHECK(internal_cookie_field != nullptr);
435 art::Handle<art::mirror::LongArray> cookie(
436 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
437 // TODO Maybe make these non-fatal.
438 CHECK(cookie.Get() != nullptr);
439 CHECK_GE(cookie->GetLength(), 1);
440 art::Handle<art::mirror::LongArray> new_cookie(
Alex Light0e692732017-01-10 15:00:05 -0800441 hs.NewHandle(art::mirror::LongArray::Alloc(driver_->self_, cookie->GetLength() + 1)));
Alex Lighta01de592016-11-15 10:43:06 -0800442 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800443 driver_->self_->AssertPendingOOMException();
Alex Lighta01de592016-11-15 10:43:06 -0800444 return nullptr;
445 }
446 // Copy the oat-dex field at the start.
447 // TODO Should I clear this field?
448 // TODO This is a really crappy thing here with the first element being different.
449 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
450 new_cookie->SetWithoutChecks<false>(
451 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
452 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
453 return new_cookie.Get();
454}
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 Light0e692732017-01-10 15:00:05 -0800465bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lighta01de592016-11-15 10:43:06 -0800466 /*out*/art::MutableHandle<art::mirror::ClassLoader>* source_class_loader,
467 /*out*/art::MutableHandle<art::mirror::Object>* java_dex_file_obj,
468 /*out*/art::MutableHandle<art::mirror::LongArray>* new_dex_file_cookie,
469 /*out*/art::MutableHandle<art::mirror::DexCache>* new_dex_cache) {
Alex Light0e692732017-01-10 15:00:05 -0800470 art::StackHandleScope<4> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800471 // This shouldn't allocate
472 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
473 if (loader.Get() == nullptr) {
474 // TODO Better error msg.
475 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
476 return false;
477 }
478 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
479 if (dex_file_obj.Get() == nullptr) {
480 // TODO Better error msg.
481 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
482 return false;
483 }
484 art::Handle<art::mirror::LongArray> new_cookie(hs.NewHandle(AllocateDexFileCookie(dex_file_obj)));
485 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800486 driver_->self_->AssertPendingOOMException();
487 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800488 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
489 return false;
490 }
491 art::Handle<art::mirror::DexCache> dex_cache(hs.NewHandle(CreateNewDexCache(loader)));
492 if (dex_cache.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800493 driver_->self_->AssertPendingOOMException();
494 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800495 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
496 return false;
497 }
498 source_class_loader->Assign(loader.Get());
499 java_dex_file_obj->Assign(dex_file_obj.Get());
500 new_dex_file_cookie->Assign(new_cookie.Get());
501 new_dex_cache->Assign(dex_cache.Get());
502 return true;
503}
504
Alex Lightdba61482016-12-21 08:20:29 -0800505struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800506 art::LinearAlloc* allocator;
507 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
508 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800509
Alex Light0e692732017-01-10 15:00:05 -0800510 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800511};
512
Alex Lightdba61482016-12-21 08:20:29 -0800513void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
514 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800515 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
516 data->allocator,
517 data->obsolete_methods,
518 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800519}
520
521// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
522// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800523// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
524void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800525 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
526 art::mirror::ClassExt* ext = art_klass->GetExtData();
527 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800528 CallbackCtx ctx(art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800529 // Add all the declared methods to the map
530 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
531 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800532 // TODO Allow this or check in IsModifiableClass.
533 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800534 }
535 {
Alex Light0e692732017-01-10 15:00:05 -0800536 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800537 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
538 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800539 }
540 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800541}
542
543// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
544// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800545void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800546 art::mirror::Class* art_klass,
547 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
548 int32_t index = 0;
549 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
550 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
551 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
552 ext_data->GetObsoleteDexCaches();
553 int32_t num_method_slots = obsolete_methods->GetLength();
554 // Find the first empty index.
555 for (; index < num_method_slots; index++) {
556 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
557 index, art::kRuntimePointerSize) == nullptr) {
558 break;
559 }
560 }
561 // Make sure we have enough space.
562 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
563 CHECK(obsolete_dex_caches->Get(index) == nullptr);
564 // Fill in the map.
565 for (auto& obs : obsoletes) {
566 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
567 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
568 index++;
569 }
570}
571
572// TODO It should be possible to only deoptimize the specific obsolete methods.
573// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
574// If one of these frames is an obsolete method we have a problem. b/33616143
575// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
576// registers across suspend points.
577// TODO Pending b/33630159
578void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
579 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
580 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
581 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
582}
583
Alex Light0e692732017-01-10 15:00:05 -0800584bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000585 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800586 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000587 // Easy check that only 1 class def is present.
588 if (dex_file_->NumClassDefs() != 1) {
589 RecordFailure(ERR(ILLEGAL_ARGUMENT),
590 StringPrintf("Expected 1 class def in dex file but found %d",
591 dex_file_->NumClassDefs()));
592 return false;
593 }
594 // Get the ClassDef from the new DexFile.
595 // Since the dex file has only a single class def the index is always 0.
596 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
597 // Get the class as it is now.
598 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
599
600 // Check the access flags didn't change.
601 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
602 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
603 "Cannot change modifiers of class by redefinition");
604 return false;
605 }
606
607 // Check class name.
608 // These should have been checked by the dexfile verifier on load.
609 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
610 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
611 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
612 if (!current_class->DescriptorEquals(descriptor)) {
613 std::string storage;
614 RecordFailure(ERR(NAMES_DONT_MATCH),
615 StringPrintf("expected file to contain class called '%s' but found '%s'!",
616 current_class->GetDescriptor(&storage),
617 descriptor));
618 return false;
619 }
620 if (current_class->IsObjectClass()) {
621 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
622 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
623 return false;
624 }
625 } else {
626 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
627 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
628 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
629 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
630 return false;
631 }
632 }
633 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
634 if (interfaces == nullptr) {
635 if (current_class->NumDirectInterfaces() != 0) {
636 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
637 return false;
638 }
639 } else {
640 DCHECK(!current_class->IsProxyClass());
641 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
642 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
643 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
644 return false;
645 }
646 // The order of interfaces is (barely) meaningful so we error if it changes.
647 const art::DexFile& orig_dex_file = current_class->GetDexFile();
648 for (uint32_t i = 0; i < interfaces->Size(); i++) {
649 if (strcmp(
650 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
651 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
652 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
653 "Interfaces changed or re-ordered");
654 return false;
655 }
656 }
657 }
658 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800659 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000660
661 return true;
662}
663
664// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800665bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800666 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800667 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000668
Alex Lighte4a88632017-01-10 07:41:24 -0800669 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
670 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
671 if (res != OK) {
672 RecordFailure(res, err);
673 return false;
674 } else {
675 return true;
676 }
Alex Light460d1b42017-01-10 15:37:17 +0000677}
678
Alex Light0e692732017-01-10 15:00:05 -0800679bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000680 return CheckRedefinable() &&
681 CheckClass() &&
682 CheckSameFields() &&
683 CheckSameMethods();
684}
685
Alex Light0e692732017-01-10 15:00:05 -0800686// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
687// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
688// having to deal with the fact that we need to hold an arbitrary number of references live.
689class RedefinitionDataHolder {
690 public:
691 enum DataSlot : int32_t {
692 kSlotSourceClassLoader = 0,
693 kSlotJavaDexFile = 1,
694 kSlotNewDexFileCookie = 2,
695 kSlotNewDexCache = 3,
696 kSlotMirrorClass = 4,
697
698 // Must be last one.
699 kNumSlots = 5,
700 };
701
702 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
703 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
704 // the passed in handle-scope.
705 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
706 art::Runtime* runtime,
707 art::Thread* self,
708 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
709 arr_(
710 hs->NewHandle(
711 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
712 self,
713 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
714 num_redefinitions * kNumSlots))) {}
715
716 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
717 return arr_.IsNull();
718 }
719
720 // TODO Maybe make an iterable view type to simplify using this.
721 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
722 REQUIRES_SHARED(art::Locks::mutator_lock_) {
723 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
724 }
725 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
726 return GetSlot(klass_index, kSlotJavaDexFile);
727 }
728 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
729 REQUIRES_SHARED(art::Locks::mutator_lock_) {
730 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
731 }
732 art::mirror::DexCache* GetNewDexCache(jint klass_index)
733 REQUIRES_SHARED(art::Locks::mutator_lock_) {
734 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
735 }
736 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
737 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
738 }
739
740 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
741 REQUIRES_SHARED(art::Locks::mutator_lock_) {
742 SetSlot(klass_index, kSlotSourceClassLoader, loader);
743 }
744 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
745 REQUIRES_SHARED(art::Locks::mutator_lock_) {
746 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
747 }
748 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
749 REQUIRES_SHARED(art::Locks::mutator_lock_) {
750 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
751 }
752 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
753 REQUIRES_SHARED(art::Locks::mutator_lock_) {
754 SetSlot(klass_index, kSlotNewDexCache, cache);
755 }
756 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
757 REQUIRES_SHARED(art::Locks::mutator_lock_) {
758 SetSlot(klass_index, kSlotMirrorClass, klass);
759 }
760
761 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
762 return arr_->GetLength() / kNumSlots;
763 }
764
765 private:
766 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
767
768 art::mirror::Object* GetSlot(jint klass_index,
769 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
770 DCHECK_LT(klass_index, Length());
771 return arr_->Get((kNumSlots * klass_index) + slot);
772 }
773
774 void SetSlot(jint klass_index,
775 DataSlot slot,
776 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
777 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
778 DCHECK_LT(klass_index, Length());
779 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
780 }
781
782 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
783};
784
785bool Redefiner::CheckAllRedefinitionAreValid() {
786 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
787 if (!redef.CheckRedefinitionIsValid()) {
788 return false;
789 }
790 }
791 return true;
792}
793
794bool Redefiner::EnsureAllClassAllocationsFinished() {
795 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
796 if (!redef.EnsureClassAllocationsFinished()) {
797 return false;
798 }
799 }
800 return true;
801}
802
803bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
804 int32_t cnt = 0;
805 art::StackHandleScope<4> hs(self_);
806 art::MutableHandle<art::mirror::Object> java_dex_file(hs.NewHandle<art::mirror::Object>(nullptr));
807 art::MutableHandle<art::mirror::ClassLoader> source_class_loader(
808 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
809 art::MutableHandle<art::mirror::LongArray> new_dex_file_cookie(
810 hs.NewHandle<art::mirror::LongArray>(nullptr));
811 art::MutableHandle<art::mirror::DexCache> new_dex_cache(
812 hs.NewHandle<art::mirror::DexCache>(nullptr));
813 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
814 // Reset the out pointers to null
815 source_class_loader.Assign(nullptr);
816 java_dex_file.Assign(nullptr);
817 new_dex_file_cookie.Assign(nullptr);
818 new_dex_cache.Assign(nullptr);
819 // Allocate the data this redefinition requires.
820 if (!redef.FinishRemainingAllocations(&source_class_loader,
821 &java_dex_file,
822 &new_dex_file_cookie,
823 &new_dex_cache)) {
824 return false;
825 }
826 // Save the allocated data into the holder.
827 holder.SetSourceClassLoader(cnt, source_class_loader.Get());
828 holder.SetJavaDexFile(cnt, java_dex_file.Get());
829 holder.SetNewDexFileCookie(cnt, new_dex_file_cookie.Get());
830 holder.SetNewDexCache(cnt, new_dex_cache.Get());
831 holder.SetMirrorClass(cnt, redef.GetMirrorClass());
832 cnt++;
833 }
834 return true;
835}
836
837void Redefiner::ClassRedefinition::ReleaseDexFile() {
838 dex_file_.release();
839}
840
841void Redefiner::ReleaseAllDexFiles() {
842 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
843 redef.ReleaseDexFile();
844 }
845}
846
Alex Lighta01de592016-11-15 10:43:06 -0800847jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800848 art::StackHandleScope<1> hs(self_);
849 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
850 // We will let this be collected after the end of this function.
851 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
852 if (holder.IsNull()) {
853 self_->AssertPendingOOMException();
854 self_->ClearException();
855 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
856 return result_;
857 }
858
Alex Lighta01de592016-11-15 10:43:06 -0800859 // First we just allocate the ClassExt and its fields that we need. These can be updated
860 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
861 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
862 // between allocating them and pausing all threads before we can update them so we need to do a
863 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800864 if (!CheckAllRedefinitionAreValid() ||
865 !EnsureAllClassAllocationsFinished() ||
866 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800867 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
868 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800869 // declared_methods_.length) but would be good to get rid of. All other allocations should be
870 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800871 return result_;
872 }
Alex Light6abd5392017-01-05 17:53:00 -0800873 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
874 // allocating so no deadlocks.
875 art::gc::Heap* heap = runtime_->GetHeap();
876 if (heap->IsGcConcurrentAndMoving()) {
877 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
878 heap->IncrementDisableMovingGC(self_);
879 }
Alex Lighta01de592016-11-15 10:43:06 -0800880 // Do transition to final suspension
881 // TODO We might want to give this its own suspended state!
882 // TODO This isn't right. We need to change state without any chance of suspend ideally!
883 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
884 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800885 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800886 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
887 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
888 // TODO We need to update all debugger MethodIDs so they note the method they point to is
889 // obsolete or implement some other well defined semantics.
890 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light0e692732017-01-10 15:00:05 -0800891 int32_t cnt = 0;
892 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
893 art::mirror::Class* klass = holder.GetMirrorClass(cnt);
894 redef.UpdateJavaDexFile(holder.GetJavaDexFile(cnt), holder.GetNewDexFileCookie(cnt));
895 // TODO Rewrite so we don't do a stack walk for each and every class.
896 redef.FindAndAllocateObsoleteMethods(klass);
897 redef.UpdateClass(klass, holder.GetNewDexCache(cnt));
898 cnt++;
899 }
Alex Lightdba61482016-12-21 08:20:29 -0800900 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
901 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
Alex Light0e692732017-01-10 15:00:05 -0800902 // DexCache. (b/33630159)
Alex Lightdba61482016-12-21 08:20:29 -0800903 // TODO This can fail (leave some methods optimized) near runtime methods (including
904 // quick-to-interpreter transition function).
905 // TODO We probably don't need this at all once we have a way to ensure that the
906 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
907 // stack-walker.
908 EnsureObsoleteMethodsAreDeoptimized();
909 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -0800910 // TODO Shrink the obsolete method maps if possible?
911 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800912 // TODO Put this into a scoped thing.
913 runtime_->GetThreadList()->ResumeAll();
914 // Get back shared mutator lock as expected for return.
915 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800916 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
917 // owns the DexFile and when ownership is transferred.
918 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -0800919 if (heap->IsGcConcurrentAndMoving()) {
920 heap->DecrementDisableMovingGC(self_);
921 }
Alex Lighta01de592016-11-15 10:43:06 -0800922 return OK;
923}
924
Alex Light0e692732017-01-10 15:00:05 -0800925void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
926 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
927 const art::DexFile::ClassDef& class_def) {
928 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800929 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800930 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800931 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800932 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800933 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
934 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
935 art::dex::TypeIndex method_return_idx =
936 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
937 const auto* old_type_list = method.GetParameterTypeList();
938 std::vector<art::dex::TypeIndex> new_type_list;
939 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
940 new_type_list.push_back(
941 dex_file_->GetIndexForTypeId(
942 *dex_file_->FindTypeId(
943 old_dex_file.GetTypeDescriptor(
944 old_dex_file.GetTypeId(
945 old_type_list->GetTypeItem(i).type_idx_)))));
946 }
947 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
948 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000949 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800950 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800951 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
952 *new_name_id,
953 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000954 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800955 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800956 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
957 method.SetDexMethodIndex(dex_method_idx);
958 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800959 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800960 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800961 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -0800962 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -0800963 if (jit != nullptr) {
964 jit->GetCodeCache()->NotifyMethodRedefined(&method);
965 }
Alex Lighta01de592016-11-15 10:43:06 -0800966 }
Alex Light200b9d72016-12-15 11:34:13 -0800967}
968
Alex Light0e692732017-01-10 15:00:05 -0800969void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -0800970 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
971 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
972 for (art::ArtField& field : fields_iter) {
973 std::string declaring_class_name;
974 const art::DexFile::TypeId* new_declaring_id =
975 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
976 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
977 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
978 // TODO Handle error, cleanup.
979 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
980 const art::DexFile::FieldId* new_field_id =
981 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
982 CHECK(new_field_id != nullptr);
983 // We only need to update the index since the other data in the ArtField cannot be updated.
984 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
985 }
986 }
Alex Light200b9d72016-12-15 11:34:13 -0800987}
988
989// Performs updates to class that will allow us to verify it.
Alex Light0e692732017-01-10 15:00:05 -0800990void Redefiner::ClassRedefinition::UpdateClass(art::ObjPtr<art::mirror::Class> mclass,
991 art::ObjPtr<art::mirror::DexCache> new_dex_cache) {
Alex Light52a2db52017-01-19 23:00:21 +0000992 const art::DexFile::ClassDef* class_def = art::OatFile::OatDexFile::FindClassDef(
993 *dex_file_, class_sig_.c_str(), art::ComputeModifiedUtf8Hash(class_sig_.c_str()));
994 DCHECK(class_def != nullptr);
995 UpdateMethods(mclass, new_dex_cache, *class_def);
Alex Light007ada22017-01-10 13:33:56 -0800996 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -0800997
Alex Lighta01de592016-11-15 10:43:06 -0800998 // Update the class fields.
999 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1000 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1001 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light52a2db52017-01-19 23:00:21 +00001002 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(*class_def));
Alex Light0e692732017-01-10 15:00:05 -08001003 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta01de592016-11-15 10:43:06 -08001004}
1005
Alex Light0e692732017-01-10 15:00:05 -08001006void Redefiner::ClassRedefinition::UpdateJavaDexFile(
1007 art::ObjPtr<art::mirror::Object> java_dex_file,
1008 art::ObjPtr<art::mirror::LongArray> new_cookie) {
Alex Lighta01de592016-11-15 10:43:06 -08001009 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1010 "mInternalCookie", "Ljava/lang/Object;");
1011 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1012 "mCookie", "Ljava/lang/Object;");
1013 CHECK(internal_cookie_field != nullptr);
1014 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
1015 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
1016 art::ObjPtr<art::mirror::LongArray> orig_cookie(
1017 cookie_field->GetObject(java_dex_file)->AsLongArray());
1018 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
Alex Lighta01de592016-11-15 10:43:06 -08001019 if (!orig_cookie.IsNull()) {
1020 cookie_field->SetObject<false>(java_dex_file, new_cookie);
1021 }
Alex Lighta01de592016-11-15 10:43:06 -08001022}
1023
1024// This function does all (java) allocations we need to do for the Class being redefined.
1025// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001026bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1027 art::StackHandleScope<2> hs(driver_->self_);
1028 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1029 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001030 if (klass.Get() == nullptr) {
1031 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1032 return false;
1033 }
1034 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001035 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001036 if (ext.Get() == nullptr) {
1037 // No memory. Clear exception (it's not useful) and return error.
1038 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1039 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001040 driver_->self_->AssertPendingOOMException();
1041 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001042 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1043 return false;
1044 }
1045 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1046 // are only modified when all threads (other than the modifying one) are suspended we don't need
1047 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1048 // however, since that can happen at any time.
1049 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1050 // are no obsolete methods.
1051 {
Alex Light0e692732017-01-10 15:00:05 -08001052 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001053 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001054 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001055 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001056 driver_->self_->AssertPendingOOMException();
1057 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001058 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1059 return false;
1060 }
1061 }
1062 return true;
1063}
1064
1065} // namespace openjdkjvmti