blob: adec6c94bc6c993e9a861e5112aec77191fb318d [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* Copyright (C) 2016 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvmti.h. This implementation
5 * is licensed under the same terms as the file jvmti.h. The
6 * copyright and license information for the file jvmti.h follows.
7 *
8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32#include "ti_redefine.h"
33
34#include <limits>
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Alex Lighta01de592016-11-15 10:43:06 -080038#include "art_jvmti.h"
39#include "base/logging.h"
Alex Light460d1b42017-01-10 15:37:17 +000040#include "dex_file.h"
41#include "dex_file_types.h"
Alex Lighta01de592016-11-15 10:43:06 -080042#include "events-inl.h"
43#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080044#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080045#include "instrumentation.h"
Alex Lightdba61482016-12-21 08:20:29 -080046#include "jit/jit.h"
47#include "jit/jit_code_cache.h"
Alex Lighta01de592016-11-15 10:43:06 -080048#include "jni_env_ext-inl.h"
49#include "jvmti_allocator.h"
50#include "mirror/class.h"
51#include "mirror/class_ext.h"
52#include "mirror/object.h"
53#include "object_lock.h"
54#include "runtime.h"
55#include "ScopedLocalRef.h"
56
57namespace openjdkjvmti {
58
Andreas Gampe46ee31b2016-12-14 10:11:49 -080059using android::base::StringPrintf;
60
Alex Lightdba61482016-12-21 08:20:29 -080061// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
62// some basic sanity checks that the obsolete method is sane.
63class ObsoleteMethodStackVisitor : public art::StackVisitor {
64 protected:
65 ObsoleteMethodStackVisitor(
66 art::Thread* thread,
67 art::LinearAlloc* allocator,
68 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
69 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps,
70 /*out*/bool* success,
71 /*out*/std::string* error_msg)
72 : StackVisitor(thread,
73 /*context*/nullptr,
74 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
75 allocator_(allocator),
76 obsoleted_methods_(obsoleted_methods),
77 obsolete_maps_(obsolete_maps),
78 success_(success),
79 is_runtime_frame_(false),
80 error_msg_(error_msg) {
81 *success_ = true;
82 }
83
84 ~ObsoleteMethodStackVisitor() OVERRIDE {}
85
86 public:
87 // Returns true if we successfully installed obsolete methods on this thread, filling
88 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
89 // The stack is cleaned up when we fail.
90 static bool UpdateObsoleteFrames(
91 art::Thread* thread,
92 art::LinearAlloc* allocator,
93 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
94 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps,
95 /*out*/std::string* error_msg) REQUIRES(art::Locks::mutator_lock_) {
96 bool success = true;
97 ObsoleteMethodStackVisitor visitor(thread,
98 allocator,
99 obsoleted_methods,
100 obsolete_maps,
101 &success,
102 error_msg);
103 visitor.WalkStack();
104 if (!success) {
105 RestoreFrames(thread, *obsolete_maps, error_msg);
106 return false;
107 } else {
108 return true;
109 }
110 }
111
112 static void RestoreFrames(
113 art::Thread* thread ATTRIBUTE_UNUSED,
114 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsolete_maps ATTRIBUTE_UNUSED,
115 std::string* error_msg)
116 REQUIRES(art::Locks::mutator_lock_) {
117 LOG(FATAL) << "Restoring stack frames is not yet supported. Error was: " << *error_msg;
118 }
119
120 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
121 art::ArtMethod* old_method = GetMethod();
122 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
123 // works through runtime methods.
124 bool prev_was_runtime_frame_ = is_runtime_frame_;
125 is_runtime_frame_ = old_method->IsRuntimeMethod();
126 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
127 // The check below works since when we deoptimize we set shadow frames for all frames until a
128 // native/runtime transition and for those set the return PC to a function that will complete
129 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
130 // below runtime frames cannot be deoptimized at the moment.
131 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
132 // works through runtime methods.
133 // TODO b/33616143
134 if (!IsShadowFrame() && prev_was_runtime_frame_) {
135 *error_msg_ = StringPrintf("Deoptimization failed due to runtime method in stack.");
136 *success_ = false;
137 return false;
138 }
139 // We cannot ensure that the right dex file is used in inlined frames so we don't support
140 // redefining them.
141 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
142 // TODO We should really support intrinsic obsolete methods.
143 // TODO We should really support redefining intrinsics.
144 // We don't support intrinsics so check for them here.
145 DCHECK(!old_method->IsIntrinsic());
146 art::ArtMethod* new_obsolete_method = nullptr;
147 auto obsolete_method_pair = obsolete_maps_->find(old_method);
148 if (obsolete_method_pair == obsolete_maps_->end()) {
149 // Create a new Obsolete Method and put it in the list.
150 art::Runtime* runtime = art::Runtime::Current();
151 art::ClassLinker* cl = runtime->GetClassLinker();
152 auto ptr_size = cl->GetImagePointerSize();
153 const size_t method_size = art::ArtMethod::Size(ptr_size);
154 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
155 if (method_storage == nullptr) {
156 *success_ = false;
157 *error_msg_ = StringPrintf("Unable to allocate storage for obsolete version of '%s'",
158 old_method->PrettyMethod().c_str());
159 return false;
160 }
161 new_obsolete_method = new (method_storage) art::ArtMethod();
162 new_obsolete_method->CopyFrom(old_method, ptr_size);
163 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
164 new_obsolete_method->SetIsObsolete();
165 obsolete_maps_->insert({old_method, new_obsolete_method});
166 // Update JIT Data structures to point to the new method.
167 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
168 if (jit != nullptr) {
169 // Notify the JIT we are making this obsolete method. It will update the jit's internal
170 // structures to keep track of the new obsolete method.
171 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
172 }
173 } else {
174 new_obsolete_method = obsolete_method_pair->second;
175 }
176 DCHECK(new_obsolete_method != nullptr);
177 SetMethod(new_obsolete_method);
178 }
179 return true;
180 }
181
182 private:
183 // The linear allocator we should use to make new methods.
184 art::LinearAlloc* allocator_;
185 // The set of all methods which could be obsoleted.
186 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
187 // A map from the original to the newly allocated obsolete method for frames on this thread. The
188 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
189 // the redefined classes ClassExt by the caller.
190 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
191 bool* success_;
192 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
193 // works through runtime methods.
194 bool is_runtime_frame_;
195 std::string* error_msg_;
196};
197
Alex Lighte4a88632017-01-10 07:41:24 -0800198jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
199 jclass klass,
200 jboolean* is_redefinable) {
201 // TODO Check for the appropriate feature flags once we have enabled them.
202 art::Thread* self = art::Thread::Current();
203 art::ScopedObjectAccess soa(self);
204 art::StackHandleScope<1> hs(self);
205 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
206 if (obj.IsNull()) {
207 return ERR(INVALID_CLASS);
208 }
209 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
210 std::string err_unused;
211 *is_redefinable =
212 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
213 return OK;
214}
215
216jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
217 /*out*/std::string* error_msg) {
218 if (klass->IsPrimitive()) {
219 *error_msg = "Modification of primitive classes is not supported";
220 return ERR(UNMODIFIABLE_CLASS);
221 } else if (klass->IsInterface()) {
222 *error_msg = "Modification of Interface classes is currently not supported";
223 return ERR(UNMODIFIABLE_CLASS);
224 } else if (klass->IsArrayClass()) {
225 *error_msg = "Modification of Array classes is not supported";
226 return ERR(UNMODIFIABLE_CLASS);
227 } else if (klass->IsProxyClass()) {
228 *error_msg = "Modification of proxy classes is not supported";
229 return ERR(UNMODIFIABLE_CLASS);
230 }
231
232 // TODO We should check if the class has non-obsoletable methods on the stack
233 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
234 return OK;
235}
236
Alex Lighta01de592016-11-15 10:43:06 -0800237// Moves dex data to an anonymous, read-only mmap'd region.
238std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
239 jint data_len,
240 unsigned char* dex_data,
241 std::string* error_msg) {
242 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800243 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800244 nullptr,
245 data_len,
246 PROT_READ|PROT_WRITE,
247 /*low_4gb*/false,
248 /*reuse*/false,
249 error_msg));
250 if (map == nullptr) {
251 return map;
252 }
253 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800254 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
255 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800256 map->Protect(PROT_READ);
257 return map;
258}
259
Alex Lightdba61482016-12-21 08:20:29 -0800260// TODO This should handle doing multiple classes at once so we need to do less cleanup when things
261// go wrong.
Alex Lighta01de592016-11-15 10:43:06 -0800262jvmtiError Redefiner::RedefineClass(ArtJvmTiEnv* env,
263 art::Runtime* runtime,
264 art::Thread* self,
265 jclass klass,
266 const std::string& original_dex_location,
267 jint data_len,
268 unsigned char* dex_data,
269 std::string* error_msg) {
270 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
271 data_len,
272 dex_data,
273 error_msg));
274 std::ostringstream os;
275 char* generic_ptr_unused = nullptr;
276 char* signature_ptr = nullptr;
277 if (env->GetClassSignature(klass, &signature_ptr, &generic_ptr_unused) != OK) {
278 signature_ptr = const_cast<char*>("<UNKNOWN CLASS>");
279 }
280 if (map.get() == nullptr) {
281 os << "Failed to create anonymous mmap for modified dex file of class " << signature_ptr
282 << "in dex file " << original_dex_location << " because: " << *error_msg;
283 *error_msg = os.str();
284 return ERR(OUT_OF_MEMORY);
285 }
286 if (map->Size() < sizeof(art::DexFile::Header)) {
287 *error_msg = "Could not read dex file header because dex_data was too short";
288 return ERR(INVALID_CLASS_FORMAT);
289 }
290 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
291 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
292 checksum,
293 std::move(map),
294 /*verify*/true,
295 /*verify_checksum*/true,
296 error_msg));
297 if (dex_file.get() == nullptr) {
298 os << "Unable to load modified dex file for " << signature_ptr << ": " << *error_msg;
299 *error_msg = os.str();
300 return ERR(INVALID_CLASS_FORMAT);
301 }
Alex Lightdba61482016-12-21 08:20:29 -0800302 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
303 // are going to redefine.
304 art::jit::ScopedJitSuspend suspend_jit;
Alex Lighta01de592016-11-15 10:43:06 -0800305 // Get shared mutator lock.
306 art::ScopedObjectAccess soa(self);
307 art::StackHandleScope<1> hs(self);
308 Redefiner r(runtime, self, klass, signature_ptr, dex_file, error_msg);
309 // Lock around this class to avoid races.
310 art::ObjectLock<art::mirror::Class> lock(self, hs.NewHandle(r.GetMirrorClass()));
311 return r.Run();
312}
313
314// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
315// TODO Make mirror of DexFile and associated types to make this less hellish.
316// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
317art::mirror::Object* Redefiner::FindSourceDexFileObject(
318 art::Handle<art::mirror::ClassLoader> loader) {
319 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
320 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
321 const char* dex_file_name = "Ldalvik/system/DexFile;";
322 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
323 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
324
325 CHECK(!self_->IsExceptionPending());
326 art::StackHandleScope<11> hs(self_);
327 art::ClassLinker* class_linker = runtime_->GetClassLinker();
328
329 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
330 nullptr));
331 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
332 self_, dex_class_loader_name, null_loader)));
333
334 // Get all the ArtFields so we can look in the BaseDexClassLoader
335 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
336 "pathList", dex_path_list_name);
337 CHECK(path_list_field != nullptr);
338
339 art::ArtField* dex_path_list_element_field =
340 class_linker->FindClass(self_, dex_path_list_name, null_loader)
341 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
342 CHECK(dex_path_list_element_field != nullptr);
343
344 art::ArtField* element_dex_file_field =
345 class_linker->FindClass(self_, dex_path_list_element_name, null_loader)
346 ->FindDeclaredInstanceField("dexFile", dex_file_name);
347 CHECK(element_dex_file_field != nullptr);
348
349 // Check if loader is a BaseDexClassLoader
350 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
351 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
352 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
353 << "supported class loader type!";
354 return nullptr;
355 }
356 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
357 art::Handle<art::mirror::Object> path_list(
358 hs.NewHandle(path_list_field->GetObject(loader.Get())));
359 CHECK(path_list.Get() != nullptr);
360 CHECK(!self_->IsExceptionPending());
361 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
362 dex_path_list_element_field->GetObject(path_list.Get())->
363 AsObjectArray<art::mirror::Object>()));
364 CHECK(!self_->IsExceptionPending());
365 CHECK(dex_elements_list.Get() != nullptr);
366 size_t num_elements = dex_elements_list->GetLength();
367 art::MutableHandle<art::mirror::Object> current_element(
368 hs.NewHandle<art::mirror::Object>(nullptr));
369 art::MutableHandle<art::mirror::Object> first_dex_file(
370 hs.NewHandle<art::mirror::Object>(nullptr));
371 // Iterate over the DexPathList$Element to find the right one
372 // TODO Or not ATM just return the first one.
373 for (size_t i = 0; i < num_elements; i++) {
374 current_element.Assign(dex_elements_list->Get(i));
375 CHECK(current_element.Get() != nullptr);
376 CHECK(!self_->IsExceptionPending());
377 CHECK(dex_elements_list.Get() != nullptr);
378 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(self_,
379 dex_path_list_element_name,
380 null_loader));
381 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
382 // comes from but it is more annoying because we would need to find this class. It is not
383 // necessary for proper function since we just need to be in front of the classes old dex file
384 // in the path.
385 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
386 if (first_dex_file.Get() != nullptr) {
387 return first_dex_file.Get();
388 }
389 }
390 return nullptr;
391}
392
393art::mirror::Class* Redefiner::GetMirrorClass() {
394 return self_->DecodeJObject(klass_)->AsClass();
395}
396
397art::mirror::ClassLoader* Redefiner::GetClassLoader() {
398 return GetMirrorClass()->GetClassLoader();
399}
400
401art::mirror::DexCache* Redefiner::CreateNewDexCache(art::Handle<art::mirror::ClassLoader> loader) {
402 return runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
403}
404
405// TODO Really wishing I had that mirror of java.lang.DexFile now.
406art::mirror::LongArray* Redefiner::AllocateDexFileCookie(
407 art::Handle<art::mirror::Object> java_dex_file_obj) {
408 art::StackHandleScope<2> hs(self_);
409 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
410 // the object is finalized. Since they always point to the same array if mCookie is not null we
411 // just use the mInternalCookie field. We will update one or both of these fields later.
412 // TODO Should I get the class from the classloader or directly?
413 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
414 "mInternalCookie", "Ljava/lang/Object;");
415 // TODO Add check that mCookie is either null or same as mInternalCookie
416 CHECK(internal_cookie_field != nullptr);
417 art::Handle<art::mirror::LongArray> cookie(
418 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
419 // TODO Maybe make these non-fatal.
420 CHECK(cookie.Get() != nullptr);
421 CHECK_GE(cookie->GetLength(), 1);
422 art::Handle<art::mirror::LongArray> new_cookie(
423 hs.NewHandle(art::mirror::LongArray::Alloc(self_, cookie->GetLength() + 1)));
424 if (new_cookie.Get() == nullptr) {
425 self_->AssertPendingOOMException();
426 return nullptr;
427 }
428 // Copy the oat-dex field at the start.
429 // TODO Should I clear this field?
430 // TODO This is a really crappy thing here with the first element being different.
431 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
432 new_cookie->SetWithoutChecks<false>(
433 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
434 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
435 return new_cookie.Get();
436}
437
438void Redefiner::RecordFailure(jvmtiError result, const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800439 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
440 class_sig_,
441 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800442 result_ = result;
443}
444
445bool Redefiner::FinishRemainingAllocations(
446 /*out*/art::MutableHandle<art::mirror::ClassLoader>* source_class_loader,
447 /*out*/art::MutableHandle<art::mirror::Object>* java_dex_file_obj,
448 /*out*/art::MutableHandle<art::mirror::LongArray>* new_dex_file_cookie,
449 /*out*/art::MutableHandle<art::mirror::DexCache>* new_dex_cache) {
450 art::StackHandleScope<4> hs(self_);
451 // This shouldn't allocate
452 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
453 if (loader.Get() == nullptr) {
454 // TODO Better error msg.
455 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
456 return false;
457 }
458 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
459 if (dex_file_obj.Get() == nullptr) {
460 // TODO Better error msg.
461 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
462 return false;
463 }
464 art::Handle<art::mirror::LongArray> new_cookie(hs.NewHandle(AllocateDexFileCookie(dex_file_obj)));
465 if (new_cookie.Get() == nullptr) {
466 self_->AssertPendingOOMException();
467 self_->ClearException();
468 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
469 return false;
470 }
471 art::Handle<art::mirror::DexCache> dex_cache(hs.NewHandle(CreateNewDexCache(loader)));
472 if (dex_cache.Get() == nullptr) {
473 self_->AssertPendingOOMException();
474 self_->ClearException();
475 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
476 return false;
477 }
478 source_class_loader->Assign(loader.Get());
479 java_dex_file_obj->Assign(dex_file_obj.Get());
480 new_dex_file_cookie->Assign(new_cookie.Get());
481 new_dex_cache->Assign(dex_cache.Get());
482 return true;
483}
484
Alex Lightdba61482016-12-21 08:20:29 -0800485struct CallbackCtx {
486 Redefiner* const r;
487 art::LinearAlloc* allocator;
488 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
489 std::unordered_set<art::ArtMethod*> obsolete_methods;
490 bool success;
491 std::string* error_msg;
492
493 CallbackCtx(Redefiner* self, art::LinearAlloc* alloc, std::string* error)
494 : r(self), allocator(alloc), success(true), error_msg(error) {}
495};
496
497void DoRestoreObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
498 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
499 ObsoleteMethodStackVisitor::RestoreFrames(t, data->obsolete_map, data->error_msg);
500}
501
502void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
503 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
504 if (data->success) {
505 // Don't do anything if we already failed once.
506 data->success = ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
507 data->allocator,
508 data->obsolete_methods,
509 &data->obsolete_map,
510 data->error_msg);
511 }
512}
513
514// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
515// updated so they will be run.
516bool Redefiner::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
517 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
518 art::mirror::ClassExt* ext = art_klass->GetExtData();
519 CHECK(ext->GetObsoleteMethods() != nullptr);
520 CallbackCtx ctx(this, art_klass->GetClassLoader()->GetAllocator(), error_msg_);
521 // Add all the declared methods to the map
522 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
523 ctx.obsolete_methods.insert(&m);
524 }
525 for (art::ArtMethod* old_method : ctx.obsolete_methods) {
526 if (old_method->IsIntrinsic()) {
527 *error_msg_ = StringPrintf("Method '%s' is intrinsic and cannot be made obsolete!",
528 old_method->PrettyMethod().c_str());
529 return false;
530 }
531 }
532 {
533 art::MutexLock mu(self_, *art::Locks::thread_list_lock_);
534 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
535 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
536 if (!ctx.success) {
537 list->ForEach(DoRestoreObsoleteMethodsCallback, static_cast<void*>(&ctx));
538 return false;
539 }
540 }
541 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
542 return true;
543}
544
545// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
546// figure out their DexCaches.
547void Redefiner::FillObsoleteMethodMap(
548 art::mirror::Class* art_klass,
549 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
550 int32_t index = 0;
551 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
552 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
553 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
554 ext_data->GetObsoleteDexCaches();
555 int32_t num_method_slots = obsolete_methods->GetLength();
556 // Find the first empty index.
557 for (; index < num_method_slots; index++) {
558 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
559 index, art::kRuntimePointerSize) == nullptr) {
560 break;
561 }
562 }
563 // Make sure we have enough space.
564 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
565 CHECK(obsolete_dex_caches->Get(index) == nullptr);
566 // Fill in the map.
567 for (auto& obs : obsoletes) {
568 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
569 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
570 index++;
571 }
572}
573
574// TODO It should be possible to only deoptimize the specific obsolete methods.
575// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
576// If one of these frames is an obsolete method we have a problem. b/33616143
577// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
578// registers across suspend points.
579// TODO Pending b/33630159
580void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
581 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
582 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
583 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
584}
585
Alex Light460d1b42017-01-10 15:37:17 +0000586bool Redefiner::CheckClass() {
587 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
588 art::StackHandleScope<1> hs(self_);
589 // Easy check that only 1 class def is present.
590 if (dex_file_->NumClassDefs() != 1) {
591 RecordFailure(ERR(ILLEGAL_ARGUMENT),
592 StringPrintf("Expected 1 class def in dex file but found %d",
593 dex_file_->NumClassDefs()));
594 return false;
595 }
596 // Get the ClassDef from the new DexFile.
597 // Since the dex file has only a single class def the index is always 0.
598 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
599 // Get the class as it is now.
600 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
601
602 // Check the access flags didn't change.
603 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
604 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
605 "Cannot change modifiers of class by redefinition");
606 return false;
607 }
608
609 // Check class name.
610 // These should have been checked by the dexfile verifier on load.
611 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
612 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
613 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
614 if (!current_class->DescriptorEquals(descriptor)) {
615 std::string storage;
616 RecordFailure(ERR(NAMES_DONT_MATCH),
617 StringPrintf("expected file to contain class called '%s' but found '%s'!",
618 current_class->GetDescriptor(&storage),
619 descriptor));
620 return false;
621 }
622 if (current_class->IsObjectClass()) {
623 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
624 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
625 return false;
626 }
627 } else {
628 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
629 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
630 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
631 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
632 return false;
633 }
634 }
635 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
636 if (interfaces == nullptr) {
637 if (current_class->NumDirectInterfaces() != 0) {
638 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
639 return false;
640 }
641 } else {
642 DCHECK(!current_class->IsProxyClass());
643 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
644 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
645 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
646 return false;
647 }
648 // The order of interfaces is (barely) meaningful so we error if it changes.
649 const art::DexFile& orig_dex_file = current_class->GetDexFile();
650 for (uint32_t i = 0; i < interfaces->Size(); i++) {
651 if (strcmp(
652 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
653 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
654 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
655 "Interfaces changed or re-ordered");
656 return false;
657 }
658 }
659 }
660 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
661
662 return true;
663}
664
665// TODO Move this to use IsRedefinable when that function is made.
666bool Redefiner::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800667 std::string err;
668 art::StackHandleScope<1> hs(self_);
Alex Light460d1b42017-01-10 15:37:17 +0000669
Alex Lighte4a88632017-01-10 07:41:24 -0800670 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
671 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
672 if (res != OK) {
673 RecordFailure(res, err);
674 return false;
675 } else {
676 return true;
677 }
Alex Light460d1b42017-01-10 15:37:17 +0000678}
679
680bool Redefiner::CheckRedefinitionIsValid() {
681 return CheckRedefinable() &&
682 CheckClass() &&
683 CheckSameFields() &&
684 CheckSameMethods();
685}
686
Alex Lighta01de592016-11-15 10:43:06 -0800687jvmtiError Redefiner::Run() {
688 art::StackHandleScope<5> hs(self_);
689 // TODO We might want to have a global lock (or one based on the class being redefined at least)
690 // in order to make cleanup easier. Not a huge deal though.
691 //
692 // First we just allocate the ClassExt and its fields that we need. These can be updated
693 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
694 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
695 // between allocating them and pausing all threads before we can update them so we need to do a
696 // try loop.
Alex Light460d1b42017-01-10 15:37:17 +0000697 if (!CheckRedefinitionIsValid() || !EnsureClassAllocationsFinished()) {
Alex Lighta01de592016-11-15 10:43:06 -0800698 return result_;
699 }
700 art::MutableHandle<art::mirror::ClassLoader> source_class_loader(
701 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
702 art::MutableHandle<art::mirror::Object> java_dex_file(
703 hs.NewHandle<art::mirror::Object>(nullptr));
704 art::MutableHandle<art::mirror::LongArray> new_dex_file_cookie(
705 hs.NewHandle<art::mirror::LongArray>(nullptr));
706 art::MutableHandle<art::mirror::DexCache> new_dex_cache(
707 hs.NewHandle<art::mirror::DexCache>(nullptr));
708 if (!FinishRemainingAllocations(&source_class_loader,
709 &java_dex_file,
710 &new_dex_file_cookie,
711 &new_dex_cache)) {
712 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
713 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
714 // declared_methods_.length) but would be good to get rid of.
715 // new_dex_file_cookie & new_dex_cache should be cleaned up by the GC.
716 return result_;
717 }
718 // Get the mirror class now that we aren't allocating anymore.
719 art::Handle<art::mirror::Class> art_class(hs.NewHandle(GetMirrorClass()));
Alex Light6abd5392017-01-05 17:53:00 -0800720 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
721 // allocating so no deadlocks.
722 art::gc::Heap* heap = runtime_->GetHeap();
723 if (heap->IsGcConcurrentAndMoving()) {
724 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
725 heap->IncrementDisableMovingGC(self_);
726 }
Alex Lighta01de592016-11-15 10:43:06 -0800727 // Enable assertion that this thread isn't interrupted during this installation.
728 // After this we will need to do real cleanup in case of failure. Prior to this we could simply
729 // return and would let everything get cleaned up or harmlessly leaked.
730 // Do transition to final suspension
731 // TODO We might want to give this its own suspended state!
732 // TODO This isn't right. We need to change state without any chance of suspend ideally!
733 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
734 runtime_->GetThreadList()->SuspendAll(
735 "Final installation of redefined Class!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800736 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
737 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
738 // TODO We need to update all debugger MethodIDs so they note the method they point to is
739 // obsolete or implement some other well defined semantics.
740 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Lighta01de592016-11-15 10:43:06 -0800741 // TODO Might want to move this into a different type.
742 // Now we reach the part where we must do active cleanup if something fails.
743 // TODO We should really Retry if this fails instead of simply aborting.
744 // Set the new DexFileCookie returns the original so we can fix it back up if redefinition fails
745 art::ObjPtr<art::mirror::LongArray> original_dex_file_cookie(nullptr);
746 if (!UpdateJavaDexFile(java_dex_file.Get(),
747 new_dex_file_cookie.Get(),
Alex Lightdba61482016-12-21 08:20:29 -0800748 &original_dex_file_cookie) ||
749 !FindAndAllocateObsoleteMethods(art_class.Get())) {
Alex Lighta01de592016-11-15 10:43:06 -0800750 // Release suspendAll
751 runtime_->GetThreadList()->ResumeAll();
752 // Get back shared mutator lock as expected for return.
753 self_->TransitionFromSuspendedToRunnable();
Alex Light6abd5392017-01-05 17:53:00 -0800754 if (heap->IsGcConcurrentAndMoving()) {
755 heap->DecrementDisableMovingGC(self_);
756 }
Alex Lighta01de592016-11-15 10:43:06 -0800757 return result_;
758 }
759 if (!UpdateClass(art_class.Get(), new_dex_cache.Get())) {
760 // TODO Should have some form of scope to do this.
761 RestoreJavaDexFile(java_dex_file.Get(), original_dex_file_cookie);
762 // Release suspendAll
763 runtime_->GetThreadList()->ResumeAll();
764 // Get back shared mutator lock as expected for return.
765 self_->TransitionFromSuspendedToRunnable();
Alex Light6abd5392017-01-05 17:53:00 -0800766 if (heap->IsGcConcurrentAndMoving()) {
767 heap->DecrementDisableMovingGC(self_);
768 }
Alex Lighta01de592016-11-15 10:43:06 -0800769 return result_;
770 }
Alex Lightdba61482016-12-21 08:20:29 -0800771 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
772 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
773 // DexCache.
774 // TODO This can fail (leave some methods optimized) near runtime methods (including
775 // quick-to-interpreter transition function).
776 // TODO We probably don't need this at all once we have a way to ensure that the
777 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
778 // stack-walker.
779 EnsureObsoleteMethodsAreDeoptimized();
780 // TODO Verify the new Class.
781 // TODO Failure then undo updates to class
782 // TODO Shrink the obsolete method maps if possible?
783 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800784 // TODO Put this into a scoped thing.
785 runtime_->GetThreadList()->ResumeAll();
786 // Get back shared mutator lock as expected for return.
787 self_->TransitionFromSuspendedToRunnable();
Alex Lightdba61482016-12-21 08:20:29 -0800788 // TODO Do the dex_file_ release at a more reasonable place. This works but it muddles who really
789 // owns the DexFile.
Alex Lighta01de592016-11-15 10:43:06 -0800790 dex_file_.release();
Alex Light6abd5392017-01-05 17:53:00 -0800791 if (heap->IsGcConcurrentAndMoving()) {
792 heap->DecrementDisableMovingGC(self_);
793 }
Alex Lighta01de592016-11-15 10:43:06 -0800794 return OK;
795}
796
797void Redefiner::RestoreJavaDexFile(art::ObjPtr<art::mirror::Object> java_dex_file,
798 art::ObjPtr<art::mirror::LongArray> orig_cookie) {
799 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
800 "mInternalCookie", "Ljava/lang/Object;");
801 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
802 "mCookie", "Ljava/lang/Object;");
803 art::ObjPtr<art::mirror::LongArray> new_cookie(
804 cookie_field->GetObject(java_dex_file)->AsLongArray());
805 internal_cookie_field->SetObject<false>(java_dex_file, orig_cookie);
806 if (!new_cookie.IsNull()) {
807 cookie_field->SetObject<false>(java_dex_file, orig_cookie);
808 }
809}
810
Alex Light200b9d72016-12-15 11:34:13 -0800811bool Redefiner::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
812 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
813 const art::DexFile::ClassDef& class_def) {
Alex Lighta01de592016-11-15 10:43:06 -0800814 art::ClassLinker* linker = runtime_->GetClassLinker();
815 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800816 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800817 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800818 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800819 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
820 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
821 art::dex::TypeIndex method_return_idx =
822 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
823 const auto* old_type_list = method.GetParameterTypeList();
824 std::vector<art::dex::TypeIndex> new_type_list;
825 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
826 new_type_list.push_back(
827 dex_file_->GetIndexForTypeId(
828 *dex_file_->FindTypeId(
829 old_dex_file.GetTypeDescriptor(
830 old_dex_file.GetTypeId(
831 old_type_list->GetTypeItem(i).type_idx_)))));
832 }
833 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
834 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000835 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800836 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800837 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
838 *new_name_id,
839 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000840 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800841 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800842 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
843 method.SetDexMethodIndex(dex_method_idx);
844 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800845 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800846 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
847 method.SetDexCacheResolvedTypes(new_dex_cache->GetResolvedTypes(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800848 // Notify the jit that this method is redefined.
849 art::jit::Jit* jit = runtime_->GetJit();
850 if (jit != nullptr) {
851 jit->GetCodeCache()->NotifyMethodRedefined(&method);
852 }
Alex Lighta01de592016-11-15 10:43:06 -0800853 }
Alex Light200b9d72016-12-15 11:34:13 -0800854 return true;
855}
856
857bool Redefiner::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
858 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
859 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
860 for (art::ArtField& field : fields_iter) {
861 std::string declaring_class_name;
862 const art::DexFile::TypeId* new_declaring_id =
863 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
864 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
865 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
866 // TODO Handle error, cleanup.
867 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
868 const art::DexFile::FieldId* new_field_id =
869 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
870 CHECK(new_field_id != nullptr);
871 // We only need to update the index since the other data in the ArtField cannot be updated.
872 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
873 }
874 }
875 return true;
876}
877
878// Performs updates to class that will allow us to verify it.
879bool Redefiner::UpdateClass(art::ObjPtr<art::mirror::Class> mclass,
880 art::ObjPtr<art::mirror::DexCache> new_dex_cache) {
881 const art::DexFile::ClassDef* class_def = art::OatFile::OatDexFile::FindClassDef(
882 *dex_file_, class_sig_, art::ComputeModifiedUtf8Hash(class_sig_));
883 if (class_def == nullptr) {
884 RecordFailure(ERR(INVALID_CLASS_FORMAT), "Unable to find ClassDef!");
885 return false;
886 }
887 if (!UpdateMethods(mclass, new_dex_cache, *class_def)) {
888 // TODO Investigate appropriate error types.
889 RecordFailure(ERR(INTERNAL), "Unable to update class methods.");
890 return false;
891 }
892 if (!UpdateFields(mclass)) {
893 // TODO Investigate appropriate error types.
894 RecordFailure(ERR(INTERNAL), "Unable to update class fields.");
895 return false;
896 }
897
Alex Lighta01de592016-11-15 10:43:06 -0800898 // Update the class fields.
899 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
900 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
901 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Lighta01de592016-11-15 10:43:06 -0800902 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(*class_def));
903 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_)));
904 return true;
905}
906
907bool Redefiner::UpdateJavaDexFile(art::ObjPtr<art::mirror::Object> java_dex_file,
908 art::ObjPtr<art::mirror::LongArray> new_cookie,
909 /*out*/art::ObjPtr<art::mirror::LongArray>* original_cookie) {
910 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
911 "mInternalCookie", "Ljava/lang/Object;");
912 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
913 "mCookie", "Ljava/lang/Object;");
914 CHECK(internal_cookie_field != nullptr);
915 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
916 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
917 art::ObjPtr<art::mirror::LongArray> orig_cookie(
918 cookie_field->GetObject(java_dex_file)->AsLongArray());
919 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
920 *original_cookie = orig_internal_cookie;
921 if (!orig_cookie.IsNull()) {
922 cookie_field->SetObject<false>(java_dex_file, new_cookie);
923 }
924 return true;
925}
926
927// This function does all (java) allocations we need to do for the Class being redefined.
928// TODO Change this name maybe?
929bool Redefiner::EnsureClassAllocationsFinished() {
930 art::StackHandleScope<2> hs(self_);
931 art::Handle<art::mirror::Class> klass(hs.NewHandle(self_->DecodeJObject(klass_)->AsClass()));
932 if (klass.Get() == nullptr) {
933 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
934 return false;
935 }
936 // Allocate the classExt
937 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self_)));
938 if (ext.Get() == nullptr) {
939 // No memory. Clear exception (it's not useful) and return error.
940 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
941 // this case.
942 self_->AssertPendingOOMException();
943 self_->ClearException();
944 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
945 return false;
946 }
947 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
948 // are only modified when all threads (other than the modifying one) are suspended we don't need
949 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
950 // however, since that can happen at any time.
951 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
952 // are no obsolete methods.
953 {
954 art::ObjectLock<art::mirror::ClassExt> lock(self_, ext);
955 if (!ext->ExtendObsoleteArrays(
956 self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
957 // OOM. Clear exception and return error.
958 self_->AssertPendingOOMException();
959 self_->ClearException();
960 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
961 return false;
962 }
963 }
964 return true;
965}
966
967} // namespace openjdkjvmti