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