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