blob: 28ea2677fcac0fa2f2896f52925aeb0f6bdbfa96 [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 Lighta6c5e972017-01-13 14:15:41 -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 Lighta6c5e972017-01-13 14:15:41 -0800264 std::vector<ArtClassDefinition> def_vector;
265 def_vector.reserve(class_count);
266 for (jint i = 0; i < class_count; i++) {
267 ArtClassDefinition def;
268 def.dex_len = definitions[i].class_byte_count;
269 def.dex_data = MakeJvmtiUniquePtr(env, const_cast<unsigned char*>(definitions[i].class_bytes));
270 // We are definitely modified.
271 def.modified = true;
272 jvmtiError res = Transformer::FillInTransformationData(env, definitions[i].klass, &def);
273 if (res != OK) {
274 return res;
275 }
276 def_vector.push_back(std::move(def));
277 }
278 // Call all the transformation events.
279 jvmtiError res = Transformer::RetransformClassesDirect(env,
280 self,
281 &def_vector);
282 if (res != OK) {
283 // Something went wrong with transformation!
284 return res;
285 }
286 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
287}
288
289jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
290 art::Runtime* runtime,
291 art::Thread* self,
292 const std::vector<ArtClassDefinition>& definitions,
293 std::string* error_msg) {
294 DCHECK(env != nullptr);
295 if (definitions.size() == 0) {
296 // We don't actually need to do anything. Just return OK.
297 return OK;
298 }
Alex Light0e692732017-01-10 15:00:05 -0800299 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
300 // are going to redefine.
301 art::jit::ScopedJitSuspend suspend_jit;
302 // Get shared mutator lock so we can lock all the classes.
303 art::ScopedObjectAccess soa(self);
304 std::vector<Redefiner::ClassRedefinition> redefinitions;
Alex Lighta6c5e972017-01-13 14:15:41 -0800305 redefinitions.reserve(definitions.size());
Alex Light0e692732017-01-10 15:00:05 -0800306 Redefiner r(runtime, self, error_msg);
Alex Lighta6c5e972017-01-13 14:15:41 -0800307 for (const ArtClassDefinition& def : definitions) {
308 // Only try to transform classes that have been modified.
309 if (def.modified) {
310 jvmtiError res = r.AddRedefinition(env, def);
311 if (res != OK) {
312 return res;
313 }
Alex Light0e692732017-01-10 15:00:05 -0800314 }
315 }
316 return r.Run();
317}
318
Alex Lighta6c5e972017-01-13 14:15:41 -0800319jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800320 std::string original_dex_location;
321 jvmtiError ret = OK;
322 if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) {
323 *error_msg_ = "Unable to get original dex file location!";
324 return ret;
325 }
Alex Lighta01de592016-11-15 10:43:06 -0800326 char* generic_ptr_unused = nullptr;
327 char* signature_ptr = nullptr;
Alex Lighta6c5e972017-01-13 14:15:41 -0800328 if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) {
329 *error_msg_ = "Unable to get class signature!";
330 return ret;
Alex Lighta01de592016-11-15 10:43:06 -0800331 }
Alex Light0e692732017-01-10 15:00:05 -0800332 JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
Alex Lighta6c5e972017-01-13 14:15:41 -0800333 JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
334 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
335 def.dex_len,
336 def.dex_data.get(),
337 error_msg_));
338 std::ostringstream os;
Alex Lighta01de592016-11-15 10:43:06 -0800339 if (map.get() == nullptr) {
Alex Lighta6c5e972017-01-13 14:15:41 -0800340 os << "Failed to create anonymous mmap for modified dex file of class " << def.name
Alex Light0e692732017-01-10 15:00:05 -0800341 << "in dex file " << original_dex_location << " because: " << *error_msg_;
342 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800343 return ERR(OUT_OF_MEMORY);
344 }
345 if (map->Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800346 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800347 return ERR(INVALID_CLASS_FORMAT);
348 }
349 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
350 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
351 checksum,
352 std::move(map),
353 /*verify*/true,
354 /*verify_checksum*/true,
Alex Light0e692732017-01-10 15:00:05 -0800355 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800356 if (dex_file.get() == nullptr) {
Alex Lighta6c5e972017-01-13 14:15:41 -0800357 os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800358 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800359 return ERR(INVALID_CLASS_FORMAT);
360 }
Alex Light0e692732017-01-10 15:00:05 -0800361 redefinitions_.push_back(
362 Redefiner::ClassRedefinition(this, def.klass, dex_file.release(), signature_ptr));
363 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800364}
365
366// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
367// TODO Make mirror of DexFile and associated types to make this less hellish.
368// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
Alex Light0e692732017-01-10 15:00:05 -0800369art::mirror::Object* Redefiner::ClassRedefinition::FindSourceDexFileObject(
Alex Lighta01de592016-11-15 10:43:06 -0800370 art::Handle<art::mirror::ClassLoader> loader) {
371 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
372 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
373 const char* dex_file_name = "Ldalvik/system/DexFile;";
374 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
375 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
376
Alex Light0e692732017-01-10 15:00:05 -0800377 CHECK(!driver_->self_->IsExceptionPending());
378 art::StackHandleScope<11> hs(driver_->self_);
379 art::ClassLinker* class_linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800380
381 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
382 nullptr));
383 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
Alex Light0e692732017-01-10 15:00:05 -0800384 driver_->self_, dex_class_loader_name, null_loader)));
Alex Lighta01de592016-11-15 10:43:06 -0800385
386 // Get all the ArtFields so we can look in the BaseDexClassLoader
387 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
388 "pathList", dex_path_list_name);
389 CHECK(path_list_field != nullptr);
390
391 art::ArtField* dex_path_list_element_field =
Alex Light0e692732017-01-10 15:00:05 -0800392 class_linker->FindClass(driver_->self_, dex_path_list_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800393 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
394 CHECK(dex_path_list_element_field != nullptr);
395
396 art::ArtField* element_dex_file_field =
Alex Light0e692732017-01-10 15:00:05 -0800397 class_linker->FindClass(driver_->self_, dex_path_list_element_name, null_loader)
Alex Lighta01de592016-11-15 10:43:06 -0800398 ->FindDeclaredInstanceField("dexFile", dex_file_name);
399 CHECK(element_dex_file_field != nullptr);
400
401 // Check if loader is a BaseDexClassLoader
402 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
403 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
404 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
405 << "supported class loader type!";
406 return nullptr;
407 }
408 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
409 art::Handle<art::mirror::Object> path_list(
410 hs.NewHandle(path_list_field->GetObject(loader.Get())));
411 CHECK(path_list.Get() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800412 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800413 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
414 dex_path_list_element_field->GetObject(path_list.Get())->
415 AsObjectArray<art::mirror::Object>()));
Alex Light0e692732017-01-10 15:00:05 -0800416 CHECK(!driver_->self_->IsExceptionPending());
Alex Lighta01de592016-11-15 10:43:06 -0800417 CHECK(dex_elements_list.Get() != nullptr);
418 size_t num_elements = dex_elements_list->GetLength();
419 art::MutableHandle<art::mirror::Object> current_element(
420 hs.NewHandle<art::mirror::Object>(nullptr));
421 art::MutableHandle<art::mirror::Object> first_dex_file(
422 hs.NewHandle<art::mirror::Object>(nullptr));
423 // Iterate over the DexPathList$Element to find the right one
424 // TODO Or not ATM just return the first one.
425 for (size_t i = 0; i < num_elements; i++) {
426 current_element.Assign(dex_elements_list->Get(i));
427 CHECK(current_element.Get() != nullptr);
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);
Alex Light0e692732017-01-10 15:00:05 -0800430 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(driver_->self_,
Alex Lighta01de592016-11-15 10:43:06 -0800431 dex_path_list_element_name,
432 null_loader));
433 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
434 // comes from but it is more annoying because we would need to find this class. It is not
435 // necessary for proper function since we just need to be in front of the classes old dex file
436 // in the path.
437 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
438 if (first_dex_file.Get() != nullptr) {
439 return first_dex_file.Get();
440 }
441 }
442 return nullptr;
443}
444
Alex Light0e692732017-01-10 15:00:05 -0800445art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() {
446 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800447}
448
Alex Light0e692732017-01-10 15:00:05 -0800449art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800450 return GetMirrorClass()->GetClassLoader();
451}
452
Alex Light0e692732017-01-10 15:00:05 -0800453art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
454 art::Handle<art::mirror::ClassLoader> loader) {
455 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
Alex Lighta01de592016-11-15 10:43:06 -0800456}
457
458// TODO Really wishing I had that mirror of java.lang.DexFile now.
Alex Light0e692732017-01-10 15:00:05 -0800459art::mirror::LongArray* Redefiner::ClassRedefinition::AllocateDexFileCookie(
Alex Lighta01de592016-11-15 10:43:06 -0800460 art::Handle<art::mirror::Object> java_dex_file_obj) {
Alex Light0e692732017-01-10 15:00:05 -0800461 art::StackHandleScope<2> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800462 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
463 // the object is finalized. Since they always point to the same array if mCookie is not null we
464 // just use the mInternalCookie field. We will update one or both of these fields later.
465 // TODO Should I get the class from the classloader or directly?
466 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
467 "mInternalCookie", "Ljava/lang/Object;");
468 // TODO Add check that mCookie is either null or same as mInternalCookie
469 CHECK(internal_cookie_field != nullptr);
470 art::Handle<art::mirror::LongArray> cookie(
471 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
472 // TODO Maybe make these non-fatal.
473 CHECK(cookie.Get() != nullptr);
474 CHECK_GE(cookie->GetLength(), 1);
475 art::Handle<art::mirror::LongArray> new_cookie(
Alex Light0e692732017-01-10 15:00:05 -0800476 hs.NewHandle(art::mirror::LongArray::Alloc(driver_->self_, cookie->GetLength() + 1)));
Alex Lighta01de592016-11-15 10:43:06 -0800477 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800478 driver_->self_->AssertPendingOOMException();
Alex Lighta01de592016-11-15 10:43:06 -0800479 return nullptr;
480 }
481 // Copy the oat-dex field at the start.
482 // TODO Should I clear this field?
483 // TODO This is a really crappy thing here with the first element being different.
484 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
485 new_cookie->SetWithoutChecks<false>(
486 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
487 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
488 return new_cookie.Get();
489}
490
Alex Light0e692732017-01-10 15:00:05 -0800491void Redefiner::RecordFailure(jvmtiError result,
492 const std::string& class_sig,
493 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800494 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800495 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800496 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800497 result_ = result;
498}
499
Alex Light0e692732017-01-10 15:00:05 -0800500bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lighta01de592016-11-15 10:43:06 -0800501 /*out*/art::MutableHandle<art::mirror::ClassLoader>* source_class_loader,
502 /*out*/art::MutableHandle<art::mirror::Object>* java_dex_file_obj,
503 /*out*/art::MutableHandle<art::mirror::LongArray>* new_dex_file_cookie,
504 /*out*/art::MutableHandle<art::mirror::DexCache>* new_dex_cache) {
Alex Light0e692732017-01-10 15:00:05 -0800505 art::StackHandleScope<4> hs(driver_->self_);
Alex Lighta01de592016-11-15 10:43:06 -0800506 // This shouldn't allocate
507 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
508 if (loader.Get() == nullptr) {
509 // TODO Better error msg.
510 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
511 return false;
512 }
513 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
514 if (dex_file_obj.Get() == nullptr) {
515 // TODO Better error msg.
516 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
517 return false;
518 }
519 art::Handle<art::mirror::LongArray> new_cookie(hs.NewHandle(AllocateDexFileCookie(dex_file_obj)));
520 if (new_cookie.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800521 driver_->self_->AssertPendingOOMException();
522 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800523 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
524 return false;
525 }
526 art::Handle<art::mirror::DexCache> dex_cache(hs.NewHandle(CreateNewDexCache(loader)));
527 if (dex_cache.Get() == nullptr) {
Alex Light0e692732017-01-10 15:00:05 -0800528 driver_->self_->AssertPendingOOMException();
529 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -0800530 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
531 return false;
532 }
533 source_class_loader->Assign(loader.Get());
534 java_dex_file_obj->Assign(dex_file_obj.Get());
535 new_dex_file_cookie->Assign(new_cookie.Get());
536 new_dex_cache->Assign(dex_cache.Get());
537 return true;
538}
539
Alex Lightdba61482016-12-21 08:20:29 -0800540struct CallbackCtx {
Alex Lightdba61482016-12-21 08:20:29 -0800541 art::LinearAlloc* allocator;
542 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
543 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800544
Alex Light0e692732017-01-10 15:00:05 -0800545 explicit CallbackCtx(art::LinearAlloc* alloc) : allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800546};
547
Alex Lightdba61482016-12-21 08:20:29 -0800548void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
549 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800550 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
551 data->allocator,
552 data->obsolete_methods,
553 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800554}
555
556// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
557// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800558// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
559void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800560 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
561 art::mirror::ClassExt* ext = art_klass->GetExtData();
562 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light0e692732017-01-10 15:00:05 -0800563 CallbackCtx ctx(art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800564 // Add all the declared methods to the map
565 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
566 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800567 // TODO Allow this or check in IsModifiableClass.
568 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800569 }
570 {
Alex Light0e692732017-01-10 15:00:05 -0800571 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800572 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
573 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800574 }
575 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800576}
577
578// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
579// figure out their DexCaches.
Alex Light0e692732017-01-10 15:00:05 -0800580void Redefiner::ClassRedefinition::FillObsoleteMethodMap(
Alex Lightdba61482016-12-21 08:20:29 -0800581 art::mirror::Class* art_klass,
582 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
583 int32_t index = 0;
584 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
585 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
586 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
587 ext_data->GetObsoleteDexCaches();
588 int32_t num_method_slots = obsolete_methods->GetLength();
589 // Find the first empty index.
590 for (; index < num_method_slots; index++) {
591 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
592 index, art::kRuntimePointerSize) == nullptr) {
593 break;
594 }
595 }
596 // Make sure we have enough space.
597 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
598 CHECK(obsolete_dex_caches->Get(index) == nullptr);
599 // Fill in the map.
600 for (auto& obs : obsoletes) {
601 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
602 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
603 index++;
604 }
605}
606
607// TODO It should be possible to only deoptimize the specific obsolete methods.
608// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
609// If one of these frames is an obsolete method we have a problem. b/33616143
610// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
611// registers across suspend points.
612// TODO Pending b/33630159
613void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
614 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
615 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
616 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
617}
618
Alex Light0e692732017-01-10 15:00:05 -0800619bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light460d1b42017-01-10 15:37:17 +0000620 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
Alex Light0e692732017-01-10 15:00:05 -0800621 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000622 // Easy check that only 1 class def is present.
623 if (dex_file_->NumClassDefs() != 1) {
624 RecordFailure(ERR(ILLEGAL_ARGUMENT),
625 StringPrintf("Expected 1 class def in dex file but found %d",
626 dex_file_->NumClassDefs()));
627 return false;
628 }
629 // Get the ClassDef from the new DexFile.
630 // Since the dex file has only a single class def the index is always 0.
631 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
632 // Get the class as it is now.
633 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
634
635 // Check the access flags didn't change.
636 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
637 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
638 "Cannot change modifiers of class by redefinition");
639 return false;
640 }
641
642 // Check class name.
643 // These should have been checked by the dexfile verifier on load.
644 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
645 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
646 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
647 if (!current_class->DescriptorEquals(descriptor)) {
648 std::string storage;
649 RecordFailure(ERR(NAMES_DONT_MATCH),
650 StringPrintf("expected file to contain class called '%s' but found '%s'!",
651 current_class->GetDescriptor(&storage),
652 descriptor));
653 return false;
654 }
655 if (current_class->IsObjectClass()) {
656 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
657 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
658 return false;
659 }
660 } else {
661 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
662 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
663 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
664 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
665 return false;
666 }
667 }
668 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
669 if (interfaces == nullptr) {
670 if (current_class->NumDirectInterfaces() != 0) {
671 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
672 return false;
673 }
674 } else {
675 DCHECK(!current_class->IsProxyClass());
676 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
677 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
678 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
679 return false;
680 }
681 // The order of interfaces is (barely) meaningful so we error if it changes.
682 const art::DexFile& orig_dex_file = current_class->GetDexFile();
683 for (uint32_t i = 0; i < interfaces->Size(); i++) {
684 if (strcmp(
685 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
686 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
687 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
688 "Interfaces changed or re-ordered");
689 return false;
690 }
691 }
692 }
693 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
Alex Light0e692732017-01-10 15:00:05 -0800694 LOG(WARNING) << "Bytecodes of redefinitions are not verified.";
Alex Light460d1b42017-01-10 15:37:17 +0000695
696 return true;
697}
698
699// TODO Move this to use IsRedefinable when that function is made.
Alex Light0e692732017-01-10 15:00:05 -0800700bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800701 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800702 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000703
Alex Lighte4a88632017-01-10 07:41:24 -0800704 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
705 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
706 if (res != OK) {
707 RecordFailure(res, err);
708 return false;
709 } else {
710 return true;
711 }
Alex Light460d1b42017-01-10 15:37:17 +0000712}
713
Alex Light0e692732017-01-10 15:00:05 -0800714bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000715 return CheckRedefinable() &&
716 CheckClass() &&
717 CheckSameFields() &&
718 CheckSameMethods();
719}
720
Alex Light0e692732017-01-10 15:00:05 -0800721// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
722// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
723// having to deal with the fact that we need to hold an arbitrary number of references live.
724class RedefinitionDataHolder {
725 public:
726 enum DataSlot : int32_t {
727 kSlotSourceClassLoader = 0,
728 kSlotJavaDexFile = 1,
729 kSlotNewDexFileCookie = 2,
730 kSlotNewDexCache = 3,
731 kSlotMirrorClass = 4,
732
733 // Must be last one.
734 kNumSlots = 5,
735 };
736
737 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
738 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
739 // the passed in handle-scope.
740 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
741 art::Runtime* runtime,
742 art::Thread* self,
743 int32_t num_redefinitions) REQUIRES_SHARED(art::Locks::mutator_lock_) :
744 arr_(
745 hs->NewHandle(
746 art::mirror::ObjectArray<art::mirror::Object>::Alloc(
747 self,
748 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass),
749 num_redefinitions * kNumSlots))) {}
750
751 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
752 return arr_.IsNull();
753 }
754
755 // TODO Maybe make an iterable view type to simplify using this.
756 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index)
757 REQUIRES_SHARED(art::Locks::mutator_lock_) {
758 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader));
759 }
760 art::mirror::Object* GetJavaDexFile(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
761 return GetSlot(klass_index, kSlotJavaDexFile);
762 }
763 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index)
764 REQUIRES_SHARED(art::Locks::mutator_lock_) {
765 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie));
766 }
767 art::mirror::DexCache* GetNewDexCache(jint klass_index)
768 REQUIRES_SHARED(art::Locks::mutator_lock_) {
769 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache));
770 }
771 art::mirror::Class* GetMirrorClass(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
772 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass));
773 }
774
775 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader)
776 REQUIRES_SHARED(art::Locks::mutator_lock_) {
777 SetSlot(klass_index, kSlotSourceClassLoader, loader);
778 }
779 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile)
780 REQUIRES_SHARED(art::Locks::mutator_lock_) {
781 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
782 }
783 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie)
784 REQUIRES_SHARED(art::Locks::mutator_lock_) {
785 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
786 }
787 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache)
788 REQUIRES_SHARED(art::Locks::mutator_lock_) {
789 SetSlot(klass_index, kSlotNewDexCache, cache);
790 }
791 void SetMirrorClass(jint klass_index, art::mirror::Class* klass)
792 REQUIRES_SHARED(art::Locks::mutator_lock_) {
793 SetSlot(klass_index, kSlotMirrorClass, klass);
794 }
795
796 int32_t Length() REQUIRES_SHARED(art::Locks::mutator_lock_) {
797 return arr_->GetLength() / kNumSlots;
798 }
799
800 private:
801 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
802
803 art::mirror::Object* GetSlot(jint klass_index,
804 DataSlot slot) REQUIRES_SHARED(art::Locks::mutator_lock_) {
805 DCHECK_LT(klass_index, Length());
806 return arr_->Get((kNumSlots * klass_index) + slot);
807 }
808
809 void SetSlot(jint klass_index,
810 DataSlot slot,
811 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
812 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
813 DCHECK_LT(klass_index, Length());
814 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
815 }
816
817 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
818};
819
820bool Redefiner::CheckAllRedefinitionAreValid() {
821 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
822 if (!redef.CheckRedefinitionIsValid()) {
823 return false;
824 }
825 }
826 return true;
827}
828
829bool Redefiner::EnsureAllClassAllocationsFinished() {
830 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
831 if (!redef.EnsureClassAllocationsFinished()) {
832 return false;
833 }
834 }
835 return true;
836}
837
838bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
839 int32_t cnt = 0;
840 art::StackHandleScope<4> hs(self_);
841 art::MutableHandle<art::mirror::Object> java_dex_file(hs.NewHandle<art::mirror::Object>(nullptr));
842 art::MutableHandle<art::mirror::ClassLoader> source_class_loader(
843 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
844 art::MutableHandle<art::mirror::LongArray> new_dex_file_cookie(
845 hs.NewHandle<art::mirror::LongArray>(nullptr));
846 art::MutableHandle<art::mirror::DexCache> new_dex_cache(
847 hs.NewHandle<art::mirror::DexCache>(nullptr));
848 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
849 // Reset the out pointers to null
850 source_class_loader.Assign(nullptr);
851 java_dex_file.Assign(nullptr);
852 new_dex_file_cookie.Assign(nullptr);
853 new_dex_cache.Assign(nullptr);
854 // Allocate the data this redefinition requires.
855 if (!redef.FinishRemainingAllocations(&source_class_loader,
856 &java_dex_file,
857 &new_dex_file_cookie,
858 &new_dex_cache)) {
859 return false;
860 }
861 // Save the allocated data into the holder.
862 holder.SetSourceClassLoader(cnt, source_class_loader.Get());
863 holder.SetJavaDexFile(cnt, java_dex_file.Get());
864 holder.SetNewDexFileCookie(cnt, new_dex_file_cookie.Get());
865 holder.SetNewDexCache(cnt, new_dex_cache.Get());
866 holder.SetMirrorClass(cnt, redef.GetMirrorClass());
867 cnt++;
868 }
869 return true;
870}
871
872void Redefiner::ClassRedefinition::ReleaseDexFile() {
873 dex_file_.release();
874}
875
876void Redefiner::ReleaseAllDexFiles() {
877 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
878 redef.ReleaseDexFile();
879 }
880}
881
Alex Lighta01de592016-11-15 10:43:06 -0800882jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -0800883 art::StackHandleScope<1> hs(self_);
884 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
885 // We will let this be collected after the end of this function.
886 RedefinitionDataHolder holder(&hs, runtime_, self_, redefinitions_.size());
887 if (holder.IsNull()) {
888 self_->AssertPendingOOMException();
889 self_->ClearException();
890 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
891 return result_;
892 }
893
Alex Lighta01de592016-11-15 10:43:06 -0800894 // First we just allocate the ClassExt and its fields that we need. These can be updated
895 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
896 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
897 // between allocating them and pausing all threads before we can update them so we need to do a
898 // try loop.
Alex Light0e692732017-01-10 15:00:05 -0800899 if (!CheckAllRedefinitionAreValid() ||
900 !EnsureAllClassAllocationsFinished() ||
901 !FinishAllRemainingAllocations(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -0800902 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
903 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
Alex Light0e692732017-01-10 15:00:05 -0800904 // declared_methods_.length) but would be good to get rid of. All other allocations should be
905 // cleaned up by the GC eventually.
Alex Lighta01de592016-11-15 10:43:06 -0800906 return result_;
907 }
Alex Light6abd5392017-01-05 17:53:00 -0800908 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
909 // allocating so no deadlocks.
910 art::gc::Heap* heap = runtime_->GetHeap();
911 if (heap->IsGcConcurrentAndMoving()) {
912 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
913 heap->IncrementDisableMovingGC(self_);
914 }
Alex Lighta01de592016-11-15 10:43:06 -0800915 // Do transition to final suspension
916 // TODO We might want to give this its own suspended state!
917 // TODO This isn't right. We need to change state without any chance of suspend ideally!
918 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
919 runtime_->GetThreadList()->SuspendAll(
Alex Light0e692732017-01-10 15:00:05 -0800920 "Final installation of redefined Classes!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800921 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
922 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
923 // TODO We need to update all debugger MethodIDs so they note the method they point to is
924 // obsolete or implement some other well defined semantics.
925 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Light0e692732017-01-10 15:00:05 -0800926 int32_t cnt = 0;
927 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
928 art::mirror::Class* klass = holder.GetMirrorClass(cnt);
929 redef.UpdateJavaDexFile(holder.GetJavaDexFile(cnt), holder.GetNewDexFileCookie(cnt));
930 // TODO Rewrite so we don't do a stack walk for each and every class.
931 redef.FindAndAllocateObsoleteMethods(klass);
932 redef.UpdateClass(klass, holder.GetNewDexCache(cnt));
933 cnt++;
934 }
Alex Lightdba61482016-12-21 08:20:29 -0800935 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
936 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
Alex Light0e692732017-01-10 15:00:05 -0800937 // DexCache. (b/33630159)
Alex Lightdba61482016-12-21 08:20:29 -0800938 // TODO This can fail (leave some methods optimized) near runtime methods (including
939 // quick-to-interpreter transition function).
940 // TODO We probably don't need this at all once we have a way to ensure that the
941 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
942 // stack-walker.
943 EnsureObsoleteMethodsAreDeoptimized();
944 // TODO Verify the new Class.
Alex Lightdba61482016-12-21 08:20:29 -0800945 // TODO Shrink the obsolete method maps if possible?
946 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800947 // TODO Put this into a scoped thing.
948 runtime_->GetThreadList()->ResumeAll();
949 // Get back shared mutator lock as expected for return.
950 self_->TransitionFromSuspendedToRunnable();
Alex Light0e692732017-01-10 15:00:05 -0800951 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
952 // owns the DexFile and when ownership is transferred.
953 ReleaseAllDexFiles();
Alex Light6abd5392017-01-05 17:53:00 -0800954 if (heap->IsGcConcurrentAndMoving()) {
955 heap->DecrementDisableMovingGC(self_);
956 }
Alex Lighta01de592016-11-15 10:43:06 -0800957 return OK;
958}
959
Alex Light0e692732017-01-10 15:00:05 -0800960void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
961 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
962 const art::DexFile::ClassDef& class_def) {
963 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -0800964 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800965 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800966 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800967 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800968 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
969 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
970 art::dex::TypeIndex method_return_idx =
971 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
972 const auto* old_type_list = method.GetParameterTypeList();
973 std::vector<art::dex::TypeIndex> new_type_list;
974 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
975 new_type_list.push_back(
976 dex_file_->GetIndexForTypeId(
977 *dex_file_->FindTypeId(
978 old_dex_file.GetTypeDescriptor(
979 old_dex_file.GetTypeId(
980 old_type_list->GetTypeItem(i).type_idx_)))));
981 }
982 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
983 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000984 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800985 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800986 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
987 *new_name_id,
988 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000989 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800990 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800991 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
992 method.SetDexMethodIndex(dex_method_idx);
993 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800994 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800995 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800996 // Notify the jit that this method is redefined.
Alex Light0e692732017-01-10 15:00:05 -0800997 art::jit::Jit* jit = driver_->runtime_->GetJit();
Alex Lightdba61482016-12-21 08:20:29 -0800998 if (jit != nullptr) {
999 jit->GetCodeCache()->NotifyMethodRedefined(&method);
1000 }
Alex Lighta01de592016-11-15 10:43:06 -08001001 }
Alex Light200b9d72016-12-15 11:34:13 -08001002}
1003
Alex Light0e692732017-01-10 15:00:05 -08001004void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001005 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1006 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1007 for (art::ArtField& field : fields_iter) {
1008 std::string declaring_class_name;
1009 const art::DexFile::TypeId* new_declaring_id =
1010 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
1011 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1012 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
1013 // TODO Handle error, cleanup.
1014 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
1015 const art::DexFile::FieldId* new_field_id =
1016 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1017 CHECK(new_field_id != nullptr);
1018 // We only need to update the index since the other data in the ArtField cannot be updated.
1019 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1020 }
1021 }
Alex Light200b9d72016-12-15 11:34:13 -08001022}
1023
1024// Performs updates to class that will allow us to verify it.
Alex Light0e692732017-01-10 15:00:05 -08001025void Redefiner::ClassRedefinition::UpdateClass(art::ObjPtr<art::mirror::Class> mclass,
1026 art::ObjPtr<art::mirror::DexCache> new_dex_cache) {
Alex Lighta6c5e972017-01-13 14:15:41 -08001027 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1028 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0);
1029 UpdateMethods(mclass, new_dex_cache, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001030 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001031
Alex Lighta01de592016-11-15 10:43:06 -08001032 // Update the class fields.
1033 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1034 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1035 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Lighta6c5e972017-01-13 14:15:41 -08001036 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001037 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Lighta01de592016-11-15 10:43:06 -08001038}
1039
Alex Light0e692732017-01-10 15:00:05 -08001040void Redefiner::ClassRedefinition::UpdateJavaDexFile(
1041 art::ObjPtr<art::mirror::Object> java_dex_file,
1042 art::ObjPtr<art::mirror::LongArray> new_cookie) {
Alex Lighta01de592016-11-15 10:43:06 -08001043 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1044 "mInternalCookie", "Ljava/lang/Object;");
1045 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
1046 "mCookie", "Ljava/lang/Object;");
1047 CHECK(internal_cookie_field != nullptr);
1048 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
1049 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
1050 art::ObjPtr<art::mirror::LongArray> orig_cookie(
1051 cookie_field->GetObject(java_dex_file)->AsLongArray());
1052 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
Alex Lighta01de592016-11-15 10:43:06 -08001053 if (!orig_cookie.IsNull()) {
1054 cookie_field->SetObject<false>(java_dex_file, new_cookie);
1055 }
Alex Lighta01de592016-11-15 10:43:06 -08001056}
1057
1058// This function does all (java) allocations we need to do for the Class being redefined.
1059// TODO Change this name maybe?
Alex Light0e692732017-01-10 15:00:05 -08001060bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished() {
1061 art::StackHandleScope<2> hs(driver_->self_);
1062 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1063 driver_->self_->DecodeJObject(klass_)->AsClass()));
Alex Lighta01de592016-11-15 10:43:06 -08001064 if (klass.Get() == nullptr) {
1065 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1066 return false;
1067 }
1068 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001069 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Alex Lighta01de592016-11-15 10:43:06 -08001070 if (ext.Get() == nullptr) {
1071 // No memory. Clear exception (it's not useful) and return error.
1072 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
1073 // this case.
Alex Light0e692732017-01-10 15:00:05 -08001074 driver_->self_->AssertPendingOOMException();
1075 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001076 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1077 return false;
1078 }
1079 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
1080 // are only modified when all threads (other than the modifying one) are suspended we don't need
1081 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1082 // however, since that can happen at any time.
1083 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
1084 // are no obsolete methods.
1085 {
Alex Light0e692732017-01-10 15:00:05 -08001086 art::ObjectLock<art::mirror::ClassExt> lock(driver_->self_, ext);
Alex Lighta01de592016-11-15 10:43:06 -08001087 if (!ext->ExtendObsoleteArrays(
Alex Light0e692732017-01-10 15:00:05 -08001088 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Lighta01de592016-11-15 10:43:06 -08001089 // OOM. Clear exception and return error.
Alex Light0e692732017-01-10 15:00:05 -08001090 driver_->self_->AssertPendingOOMException();
1091 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001092 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1093 return false;
1094 }
1095 }
1096 return true;
1097}
1098
1099} // namespace openjdkjvmti