blob: d2ddc21cd4ff106ed351cd79084860ad4f496488 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
Alex Lighta7e38d82017-01-19 14:57:28 -080039#include "base/array_slice.h"
Alex Lighta01de592016-11-15 10:43:06 -080040#include "base/logging.h"
Alex Light460d1b42017-01-10 15:37:17 +000041#include "dex_file.h"
42#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080043#include "events-inl.h"
44#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080045#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080046#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080047#include "jit/jit.h"
48#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080049#include "jni_env_ext-inl.h"
50#include "jvmti_allocator.h"
51#include "mirror/class.h"
52#include "mirror/class_ext.h"
53#include "mirror/object.h"
54#include "object_lock.h"
55#include "runtime.h"
56#include "ScopedLocalRef.h"
Alex Light0e692732017-01-10 15:00:05 -080057#include "transform.h"
Alex Lighta01de592016-11-15 10:43:06 -080058
59namespace openjdkjvmti {
60
Andreas Gampe46ee31b2016-12-14 10:11:49 -080061using android::base::StringPrintf;
62
Alex Lightdba61482016-12-21 08:20:29 -080063// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
64// some basic sanity checks that the obsolete method is sane.
65class ObsoleteMethodStackVisitor : public art::StackVisitor {
66 protected:
67 ObsoleteMethodStackVisitor(
68 art::Thread* thread,
69 art::LinearAlloc* allocator,
70 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080071 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -080072 : StackVisitor(thread,
73 /*context*/nullptr,
74 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
75 allocator_(allocator),
76 obsoleted_methods_(obsoleted_methods),
77 obsolete_maps_(obsolete_maps),
Alex Light007ada22017-01-10 13:33:56 -080078 is_runtime_frame_(false) {
Alex Lightdba61482016-12-21 08:20:29 -080079 }
80
81 ~ObsoleteMethodStackVisitor() OVERRIDE {}
82
83 public:
84 // Returns true if we successfully installed obsolete methods on this thread, filling
85 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
86 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080087 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080088 art::Thread* thread,
89 art::LinearAlloc* allocator,
90 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080091 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
92 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080093 ObsoleteMethodStackVisitor visitor(thread,
94 allocator,
95 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080096 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -080097 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -080098 }
99
100 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
101 art::ArtMethod* old_method = GetMethod();
102 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
103 // works through runtime methods.
104 bool prev_was_runtime_frame_ = is_runtime_frame_;
105 is_runtime_frame_ = old_method->IsRuntimeMethod();
106 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
107 // The check below works since when we deoptimize we set shadow frames for all frames until a
108 // native/runtime transition and for those set the return PC to a function that will complete
109 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
110 // below runtime frames cannot be deoptimized at the moment.
111 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
112 // works through runtime methods.
113 // TODO b/33616143
114 if (!IsShadowFrame() && prev_was_runtime_frame_) {
Alex Light007ada22017-01-10 13:33:56 -0800115 LOG(FATAL) << "Deoptimization failed due to runtime method in stack. See b/33616143";
Alex Lightdba61482016-12-21 08:20:29 -0800116 }
117 // We cannot ensure that the right dex file is used in inlined frames so we don't support
118 // redefining them.
119 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
120 // TODO We should really support intrinsic obsolete methods.
121 // TODO We should really support redefining intrinsics.
122 // We don't support intrinsics so check for them here.
123 DCHECK(!old_method->IsIntrinsic());
124 art::ArtMethod* new_obsolete_method = nullptr;
125 auto obsolete_method_pair = obsolete_maps_->find(old_method);
126 if (obsolete_method_pair == obsolete_maps_->end()) {
127 // Create a new Obsolete Method and put it in the list.
128 art::Runtime* runtime = art::Runtime::Current();
129 art::ClassLinker* cl = runtime->GetClassLinker();
130 auto ptr_size = cl->GetImagePointerSize();
131 const size_t method_size = art::ArtMethod::Size(ptr_size);
132 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800133 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
134 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800135 new_obsolete_method = new (method_storage) art::ArtMethod();
136 new_obsolete_method->CopyFrom(old_method, ptr_size);
137 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
138 new_obsolete_method->SetIsObsolete();
139 obsolete_maps_->insert({old_method, new_obsolete_method});
140 // Update JIT Data structures to point to the new method.
141 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
142 if (jit != nullptr) {
143 // Notify the JIT we are making this obsolete method. It will update the jit's internal
144 // structures to keep track of the new obsolete method.
145 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
146 }
147 } else {
148 new_obsolete_method = obsolete_method_pair->second;
149 }
150 DCHECK(new_obsolete_method != nullptr);
151 SetMethod(new_obsolete_method);
152 }
153 return true;
154 }
155
156 private:
157 // The linear allocator we should use to make new methods.
158 art::LinearAlloc* allocator_;
159 // The set of all methods which could be obsoleted.
160 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
161 // A map from the original to the newly allocated obsolete method for frames on this thread. The
162 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
163 // the redefined classes ClassExt by the caller.
164 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800165 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
166 // works through runtime methods.
167 bool is_runtime_frame_;
Alex Lightdba61482016-12-21 08:20:29 -0800168};
169
Alex Lighte4a88632017-01-10 07:41:24 -0800170jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
171 jclass klass,
172 jboolean* is_redefinable) {
173 // TODO Check for the appropriate feature flags once we have enabled them.
174 art::Thread* self = art::Thread::Current();
175 art::ScopedObjectAccess soa(self);
176 art::StackHandleScope<1> hs(self);
177 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
178 if (obj.IsNull()) {
179 return ERR(INVALID_CLASS);
180 }
181 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
182 std::string err_unused;
183 *is_redefinable =
184 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
185 return OK;
186}
187
188jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
189 /*out*/std::string* error_msg) {
190 if (klass->IsPrimitive()) {
191 *error_msg = "Modification of primitive classes is not supported";
192 return ERR(UNMODIFIABLE_CLASS);
193 } else if (klass->IsInterface()) {
194 *error_msg = "Modification of Interface classes is currently not supported";
195 return ERR(UNMODIFIABLE_CLASS);
196 } else if (klass->IsArrayClass()) {
197 *error_msg = "Modification of Array classes is not supported";
198 return ERR(UNMODIFIABLE_CLASS);
199 } else if (klass->IsProxyClass()) {
200 *error_msg = "Modification of proxy classes is not supported";
201 return ERR(UNMODIFIABLE_CLASS);
202 }
203
204 // TODO We should check if the class has non-obsoletable methods on the stack
205 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
206 return OK;
207}
208
Alex Lighta01de592016-11-15 10:43:06 -0800209// Moves dex data to an anonymous, read-only mmap'd region.
210std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
211 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800212 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800213 std::string* error_msg) {
214 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800215 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800216 nullptr,
217 data_len,
218 PROT_READ|PROT_WRITE,
219 /*low_4gb*/false,
220 /*reuse*/false,
221 error_msg));
222 if (map == nullptr) {
223 return map;
224 }
225 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800226 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
227 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800228 map->Protect(PROT_READ);
229 return map;
230}
231
Alex Lighta7e38d82017-01-19 14:57:28 -0800232Redefiner::ClassRedefinition::ClassRedefinition(
233 Redefiner* driver,
234 jclass klass,
235 const art::DexFile* redefined_dex_file,
236 const char* class_sig,
237 art::ArraySlice<const unsigned char> orig_dex_file) :
238 driver_(driver),
239 klass_(klass),
240 dex_file_(redefined_dex_file),
241 class_sig_(class_sig),
242 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800243 GetMirrorClass()->MonitorEnter(driver_->self_);
244}
245
246Redefiner::ClassRedefinition::~ClassRedefinition() {
247 if (driver_ != nullptr) {
248 GetMirrorClass()->MonitorExit(driver_->self_);
249 }
250}
251
Alex Light0e692732017-01-10 15:00:05 -0800252jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
253 art::Runtime* runtime,
254 art::Thread* self,
255 jint class_count,
256 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800257 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800258 if (env == nullptr) {
259 *error_msg = "env was null!";
260 return ERR(INVALID_ENVIRONMENT);
261 } else if (class_count < 0) {
262 *error_msg = "class_count was less then 0";
263 return ERR(ILLEGAL_ARGUMENT);
264 } else if (class_count == 0) {
265 // We don't actually need to do anything. Just return OK.
266 return OK;
267 } else if (definitions == nullptr) {
268 *error_msg = "null definitions!";
269 return ERR(NULL_POINTER);
270 }
Alex Light6ac57502017-01-19 15:05:06 -0800271 std::vector<ArtClassDefinition> def_vector;
272 def_vector.reserve(class_count);
273 for (jint i = 0; i < class_count; i++) {
274 // We make a copy of the class_bytes to pass into the retransformation.
275 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
276 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
277 // to get the passed in bytes.
278 // TODO Implement saving the original bytes.
279 unsigned char* class_bytes_copy = nullptr;
280 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
281 if (res != OK) {
282 return res;
283 }
284 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
285
286 ArtClassDefinition def;
287 def.dex_len = definitions[i].class_byte_count;
288 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
289 // We are definitely modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800290 def.SetModified();
291 def.original_dex_file = art::ArraySlice<const unsigned char>(definitions[i].class_bytes,
292 definitions[i].class_byte_count);
Alex Light6ac57502017-01-19 15:05:06 -0800293 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
294 if (res != OK) {
295 return res;
296 }
297 def_vector.push_back(std::move(def));
298 }
299 // Call all the transformation events.
300 jvmtiError res = Transformer::RetransformClassesDirect(env,
301 self,
302 &def_vector);
303 if (res != OK) {
304 // Something went wrong with transformation!
305 return res;
306 }
307 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
308}
309
310jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
311 art::Runtime* runtime,
312 art::Thread* self,
313 const std::vector<ArtClassDefinition>& definitions,
314 std::string* error_msg) {
315 DCHECK(env != nullptr);
316 if (definitions.size() == 0) {
317 // We don't actually need to do anything. Just return OK.
318 return OK;
319 }
Alex Light0e692732017-01-10 15:00:05 -0800320 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
321 // are going to redefine.
322 art::jit::ScopedJitSuspend suspend_jit;
323 // Get shared mutator lock so we can lock all the classes.
324 art::ScopedObjectAccess soa(self);
Alex Light0e692732017-01-10 15:00:05 -0800325 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800326 for (const ArtClassDefinition& def : definitions) {
327 // Only try to transform classes that have been modified.
Alex Lighta7e38d82017-01-19 14:57:28 -0800328 if (def.IsModified(self)) {
Alex Light6ac57502017-01-19 15:05:06 -0800329 jvmtiError res = r.AddRedefinition(env, def);
330 if (res != OK) {
331 return res;
332 }
Alex Light0e692732017-01-10 15:00:05 -0800333 }
334 }
335 return r.Run();
336}
337
Alex Light6ac57502017-01-19 15:05:06 -0800338jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800339 std::string original_dex_location;
340 jvmtiError ret = OK;
341 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
342 *error_msg_ = "Unable to get original dex file location!";
343 return ret;
344 }
Alex Light52a2db52017-01-19 23:00:21 +0000345 char* generic_ptr_unused = nullptr;
346 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800347 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
348 *error_msg_ = "Unable to get class signature!";
349 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000350 }
Alex Light52a2db52017-01-19 23:00:21 +0000351 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800352 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
353 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
354 def.dex_len,
355 def.dex_data.get(),
356 error_msg_));
357 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800358 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800359 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800360 << "in dex file " << original_dex_location << " because: " << *error_msg_;
361 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800362 return ERR(OUT_OF_MEMORY);
363 }
364 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800365 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800366 return ERR(INVALID_CLASS_FORMAT);
367 }
368 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
369 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
370 checksum,
371 std::move(map),
372 /*verify*/true,
373 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800374 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800375 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800376 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800377 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800378 return ERR(INVALID_CLASS_FORMAT);
379 }
Alex Light0e692732017-01-10 15:00:05 -0800380 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800381 Redefiner::ClassRedefinition(this,
382 def.klass,
383 dex_file.release(),
384 signature_ptr,
385 def.original_dex_file));
Alex Light0e692732017-01-10 15:00:05 -0800386 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800387}
388
389// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
390// TODO Make mirror of DexFile and associated types to make this less hellish.
391// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
Alex Light0e692732017-01-10 15:00:05 -0800392art::mirror::Object* Redefiner::ClassRedefinition::FindSourceDexFileObject(
Alex Lighta01de592016-11-15 10:43:06 -0800393 art::Handle<art::mirror::ClassLoader> loader) {
394 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
395 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
396 const char* dex_file_name = "Ldalvik/system/DexFile;";
397 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
398 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
399
Alex Light0e692732017-01-10 15:00:05 -0800400 CHECK(!driver_->self_->IsExceptionPending());
401 art::StackHandleScope<11> hs(driver_->self_);
402 art::ClassLinker* class_linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800403
404 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
405 nullptr));
406 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
Alex Light0e692732017-01-10 15:00:05 -0800407 driver_->self_, dex_class_loader_name, null_loader)));
Alex Lighta01de592016-11-15 10:43:06 -0800408
409 // Get all the ArtFields so we can look in the BaseDexClassLoader
410 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
411 "pathList", dex_path_list_name);
412 CHECK(path_list_field != nullptr);
413
414 art::ArtField* dex_path_list_element_field =
Alex Light0e692732017-01-10 15:00:05 -0800415 class_linker->FindClass(driver_->self_, dex_path_list_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800416 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
417 CHECK(dex_path_list_element_field != nullptr);
418
419 art::ArtField* element_dex_file_field =
Alex Light0e692732017-01-10 15:00:05 -0800420 class_linker->FindClass(driver_->self_, dex_path_list_element_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800421 ->FindDeclaredInstanceField("dexFile", dex_file_name);
422 CHECK(element_dex_file_field != nullptr);
423
424 // Check if loader is a BaseDexClassLoader
425 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
426 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
427 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
428 << "supported class loader type!";
429 return nullptr;
430 }
431 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
432 art::Handle<art::mirror::Object> path_list(
433 hs.NewHandle(path_list_field->GetObject(loader.Get())));
434 CHECK(path_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800435 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800436 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
437 dex_path_list_element_field->GetObject(path_list.Get())->
438 AsObjectArray<art::mirror::Object>()));
Alex Light0e692732017-01-10 15:00:05 -0800439 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800440 CHECK(dex_elements_list.Get() != nullptr);
441 size_t num_elements = dex_elements_list->GetLength();
442 art::MutableHandle<art::mirror::Object> current_element(
443 hs.NewHandle<art::mirror::Object>(nullptr));
444 art::MutableHandle<art::mirror::Object> first_dex_file(
445 hs.NewHandle<art::mirror::Object>(nullptr));
446 // Iterate over the DexPathList$Element to find the right one
447 // TODO Or not ATM just return the first one.
448 for (size_t i = 0; i < num_elements; i++) {
449 current_element.Assign(dex_elements_list->Get(i));
450 CHECK(current_element.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800451 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800452 CHECK(dex_elements_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800453 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(driver_->self_,
Alex Lighta01de592016-11-15 10:43:06 -0800454 dex_path_list_element_name,
455 null_loader));
456 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
457 // comes from but it is more annoying because we would need to find this class. It is not
458 // necessary for proper function since we just need to be in front of the classes old dex file
459 // in the path.
460 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
461 if (first_dex_file.Get() != nullptr) {
462 return first_dex_file.Get();
463 }
464 }
465 return nullptr;
466}
467
Alex Light0e692732017-01-10 15:00:05 -0800468art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
469 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800470}
471
Alex Light0e692732017-01-10 15:00:05 -0800472art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800473 return GetMirrorClass()->GetClassLoader();
474}
475
Alex Light0e692732017-01-10 15:00:05 -0800476art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
477 art::Handle<art::mirror::ClassLoader> loader) {
478 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800479}
480
481// TODO Really wishing I had that mirror of java.lang.DexFile now.
Alex Light0e692732017-01-10 15:00:05 -0800482art::mirror::LongArray* Redefiner::ClassRedefinition::AllocateDexFileCookie(
Alex Lighta01de592016-11-15 10:43:06 -0800483 art::Handle<art::mirror::Object> java_dex_file_obj) {
Alex Light0e692732017-01-10 15:00:05 -0800484 art::StackHandleScope<2> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800485 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
486 // the object is finalized. Since they always point to the same array if mCookie is not null we
487 // just use the mInternalCookie field. We will update one or both of these fields later.
488 // TODO Should I get the class from the classloader or directly?
489 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
490 "mInternalCookie", "Ljava/lang/Object;");
491 // TODO Add check that mCookie is either null or same as mInternalCookie
492 CHECK(internal_cookie_field != nullptr);
493 art::Handle<art::mirror::LongArray> cookie(
494 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
495 // TODO Maybe make these non-fatal.
496 CHECK(cookie.Get() != nullptr);
497 CHECK_GE(cookie->GetLength(), 1);
498 art::Handle<art::mirror::LongArray> new_cookie(
Alex Light0e692732017-01-10 15:00:05 -0800499 hs.NewHandle(art::mirror::LongArray::Alloc(driver_->self_, cookie->GetLength() + 1)));
Alex Lighta01de592016-11-15 10:43:06 -0800500 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800501 driver_->self_->AssertPendingOOMException();
Alex Lighta01de592016-11-15 10:43:06 -0800502 return nullptr;
503 }
504 // Copy the oat-dex field at the start.
505 // TODO Should I clear this field?
506 // TODO This is a really crappy thing here with the first element being different.
507 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
508 new_cookie->SetWithoutChecks<false>(
509 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
510 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
511 return new_cookie.Get();
512}
513
Alex Light0e692732017-01-10 15:00:05 -0800514void Redefiner::RecordFailure(jvmtiError result,
515 const std::string& class_sig,
516 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800517 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800518 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800519 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800520 result_ = result;
521}
522
Alex Lighta7e38d82017-01-19 14:57:28 -0800523art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
524 // If we have been specifically given a new set of bytes use that
525 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800526 return art::mirror::ByteArray::AllocateAndFill(
527 driver_->self_,
528 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)),
529 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800530 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800531
532 // See if we already have one set.
533 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
534 if (!ext.IsNull()) {
535 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
536 if (!old_original_bytes.IsNull()) {
537 // We do. Use it.
538 return old_original_bytes.Ptr();
539 }
Alex Lighta01de592016-11-15 10:43:06 -0800540 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800541
542 // Copy the current dex_file
543 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
544 // TODO Handle this or make it so it cannot happen.
545 if (current_dex_file.NumClassDefs() != 1) {
546 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
547 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800548 }
Alex Light440b5d92017-01-24 15:32:25 -0800549 return art::mirror::ByteArray::AllocateAndFill(
550 driver_->self_,
551 reinterpret_cast<const signed char*>(current_dex_file.Begin()),
552 current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800553}
554
Alex Lightdba61482016-12-21 08:20:29 -0800555struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800556 art::LinearAlloc* allocator;
557 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
558 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800559
Alex Light0e692732017-01-10 15:00:05 -0800560 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800561};
562
Alex Lightdba61482016-12-21 08:20:29 -0800563void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
564 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800565 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
566 data->allocator,
567 data->obsolete_methods,
568 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800569}
570
571// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
572// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800573// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
574void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800575 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
576 art::mirror::ClassExt* ext = art_klass->GetExtData();
577 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800578 CallbackCtx ctx(art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800579 // Add all the declared methods to the map
580 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
581 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800582 // TODO Allow this or check in IsModifiableClass.
583 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800584 }
585 {
Alex Light0e692732017-01-10 15:00:05 -0800586 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800587 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
588 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800589 }
590 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800591}
592
593// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
594// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800595void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800596 art::mirror::Class* art_klass,
597 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
598 int32_t index = 0;
599 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
600 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
601 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
602 ext_data->GetObsoleteDexCaches();
603 int32_t num_method_slots = obsolete_methods->GetLength();
604 // Find the first empty index.
605 for (; index < num_method_slots; index++) {
606 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
607 index, art::kRuntimePointerSize) == nullptr) {
608 break;
609 }
610 }
611 // Make sure we have enough space.
612 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
613 CHECK(obsolete_dex_caches->Get(index) == nullptr);
614 // Fill in the map.
615 for (auto& obs : obsoletes) {
616 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
617 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
618 index++;
619 }
620}
621
622// TODO It should be possible to only deoptimize the specific obsolete methods.
623// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
624// If one of these frames is an obsolete method we have a problem. b/33616143
625// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
626// registers across suspend points.
627// TODO Pending b/33630159
628void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
629 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
630 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
631 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
632}
633
Alex Light0e692732017-01-10 15:00:05 -0800634bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000635 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800636 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000637 // Easy check that only 1 class def is present.
638 if (dex_file_->NumClassDefs() != 1) {
639 RecordFailure(ERR(ILLEGAL_ARGUMENT),
640 StringPrintf("Expected 1 class def in dex file but found %d",
641 dex_file_->NumClassDefs()));
642 return false;
643 }
644 // Get the ClassDef from the new DexFile.
645 // Since the dex file has only a single class def the index is always 0.
646 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
647 // Get the class as it is now.
648 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
649
650 // Check the access flags didn't change.
651 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
652 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
653 "Cannot change modifiers of class by redefinition");
654 return false;
655 }
656
657 // Check class name.
658 // These should have been checked by the dexfile verifier on load.
659 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
660 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
661 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
662 if (!current_class->DescriptorEquals(descriptor)) {
663 std::string storage;
664 RecordFailure(ERR(NAMES_DONT_MATCH),
665 StringPrintf("expected file to contain class called '%s' but found '%s'!",
666 current_class->GetDescriptor(&storage),
667 descriptor));
668 return false;
669 }
670 if (current_class->IsObjectClass()) {
671 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
672 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
673 return false;
674 }
675 } else {
676 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
677 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
678 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
679 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
680 return false;
681 }
682 }
683 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
684 if (interfaces == nullptr) {
685 if (current_class->NumDirectInterfaces() != 0) {
686 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
687 return false;
688 }
689 } else {
690 DCHECK(!current_class->IsProxyClass());
691 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
692 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
693 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
694 return false;
695 }
696 // The order of interfaces is (barely) meaningful so we error if it changes.
697 const art::DexFile& orig_dex_file = current_class->GetDexFile();
698 for (uint32_t i = 0; i < interfaces->Size(); i++) {
699 if (strcmp(
700 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
701 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
702 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
703 "Interfaces changed or re-ordered");
704 return false;
705 }
706 }
707 }
708 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800709 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000710
711 return true;
712}
713
714// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800715bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800716 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800717 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000718
Alex Lighte4a88632017-01-10 07:41:24 -0800719 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
720 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
721 if (res != OK) {
722 RecordFailure(res, err);
723 return false;
724 } else {
725 return true;
726 }
Alex Light460d1b42017-01-10 15:37:17 +0000727}
728
Alex Light0e692732017-01-10 15:00:05 -0800729bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000730 return CheckRedefinable() &&
731 CheckClass() &&
732 CheckSameFields() &&
733 CheckSameMethods();
734}
735
Alex Light0e692732017-01-10 15:00:05 -0800736// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
737// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
738// having to deal with the fact that we need to hold an arbitrary number of references live.
739class RedefinitionDataHolder {
740 public:
741 enum DataSlot : int32_t {
742 kSlotSourceClassLoader = 0,
743 kSlotJavaDexFile = 1,
744 kSlotNewDexFileCookie = 2,
745 kSlotNewDexCache = 3,
746 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800747 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800748
749 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800750 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800751 };
752
753 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
754 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
755 // the passed in handle-scope.
756 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
757 art::Runtime* runtime,
758 art::Thread* self,
759 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
760 arr_(
761 hs->NewHandle(
762 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
763 self,
764 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
765 num_redefinitions * kNumSlots))) {}
766
767 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
768 return arr_.IsNull();
769 }
770
771 // TODO Maybe make an iterable view type to simplify using this.
772 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
773 REQUIRES_SHARED(art::Locks::mutator_lock_) {
774 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
775 }
776 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
777 return GetSlot(klass_index, kSlotJavaDexFile);
778 }
779 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
780 REQUIRES_SHARED(art::Locks::mutator_lock_) {
781 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
782 }
783 art::mirror::DexCache* GetNewDexCache(jint klass_index)
784 REQUIRES_SHARED(art::Locks::mutator_lock_) {
785 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
786 }
787 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
788 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
789 }
790
Alex Lighta7e38d82017-01-19 14:57:28 -0800791 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index)
792 REQUIRES_SHARED(art::Locks::mutator_lock_) {
793 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
794 }
795
Alex Light0e692732017-01-10 15:00:05 -0800796 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
797 REQUIRES_SHARED(art::Locks::mutator_lock_) {
798 SetSlot(klass_index, kSlotSourceClassLoader, loader);
799 }
800 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
801 REQUIRES_SHARED(art::Locks::mutator_lock_) {
802 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
803 }
804 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
805 REQUIRES_SHARED(art::Locks::mutator_lock_) {
806 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
807 }
808 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
809 REQUIRES_SHARED(art::Locks::mutator_lock_) {
810 SetSlot(klass_index, kSlotNewDexCache, cache);
811 }
812 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
813 REQUIRES_SHARED(art::Locks::mutator_lock_) {
814 SetSlot(klass_index, kSlotMirrorClass, klass);
815 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800816 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
817 REQUIRES_SHARED(art::Locks::mutator_lock_) {
818 SetSlot(klass_index, kSlotOrigDexFile, bytes);
819 }
Alex Light0e692732017-01-10 15:00:05 -0800820
821 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
822 return arr_->GetLength() / kNumSlots;
823 }
824
825 private:
826 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
827
828 art::mirror::Object* GetSlot(jint klass_index,
829 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
830 DCHECK_LT(klass_index, Length());
831 return arr_->Get((kNumSlots * klass_index) + slot);
832 }
833
834 void SetSlot(jint klass_index,
835 DataSlot slot,
836 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
837 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
838 DCHECK_LT(klass_index, Length());
839 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
840 }
841
842 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
843};
844
Alex Lighta7e38d82017-01-19 14:57:28 -0800845bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
846 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
847 art::StackHandleScope<2> hs(driver_->self_);
848 holder->SetMirrorClass(klass_index, GetMirrorClass());
849 // This shouldn't allocate
850 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
851 holder->SetSourceClassLoader(klass_index, loader.Get());
852 if (loader.Get() == nullptr) {
853 // TODO Better error msg.
854 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
855 return false;
856 }
857 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
858 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
859 if (dex_file_obj.Get() == nullptr) {
860 // TODO Better error msg.
861 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
862 return false;
863 }
864 holder->SetNewDexFileCookie(klass_index, AllocateDexFileCookie(dex_file_obj));
865 if (holder->GetNewDexFileCookie(klass_index) == nullptr) {
866 driver_->self_->AssertPendingOOMException();
867 driver_->self_->ClearException();
868 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
869 return false;
870 }
871 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
872 if (holder->GetNewDexCache(klass_index) == nullptr) {
873 driver_->self_->AssertPendingOOMException();
874 driver_->self_->ClearException();
875 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
876 return false;
877 }
878
879 // We won't always need to set this field.
880 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
881 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
882 driver_->self_->AssertPendingOOMException();
883 driver_->self_->ClearException();
884 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
885 return false;
886 }
887 return true;
888}
889
Alex Light0e692732017-01-10 15:00:05 -0800890bool Redefiner::CheckAllRedefinitionAreValid() {
891 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
892 if (!redef.CheckRedefinitionIsValid()) {
893 return false;
894 }
895 }
896 return true;
897}
898
899bool Redefiner::EnsureAllClassAllocationsFinished() {
900 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
901 if (!redef.EnsureClassAllocationsFinished()) {
902 return false;
903 }
904 }
905 return true;
906}
907
908bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
909 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -0800910 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -0800911 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -0800912 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -0800913 return false;
914 }
Alex Light0e692732017-01-10 15:00:05 -0800915 cnt++;
916 }
917 return true;
918}
919
920void Redefiner::ClassRedefinition::ReleaseDexFile() {
921 dex_file_.release();
922}
923
924void Redefiner::ReleaseAllDexFiles() {
925 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
926 redef.ReleaseDexFile();
927 }
928}
929
Alex Lighta01de592016-11-15 10:43:06 -0800930jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800931 art::StackHandleScope<1> hs(self_);
932 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
933 // We will let this be collected after the end of this function.
934 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
935 if (holder.IsNull()) {
936 self_->AssertPendingOOMException();
937 self_->ClearException();
938 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
939 return result_;
940 }
941
Alex Lighta01de592016-11-15 10:43:06 -0800942 // First we just allocate the ClassExt and its fields that we need. These can be updated
943 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
944 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
945 // between allocating them and pausing all threads before we can update them so we need to do a
946 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800947 if (!CheckAllRedefinitionAreValid() ||
948 !EnsureAllClassAllocationsFinished() ||
949 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800950 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
951 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800952 // declared_methods_.length) but would be good to get rid of. All other allocations should be
953 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800954 return result_;
955 }
Alex Light6abd5392017-01-05 17:53:00 -0800956 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
957 // allocating so no deadlocks.
958 art::gc::Heap* heap = runtime_->GetHeap();
959 if (heap->IsGcConcurrentAndMoving()) {
960 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
961 heap->IncrementDisableMovingGC(self_);
962 }
Alex Lighta01de592016-11-15 10:43:06 -0800963 // Do transition to final suspension
964 // TODO We might want to give this its own suspended state!
965 // TODO This isn't right. We need to change state without any chance of suspend ideally!
966 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
967 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800968 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800969 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
970 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
971 // TODO We need to update all debugger MethodIDs so they note the method they point to is
972 // obsolete or implement some other well defined semantics.
973 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light0e692732017-01-10 15:00:05 -0800974 int32_t cnt = 0;
975 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
976 art::mirror::Class* klass = holder.GetMirrorClass(cnt);
977 redef.UpdateJavaDexFile(holder.GetJavaDexFile(cnt), holder.GetNewDexFileCookie(cnt));
978 // TODO Rewrite so we don't do a stack walk for each and every class.
979 redef.FindAndAllocateObsoleteMethods(klass);
Alex Lighta7e38d82017-01-19 14:57:28 -0800980 redef.UpdateClass(klass, holder.GetNewDexCache(cnt), holder.GetOriginalDexFileBytes(cnt));
Alex Light0e692732017-01-10 15:00:05 -0800981 cnt++;
982 }
Alex Lightdba61482016-12-21 08:20:29 -0800983 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
984 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
Alex Light0e692732017-01-10 15:00:05 -0800985 // DexCache. (b/33630159)
Alex Lightdba61482016-12-21 08:20:29 -0800986 // TODO This can fail (leave some methods optimized) near runtime methods (including
987 // quick-to-interpreter transition function).
988 // TODO We probably don't need this at all once we have a way to ensure that the
989 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
990 // stack-walker.
991 EnsureObsoleteMethodsAreDeoptimized();
992 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -0800993 // TODO Shrink the obsolete method maps if possible?
994 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800995 // TODO Put this into a scoped thing.
996 runtime_->GetThreadList()->ResumeAll();
997 // Get back shared mutator lock as expected for return.
998 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800999 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1000 // owns the DexFile and when ownership is transferred.
1001 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001002 if (heap->IsGcConcurrentAndMoving()) {
1003 heap->DecrementDisableMovingGC(self_);
1004 }
Alex Lighta01de592016-11-15 10:43:06 -08001005 return OK;
1006}
1007
Alex Light0e692732017-01-10 15:00:05 -08001008void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1009 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1010 const art::DexFile::ClassDef& class_def) {
1011 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001012 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001013 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001014 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001015 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001016 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1017 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1018 art::dex::TypeIndex method_return_idx =
1019 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1020 const auto* old_type_list = method.GetParameterTypeList();
1021 std::vector<art::dex::TypeIndex> new_type_list;
1022 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1023 new_type_list.push_back(
1024 dex_file_->GetIndexForTypeId(
1025 *dex_file_->FindTypeId(
1026 old_dex_file.GetTypeDescriptor(
1027 old_dex_file.GetTypeId(
1028 old_type_list->GetTypeItem(i).type_idx_)))));
1029 }
1030 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1031 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001032 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001033 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001034 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1035 *new_name_id,
1036 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001037 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001038 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001039 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1040 method.SetDexMethodIndex(dex_method_idx);
1041 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001042 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001043 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -08001044 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001045 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001046 if (jit != nullptr) {
1047 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1048 }
Alex Lighta01de592016-11-15 10:43:06 -08001049 }
Alex Light200b9d72016-12-15 11:34:13 -08001050}
1051
Alex Light0e692732017-01-10 15:00:05 -08001052void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001053 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1054 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1055 for (art::ArtField& field : fields_iter) {
1056 std::string declaring_class_name;
1057 const art::DexFile::TypeId* new_declaring_id =
1058 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1059 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1060 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1061 // TODO Handle error, cleanup.
1062 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1063 const art::DexFile::FieldId* new_field_id =
1064 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1065 CHECK(new_field_id != nullptr);
1066 // We only need to update the index since the other data in the ArtField cannot be updated.
1067 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1068 }
1069 }
Alex Light200b9d72016-12-15 11:34:13 -08001070}
1071
1072// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001073void Redefiner::ClassRedefinition::UpdateClass(
1074 art::ObjPtr<art::mirror::Class> mclass,
1075 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1076 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001077 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1078 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1079 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001080 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001081
Alex Lighta01de592016-11-15 10:43:06 -08001082 // Update the class fields.
1083 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1084 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1085 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001086 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001087 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001088 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1089 CHECK(!ext.IsNull());
1090 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001091}
1092
Alex Light0e692732017-01-10 15:00:05 -08001093void Redefiner::ClassRedefinition::UpdateJavaDexFile(
1094 art::ObjPtr<art::mirror::Object> java_dex_file,
1095 art::ObjPtr<art::mirror::LongArray> new_cookie) {
Alex Lighta01de592016-11-15 10:43:06 -08001096 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1097 "mInternalCookie", "Ljava/lang/Object;");
1098 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1099 "mCookie", "Ljava/lang/Object;");
1100 CHECK(internal_cookie_field != nullptr);
1101 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
1102 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
1103 art::ObjPtr<art::mirror::LongArray> orig_cookie(
1104 cookie_field->GetObject(java_dex_file)->AsLongArray());
1105 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
Alex Lighta01de592016-11-15 10:43:06 -08001106 if (!orig_cookie.IsNull()) {
1107 cookie_field->SetObject<false>(java_dex_file, new_cookie);
1108 }
Alex Lighta01de592016-11-15 10:43:06 -08001109}
1110
1111// This function does all (java) allocations we need to do for the Class being redefined.
1112// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001113bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1114 art::StackHandleScope<2> hs(driver_->self_);
1115 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1116 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001117 if (klass.Get() == nullptr) {
1118 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1119 return false;
1120 }
1121 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001122 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001123 if (ext.Get() == nullptr) {
1124 // No memory. Clear exception (it's not useful) and return error.
1125 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1126 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001127 driver_->self_->AssertPendingOOMException();
1128 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001129 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1130 return false;
1131 }
1132 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1133 // are only modified when all threads (other than the modifying one) are suspended we don't need
1134 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1135 // however, since that can happen at any time.
1136 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1137 // are no obsolete methods.
1138 {
Alex Light0e692732017-01-10 15:00:05 -08001139 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001140 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001141 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001142 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001143 driver_->self_->AssertPendingOOMException();
1144 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001145 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1146 return false;
1147 }
1148 }
1149 return true;
1150}
1151
1152} // namespace openjdkjvmti