blob: 34efc502e1b93e35a96cc7b167186575a3624dfe [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 -0800523// Allocates a ByteArray big enough to store the given number of bytes and copies them from the
524// bytes pointer.
525static art::mirror::ByteArray* AllocateAndFillBytes(art::Thread* self,
526 const uint8_t* bytes,
527 int32_t num_bytes)
528 REQUIRES_SHARED(art::Locks::mutator_lock_) {
529 art::StackHandleScope<1> hs(self);
530 art::Handle<art::mirror::ByteArray> arr(hs.NewHandle(
531 art::mirror::ByteArray::Alloc(self, num_bytes)));
532 if (!arr.IsNull()) {
533 // Copy it in. Just skip if it's null
534 memcpy(arr->GetData(), bytes, num_bytes);
Alex Lighta01de592016-11-15 10:43:06 -0800535 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800536 return arr.Get();
537}
538
539art::mirror::ByteArray* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFileBytes() {
540 // If we have been specifically given a new set of bytes use that
541 if (original_dex_file_.size() != 0) {
542 return AllocateAndFillBytes(driver_->self_,
543 &original_dex_file_.At(0),
544 original_dex_file_.size());
Alex Lighta01de592016-11-15 10:43:06 -0800545 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800546
547 // See if we already have one set.
548 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
549 if (!ext.IsNull()) {
550 art::ObjPtr<art::mirror::ByteArray> old_original_bytes(ext->GetOriginalDexFileBytes());
551 if (!old_original_bytes.IsNull()) {
552 // We do. Use it.
553 return old_original_bytes.Ptr();
554 }
Alex Lighta01de592016-11-15 10:43:06 -0800555 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800556
557 // Copy the current dex_file
558 const art::DexFile& current_dex_file = GetMirrorClass()->GetDexFile();
559 // TODO Handle this or make it so it cannot happen.
560 if (current_dex_file.NumClassDefs() != 1) {
561 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
562 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800563 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800564 return AllocateAndFillBytes(driver_->self_, current_dex_file.Begin(), current_dex_file.Size());
Alex Lighta01de592016-11-15 10:43:06 -0800565}
566
Alex Lightdba61482016-12-21 08:20:29 -0800567struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800568 art::LinearAlloc* allocator;
569 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
570 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800571
Alex Light0e692732017-01-10 15:00:05 -0800572 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800573};
574
Alex Lightdba61482016-12-21 08:20:29 -0800575void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
576 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800577 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
578 data->allocator,
579 data->obsolete_methods,
580 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800581}
582
583// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
584// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800585// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
586void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800587 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
588 art::mirror::ClassExt* ext = art_klass->GetExtData();
589 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800590 CallbackCtx ctx(art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800591 // Add all the declared methods to the map
592 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
593 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800594 // TODO Allow this or check in IsModifiableClass.
595 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800596 }
597 {
Alex Light0e692732017-01-10 15:00:05 -0800598 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800599 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
600 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800601 }
602 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800603}
604
605// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
606// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800607void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800608 art::mirror::Class* art_klass,
609 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
610 int32_t index = 0;
611 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
612 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
613 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
614 ext_data->GetObsoleteDexCaches();
615 int32_t num_method_slots = obsolete_methods->GetLength();
616 // Find the first empty index.
617 for (; index < num_method_slots; index++) {
618 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
619 index, art::kRuntimePointerSize) == nullptr) {
620 break;
621 }
622 }
623 // Make sure we have enough space.
624 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
625 CHECK(obsolete_dex_caches->Get(index) == nullptr);
626 // Fill in the map.
627 for (auto& obs : obsoletes) {
628 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
629 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
630 index++;
631 }
632}
633
634// TODO It should be possible to only deoptimize the specific obsolete methods.
635// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
636// If one of these frames is an obsolete method we have a problem. b/33616143
637// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
638// registers across suspend points.
639// TODO Pending b/33630159
640void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
641 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
642 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
643 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
644}
645
Alex Light0e692732017-01-10 15:00:05 -0800646bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000647 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800648 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000649 // Easy check that only 1 class def is present.
650 if (dex_file_->NumClassDefs() != 1) {
651 RecordFailure(ERR(ILLEGAL_ARGUMENT),
652 StringPrintf("Expected 1 class def in dex file but found %d",
653 dex_file_->NumClassDefs()));
654 return false;
655 }
656 // Get the ClassDef from the new DexFile.
657 // Since the dex file has only a single class def the index is always 0.
658 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
659 // Get the class as it is now.
660 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
661
662 // Check the access flags didn't change.
663 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
664 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
665 "Cannot change modifiers of class by redefinition");
666 return false;
667 }
668
669 // Check class name.
670 // These should have been checked by the dexfile verifier on load.
671 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
672 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
673 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
674 if (!current_class->DescriptorEquals(descriptor)) {
675 std::string storage;
676 RecordFailure(ERR(NAMES_DONT_MATCH),
677 StringPrintf("expected file to contain class called '%s' but found '%s'!",
678 current_class->GetDescriptor(&storage),
679 descriptor));
680 return false;
681 }
682 if (current_class->IsObjectClass()) {
683 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
684 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
685 return false;
686 }
687 } else {
688 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
689 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
690 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
691 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
692 return false;
693 }
694 }
695 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
696 if (interfaces == nullptr) {
697 if (current_class->NumDirectInterfaces() != 0) {
698 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
699 return false;
700 }
701 } else {
702 DCHECK(!current_class->IsProxyClass());
703 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
704 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
705 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
706 return false;
707 }
708 // The order of interfaces is (barely) meaningful so we error if it changes.
709 const art::DexFile& orig_dex_file = current_class->GetDexFile();
710 for (uint32_t i = 0; i < interfaces->Size(); i++) {
711 if (strcmp(
712 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
713 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
714 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
715 "Interfaces changed or re-ordered");
716 return false;
717 }
718 }
719 }
720 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800721 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000722
723 return true;
724}
725
726// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800727bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800728 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800729 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000730
Alex Lighte4a88632017-01-10 07:41:24 -0800731 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
732 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
733 if (res != OK) {
734 RecordFailure(res, err);
735 return false;
736 } else {
737 return true;
738 }
Alex Light460d1b42017-01-10 15:37:17 +0000739}
740
Alex Light0e692732017-01-10 15:00:05 -0800741bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000742 return CheckRedefinable() &&
743 CheckClass() &&
744 CheckSameFields() &&
745 CheckSameMethods();
746}
747
Alex Light0e692732017-01-10 15:00:05 -0800748// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
749// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
750// having to deal with the fact that we need to hold an arbitrary number of references live.
751class RedefinitionDataHolder {
752 public:
753 enum DataSlot : int32_t {
754 kSlotSourceClassLoader = 0,
755 kSlotJavaDexFile = 1,
756 kSlotNewDexFileCookie = 2,
757 kSlotNewDexCache = 3,
758 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800759 kSlotOrigDexFile = 5,
Alex Light0e692732017-01-10 15:00:05 -0800760
761 // Must be last one.
Alex Lighta7e38d82017-01-19 14:57:28 -0800762 kNumSlots = 6,
Alex Light0e692732017-01-10 15:00:05 -0800763 };
764
765 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
766 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
767 // the passed in handle-scope.
768 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
769 art::Runtime* runtime,
770 art::Thread* self,
771 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
772 arr_(
773 hs->NewHandle(
774 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
775 self,
776 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
777 num_redefinitions * kNumSlots))) {}
778
779 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
780 return arr_.IsNull();
781 }
782
783 // TODO Maybe make an iterable view type to simplify using this.
784 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
785 REQUIRES_SHARED(art::Locks::mutator_lock_) {
786 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
787 }
788 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
789 return GetSlot(klass_index, kSlotJavaDexFile);
790 }
791 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
792 REQUIRES_SHARED(art::Locks::mutator_lock_) {
793 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
794 }
795 art::mirror::DexCache* GetNewDexCache(jint klass_index)
796 REQUIRES_SHARED(art::Locks::mutator_lock_) {
797 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
798 }
799 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
800 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
801 }
802
Alex Lighta7e38d82017-01-19 14:57:28 -0800803 art::mirror::ByteArray* GetOriginalDexFileBytes(jint klass_index)
804 REQUIRES_SHARED(art::Locks::mutator_lock_) {
805 return art::down_cast<art::mirror::ByteArray*>(GetSlot(klass_index, kSlotOrigDexFile));
806 }
807
Alex Light0e692732017-01-10 15:00:05 -0800808 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
809 REQUIRES_SHARED(art::Locks::mutator_lock_) {
810 SetSlot(klass_index, kSlotSourceClassLoader, loader);
811 }
812 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
813 REQUIRES_SHARED(art::Locks::mutator_lock_) {
814 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
815 }
816 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
817 REQUIRES_SHARED(art::Locks::mutator_lock_) {
818 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
819 }
820 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
821 REQUIRES_SHARED(art::Locks::mutator_lock_) {
822 SetSlot(klass_index, kSlotNewDexCache, cache);
823 }
824 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
825 REQUIRES_SHARED(art::Locks::mutator_lock_) {
826 SetSlot(klass_index, kSlotMirrorClass, klass);
827 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800828 void SetOriginalDexFileBytes(jint klass_index, art::mirror::ByteArray* bytes)
829 REQUIRES_SHARED(art::Locks::mutator_lock_) {
830 SetSlot(klass_index, kSlotOrigDexFile, bytes);
831 }
Alex Light0e692732017-01-10 15:00:05 -0800832
833 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
834 return arr_->GetLength() / kNumSlots;
835 }
836
837 private:
838 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
839
840 art::mirror::Object* GetSlot(jint klass_index,
841 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
842 DCHECK_LT(klass_index, Length());
843 return arr_->Get((kNumSlots * klass_index) + slot);
844 }
845
846 void SetSlot(jint klass_index,
847 DataSlot slot,
848 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
849 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
850 DCHECK_LT(klass_index, Length());
851 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
852 }
853
854 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
855};
856
Alex Lighta7e38d82017-01-19 14:57:28 -0800857bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
858 int32_t klass_index, /*out*/RedefinitionDataHolder* holder) {
859 art::StackHandleScope<2> hs(driver_->self_);
860 holder->SetMirrorClass(klass_index, GetMirrorClass());
861 // This shouldn't allocate
862 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
863 holder->SetSourceClassLoader(klass_index, loader.Get());
864 if (loader.Get() == nullptr) {
865 // TODO Better error msg.
866 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
867 return false;
868 }
869 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
870 holder->SetJavaDexFile(klass_index, dex_file_obj.Get());
871 if (dex_file_obj.Get() == nullptr) {
872 // TODO Better error msg.
873 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
874 return false;
875 }
876 holder->SetNewDexFileCookie(klass_index, AllocateDexFileCookie(dex_file_obj));
877 if (holder->GetNewDexFileCookie(klass_index) == nullptr) {
878 driver_->self_->AssertPendingOOMException();
879 driver_->self_->ClearException();
880 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
881 return false;
882 }
883 holder->SetNewDexCache(klass_index, CreateNewDexCache(loader));
884 if (holder->GetNewDexCache(klass_index) == nullptr) {
885 driver_->self_->AssertPendingOOMException();
886 driver_->self_->ClearException();
887 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
888 return false;
889 }
890
891 // We won't always need to set this field.
892 holder->SetOriginalDexFileBytes(klass_index, AllocateOrGetOriginalDexFileBytes());
893 if (holder->GetOriginalDexFileBytes(klass_index) == nullptr) {
894 driver_->self_->AssertPendingOOMException();
895 driver_->self_->ClearException();
896 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
897 return false;
898 }
899 return true;
900}
901
Alex Light0e692732017-01-10 15:00:05 -0800902bool Redefiner::CheckAllRedefinitionAreValid() {
903 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
904 if (!redef.CheckRedefinitionIsValid()) {
905 return false;
906 }
907 }
908 return true;
909}
910
911bool Redefiner::EnsureAllClassAllocationsFinished() {
912 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
913 if (!redef.EnsureClassAllocationsFinished()) {
914 return false;
915 }
916 }
917 return true;
918}
919
920bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
921 int32_t cnt = 0;
Alex Light0e692732017-01-10 15:00:05 -0800922 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Light0e692732017-01-10 15:00:05 -0800923 // Allocate the data this redefinition requires.
Alex Lighta7e38d82017-01-19 14:57:28 -0800924 if (!redef.FinishRemainingAllocations(cnt, &holder)) {
Alex Light0e692732017-01-10 15:00:05 -0800925 return false;
926 }
Alex Light0e692732017-01-10 15:00:05 -0800927 cnt++;
928 }
929 return true;
930}
931
932void Redefiner::ClassRedefinition::ReleaseDexFile() {
933 dex_file_.release();
934}
935
936void Redefiner::ReleaseAllDexFiles() {
937 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
938 redef.ReleaseDexFile();
939 }
940}
941
Alex Lighta01de592016-11-15 10:43:06 -0800942jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800943 art::StackHandleScope<1> hs(self_);
944 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
945 // We will let this be collected after the end of this function.
946 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
947 if (holder.IsNull()) {
948 self_->AssertPendingOOMException();
949 self_->ClearException();
950 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
951 return result_;
952 }
953
Alex Lighta01de592016-11-15 10:43:06 -0800954 // First we just allocate the ClassExt and its fields that we need. These can be updated
955 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
956 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
957 // between allocating them and pausing all threads before we can update them so we need to do a
958 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800959 if (!CheckAllRedefinitionAreValid() ||
960 !EnsureAllClassAllocationsFinished() ||
961 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800962 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
963 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800964 // declared_methods_.length) but would be good to get rid of. All other allocations should be
965 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800966 return result_;
967 }
Alex Light6abd5392017-01-05 17:53:00 -0800968 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
969 // allocating so no deadlocks.
970 art::gc::Heap* heap = runtime_->GetHeap();
971 if (heap->IsGcConcurrentAndMoving()) {
972 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
973 heap->IncrementDisableMovingGC(self_);
974 }
Alex Lighta01de592016-11-15 10:43:06 -0800975 // Do transition to final suspension
976 // TODO We might want to give this its own suspended state!
977 // TODO This isn't right. We need to change state without any chance of suspend ideally!
978 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
979 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800980 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800981 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
982 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
983 // TODO We need to update all debugger MethodIDs so they note the method they point to is
984 // obsolete or implement some other well defined semantics.
985 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light0e692732017-01-10 15:00:05 -0800986 int32_t cnt = 0;
987 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
988 art::mirror::Class* klass = holder.GetMirrorClass(cnt);
989 redef.UpdateJavaDexFile(holder.GetJavaDexFile(cnt), holder.GetNewDexFileCookie(cnt));
990 // TODO Rewrite so we don't do a stack walk for each and every class.
991 redef.FindAndAllocateObsoleteMethods(klass);
Alex Lighta7e38d82017-01-19 14:57:28 -0800992 redef.UpdateClass(klass, holder.GetNewDexCache(cnt), holder.GetOriginalDexFileBytes(cnt));
Alex Light0e692732017-01-10 15:00:05 -0800993 cnt++;
994 }
Alex Lightdba61482016-12-21 08:20:29 -0800995 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
996 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
Alex Light0e692732017-01-10 15:00:05 -0800997 // DexCache. (b/33630159)
Alex Lightdba61482016-12-21 08:20:29 -0800998 // TODO This can fail (leave some methods optimized) near runtime methods (including
999 // quick-to-interpreter transition function).
1000 // TODO We probably don't need this at all once we have a way to ensure that the
1001 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
1002 // stack-walker.
1003 EnsureObsoleteMethodsAreDeoptimized();
1004 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -08001005 // TODO Shrink the obsolete method maps if possible?
1006 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -08001007 // TODO Put this into a scoped thing.
1008 runtime_->GetThreadList()->ResumeAll();
1009 // Get back shared mutator lock as expected for return.
1010 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -08001011 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1012 // owns the DexFile and when ownership is transferred.
1013 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -08001014 if (heap->IsGcConcurrentAndMoving()) {
1015 heap->DecrementDisableMovingGC(self_);
1016 }
Alex Lighta01de592016-11-15 10:43:06 -08001017 return OK;
1018}
1019
Alex Light0e692732017-01-10 15:00:05 -08001020void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
1021 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1022 const art::DexFile::ClassDef& class_def) {
1023 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001024 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -08001025 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001026 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001027 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -08001028 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
1029 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
1030 art::dex::TypeIndex method_return_idx =
1031 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1032 const auto* old_type_list = method.GetParameterTypeList();
1033 std::vector<art::dex::TypeIndex> new_type_list;
1034 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1035 new_type_list.push_back(
1036 dex_file_->GetIndexForTypeId(
1037 *dex_file_->FindTypeId(
1038 old_dex_file.GetTypeDescriptor(
1039 old_dex_file.GetTypeId(
1040 old_type_list->GetTypeItem(i).type_idx_)))));
1041 }
1042 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
1043 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001044 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001045 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001046 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1047 *new_name_id,
1048 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001049 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001050 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001051 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1052 method.SetDexMethodIndex(dex_method_idx);
1053 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001054 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001055 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -08001056 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001057 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001058 if (jit != nullptr) {
1059 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1060 }
Alex Lighta01de592016-11-15 10:43:06 -08001061 }
Alex Light200b9d72016-12-15 11:34:13 -08001062}
1063
Alex Light0e692732017-01-10 15:00:05 -08001064void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001065 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1066 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1067 for (art::ArtField& field : fields_iter) {
1068 std::string declaring_class_name;
1069 const art::DexFile::TypeId* new_declaring_id =
1070 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1071 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1072 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1073 // TODO Handle error, cleanup.
1074 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1075 const art::DexFile::FieldId* new_field_id =
1076 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1077 CHECK(new_field_id != nullptr);
1078 // We only need to update the index since the other data in the ArtField cannot be updated.
1079 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1080 }
1081 }
Alex Light200b9d72016-12-15 11:34:13 -08001082}
1083
1084// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001085void Redefiner::ClassRedefinition::UpdateClass(
1086 art::ObjPtr<art::mirror::Class> mclass,
1087 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
1088 art::ObjPtr<art::mirror::ByteArray> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001089 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1090 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1091 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001092 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001093
Alex Lighta01de592016-11-15 10:43:06 -08001094 // Update the class fields.
1095 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1096 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1097 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001098 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001099 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta7e38d82017-01-19 14:57:28 -08001100 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1101 CHECK(!ext.IsNull());
1102 ext->SetOriginalDexFileBytes(original_dex_file);
Alex Lighta01de592016-11-15 10:43:06 -08001103}
1104
Alex Light0e692732017-01-10 15:00:05 -08001105void Redefiner::ClassRedefinition::UpdateJavaDexFile(
1106 art::ObjPtr<art::mirror::Object> java_dex_file,
1107 art::ObjPtr<art::mirror::LongArray> new_cookie) {
Alex Lighta01de592016-11-15 10:43:06 -08001108 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1109 "mInternalCookie", "Ljava/lang/Object;");
1110 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1111 "mCookie", "Ljava/lang/Object;");
1112 CHECK(internal_cookie_field != nullptr);
1113 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
1114 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
1115 art::ObjPtr<art::mirror::LongArray> orig_cookie(
1116 cookie_field->GetObject(java_dex_file)->AsLongArray());
1117 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
Alex Lighta01de592016-11-15 10:43:06 -08001118 if (!orig_cookie.IsNull()) {
1119 cookie_field->SetObject<false>(java_dex_file, new_cookie);
1120 }
Alex Lighta01de592016-11-15 10:43:06 -08001121}
1122
1123// This function does all (java) allocations we need to do for the Class being redefined.
1124// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001125bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1126 art::StackHandleScope<2> hs(driver_->self_);
1127 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1128 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001129 if (klass.Get() == nullptr) {
1130 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1131 return false;
1132 }
1133 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001134 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001135 if (ext.Get() == nullptr) {
1136 // No memory. Clear exception (it's not useful) and return error.
1137 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1138 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001139 driver_->self_->AssertPendingOOMException();
1140 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001141 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1142 return false;
1143 }
1144 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1145 // are only modified when all threads (other than the modifying one) are suspended we don't need
1146 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1147 // however, since that can happen at any time.
1148 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1149 // are no obsolete methods.
1150 {
Alex Light0e692732017-01-10 15:00:05 -08001151 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001152 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001153 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001154 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001155 driver_->self_->AssertPendingOOMException();
1156 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001157 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1158 return false;
1159 }
1160 }
1161 return true;
1162}
1163
1164} // namespace openjdkjvmti