blob: 2db8a40ad4938c605c917940c979827fa5364ece [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
39#include "base/logging.h"
Alex Light460d1b42017-01-10 15:37:17 +000040#include "dex_file.h"
41#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080042#include "events-inl.h"
43#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080044#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080045#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080048#include "jni_env_ext-inl.h"
49#include "jvmti_allocator.h"
50#include "mirror/class.h"
51#include "mirror/class_ext.h"
52#include "mirror/object.h"
53#include "object_lock.h"
54#include "runtime.h"
55#include "ScopedLocalRef.h"
Alex Light0e692732017-01-10 15:00:05 -080056#include "transform.h"
Alex Lighta01de592016-11-15 10:43:06 -080057
58namespace openjdkjvmti {
59
Andreas Gampe46ee31b2016-12-14 10:11:49 -080060using android::base::StringPrintf;
61
Alex Lightdba61482016-12-21 08:20:29 -080062// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
63// some basic sanity checks that the obsolete method is sane.
64class ObsoleteMethodStackVisitor : public art::StackVisitor {
65 protected:
66 ObsoleteMethodStackVisitor(
67 art::Thread* thread,
68 art::LinearAlloc* allocator,
69 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080070 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -080071 : StackVisitor(thread,
72 /*context*/nullptr,
73 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
74 allocator_(allocator),
75 obsoleted_methods_(obsoleted_methods),
76 obsolete_maps_(obsolete_maps),
Alex Light007ada22017-01-10 13:33:56 -080077 is_runtime_frame_(false) {
Alex Lightdba61482016-12-21 08:20:29 -080078 }
79
80 ~ObsoleteMethodStackVisitor() OVERRIDE {}
81
82 public:
83 // Returns true if we successfully installed obsolete methods on this thread, filling
84 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
85 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080086 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080087 art::Thread* thread,
88 art::LinearAlloc* allocator,
89 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080090 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
91 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080092 ObsoleteMethodStackVisitor visitor(thread,
93 allocator,
94 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080095 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -080096 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -080097 }
98
99 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
100 art::ArtMethod* old_method = GetMethod();
101 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
102 // works through runtime methods.
103 bool prev_was_runtime_frame_ = is_runtime_frame_;
104 is_runtime_frame_ = old_method->IsRuntimeMethod();
105 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
106 // The check below works since when we deoptimize we set shadow frames for all frames until a
107 // native/runtime transition and for those set the return PC to a function that will complete
108 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
109 // below runtime frames cannot be deoptimized at the moment.
110 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
111 // works through runtime methods.
112 // TODO b/33616143
113 if (!IsShadowFrame() && prev_was_runtime_frame_) {
Alex Light007ada22017-01-10 13:33:56 -0800114 LOG(FATAL) << "Deoptimization failed due to runtime method in stack. See b/33616143";
Alex Lightdba61482016-12-21 08:20:29 -0800115 }
116 // We cannot ensure that the right dex file is used in inlined frames so we don't support
117 // redefining them.
118 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
119 // TODO We should really support intrinsic obsolete methods.
120 // TODO We should really support redefining intrinsics.
121 // We don't support intrinsics so check for them here.
122 DCHECK(!old_method->IsIntrinsic());
123 art::ArtMethod* new_obsolete_method = nullptr;
124 auto obsolete_method_pair = obsolete_maps_->find(old_method);
125 if (obsolete_method_pair == obsolete_maps_->end()) {
126 // Create a new Obsolete Method and put it in the list.
127 art::Runtime* runtime = art::Runtime::Current();
128 art::ClassLinker* cl = runtime->GetClassLinker();
129 auto ptr_size = cl->GetImagePointerSize();
130 const size_t method_size = art::ArtMethod::Size(ptr_size);
131 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800132 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
133 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800134 new_obsolete_method = new (method_storage) art::ArtMethod();
135 new_obsolete_method->CopyFrom(old_method, ptr_size);
136 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
137 new_obsolete_method->SetIsObsolete();
138 obsolete_maps_->insert({old_method, new_obsolete_method});
139 // Update JIT Data structures to point to the new method.
140 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
141 if (jit != nullptr) {
142 // Notify the JIT we are making this obsolete method. It will update the jit's internal
143 // structures to keep track of the new obsolete method.
144 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
145 }
146 } else {
147 new_obsolete_method = obsolete_method_pair->second;
148 }
149 DCHECK(new_obsolete_method != nullptr);
150 SetMethod(new_obsolete_method);
151 }
152 return true;
153 }
154
155 private:
156 // The linear allocator we should use to make new methods.
157 art::LinearAlloc* allocator_;
158 // The set of all methods which could be obsoleted.
159 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
160 // A map from the original to the newly allocated obsolete method for frames on this thread. The
161 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
162 // the redefined classes ClassExt by the caller.
163 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800164 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
165 // works through runtime methods.
166 bool is_runtime_frame_;
Alex Lightdba61482016-12-21 08:20:29 -0800167};
168
Alex Lighte4a88632017-01-10 07:41:24 -0800169jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
170 jclass klass,
171 jboolean* is_redefinable) {
172 // TODO Check for the appropriate feature flags once we have enabled them.
173 art::Thread* self = art::Thread::Current();
174 art::ScopedObjectAccess soa(self);
175 art::StackHandleScope<1> hs(self);
176 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
177 if (obj.IsNull()) {
178 return ERR(INVALID_CLASS);
179 }
180 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
181 std::string err_unused;
182 *is_redefinable =
183 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
184 return OK;
185}
186
187jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
188 /*out*/std::string* error_msg) {
189 if (klass->IsPrimitive()) {
190 *error_msg = "Modification of primitive classes is not supported";
191 return ERR(UNMODIFIABLE_CLASS);
192 } else if (klass->IsInterface()) {
193 *error_msg = "Modification of Interface classes is currently not supported";
194 return ERR(UNMODIFIABLE_CLASS);
195 } else if (klass->IsArrayClass()) {
196 *error_msg = "Modification of Array classes is not supported";
197 return ERR(UNMODIFIABLE_CLASS);
198 } else if (klass->IsProxyClass()) {
199 *error_msg = "Modification of proxy classes is not supported";
200 return ERR(UNMODIFIABLE_CLASS);
201 }
202
203 // TODO We should check if the class has non-obsoletable methods on the stack
204 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
205 return OK;
206}
207
Alex Lighta01de592016-11-15 10:43:06 -0800208// Moves dex data to an anonymous, read-only mmap'd region.
209std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
210 jint data_len,
Alex Light0e692732017-01-10 15:00:05 -0800211 const unsigned char* dex_data,
Alex Lighta01de592016-11-15 10:43:06 -0800212 std::string* error_msg) {
213 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800214 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800215 nullptr,
216 data_len,
217 PROT_READ|PROT_WRITE,
218 /*low_4gb*/false,
219 /*reuse*/false,
220 error_msg));
221 if (map == nullptr) {
222 return map;
223 }
224 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800225 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
226 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800227 map->Protect(PROT_READ);
228 return map;
229}
230
Alex Light0e692732017-01-10 15:00:05 -0800231Redefiner::ClassRedefinition::ClassRedefinition(Redefiner* driver,
232 jclass klass,
233 const art::DexFile* redefined_dex_file,
234 const char* class_sig) :
235 driver_(driver), klass_(klass), dex_file_(redefined_dex_file), class_sig_(class_sig) {
236 GetMirrorClass()->MonitorEnter(driver_->self_);
237}
238
239Redefiner::ClassRedefinition::~ClassRedefinition() {
240 if (driver_ != nullptr) {
241 GetMirrorClass()->MonitorExit(driver_->self_);
242 }
243}
244
Alex Light0e692732017-01-10 15:00:05 -0800245jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
246 art::Runtime* runtime,
247 art::Thread* self,
248 jint class_count,
249 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800250 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800251 if (env == nullptr) {
252 *error_msg = "env was null!";
253 return ERR(INVALID_ENVIRONMENT);
254 } else if (class_count < 0) {
255 *error_msg = "class_count was less then 0";
256 return ERR(ILLEGAL_ARGUMENT);
257 } else if (class_count == 0) {
258 // We don't actually need to do anything. Just return OK.
259 return OK;
260 } else if (definitions == nullptr) {
261 *error_msg = "null definitions!";
262 return ERR(NULL_POINTER);
263 }
Alex Light6ac57502017-01-19 15:05:06 -0800264 std::vector<ArtClassDefinition> def_vector;
265 def_vector.reserve(class_count);
266 for (jint i = 0; i < class_count; i++) {
267 // We make a copy of the class_bytes to pass into the retransformation.
268 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we
269 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls
270 // to get the passed in bytes.
271 // TODO Implement saving the original bytes.
272 unsigned char* class_bytes_copy = nullptr;
273 jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy);
274 if (res != OK) {
275 return res;
276 }
277 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count);
278
279 ArtClassDefinition def;
280 def.dex_len = definitions[i].class_byte_count;
281 def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy);
282 // We are definitely modified.
283 def.modified = true;
284 res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
285 if (res != OK) {
286 return res;
287 }
288 def_vector.push_back(std::move(def));
289 }
290 // Call all the transformation events.
291 jvmtiError res = Transformer::RetransformClassesDirect(env,
292 self,
293 &def_vector);
294 if (res != OK) {
295 // Something went wrong with transformation!
296 return res;
297 }
298 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
299}
300
301jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
302 art::Runtime* runtime,
303 art::Thread* self,
304 const std::vector<ArtClassDefinition>& definitions,
305 std::string* error_msg) {
306 DCHECK(env != nullptr);
307 if (definitions.size() == 0) {
308 // We don't actually need to do anything. Just return OK.
309 return OK;
310 }
Alex Light0e692732017-01-10 15:00:05 -0800311 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
312 // are going to redefine.
313 art::jit::ScopedJitSuspend suspend_jit;
314 // Get shared mutator lock so we can lock all the classes.
315 art::ScopedObjectAccess soa(self);
316 std::vector<Redefiner::ClassRedefinition> redefinitions;
Alex Light6ac57502017-01-19 15:05:06 -0800317 redefinitions.reserve(definitions.size());
Alex Light0e692732017-01-10 15:00:05 -0800318 Redefiner r(runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800319 for (const ArtClassDefinition& def : definitions) {
320 // Only try to transform classes that have been modified.
321 if (def.modified) {
322 jvmtiError res = r.AddRedefinition(env, def);
323 if (res != OK) {
324 return res;
325 }
Alex Light0e692732017-01-10 15:00:05 -0800326 }
327 }
328 return r.Run();
329}
330
Alex Light6ac57502017-01-19 15:05:06 -0800331jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800332 std::string original_dex_location;
333 jvmtiError ret = OK;
334 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
335 *error_msg_ = "Unable to get original dex file location!";
336 return ret;
337 }
Alex Light52a2db52017-01-19 23:00:21 +0000338 char* generic_ptr_unused = nullptr;
339 char* signature_ptr = nullptr;
Alex Light6ac57502017-01-19 15:05:06 -0800340 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
341 *error_msg_ = "Unable to get class signature!";
342 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000343 }
Alex Light52a2db52017-01-19 23:00:21 +0000344 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Light6ac57502017-01-19 15:05:06 -0800345 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
346 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
347 def.dex_len,
348 def.dex_data.get(),
349 error_msg_));
350 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800351 if (map.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800352 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800353 << "in dex file " << original_dex_location << " because: " << *error_msg_;
354 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800355 return ERR(OUT_OF_MEMORY);
356 }
357 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800358 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800359 return ERR(INVALID_CLASS_FORMAT);
360 }
361 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
362 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
363 checksum,
364 std::move(map),
365 /*verify*/true,
366 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800367 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800368 if (dex_file.get() == nullptr) {
Alex Light6ac57502017-01-19 15:05:06 -0800369 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800370 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800371 return ERR(INVALID_CLASS_FORMAT);
372 }
Alex Light0e692732017-01-10 15:00:05 -0800373 redefinitions_.push_back(
374 Redefiner::ClassRedefinition(this, def.klass, dex_file.release(), signature_ptr));
375 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800376}
377
378// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
379// TODO Make mirror of DexFile and associated types to make this less hellish.
380// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
Alex Light0e692732017-01-10 15:00:05 -0800381art::mirror::Object* Redefiner::ClassRedefinition::FindSourceDexFileObject(
Alex Lighta01de592016-11-15 10:43:06 -0800382 art::Handle<art::mirror::ClassLoader> loader) {
383 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
384 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
385 const char* dex_file_name = "Ldalvik/system/DexFile;";
386 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
387 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
388
Alex Light0e692732017-01-10 15:00:05 -0800389 CHECK(!driver_->self_->IsExceptionPending());
390 art::StackHandleScope<11> hs(driver_->self_);
391 art::ClassLinker* class_linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800392
393 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
394 nullptr));
395 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
Alex Light0e692732017-01-10 15:00:05 -0800396 driver_->self_, dex_class_loader_name, null_loader)));
Alex Lighta01de592016-11-15 10:43:06 -0800397
398 // Get all the ArtFields so we can look in the BaseDexClassLoader
399 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
400 "pathList", dex_path_list_name);
401 CHECK(path_list_field != nullptr);
402
403 art::ArtField* dex_path_list_element_field =
Alex Light0e692732017-01-10 15:00:05 -0800404 class_linker->FindClass(driver_->self_, dex_path_list_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800405 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
406 CHECK(dex_path_list_element_field != nullptr);
407
408 art::ArtField* element_dex_file_field =
Alex Light0e692732017-01-10 15:00:05 -0800409 class_linker->FindClass(driver_->self_, dex_path_list_element_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800410 ->FindDeclaredInstanceField("dexFile", dex_file_name);
411 CHECK(element_dex_file_field != nullptr);
412
413 // Check if loader is a BaseDexClassLoader
414 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
415 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
416 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
417 << "supported class loader type!";
418 return nullptr;
419 }
420 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
421 art::Handle<art::mirror::Object> path_list(
422 hs.NewHandle(path_list_field->GetObject(loader.Get())));
423 CHECK(path_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800424 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800425 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
426 dex_path_list_element_field->GetObject(path_list.Get())->
427 AsObjectArray<art::mirror::Object>()));
Alex Light0e692732017-01-10 15:00:05 -0800428 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800429 CHECK(dex_elements_list.Get() != nullptr);
430 size_t num_elements = dex_elements_list->GetLength();
431 art::MutableHandle<art::mirror::Object> current_element(
432 hs.NewHandle<art::mirror::Object>(nullptr));
433 art::MutableHandle<art::mirror::Object> first_dex_file(
434 hs.NewHandle<art::mirror::Object>(nullptr));
435 // Iterate over the DexPathList$Element to find the right one
436 // TODO Or not ATM just return the first one.
437 for (size_t i = 0; i < num_elements; i++) {
438 current_element.Assign(dex_elements_list->Get(i));
439 CHECK(current_element.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800440 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800441 CHECK(dex_elements_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800442 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(driver_->self_,
Alex Lighta01de592016-11-15 10:43:06 -0800443 dex_path_list_element_name,
444 null_loader));
445 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
446 // comes from but it is more annoying because we would need to find this class. It is not
447 // necessary for proper function since we just need to be in front of the classes old dex file
448 // in the path.
449 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
450 if (first_dex_file.Get() != nullptr) {
451 return first_dex_file.Get();
452 }
453 }
454 return nullptr;
455}
456
Alex Light0e692732017-01-10 15:00:05 -0800457art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
458 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800459}
460
Alex Light0e692732017-01-10 15:00:05 -0800461art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800462 return GetMirrorClass()->GetClassLoader();
463}
464
Alex Light0e692732017-01-10 15:00:05 -0800465art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
466 art::Handle<art::mirror::ClassLoader> loader) {
467 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800468}
469
470// TODO Really wishing I had that mirror of java.lang.DexFile now.
Alex Light0e692732017-01-10 15:00:05 -0800471art::mirror::LongArray* Redefiner::ClassRedefinition::AllocateDexFileCookie(
Alex Lighta01de592016-11-15 10:43:06 -0800472 art::Handle<art::mirror::Object> java_dex_file_obj) {
Alex Light0e692732017-01-10 15:00:05 -0800473 art::StackHandleScope<2> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800474 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
475 // the object is finalized. Since they always point to the same array if mCookie is not null we
476 // just use the mInternalCookie field. We will update one or both of these fields later.
477 // TODO Should I get the class from the classloader or directly?
478 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
479 "mInternalCookie", "Ljava/lang/Object;");
480 // TODO Add check that mCookie is either null or same as mInternalCookie
481 CHECK(internal_cookie_field != nullptr);
482 art::Handle<art::mirror::LongArray> cookie(
483 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
484 // TODO Maybe make these non-fatal.
485 CHECK(cookie.Get() != nullptr);
486 CHECK_GE(cookie->GetLength(), 1);
487 art::Handle<art::mirror::LongArray> new_cookie(
Alex Light0e692732017-01-10 15:00:05 -0800488 hs.NewHandle(art::mirror::LongArray::Alloc(driver_->self_, cookie->GetLength() + 1)));
Alex Lighta01de592016-11-15 10:43:06 -0800489 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800490 driver_->self_->AssertPendingOOMException();
Alex Lighta01de592016-11-15 10:43:06 -0800491 return nullptr;
492 }
493 // Copy the oat-dex field at the start.
494 // TODO Should I clear this field?
495 // TODO This is a really crappy thing here with the first element being different.
496 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
497 new_cookie->SetWithoutChecks<false>(
498 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
499 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
500 return new_cookie.Get();
501}
502
Alex Light0e692732017-01-10 15:00:05 -0800503void Redefiner::RecordFailure(jvmtiError result,
504 const std::string& class_sig,
505 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800506 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800507 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800508 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800509 result_ = result;
510}
511
Alex Light0e692732017-01-10 15:00:05 -0800512bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lighta01de592016-11-15 10:43:06 -0800513 /*out*/art::MutableHandle<art::mirror::ClassLoader>* source_class_loader,
514 /*out*/art::MutableHandle<art::mirror::Object>* java_dex_file_obj,
515 /*out*/art::MutableHandle<art::mirror::LongArray>* new_dex_file_cookie,
516 /*out*/art::MutableHandle<art::mirror::DexCache>* new_dex_cache) {
Alex Light0e692732017-01-10 15:00:05 -0800517 art::StackHandleScope<4> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800518 // This shouldn't allocate
519 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
520 if (loader.Get() == nullptr) {
521 // TODO Better error msg.
522 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
523 return false;
524 }
525 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
526 if (dex_file_obj.Get() == nullptr) {
527 // TODO Better error msg.
528 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
529 return false;
530 }
531 art::Handle<art::mirror::LongArray> new_cookie(hs.NewHandle(AllocateDexFileCookie(dex_file_obj)));
532 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800533 driver_->self_->AssertPendingOOMException();
534 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800535 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
536 return false;
537 }
538 art::Handle<art::mirror::DexCache> dex_cache(hs.NewHandle(CreateNewDexCache(loader)));
539 if (dex_cache.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800540 driver_->self_->AssertPendingOOMException();
541 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800542 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
543 return false;
544 }
545 source_class_loader->Assign(loader.Get());
546 java_dex_file_obj->Assign(dex_file_obj.Get());
547 new_dex_file_cookie->Assign(new_cookie.Get());
548 new_dex_cache->Assign(dex_cache.Get());
549 return true;
550}
551
Alex Lightdba61482016-12-21 08:20:29 -0800552struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800553 art::LinearAlloc* allocator;
554 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
555 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800556
Alex Light0e692732017-01-10 15:00:05 -0800557 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800558};
559
Alex Lightdba61482016-12-21 08:20:29 -0800560void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
561 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800562 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
563 data->allocator,
564 data->obsolete_methods,
565 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800566}
567
568// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
569// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800570// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
571void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800572 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
573 art::mirror::ClassExt* ext = art_klass->GetExtData();
574 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800575 CallbackCtx ctx(art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800576 // Add all the declared methods to the map
577 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
578 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800579 // TODO Allow this or check in IsModifiableClass.
580 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800581 }
582 {
Alex Light0e692732017-01-10 15:00:05 -0800583 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800584 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
585 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800586 }
587 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800588}
589
590// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
591// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800592void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800593 art::mirror::Class* art_klass,
594 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
595 int32_t index = 0;
596 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
597 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
598 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
599 ext_data->GetObsoleteDexCaches();
600 int32_t num_method_slots = obsolete_methods->GetLength();
601 // Find the first empty index.
602 for (; index < num_method_slots; index++) {
603 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
604 index, art::kRuntimePointerSize) == nullptr) {
605 break;
606 }
607 }
608 // Make sure we have enough space.
609 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
610 CHECK(obsolete_dex_caches->Get(index) == nullptr);
611 // Fill in the map.
612 for (auto& obs : obsoletes) {
613 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
614 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
615 index++;
616 }
617}
618
619// TODO It should be possible to only deoptimize the specific obsolete methods.
620// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
621// If one of these frames is an obsolete method we have a problem. b/33616143
622// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
623// registers across suspend points.
624// TODO Pending b/33630159
625void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
626 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
627 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
628 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
629}
630
Alex Light0e692732017-01-10 15:00:05 -0800631bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000632 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800633 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000634 // Easy check that only 1 class def is present.
635 if (dex_file_->NumClassDefs() != 1) {
636 RecordFailure(ERR(ILLEGAL_ARGUMENT),
637 StringPrintf("Expected 1 class def in dex file but found %d",
638 dex_file_->NumClassDefs()));
639 return false;
640 }
641 // Get the ClassDef from the new DexFile.
642 // Since the dex file has only a single class def the index is always 0.
643 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
644 // Get the class as it is now.
645 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
646
647 // Check the access flags didn't change.
648 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
649 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
650 "Cannot change modifiers of class by redefinition");
651 return false;
652 }
653
654 // Check class name.
655 // These should have been checked by the dexfile verifier on load.
656 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
657 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
658 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
659 if (!current_class->DescriptorEquals(descriptor)) {
660 std::string storage;
661 RecordFailure(ERR(NAMES_DONT_MATCH),
662 StringPrintf("expected file to contain class called '%s' but found '%s'!",
663 current_class->GetDescriptor(&storage),
664 descriptor));
665 return false;
666 }
667 if (current_class->IsObjectClass()) {
668 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
669 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
670 return false;
671 }
672 } else {
673 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
674 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
675 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
676 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
677 return false;
678 }
679 }
680 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
681 if (interfaces == nullptr) {
682 if (current_class->NumDirectInterfaces() != 0) {
683 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
684 return false;
685 }
686 } else {
687 DCHECK(!current_class->IsProxyClass());
688 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
689 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
690 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
691 return false;
692 }
693 // The order of interfaces is (barely) meaningful so we error if it changes.
694 const art::DexFile& orig_dex_file = current_class->GetDexFile();
695 for (uint32_t i = 0; i < interfaces->Size(); i++) {
696 if (strcmp(
697 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
698 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
699 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
700 "Interfaces changed or re-ordered");
701 return false;
702 }
703 }
704 }
705 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800706 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000707
708 return true;
709}
710
711// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800712bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800713 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800714 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000715
Alex Lighte4a88632017-01-10 07:41:24 -0800716 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
717 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
718 if (res != OK) {
719 RecordFailure(res, err);
720 return false;
721 } else {
722 return true;
723 }
Alex Light460d1b42017-01-10 15:37:17 +0000724}
725
Alex Light0e692732017-01-10 15:00:05 -0800726bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000727 return CheckRedefinable() &&
728 CheckClass() &&
729 CheckSameFields() &&
730 CheckSameMethods();
731}
732
Alex Light0e692732017-01-10 15:00:05 -0800733// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
734// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
735// having to deal with the fact that we need to hold an arbitrary number of references live.
736class RedefinitionDataHolder {
737 public:
738 enum DataSlot : int32_t {
739 kSlotSourceClassLoader = 0,
740 kSlotJavaDexFile = 1,
741 kSlotNewDexFileCookie = 2,
742 kSlotNewDexCache = 3,
743 kSlotMirrorClass = 4,
744
745 // Must be last one.
746 kNumSlots = 5,
747 };
748
749 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
750 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
751 // the passed in handle-scope.
752 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
753 art::Runtime* runtime,
754 art::Thread* self,
755 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
756 arr_(
757 hs->NewHandle(
758 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
759 self,
760 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
761 num_redefinitions * kNumSlots))) {}
762
763 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
764 return arr_.IsNull();
765 }
766
767 // TODO Maybe make an iterable view type to simplify using this.
768 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
769 REQUIRES_SHARED(art::Locks::mutator_lock_) {
770 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
771 }
772 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
773 return GetSlot(klass_index, kSlotJavaDexFile);
774 }
775 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
776 REQUIRES_SHARED(art::Locks::mutator_lock_) {
777 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
778 }
779 art::mirror::DexCache* GetNewDexCache(jint klass_index)
780 REQUIRES_SHARED(art::Locks::mutator_lock_) {
781 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
782 }
783 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
784 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
785 }
786
787 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
788 REQUIRES_SHARED(art::Locks::mutator_lock_) {
789 SetSlot(klass_index, kSlotSourceClassLoader, loader);
790 }
791 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
792 REQUIRES_SHARED(art::Locks::mutator_lock_) {
793 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
794 }
795 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
796 REQUIRES_SHARED(art::Locks::mutator_lock_) {
797 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
798 }
799 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
800 REQUIRES_SHARED(art::Locks::mutator_lock_) {
801 SetSlot(klass_index, kSlotNewDexCache, cache);
802 }
803 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
804 REQUIRES_SHARED(art::Locks::mutator_lock_) {
805 SetSlot(klass_index, kSlotMirrorClass, klass);
806 }
807
808 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
809 return arr_->GetLength() / kNumSlots;
810 }
811
812 private:
813 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
814
815 art::mirror::Object* GetSlot(jint klass_index,
816 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
817 DCHECK_LT(klass_index, Length());
818 return arr_->Get((kNumSlots * klass_index) + slot);
819 }
820
821 void SetSlot(jint klass_index,
822 DataSlot slot,
823 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
824 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
825 DCHECK_LT(klass_index, Length());
826 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
827 }
828
829 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
830};
831
832bool Redefiner::CheckAllRedefinitionAreValid() {
833 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
834 if (!redef.CheckRedefinitionIsValid()) {
835 return false;
836 }
837 }
838 return true;
839}
840
841bool Redefiner::EnsureAllClassAllocationsFinished() {
842 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
843 if (!redef.EnsureClassAllocationsFinished()) {
844 return false;
845 }
846 }
847 return true;
848}
849
850bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
851 int32_t cnt = 0;
852 art::StackHandleScope<4> hs(self_);
853 art::MutableHandle<art::mirror::Object> java_dex_file(hs.NewHandle<art::mirror::Object>(nullptr));
854 art::MutableHandle<art::mirror::ClassLoader> source_class_loader(
855 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
856 art::MutableHandle<art::mirror::LongArray> new_dex_file_cookie(
857 hs.NewHandle<art::mirror::LongArray>(nullptr));
858 art::MutableHandle<art::mirror::DexCache> new_dex_cache(
859 hs.NewHandle<art::mirror::DexCache>(nullptr));
860 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
861 // Reset the out pointers to null
862 source_class_loader.Assign(nullptr);
863 java_dex_file.Assign(nullptr);
864 new_dex_file_cookie.Assign(nullptr);
865 new_dex_cache.Assign(nullptr);
866 // Allocate the data this redefinition requires.
867 if (!redef.FinishRemainingAllocations(&source_class_loader,
868 &java_dex_file,
869 &new_dex_file_cookie,
870 &new_dex_cache)) {
871 return false;
872 }
873 // Save the allocated data into the holder.
874 holder.SetSourceClassLoader(cnt, source_class_loader.Get());
875 holder.SetJavaDexFile(cnt, java_dex_file.Get());
876 holder.SetNewDexFileCookie(cnt, new_dex_file_cookie.Get());
877 holder.SetNewDexCache(cnt, new_dex_cache.Get());
878 holder.SetMirrorClass(cnt, redef.GetMirrorClass());
879 cnt++;
880 }
881 return true;
882}
883
884void Redefiner::ClassRedefinition::ReleaseDexFile() {
885 dex_file_.release();
886}
887
888void Redefiner::ReleaseAllDexFiles() {
889 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
890 redef.ReleaseDexFile();
891 }
892}
893
Alex Lighta01de592016-11-15 10:43:06 -0800894jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800895 art::StackHandleScope<1> hs(self_);
896 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
897 // We will let this be collected after the end of this function.
898 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
899 if (holder.IsNull()) {
900 self_->AssertPendingOOMException();
901 self_->ClearException();
902 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
903 return result_;
904 }
905
Alex Lighta01de592016-11-15 10:43:06 -0800906 // First we just allocate the ClassExt and its fields that we need. These can be updated
907 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
908 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
909 // between allocating them and pausing all threads before we can update them so we need to do a
910 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800911 if (!CheckAllRedefinitionAreValid() ||
912 !EnsureAllClassAllocationsFinished() ||
913 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800914 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
915 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800916 // declared_methods_.length) but would be good to get rid of. All other allocations should be
917 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800918 return result_;
919 }
Alex Light6abd5392017-01-05 17:53:00 -0800920 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
921 // allocating so no deadlocks.
922 art::gc::Heap* heap = runtime_->GetHeap();
923 if (heap->IsGcConcurrentAndMoving()) {
924 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
925 heap->IncrementDisableMovingGC(self_);
926 }
Alex Lighta01de592016-11-15 10:43:06 -0800927 // Do transition to final suspension
928 // TODO We might want to give this its own suspended state!
929 // TODO This isn't right. We need to change state without any chance of suspend ideally!
930 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
931 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800932 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800933 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
934 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
935 // TODO We need to update all debugger MethodIDs so they note the method they point to is
936 // obsolete or implement some other well defined semantics.
937 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light0e692732017-01-10 15:00:05 -0800938 int32_t cnt = 0;
939 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
940 art::mirror::Class* klass = holder.GetMirrorClass(cnt);
941 redef.UpdateJavaDexFile(holder.GetJavaDexFile(cnt), holder.GetNewDexFileCookie(cnt));
942 // TODO Rewrite so we don't do a stack walk for each and every class.
943 redef.FindAndAllocateObsoleteMethods(klass);
944 redef.UpdateClass(klass, holder.GetNewDexCache(cnt));
945 cnt++;
946 }
Alex Lightdba61482016-12-21 08:20:29 -0800947 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
948 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
Alex Light0e692732017-01-10 15:00:05 -0800949 // DexCache. (b/33630159)
Alex Lightdba61482016-12-21 08:20:29 -0800950 // TODO This can fail (leave some methods optimized) near runtime methods (including
951 // quick-to-interpreter transition function).
952 // TODO We probably don't need this at all once we have a way to ensure that the
953 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
954 // stack-walker.
955 EnsureObsoleteMethodsAreDeoptimized();
956 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -0800957 // TODO Shrink the obsolete method maps if possible?
958 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800959 // TODO Put this into a scoped thing.
960 runtime_->GetThreadList()->ResumeAll();
961 // Get back shared mutator lock as expected for return.
962 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800963 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
964 // owns the DexFile and when ownership is transferred.
965 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -0800966 if (heap->IsGcConcurrentAndMoving()) {
967 heap->DecrementDisableMovingGC(self_);
968 }
Alex Lighta01de592016-11-15 10:43:06 -0800969 return OK;
970}
971
Alex Light0e692732017-01-10 15:00:05 -0800972void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
973 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
974 const art::DexFile::ClassDef& class_def) {
975 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800976 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800977 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800978 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800979 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800980 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
981 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
982 art::dex::TypeIndex method_return_idx =
983 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
984 const auto* old_type_list = method.GetParameterTypeList();
985 std::vector<art::dex::TypeIndex> new_type_list;
986 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
987 new_type_list.push_back(
988 dex_file_->GetIndexForTypeId(
989 *dex_file_->FindTypeId(
990 old_dex_file.GetTypeDescriptor(
991 old_dex_file.GetTypeId(
992 old_type_list->GetTypeItem(i).type_idx_)))));
993 }
994 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
995 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000996 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800997 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800998 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
999 *new_name_id,
1000 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +00001001 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -08001002 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001003 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1004 method.SetDexMethodIndex(dex_method_idx);
1005 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001006 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -08001007 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -08001008 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -08001009 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -08001010 if (jit != nullptr) {
1011 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1012 }
Alex Lighta01de592016-11-15 10:43:06 -08001013 }
Alex Light200b9d72016-12-15 11:34:13 -08001014}
1015
Alex Light0e692732017-01-10 15:00:05 -08001016void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001017 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1018 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1019 for (art::ArtField& field : fields_iter) {
1020 std::string declaring_class_name;
1021 const art::DexFile::TypeId* new_declaring_id =
1022 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1023 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1024 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1025 // TODO Handle error, cleanup.
1026 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1027 const art::DexFile::FieldId* new_field_id =
1028 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1029 CHECK(new_field_id != nullptr);
1030 // We only need to update the index since the other data in the ArtField cannot be updated.
1031 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1032 }
1033 }
Alex Light200b9d72016-12-15 11:34:13 -08001034}
1035
1036// Performs updates to class that will allow us to verify it.
Alex Light0e692732017-01-10 15:00:05 -08001037void Redefiner::ClassRedefinition::UpdateClass(art::ObjPtr<art::mirror::Class> mclass,
1038 art::ObjPtr<art::mirror::DexCache> new_dex_cache) {
Alex Light6ac57502017-01-19 15:05:06 -08001039 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1040 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1041 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001042 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001043
Alex Lighta01de592016-11-15 10:43:06 -08001044 // Update the class fields.
1045 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1046 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1047 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001048 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001049 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta01de592016-11-15 10:43:06 -08001050}
1051
Alex Light0e692732017-01-10 15:00:05 -08001052void Redefiner::ClassRedefinition::UpdateJavaDexFile(
1053 art::ObjPtr<art::mirror::Object> java_dex_file,
1054 art::ObjPtr<art::mirror::LongArray> new_cookie) {
Alex Lighta01de592016-11-15 10:43:06 -08001055 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1056 "mInternalCookie", "Ljava/lang/Object;");
1057 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1058 "mCookie", "Ljava/lang/Object;");
1059 CHECK(internal_cookie_field != nullptr);
1060 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
1061 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
1062 art::ObjPtr<art::mirror::LongArray> orig_cookie(
1063 cookie_field->GetObject(java_dex_file)->AsLongArray());
1064 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
Alex Lighta01de592016-11-15 10:43:06 -08001065 if (!orig_cookie.IsNull()) {
1066 cookie_field->SetObject<false>(java_dex_file, new_cookie);
1067 }
Alex Lighta01de592016-11-15 10:43:06 -08001068}
1069
1070// This function does all (java) allocations we need to do for the Class being redefined.
1071// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001072bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1073 art::StackHandleScope<2> hs(driver_->self_);
1074 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1075 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001076 if (klass.Get() == nullptr) {
1077 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1078 return false;
1079 }
1080 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001081 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001082 if (ext.Get() == nullptr) {
1083 // No memory. Clear exception (it's not useful) and return error.
1084 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1085 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001086 driver_->self_->AssertPendingOOMException();
1087 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001088 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1089 return false;
1090 }
1091 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1092 // are only modified when all threads (other than the modifying one) are suspended we don't need
1093 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1094 // however, since that can happen at any time.
1095 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1096 // are no obsolete methods.
1097 {
Alex Light0e692732017-01-10 15:00:05 -08001098 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001099 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001100 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001101 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001102 driver_->self_->AssertPendingOOMException();
1103 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001104 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1105 return false;
1106 }
1107 }
1108 return true;
1109}
1110
1111} // namespace openjdkjvmti