blob: 57cc938ec7060041d38969d294d43bda76e347f8 [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"
40#include "events-inl.h"
41#include "gc/allocation_listener.h"
42#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080043#include "jit/jit.h"
44#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080045#include "jni_env_ext-inl.h"
46#include "jvmti_allocator.h"
47#include "mirror/class.h"
48#include "mirror/class_ext.h"
49#include "mirror/object.h"
50#include "object_lock.h"
51#include "runtime.h"
52#include "ScopedLocalRef.h"
53
54namespace openjdkjvmti {
55
Andreas Gampe46ee31b2016-12-14 10:11:49 -080056using android::base::StringPrintf;
57
Alex Lightdba61482016-12-21 08:20:29 -080058// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
59// some basic sanity checks that the obsolete method is sane.
60class ObsoleteMethodStackVisitor : public art::StackVisitor {
61 protected:
62 ObsoleteMethodStackVisitor(
63 art::Thread* thread,
64 art::LinearAlloc* allocator,
65 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
66 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps,
67 /*out*/bool* success,
68 /*out*/std::string* error_msg)
69 : StackVisitor(thread,
70 /*context*/nullptr,
71 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
72 allocator_(allocator),
73 obsoleted_methods_(obsoleted_methods),
74 obsolete_maps_(obsolete_maps),
75 success_(success),
76 is_runtime_frame_(false),
77 error_msg_(error_msg) {
78 *success_ = true;
79 }
80
81 ~ObsoleteMethodStackVisitor() OVERRIDE {}
82
83 public:
84 // Returns true if we successfully installed obsolete methods on this thread, filling
85 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
86 // The stack is cleaned up when we fail.
87 static bool UpdateObsoleteFrames(
88 art::Thread* thread,
89 art::LinearAlloc* allocator,
90 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
91 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps,
92 /*out*/std::string* error_msg) REQUIRES(art::Locks::mutator_lock_) {
93 bool success = true;
94 ObsoleteMethodStackVisitor visitor(thread,
95 allocator,
96 obsoleted_methods,
97 obsolete_maps,
98 &success,
99 error_msg);
100 visitor.WalkStack();
101 if (!success) {
102 RestoreFrames(thread, *obsolete_maps, error_msg);
103 return false;
104 } else {
105 return true;
106 }
107 }
108
109 static void RestoreFrames(
110 art::Thread* thread ATTRIBUTE_UNUSED,
111 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsolete_maps ATTRIBUTE_UNUSED,
112 std::string* error_msg)
113 REQUIRES(art::Locks::mutator_lock_) {
114 LOG(FATAL) << "Restoring stack frames is not yet supported. Error was: " << *error_msg;
115 }
116
117 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
118 art::ArtMethod* old_method = GetMethod();
119 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
120 // works through runtime methods.
121 bool prev_was_runtime_frame_ = is_runtime_frame_;
122 is_runtime_frame_ = old_method->IsRuntimeMethod();
123 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
124 // The check below works since when we deoptimize we set shadow frames for all frames until a
125 // native/runtime transition and for those set the return PC to a function that will complete
126 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
127 // below runtime frames cannot be deoptimized at the moment.
128 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
129 // works through runtime methods.
130 // TODO b/33616143
131 if (!IsShadowFrame() && prev_was_runtime_frame_) {
132 *error_msg_ = StringPrintf("Deoptimization failed due to runtime method in stack.");
133 *success_ = false;
134 return false;
135 }
136 // We cannot ensure that the right dex file is used in inlined frames so we don't support
137 // redefining them.
138 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
139 // TODO We should really support intrinsic obsolete methods.
140 // TODO We should really support redefining intrinsics.
141 // We don't support intrinsics so check for them here.
142 DCHECK(!old_method->IsIntrinsic());
143 art::ArtMethod* new_obsolete_method = nullptr;
144 auto obsolete_method_pair = obsolete_maps_->find(old_method);
145 if (obsolete_method_pair == obsolete_maps_->end()) {
146 // Create a new Obsolete Method and put it in the list.
147 art::Runtime* runtime = art::Runtime::Current();
148 art::ClassLinker* cl = runtime->GetClassLinker();
149 auto ptr_size = cl->GetImagePointerSize();
150 const size_t method_size = art::ArtMethod::Size(ptr_size);
151 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
152 if (method_storage == nullptr) {
153 *success_ = false;
154 *error_msg_ = StringPrintf("Unable to allocate storage for obsolete version of '%s'",
155 old_method->PrettyMethod().c_str());
156 return false;
157 }
158 new_obsolete_method = new (method_storage) art::ArtMethod();
159 new_obsolete_method->CopyFrom(old_method, ptr_size);
160 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
161 new_obsolete_method->SetIsObsolete();
162 obsolete_maps_->insert({old_method, new_obsolete_method});
163 // Update JIT Data structures to point to the new method.
164 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
165 if (jit != nullptr) {
166 // Notify the JIT we are making this obsolete method. It will update the jit's internal
167 // structures to keep track of the new obsolete method.
168 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
169 }
170 } else {
171 new_obsolete_method = obsolete_method_pair->second;
172 }
173 DCHECK(new_obsolete_method != nullptr);
174 SetMethod(new_obsolete_method);
175 }
176 return true;
177 }
178
179 private:
180 // The linear allocator we should use to make new methods.
181 art::LinearAlloc* allocator_;
182 // The set of all methods which could be obsoleted.
183 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
184 // A map from the original to the newly allocated obsolete method for frames on this thread. The
185 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
186 // the redefined classes ClassExt by the caller.
187 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
188 bool* success_;
189 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
190 // works through runtime methods.
191 bool is_runtime_frame_;
192 std::string* error_msg_;
193};
194
Alex Lighta01de592016-11-15 10:43:06 -0800195// Moves dex data to an anonymous, read-only mmap'd region.
196std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
197 jint data_len,
198 unsigned char* dex_data,
199 std::string* error_msg) {
200 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800201 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800202 nullptr,
203 data_len,
204 PROT_READ|PROT_WRITE,
205 /*low_4gb*/false,
206 /*reuse*/false,
207 error_msg));
208 if (map == nullptr) {
209 return map;
210 }
211 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800212 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
213 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800214 map->Protect(PROT_READ);
215 return map;
216}
217
Alex Lightdba61482016-12-21 08:20:29 -0800218// TODO This should handle doing multiple classes at once so we need to do less cleanup when things
219// go wrong.
Alex Lighta01de592016-11-15 10:43:06 -0800220jvmtiError Redefiner::RedefineClass(ArtJvmTiEnv* env,
221 art::Runtime* runtime,
222 art::Thread* self,
223 jclass klass,
224 const std::string& original_dex_location,
225 jint data_len,
226 unsigned char* dex_data,
227 std::string* error_msg) {
228 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
229 data_len,
230 dex_data,
231 error_msg));
232 std::ostringstream os;
233 char* generic_ptr_unused = nullptr;
234 char* signature_ptr = nullptr;
235 if (env->GetClassSignature(klass, &signature_ptr, &generic_ptr_unused) != OK) {
236 signature_ptr = const_cast<char*>("<UNKNOWN CLASS>");
237 }
238 if (map.get() == nullptr) {
239 os << "Failed to create anonymous mmap for modified dex file of class " << signature_ptr
240 << "in dex file " << original_dex_location << " because: " << *error_msg;
241 *error_msg = os.str();
242 return ERR(OUT_OF_MEMORY);
243 }
244 if (map->Size() < sizeof(art::DexFile::Header)) {
245 *error_msg = "Could not read dex file header because dex_data was too short";
246 return ERR(INVALID_CLASS_FORMAT);
247 }
248 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
249 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
250 checksum,
251 std::move(map),
252 /*verify*/true,
253 /*verify_checksum*/true,
254 error_msg));
255 if (dex_file.get() == nullptr) {
256 os << "Unable to load modified dex file for " << signature_ptr << ": " << *error_msg;
257 *error_msg = os.str();
258 return ERR(INVALID_CLASS_FORMAT);
259 }
Alex Lightdba61482016-12-21 08:20:29 -0800260 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
261 // are going to redefine.
262 art::jit::ScopedJitSuspend suspend_jit;
Alex Lighta01de592016-11-15 10:43:06 -0800263 // Get shared mutator lock.
264 art::ScopedObjectAccess soa(self);
265 art::StackHandleScope<1> hs(self);
266 Redefiner r(runtime, self, klass, signature_ptr, dex_file, error_msg);
267 // Lock around this class to avoid races.
268 art::ObjectLock<art::mirror::Class> lock(self, hs.NewHandle(r.GetMirrorClass()));
269 return r.Run();
270}
271
272// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
273// TODO Make mirror of DexFile and associated types to make this less hellish.
274// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
275art::mirror::Object* Redefiner::FindSourceDexFileObject(
276 art::Handle<art::mirror::ClassLoader> loader) {
277 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
278 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
279 const char* dex_file_name = "Ldalvik/system/DexFile;";
280 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
281 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
282
283 CHECK(!self_->IsExceptionPending());
284 art::StackHandleScope<11> hs(self_);
285 art::ClassLinker* class_linker = runtime_->GetClassLinker();
286
287 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
288 nullptr));
289 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
290 self_, dex_class_loader_name, null_loader)));
291
292 // Get all the ArtFields so we can look in the BaseDexClassLoader
293 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
294 "pathList", dex_path_list_name);
295 CHECK(path_list_field != nullptr);
296
297 art::ArtField* dex_path_list_element_field =
298 class_linker->FindClass(self_, dex_path_list_name, null_loader)
299 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
300 CHECK(dex_path_list_element_field != nullptr);
301
302 art::ArtField* element_dex_file_field =
303 class_linker->FindClass(self_, dex_path_list_element_name, null_loader)
304 ->FindDeclaredInstanceField("dexFile", dex_file_name);
305 CHECK(element_dex_file_field != nullptr);
306
307 // Check if loader is a BaseDexClassLoader
308 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
309 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
310 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
311 << "supported class loader type!";
312 return nullptr;
313 }
314 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
315 art::Handle<art::mirror::Object> path_list(
316 hs.NewHandle(path_list_field->GetObject(loader.Get())));
317 CHECK(path_list.Get() != nullptr);
318 CHECK(!self_->IsExceptionPending());
319 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
320 dex_path_list_element_field->GetObject(path_list.Get())->
321 AsObjectArray<art::mirror::Object>()));
322 CHECK(!self_->IsExceptionPending());
323 CHECK(dex_elements_list.Get() != nullptr);
324 size_t num_elements = dex_elements_list->GetLength();
325 art::MutableHandle<art::mirror::Object> current_element(
326 hs.NewHandle<art::mirror::Object>(nullptr));
327 art::MutableHandle<art::mirror::Object> first_dex_file(
328 hs.NewHandle<art::mirror::Object>(nullptr));
329 // Iterate over the DexPathList$Element to find the right one
330 // TODO Or not ATM just return the first one.
331 for (size_t i = 0; i < num_elements; i++) {
332 current_element.Assign(dex_elements_list->Get(i));
333 CHECK(current_element.Get() != nullptr);
334 CHECK(!self_->IsExceptionPending());
335 CHECK(dex_elements_list.Get() != nullptr);
336 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(self_,
337 dex_path_list_element_name,
338 null_loader));
339 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
340 // comes from but it is more annoying because we would need to find this class. It is not
341 // necessary for proper function since we just need to be in front of the classes old dex file
342 // in the path.
343 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
344 if (first_dex_file.Get() != nullptr) {
345 return first_dex_file.Get();
346 }
347 }
348 return nullptr;
349}
350
351art::mirror::Class* Redefiner::GetMirrorClass() {
352 return self_->DecodeJObject(klass_)->AsClass();
353}
354
355art::mirror::ClassLoader* Redefiner::GetClassLoader() {
356 return GetMirrorClass()->GetClassLoader();
357}
358
359art::mirror::DexCache* Redefiner::CreateNewDexCache(art::Handle<art::mirror::ClassLoader> loader) {
360 return runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
361}
362
363// TODO Really wishing I had that mirror of java.lang.DexFile now.
364art::mirror::LongArray* Redefiner::AllocateDexFileCookie(
365 art::Handle<art::mirror::Object> java_dex_file_obj) {
366 art::StackHandleScope<2> hs(self_);
367 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
368 // the object is finalized. Since they always point to the same array if mCookie is not null we
369 // just use the mInternalCookie field. We will update one or both of these fields later.
370 // TODO Should I get the class from the classloader or directly?
371 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
372 "mInternalCookie", "Ljava/lang/Object;");
373 // TODO Add check that mCookie is either null or same as mInternalCookie
374 CHECK(internal_cookie_field != nullptr);
375 art::Handle<art::mirror::LongArray> cookie(
376 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
377 // TODO Maybe make these non-fatal.
378 CHECK(cookie.Get() != nullptr);
379 CHECK_GE(cookie->GetLength(), 1);
380 art::Handle<art::mirror::LongArray> new_cookie(
381 hs.NewHandle(art::mirror::LongArray::Alloc(self_, cookie->GetLength() + 1)));
382 if (new_cookie.Get() == nullptr) {
383 self_->AssertPendingOOMException();
384 return nullptr;
385 }
386 // Copy the oat-dex field at the start.
387 // TODO Should I clear this field?
388 // TODO This is a really crappy thing here with the first element being different.
389 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
390 new_cookie->SetWithoutChecks<false>(
391 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
392 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
393 return new_cookie.Get();
394}
395
396void Redefiner::RecordFailure(jvmtiError result, const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800397 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
398 class_sig_,
399 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800400 result_ = result;
401}
402
403bool Redefiner::FinishRemainingAllocations(
404 /*out*/art::MutableHandle<art::mirror::ClassLoader>* source_class_loader,
405 /*out*/art::MutableHandle<art::mirror::Object>* java_dex_file_obj,
406 /*out*/art::MutableHandle<art::mirror::LongArray>* new_dex_file_cookie,
407 /*out*/art::MutableHandle<art::mirror::DexCache>* new_dex_cache) {
408 art::StackHandleScope<4> hs(self_);
409 // This shouldn't allocate
410 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
411 if (loader.Get() == nullptr) {
412 // TODO Better error msg.
413 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
414 return false;
415 }
416 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
417 if (dex_file_obj.Get() == nullptr) {
418 // TODO Better error msg.
419 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
420 return false;
421 }
422 art::Handle<art::mirror::LongArray> new_cookie(hs.NewHandle(AllocateDexFileCookie(dex_file_obj)));
423 if (new_cookie.Get() == nullptr) {
424 self_->AssertPendingOOMException();
425 self_->ClearException();
426 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
427 return false;
428 }
429 art::Handle<art::mirror::DexCache> dex_cache(hs.NewHandle(CreateNewDexCache(loader)));
430 if (dex_cache.Get() == nullptr) {
431 self_->AssertPendingOOMException();
432 self_->ClearException();
433 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
434 return false;
435 }
436 source_class_loader->Assign(loader.Get());
437 java_dex_file_obj->Assign(dex_file_obj.Get());
438 new_dex_file_cookie->Assign(new_cookie.Get());
439 new_dex_cache->Assign(dex_cache.Get());
440 return true;
441}
442
Alex Lightdba61482016-12-21 08:20:29 -0800443struct CallbackCtx {
444 Redefiner* const r;
445 art::LinearAlloc* allocator;
446 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
447 std::unordered_set<art::ArtMethod*> obsolete_methods;
448 bool success;
449 std::string* error_msg;
450
451 CallbackCtx(Redefiner* self, art::LinearAlloc* alloc, std::string* error)
452 : r(self), allocator(alloc), success(true), error_msg(error) {}
453};
454
455void DoRestoreObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
456 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
457 ObsoleteMethodStackVisitor::RestoreFrames(t, data->obsolete_map, data->error_msg);
458}
459
460void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
461 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
462 if (data->success) {
463 // Don't do anything if we already failed once.
464 data->success = ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
465 data->allocator,
466 data->obsolete_methods,
467 &data->obsolete_map,
468 data->error_msg);
469 }
470}
471
472// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
473// updated so they will be run.
474bool Redefiner::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
475 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
476 art::mirror::ClassExt* ext = art_klass->GetExtData();
477 CHECK(ext->GetObsoleteMethods() != nullptr);
478 CallbackCtx ctx(this, art_klass->GetClassLoader()->GetAllocator(), error_msg_);
479 // Add all the declared methods to the map
480 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
481 ctx.obsolete_methods.insert(&m);
482 }
483 for (art::ArtMethod* old_method : ctx.obsolete_methods) {
484 if (old_method->IsIntrinsic()) {
485 *error_msg_ = StringPrintf("Method '%s' is intrinsic and cannot be made obsolete!",
486 old_method->PrettyMethod().c_str());
487 return false;
488 }
489 }
490 {
491 art::MutexLock mu(self_, *art::Locks::thread_list_lock_);
492 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
493 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
494 if (!ctx.success) {
495 list->ForEach(DoRestoreObsoleteMethodsCallback, static_cast<void*>(&ctx));
496 return false;
497 }
498 }
499 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
500 return true;
501}
502
503// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
504// figure out their DexCaches.
505void Redefiner::FillObsoleteMethodMap(
506 art::mirror::Class* art_klass,
507 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
508 int32_t index = 0;
509 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
510 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
511 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
512 ext_data->GetObsoleteDexCaches();
513 int32_t num_method_slots = obsolete_methods->GetLength();
514 // Find the first empty index.
515 for (; index < num_method_slots; index++) {
516 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
517 index, art::kRuntimePointerSize) == nullptr) {
518 break;
519 }
520 }
521 // Make sure we have enough space.
522 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
523 CHECK(obsolete_dex_caches->Get(index) == nullptr);
524 // Fill in the map.
525 for (auto& obs : obsoletes) {
526 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
527 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
528 index++;
529 }
530}
531
532// TODO It should be possible to only deoptimize the specific obsolete methods.
533// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
534// If one of these frames is an obsolete method we have a problem. b/33616143
535// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
536// registers across suspend points.
537// TODO Pending b/33630159
538void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
539 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
540 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
541 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
542}
543
Alex Lighta01de592016-11-15 10:43:06 -0800544jvmtiError Redefiner::Run() {
545 art::StackHandleScope<5> hs(self_);
546 // TODO We might want to have a global lock (or one based on the class being redefined at least)
547 // in order to make cleanup easier. Not a huge deal though.
548 //
549 // First we just allocate the ClassExt and its fields that we need. These can be updated
550 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
551 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
552 // between allocating them and pausing all threads before we can update them so we need to do a
553 // try loop.
554 if (!EnsureRedefinitionIsValid() || !EnsureClassAllocationsFinished()) {
555 return result_;
556 }
557 art::MutableHandle<art::mirror::ClassLoader> source_class_loader(
558 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
559 art::MutableHandle<art::mirror::Object> java_dex_file(
560 hs.NewHandle<art::mirror::Object>(nullptr));
561 art::MutableHandle<art::mirror::LongArray> new_dex_file_cookie(
562 hs.NewHandle<art::mirror::LongArray>(nullptr));
563 art::MutableHandle<art::mirror::DexCache> new_dex_cache(
564 hs.NewHandle<art::mirror::DexCache>(nullptr));
565 if (!FinishRemainingAllocations(&source_class_loader,
566 &java_dex_file,
567 &new_dex_file_cookie,
568 &new_dex_cache)) {
569 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
570 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
571 // declared_methods_.length) but would be good to get rid of.
572 // new_dex_file_cookie & new_dex_cache should be cleaned up by the GC.
573 return result_;
574 }
575 // Get the mirror class now that we aren't allocating anymore.
576 art::Handle<art::mirror::Class> art_class(hs.NewHandle(GetMirrorClass()));
577 // Enable assertion that this thread isn't interrupted during this installation.
578 // After this we will need to do real cleanup in case of failure. Prior to this we could simply
579 // return and would let everything get cleaned up or harmlessly leaked.
580 // Do transition to final suspension
581 // TODO We might want to give this its own suspended state!
582 // TODO This isn't right. We need to change state without any chance of suspend ideally!
583 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
584 runtime_->GetThreadList()->SuspendAll(
585 "Final installation of redefined Class!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800586 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
587 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
588 // TODO We need to update all debugger MethodIDs so they note the method they point to is
589 // obsolete or implement some other well defined semantics.
590 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Lighta01de592016-11-15 10:43:06 -0800591 // TODO Might want to move this into a different type.
592 // Now we reach the part where we must do active cleanup if something fails.
593 // TODO We should really Retry if this fails instead of simply aborting.
594 // Set the new DexFileCookie returns the original so we can fix it back up if redefinition fails
595 art::ObjPtr<art::mirror::LongArray> original_dex_file_cookie(nullptr);
596 if (!UpdateJavaDexFile(java_dex_file.Get(),
597 new_dex_file_cookie.Get(),
Alex Lightdba61482016-12-21 08:20:29 -0800598 &original_dex_file_cookie) ||
599 !FindAndAllocateObsoleteMethods(art_class.Get())) {
Alex Lighta01de592016-11-15 10:43:06 -0800600 // Release suspendAll
601 runtime_->GetThreadList()->ResumeAll();
602 // Get back shared mutator lock as expected for return.
603 self_->TransitionFromSuspendedToRunnable();
604 return result_;
605 }
606 if (!UpdateClass(art_class.Get(), new_dex_cache.Get())) {
607 // TODO Should have some form of scope to do this.
608 RestoreJavaDexFile(java_dex_file.Get(), original_dex_file_cookie);
609 // Release suspendAll
610 runtime_->GetThreadList()->ResumeAll();
611 // Get back shared mutator lock as expected for return.
612 self_->TransitionFromSuspendedToRunnable();
613 return result_;
614 }
Alex Lightdba61482016-12-21 08:20:29 -0800615 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
616 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
617 // DexCache.
618 // TODO This can fail (leave some methods optimized) near runtime methods (including
619 // quick-to-interpreter transition function).
620 // TODO We probably don't need this at all once we have a way to ensure that the
621 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
622 // stack-walker.
623 EnsureObsoleteMethodsAreDeoptimized();
624 // TODO Verify the new Class.
625 // TODO Failure then undo updates to class
626 // TODO Shrink the obsolete method maps if possible?
627 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800628 // TODO Put this into a scoped thing.
629 runtime_->GetThreadList()->ResumeAll();
630 // Get back shared mutator lock as expected for return.
631 self_->TransitionFromSuspendedToRunnable();
Alex Lightdba61482016-12-21 08:20:29 -0800632 // TODO Do the dex_file_ release at a more reasonable place. This works but it muddles who really
633 // owns the DexFile.
Alex Lighta01de592016-11-15 10:43:06 -0800634 dex_file_.release();
635 return OK;
636}
637
638void Redefiner::RestoreJavaDexFile(art::ObjPtr<art::mirror::Object> java_dex_file,
639 art::ObjPtr<art::mirror::LongArray> orig_cookie) {
640 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
641 "mInternalCookie", "Ljava/lang/Object;");
642 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
643 "mCookie", "Ljava/lang/Object;");
644 art::ObjPtr<art::mirror::LongArray> new_cookie(
645 cookie_field->GetObject(java_dex_file)->AsLongArray());
646 internal_cookie_field->SetObject<false>(java_dex_file, orig_cookie);
647 if (!new_cookie.IsNull()) {
648 cookie_field->SetObject<false>(java_dex_file, orig_cookie);
649 }
650}
651
Alex Light200b9d72016-12-15 11:34:13 -0800652bool Redefiner::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
653 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
654 const art::DexFile::ClassDef& class_def) {
Alex Lighta01de592016-11-15 10:43:06 -0800655 art::ClassLinker* linker = runtime_->GetClassLinker();
656 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800657 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800658 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800659 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800660 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
661 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
662 art::dex::TypeIndex method_return_idx =
663 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
664 const auto* old_type_list = method.GetParameterTypeList();
665 std::vector<art::dex::TypeIndex> new_type_list;
666 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
667 new_type_list.push_back(
668 dex_file_->GetIndexForTypeId(
669 *dex_file_->FindTypeId(
670 old_dex_file.GetTypeDescriptor(
671 old_dex_file.GetTypeId(
672 old_type_list->GetTypeItem(i).type_idx_)))));
673 }
674 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
675 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000676 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800677 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800678 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
679 *new_name_id,
680 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000681 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800682 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800683 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
684 method.SetDexMethodIndex(dex_method_idx);
685 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800686 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800687 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
688 method.SetDexCacheResolvedTypes(new_dex_cache->GetResolvedTypes(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800689 // Notify the jit that this method is redefined.
690 art::jit::Jit* jit = runtime_->GetJit();
691 if (jit != nullptr) {
692 jit->GetCodeCache()->NotifyMethodRedefined(&method);
693 }
Alex Lighta01de592016-11-15 10:43:06 -0800694 }
Alex Light200b9d72016-12-15 11:34:13 -0800695 return true;
696}
697
698bool Redefiner::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
699 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
700 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
701 for (art::ArtField& field : fields_iter) {
702 std::string declaring_class_name;
703 const art::DexFile::TypeId* new_declaring_id =
704 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
705 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
706 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
707 // TODO Handle error, cleanup.
708 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
709 const art::DexFile::FieldId* new_field_id =
710 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
711 CHECK(new_field_id != nullptr);
712 // We only need to update the index since the other data in the ArtField cannot be updated.
713 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
714 }
715 }
716 return true;
717}
718
719// Performs updates to class that will allow us to verify it.
720bool Redefiner::UpdateClass(art::ObjPtr<art::mirror::Class> mclass,
721 art::ObjPtr<art::mirror::DexCache> new_dex_cache) {
722 const art::DexFile::ClassDef* class_def = art::OatFile::OatDexFile::FindClassDef(
723 *dex_file_, class_sig_, art::ComputeModifiedUtf8Hash(class_sig_));
724 if (class_def == nullptr) {
725 RecordFailure(ERR(INVALID_CLASS_FORMAT), "Unable to find ClassDef!");
726 return false;
727 }
728 if (!UpdateMethods(mclass, new_dex_cache, *class_def)) {
729 // TODO Investigate appropriate error types.
730 RecordFailure(ERR(INTERNAL), "Unable to update class methods.");
731 return false;
732 }
733 if (!UpdateFields(mclass)) {
734 // TODO Investigate appropriate error types.
735 RecordFailure(ERR(INTERNAL), "Unable to update class fields.");
736 return false;
737 }
738
Alex Lighta01de592016-11-15 10:43:06 -0800739 // Update the class fields.
740 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
741 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
742 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Lighta01de592016-11-15 10:43:06 -0800743 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(*class_def));
744 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_)));
745 return true;
746}
747
748bool Redefiner::UpdateJavaDexFile(art::ObjPtr<art::mirror::Object> java_dex_file,
749 art::ObjPtr<art::mirror::LongArray> new_cookie,
750 /*out*/art::ObjPtr<art::mirror::LongArray>* original_cookie) {
751 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
752 "mInternalCookie", "Ljava/lang/Object;");
753 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
754 "mCookie", "Ljava/lang/Object;");
755 CHECK(internal_cookie_field != nullptr);
756 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
757 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
758 art::ObjPtr<art::mirror::LongArray> orig_cookie(
759 cookie_field->GetObject(java_dex_file)->AsLongArray());
760 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
761 *original_cookie = orig_internal_cookie;
762 if (!orig_cookie.IsNull()) {
763 cookie_field->SetObject<false>(java_dex_file, new_cookie);
764 }
765 return true;
766}
767
768// This function does all (java) allocations we need to do for the Class being redefined.
769// TODO Change this name maybe?
770bool Redefiner::EnsureClassAllocationsFinished() {
771 art::StackHandleScope<2> hs(self_);
772 art::Handle<art::mirror::Class> klass(hs.NewHandle(self_->DecodeJObject(klass_)->AsClass()));
773 if (klass.Get() == nullptr) {
774 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
775 return false;
776 }
777 // Allocate the classExt
778 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self_)));
779 if (ext.Get() == nullptr) {
780 // No memory. Clear exception (it's not useful) and return error.
781 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
782 // this case.
783 self_->AssertPendingOOMException();
784 self_->ClearException();
785 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
786 return false;
787 }
788 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
789 // are only modified when all threads (other than the modifying one) are suspended we don't need
790 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
791 // however, since that can happen at any time.
792 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
793 // are no obsolete methods.
794 {
795 art::ObjectLock<art::mirror::ClassExt> lock(self_, ext);
796 if (!ext->ExtendObsoleteArrays(
797 self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
798 // OOM. Clear exception and return error.
799 self_->AssertPendingOOMException();
800 self_->ClearException();
801 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
802 return false;
803 }
804 }
805 return true;
806}
807
808} // namespace openjdkjvmti