blob: 5bf844564cb5466a7529367c3e95ba950561f400 [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,
Alex Light007ada22017-01-10 13:33:56 -080069 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -080070 : StackVisitor(thread,
71 /*context*/nullptr,
72 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
73 allocator_(allocator),
74 obsoleted_methods_(obsoleted_methods),
75 obsolete_maps_(obsolete_maps),
Alex Light007ada22017-01-10 13:33:56 -080076 is_runtime_frame_(false) {
Alex Lightdba61482016-12-21 08:20:29 -080077 }
78
79 ~ObsoleteMethodStackVisitor() OVERRIDE {}
80
81 public:
82 // Returns true if we successfully installed obsolete methods on this thread, filling
83 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
84 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -080085 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -080086 art::Thread* thread,
87 art::LinearAlloc* allocator,
88 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080089 /*out*/std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps)
90 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -080091 ObsoleteMethodStackVisitor visitor(thread,
92 allocator,
93 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -080094 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -080095 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -080096 }
97
98 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) {
99 art::ArtMethod* old_method = GetMethod();
100 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
101 // works through runtime methods.
102 bool prev_was_runtime_frame_ = is_runtime_frame_;
103 is_runtime_frame_ = old_method->IsRuntimeMethod();
104 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
105 // The check below works since when we deoptimize we set shadow frames for all frames until a
106 // native/runtime transition and for those set the return PC to a function that will complete
107 // the deoptimization. This does leave us with the unfortunate side-effect that frames just
108 // below runtime frames cannot be deoptimized at the moment.
109 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
110 // works through runtime methods.
111 // TODO b/33616143
112 if (!IsShadowFrame() && prev_was_runtime_frame_) {
Alex Light007ada22017-01-10 13:33:56 -0800113 LOG(FATAL) << "Deoptimization failed due to runtime method in stack. See b/33616143";
Alex Lightdba61482016-12-21 08:20:29 -0800114 }
115 // We cannot ensure that the right dex file is used in inlined frames so we don't support
116 // redefining them.
117 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition";
118 // TODO We should really support intrinsic obsolete methods.
119 // TODO We should really support redefining intrinsics.
120 // We don't support intrinsics so check for them here.
121 DCHECK(!old_method->IsIntrinsic());
122 art::ArtMethod* new_obsolete_method = nullptr;
123 auto obsolete_method_pair = obsolete_maps_->find(old_method);
124 if (obsolete_method_pair == obsolete_maps_->end()) {
125 // Create a new Obsolete Method and put it in the list.
126 art::Runtime* runtime = art::Runtime::Current();
127 art::ClassLinker* cl = runtime->GetClassLinker();
128 auto ptr_size = cl->GetImagePointerSize();
129 const size_t method_size = art::ArtMethod::Size(ptr_size);
130 auto* method_storage = allocator_->Alloc(GetThread(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800131 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
132 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800133 new_obsolete_method = new (method_storage) art::ArtMethod();
134 new_obsolete_method->CopyFrom(old_method, ptr_size);
135 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
136 new_obsolete_method->SetIsObsolete();
137 obsolete_maps_->insert({old_method, new_obsolete_method});
138 // Update JIT Data structures to point to the new method.
139 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
140 if (jit != nullptr) {
141 // Notify the JIT we are making this obsolete method. It will update the jit's internal
142 // structures to keep track of the new obsolete method.
143 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method);
144 }
145 } else {
146 new_obsolete_method = obsolete_method_pair->second;
147 }
148 DCHECK(new_obsolete_method != nullptr);
149 SetMethod(new_obsolete_method);
150 }
151 return true;
152 }
153
154 private:
155 // The linear allocator we should use to make new methods.
156 art::LinearAlloc* allocator_;
157 // The set of all methods which could be obsoleted.
158 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
159 // A map from the original to the newly allocated obsolete method for frames on this thread. The
160 // values in this map must be added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
161 // the redefined classes ClassExt by the caller.
162 std::unordered_map<art::ArtMethod*, art::ArtMethod*>* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800163 // TODO REMOVE once either current_method doesn't stick around through suspend points or deopt
164 // works through runtime methods.
165 bool is_runtime_frame_;
Alex Lightdba61482016-12-21 08:20:29 -0800166};
167
Alex Lighte4a88632017-01-10 07:41:24 -0800168jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
169 jclass klass,
170 jboolean* is_redefinable) {
171 // TODO Check for the appropriate feature flags once we have enabled them.
172 art::Thread* self = art::Thread::Current();
173 art::ScopedObjectAccess soa(self);
174 art::StackHandleScope<1> hs(self);
175 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
176 if (obj.IsNull()) {
177 return ERR(INVALID_CLASS);
178 }
179 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
180 std::string err_unused;
181 *is_redefinable =
182 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE;
183 return OK;
184}
185
186jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
187 /*out*/std::string* error_msg) {
188 if (klass->IsPrimitive()) {
189 *error_msg = "Modification of primitive classes is not supported";
190 return ERR(UNMODIFIABLE_CLASS);
191 } else if (klass->IsInterface()) {
192 *error_msg = "Modification of Interface classes is currently not supported";
193 return ERR(UNMODIFIABLE_CLASS);
194 } else if (klass->IsArrayClass()) {
195 *error_msg = "Modification of Array classes is not supported";
196 return ERR(UNMODIFIABLE_CLASS);
197 } else if (klass->IsProxyClass()) {
198 *error_msg = "Modification of proxy classes is not supported";
199 return ERR(UNMODIFIABLE_CLASS);
200 }
201
202 // TODO We should check if the class has non-obsoletable methods on the stack
203 LOG(WARNING) << "presence of non-obsoletable methods on stacks is not currently checked";
204 return OK;
205}
206
Alex Lighta01de592016-11-15 10:43:06 -0800207// Moves dex data to an anonymous, read-only mmap'd region.
208std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location,
209 jint data_len,
210 unsigned char* dex_data,
211 std::string* error_msg) {
212 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800213 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lighta01de592016-11-15 10:43:06 -0800214 nullptr,
215 data_len,
216 PROT_READ|PROT_WRITE,
217 /*low_4gb*/false,
218 /*reuse*/false,
219 error_msg));
220 if (map == nullptr) {
221 return map;
222 }
223 memcpy(map->Begin(), dex_data, data_len);
Alex Light0b772572016-12-02 17:27:31 -0800224 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
225 // programs from corrupting it.
Alex Lighta01de592016-11-15 10:43:06 -0800226 map->Protect(PROT_READ);
227 return map;
228}
229
Alex Lightdba61482016-12-21 08:20:29 -0800230// TODO This should handle doing multiple classes at once so we need to do less cleanup when things
231// go wrong.
Alex Lighta01de592016-11-15 10:43:06 -0800232jvmtiError Redefiner::RedefineClass(ArtJvmTiEnv* env,
233 art::Runtime* runtime,
234 art::Thread* self,
235 jclass klass,
236 const std::string& original_dex_location,
237 jint data_len,
238 unsigned char* dex_data,
239 std::string* error_msg) {
240 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location,
241 data_len,
242 dex_data,
243 error_msg));
244 std::ostringstream os;
245 char* generic_ptr_unused = nullptr;
246 char* signature_ptr = nullptr;
247 if (env->GetClassSignature(klass, &signature_ptr, &generic_ptr_unused) != OK) {
248 signature_ptr = const_cast<char*>("<UNKNOWN CLASS>");
249 }
250 if (map.get() == nullptr) {
251 os << "Failed to create anonymous mmap for modified dex file of class " << signature_ptr
252 << "in dex file " << original_dex_location << " because: " << *error_msg;
253 *error_msg = os.str();
254 return ERR(OUT_OF_MEMORY);
255 }
256 if (map->Size() < sizeof(art::DexFile::Header)) {
257 *error_msg = "Could not read dex file header because dex_data was too short";
258 return ERR(INVALID_CLASS_FORMAT);
259 }
260 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
261 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
262 checksum,
263 std::move(map),
264 /*verify*/true,
265 /*verify_checksum*/true,
266 error_msg));
267 if (dex_file.get() == nullptr) {
268 os << "Unable to load modified dex file for " << signature_ptr << ": " << *error_msg;
269 *error_msg = os.str();
270 return ERR(INVALID_CLASS_FORMAT);
271 }
Alex Lightdba61482016-12-21 08:20:29 -0800272 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
273 // are going to redefine.
274 art::jit::ScopedJitSuspend suspend_jit;
Alex Lighta01de592016-11-15 10:43:06 -0800275 // Get shared mutator lock.
276 art::ScopedObjectAccess soa(self);
277 art::StackHandleScope<1> hs(self);
278 Redefiner r(runtime, self, klass, signature_ptr, dex_file, error_msg);
279 // Lock around this class to avoid races.
280 art::ObjectLock<art::mirror::Class> lock(self, hs.NewHandle(r.GetMirrorClass()));
281 return r.Run();
282}
283
284// TODO *MAJOR* This should return the actual source java.lang.DexFile object for the klass.
285// TODO Make mirror of DexFile and associated types to make this less hellish.
286// TODO Make mirror of BaseDexClassLoader and associated types to make this less hellish.
287art::mirror::Object* Redefiner::FindSourceDexFileObject(
288 art::Handle<art::mirror::ClassLoader> loader) {
289 const char* dex_path_list_element_array_name = "[Ldalvik/system/DexPathList$Element;";
290 const char* dex_path_list_element_name = "Ldalvik/system/DexPathList$Element;";
291 const char* dex_file_name = "Ldalvik/system/DexFile;";
292 const char* dex_path_list_name = "Ldalvik/system/DexPathList;";
293 const char* dex_class_loader_name = "Ldalvik/system/BaseDexClassLoader;";
294
295 CHECK(!self_->IsExceptionPending());
296 art::StackHandleScope<11> hs(self_);
297 art::ClassLinker* class_linker = runtime_->GetClassLinker();
298
299 art::Handle<art::mirror::ClassLoader> null_loader(hs.NewHandle<art::mirror::ClassLoader>(
300 nullptr));
301 art::Handle<art::mirror::Class> base_dex_loader_class(hs.NewHandle(class_linker->FindClass(
302 self_, dex_class_loader_name, null_loader)));
303
304 // Get all the ArtFields so we can look in the BaseDexClassLoader
305 art::ArtField* path_list_field = base_dex_loader_class->FindDeclaredInstanceField(
306 "pathList", dex_path_list_name);
307 CHECK(path_list_field != nullptr);
308
309 art::ArtField* dex_path_list_element_field =
310 class_linker->FindClass(self_, dex_path_list_name, null_loader)
311 ->FindDeclaredInstanceField("dexElements", dex_path_list_element_array_name);
312 CHECK(dex_path_list_element_field != nullptr);
313
314 art::ArtField* element_dex_file_field =
315 class_linker->FindClass(self_, dex_path_list_element_name, null_loader)
316 ->FindDeclaredInstanceField("dexFile", dex_file_name);
317 CHECK(element_dex_file_field != nullptr);
318
319 // Check if loader is a BaseDexClassLoader
320 art::Handle<art::mirror::Class> loader_class(hs.NewHandle(loader->GetClass()));
321 if (!loader_class->IsSubClass(base_dex_loader_class.Get())) {
322 LOG(ERROR) << "The classloader is not a BaseDexClassLoader which is currently the only "
323 << "supported class loader type!";
324 return nullptr;
325 }
326 // Start navigating the fields of the loader (now known to be a BaseDexClassLoader derivative)
327 art::Handle<art::mirror::Object> path_list(
328 hs.NewHandle(path_list_field->GetObject(loader.Get())));
329 CHECK(path_list.Get() != nullptr);
330 CHECK(!self_->IsExceptionPending());
331 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> dex_elements_list(hs.NewHandle(
332 dex_path_list_element_field->GetObject(path_list.Get())->
333 AsObjectArray<art::mirror::Object>()));
334 CHECK(!self_->IsExceptionPending());
335 CHECK(dex_elements_list.Get() != nullptr);
336 size_t num_elements = dex_elements_list->GetLength();
337 art::MutableHandle<art::mirror::Object> current_element(
338 hs.NewHandle<art::mirror::Object>(nullptr));
339 art::MutableHandle<art::mirror::Object> first_dex_file(
340 hs.NewHandle<art::mirror::Object>(nullptr));
341 // Iterate over the DexPathList$Element to find the right one
342 // TODO Or not ATM just return the first one.
343 for (size_t i = 0; i < num_elements; i++) {
344 current_element.Assign(dex_elements_list->Get(i));
345 CHECK(current_element.Get() != nullptr);
346 CHECK(!self_->IsExceptionPending());
347 CHECK(dex_elements_list.Get() != nullptr);
348 CHECK_EQ(current_element->GetClass(), class_linker->FindClass(self_,
349 dex_path_list_element_name,
350 null_loader));
351 // TODO It would be cleaner to put the art::DexFile into the dalvik.system.DexFile the class
352 // comes from but it is more annoying because we would need to find this class. It is not
353 // necessary for proper function since we just need to be in front of the classes old dex file
354 // in the path.
355 first_dex_file.Assign(element_dex_file_field->GetObject(current_element.Get()));
356 if (first_dex_file.Get() != nullptr) {
357 return first_dex_file.Get();
358 }
359 }
360 return nullptr;
361}
362
363art::mirror::Class* Redefiner::GetMirrorClass() {
364 return self_->DecodeJObject(klass_)->AsClass();
365}
366
367art::mirror::ClassLoader* Redefiner::GetClassLoader() {
368 return GetMirrorClass()->GetClassLoader();
369}
370
371art::mirror::DexCache* Redefiner::CreateNewDexCache(art::Handle<art::mirror::ClassLoader> loader) {
372 return runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get());
373}
374
375// TODO Really wishing I had that mirror of java.lang.DexFile now.
376art::mirror::LongArray* Redefiner::AllocateDexFileCookie(
377 art::Handle<art::mirror::Object> java_dex_file_obj) {
378 art::StackHandleScope<2> hs(self_);
379 // mCookie is nulled out if the DexFile has been closed but mInternalCookie sticks around until
380 // the object is finalized. Since they always point to the same array if mCookie is not null we
381 // just use the mInternalCookie field. We will update one or both of these fields later.
382 // TODO Should I get the class from the classloader or directly?
383 art::ArtField* internal_cookie_field = java_dex_file_obj->GetClass()->FindDeclaredInstanceField(
384 "mInternalCookie", "Ljava/lang/Object;");
385 // TODO Add check that mCookie is either null or same as mInternalCookie
386 CHECK(internal_cookie_field != nullptr);
387 art::Handle<art::mirror::LongArray> cookie(
388 hs.NewHandle(internal_cookie_field->GetObject(java_dex_file_obj.Get())->AsLongArray()));
389 // TODO Maybe make these non-fatal.
390 CHECK(cookie.Get() != nullptr);
391 CHECK_GE(cookie->GetLength(), 1);
392 art::Handle<art::mirror::LongArray> new_cookie(
393 hs.NewHandle(art::mirror::LongArray::Alloc(self_, cookie->GetLength() + 1)));
394 if (new_cookie.Get() == nullptr) {
395 self_->AssertPendingOOMException();
396 return nullptr;
397 }
398 // Copy the oat-dex field at the start.
399 // TODO Should I clear this field?
400 // TODO This is a really crappy thing here with the first element being different.
401 new_cookie->SetWithoutChecks<false>(0, cookie->GetWithoutChecks(0));
402 new_cookie->SetWithoutChecks<false>(
403 1, static_cast<int64_t>(reinterpret_cast<intptr_t>(dex_file_.get())));
404 new_cookie->Memcpy(2, cookie.Get(), 1, cookie->GetLength() - 1);
405 return new_cookie.Get();
406}
407
408void Redefiner::RecordFailure(jvmtiError result, const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800409 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
410 class_sig_,
411 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800412 result_ = result;
413}
414
415bool Redefiner::FinishRemainingAllocations(
416 /*out*/art::MutableHandle<art::mirror::ClassLoader>* source_class_loader,
417 /*out*/art::MutableHandle<art::mirror::Object>* java_dex_file_obj,
418 /*out*/art::MutableHandle<art::mirror::LongArray>* new_dex_file_cookie,
419 /*out*/art::MutableHandle<art::mirror::DexCache>* new_dex_cache) {
420 art::StackHandleScope<4> hs(self_);
421 // This shouldn't allocate
422 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
423 if (loader.Get() == nullptr) {
424 // TODO Better error msg.
425 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
426 return false;
427 }
428 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(FindSourceDexFileObject(loader)));
429 if (dex_file_obj.Get() == nullptr) {
430 // TODO Better error msg.
431 RecordFailure(ERR(INTERNAL), "Unable to find class loader!");
432 return false;
433 }
434 art::Handle<art::mirror::LongArray> new_cookie(hs.NewHandle(AllocateDexFileCookie(dex_file_obj)));
435 if (new_cookie.Get() == nullptr) {
436 self_->AssertPendingOOMException();
437 self_->ClearException();
438 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
439 return false;
440 }
441 art::Handle<art::mirror::DexCache> dex_cache(hs.NewHandle(CreateNewDexCache(loader)));
442 if (dex_cache.Get() == nullptr) {
443 self_->AssertPendingOOMException();
444 self_->ClearException();
445 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
446 return false;
447 }
448 source_class_loader->Assign(loader.Get());
449 java_dex_file_obj->Assign(dex_file_obj.Get());
450 new_dex_file_cookie->Assign(new_cookie.Get());
451 new_dex_cache->Assign(dex_cache.Get());
452 return true;
453}
454
Alex Lightdba61482016-12-21 08:20:29 -0800455struct CallbackCtx {
456 Redefiner* const r;
457 art::LinearAlloc* allocator;
458 std::unordered_map<art::ArtMethod*, art::ArtMethod*> obsolete_map;
459 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800460
Alex Light007ada22017-01-10 13:33:56 -0800461 CallbackCtx(Redefiner* self, art::LinearAlloc* alloc)
462 : r(self), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800463};
464
Alex Lightdba61482016-12-21 08:20:29 -0800465void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
466 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800467 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
468 data->allocator,
469 data->obsolete_methods,
470 &data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800471}
472
473// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
474// updated so they will be run.
Alex Light007ada22017-01-10 13:33:56 -0800475void Redefiner::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800476 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
477 art::mirror::ClassExt* ext = art_klass->GetExtData();
478 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light007ada22017-01-10 13:33:56 -0800479 CallbackCtx ctx(this, art_klass->GetClassLoader()->GetAllocator());
Alex Lightdba61482016-12-21 08:20:29 -0800480 // Add all the declared methods to the map
481 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
482 ctx.obsolete_methods.insert(&m);
Alex Light007ada22017-01-10 13:33:56 -0800483 // TODO Allow this or check in IsModifiableClass.
484 DCHECK(!m.IsIntrinsic());
Alex Lightdba61482016-12-21 08:20:29 -0800485 }
486 {
487 art::MutexLock mu(self_, *art::Locks::thread_list_lock_);
488 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
489 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Lightdba61482016-12-21 08:20:29 -0800490 }
491 FillObsoleteMethodMap(art_klass, ctx.obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800492}
493
494// Fills the obsolete method map in the art_klass's extData. This is so obsolete methods are able to
495// figure out their DexCaches.
496void Redefiner::FillObsoleteMethodMap(
497 art::mirror::Class* art_klass,
498 const std::unordered_map<art::ArtMethod*, art::ArtMethod*>& obsoletes) {
499 int32_t index = 0;
500 art::mirror::ClassExt* ext_data = art_klass->GetExtData();
501 art::mirror::PointerArray* obsolete_methods = ext_data->GetObsoleteMethods();
502 art::mirror::ObjectArray<art::mirror::DexCache>* obsolete_dex_caches =
503 ext_data->GetObsoleteDexCaches();
504 int32_t num_method_slots = obsolete_methods->GetLength();
505 // Find the first empty index.
506 for (; index < num_method_slots; index++) {
507 if (obsolete_methods->GetElementPtrSize<art::ArtMethod*>(
508 index, art::kRuntimePointerSize) == nullptr) {
509 break;
510 }
511 }
512 // Make sure we have enough space.
513 CHECK_GT(num_method_slots, static_cast<int32_t>(obsoletes.size() + index));
514 CHECK(obsolete_dex_caches->Get(index) == nullptr);
515 // Fill in the map.
516 for (auto& obs : obsoletes) {
517 obsolete_methods->SetElementPtrSize(index, obs.second, art::kRuntimePointerSize);
518 obsolete_dex_caches->Set(index, art_klass->GetDexCache());
519 index++;
520 }
521}
522
523// TODO It should be possible to only deoptimize the specific obsolete methods.
524// TODO ReJitEverything can (sort of) fail. In certain cases it will skip deoptimizing some frames.
525// If one of these frames is an obsolete method we have a problem. b/33616143
526// TODO This shouldn't be necessary once we can ensure that the current method is not kept in
527// registers across suspend points.
528// TODO Pending b/33630159
529void Redefiner::EnsureObsoleteMethodsAreDeoptimized() {
530 art::ScopedAssertNoThreadSuspension nts("Deoptimizing everything!");
531 art::instrumentation::Instrumentation* i = runtime_->GetInstrumentation();
532 i->ReJitEverything("libOpenJkdJvmti - Class Redefinition");
533}
534
Alex Light460d1b42017-01-10 15:37:17 +0000535bool Redefiner::CheckClass() {
536 // TODO Might just want to put it in a ObjPtr and NoSuspend assert.
537 art::StackHandleScope<1> hs(self_);
538 // Easy check that only 1 class def is present.
539 if (dex_file_->NumClassDefs() != 1) {
540 RecordFailure(ERR(ILLEGAL_ARGUMENT),
541 StringPrintf("Expected 1 class def in dex file but found %d",
542 dex_file_->NumClassDefs()));
543 return false;
544 }
545 // Get the ClassDef from the new DexFile.
546 // Since the dex file has only a single class def the index is always 0.
547 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0);
548 // Get the class as it is now.
549 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
550
551 // Check the access flags didn't change.
552 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
553 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
554 "Cannot change modifiers of class by redefinition");
555 return false;
556 }
557
558 // Check class name.
559 // These should have been checked by the dexfile verifier on load.
560 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
561 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
562 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
563 if (!current_class->DescriptorEquals(descriptor)) {
564 std::string storage;
565 RecordFailure(ERR(NAMES_DONT_MATCH),
566 StringPrintf("expected file to contain class called '%s' but found '%s'!",
567 current_class->GetDescriptor(&storage),
568 descriptor));
569 return false;
570 }
571 if (current_class->IsObjectClass()) {
572 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
573 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
574 return false;
575 }
576 } else {
577 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
578 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
579 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
580 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
581 return false;
582 }
583 }
584 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def);
585 if (interfaces == nullptr) {
586 if (current_class->NumDirectInterfaces() != 0) {
587 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
588 return false;
589 }
590 } else {
591 DCHECK(!current_class->IsProxyClass());
592 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
593 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
594 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
595 return false;
596 }
597 // The order of interfaces is (barely) meaningful so we error if it changes.
598 const art::DexFile& orig_dex_file = current_class->GetDexFile();
599 for (uint32_t i = 0; i < interfaces->Size(); i++) {
600 if (strcmp(
601 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
602 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
603 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
604 "Interfaces changed or re-ordered");
605 return false;
606 }
607 }
608 }
609 LOG(WARNING) << "No verification is done on annotations of redefined classes.";
610
611 return true;
612}
613
614// TODO Move this to use IsRedefinable when that function is made.
615bool Redefiner::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800616 std::string err;
617 art::StackHandleScope<1> hs(self_);
Alex Light460d1b42017-01-10 15:37:17 +0000618
Alex Lighte4a88632017-01-10 07:41:24 -0800619 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
620 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
621 if (res != OK) {
622 RecordFailure(res, err);
623 return false;
624 } else {
625 return true;
626 }
Alex Light460d1b42017-01-10 15:37:17 +0000627}
628
629bool Redefiner::CheckRedefinitionIsValid() {
630 return CheckRedefinable() &&
631 CheckClass() &&
632 CheckSameFields() &&
633 CheckSameMethods();
634}
635
Alex Lighta01de592016-11-15 10:43:06 -0800636jvmtiError Redefiner::Run() {
637 art::StackHandleScope<5> hs(self_);
638 // TODO We might want to have a global lock (or one based on the class being redefined at least)
639 // in order to make cleanup easier. Not a huge deal though.
640 //
641 // First we just allocate the ClassExt and its fields that we need. These can be updated
642 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
643 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
644 // between allocating them and pausing all threads before we can update them so we need to do a
645 // try loop.
Alex Light460d1b42017-01-10 15:37:17 +0000646 if (!CheckRedefinitionIsValid() || !EnsureClassAllocationsFinished()) {
Alex Lighta01de592016-11-15 10:43:06 -0800647 return result_;
648 }
649 art::MutableHandle<art::mirror::ClassLoader> source_class_loader(
650 hs.NewHandle<art::mirror::ClassLoader>(nullptr));
651 art::MutableHandle<art::mirror::Object> java_dex_file(
652 hs.NewHandle<art::mirror::Object>(nullptr));
653 art::MutableHandle<art::mirror::LongArray> new_dex_file_cookie(
654 hs.NewHandle<art::mirror::LongArray>(nullptr));
655 art::MutableHandle<art::mirror::DexCache> new_dex_cache(
656 hs.NewHandle<art::mirror::DexCache>(nullptr));
657 if (!FinishRemainingAllocations(&source_class_loader,
658 &java_dex_file,
659 &new_dex_file_cookie,
660 &new_dex_cache)) {
661 // TODO Null out the ClassExt fields we allocated (if possible, might be racing with another
662 // redefineclass call which made it even bigger. Leak shouldn't be huge (2x array of size
663 // declared_methods_.length) but would be good to get rid of.
664 // new_dex_file_cookie & new_dex_cache should be cleaned up by the GC.
665 return result_;
666 }
667 // Get the mirror class now that we aren't allocating anymore.
668 art::Handle<art::mirror::Class> art_class(hs.NewHandle(GetMirrorClass()));
Alex Light6abd5392017-01-05 17:53:00 -0800669 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
670 // allocating so no deadlocks.
671 art::gc::Heap* heap = runtime_->GetHeap();
672 if (heap->IsGcConcurrentAndMoving()) {
673 // GC moving objects can cause deadlocks as we are deoptimizing the stack.
674 heap->IncrementDisableMovingGC(self_);
675 }
Alex Lighta01de592016-11-15 10:43:06 -0800676 // Enable assertion that this thread isn't interrupted during this installation.
677 // After this we will need to do real cleanup in case of failure. Prior to this we could simply
678 // return and would let everything get cleaned up or harmlessly leaked.
679 // Do transition to final suspension
680 // TODO We might want to give this its own suspended state!
681 // TODO This isn't right. We need to change state without any chance of suspend ideally!
682 self_->TransitionFromRunnableToSuspended(art::ThreadState::kNative);
683 runtime_->GetThreadList()->SuspendAll(
684 "Final installation of redefined Class!", /*long_suspend*/true);
Alex Lightdba61482016-12-21 08:20:29 -0800685 // TODO We need to invalidate all breakpoints in the redefined class with the debugger.
686 // TODO We need to deal with any instrumentation/debugger deoptimized_methods_.
687 // TODO We need to update all debugger MethodIDs so they note the method they point to is
688 // obsolete or implement some other well defined semantics.
689 // TODO We need to decide on & implement semantics for JNI jmethodids when we redefine methods.
Alex Lighta01de592016-11-15 10:43:06 -0800690 // TODO Might want to move this into a different type.
691 // Now we reach the part where we must do active cleanup if something fails.
692 // TODO We should really Retry if this fails instead of simply aborting.
693 // Set the new DexFileCookie returns the original so we can fix it back up if redefinition fails
694 art::ObjPtr<art::mirror::LongArray> original_dex_file_cookie(nullptr);
Alex Light007ada22017-01-10 13:33:56 -0800695 UpdateJavaDexFile(java_dex_file.Get(), new_dex_file_cookie.Get(), &original_dex_file_cookie);
696 FindAndAllocateObsoleteMethods(art_class.Get());
697 UpdateClass(art_class.Get(), new_dex_cache.Get());
Alex Lightdba61482016-12-21 08:20:29 -0800698 // Ensure that obsolete methods are deoptimized. This is needed since optimized methods may have
699 // pointers to their ArtMethod's stashed in registers that they then use to attempt to hit the
700 // DexCache.
701 // TODO This can fail (leave some methods optimized) near runtime methods (including
702 // quick-to-interpreter transition function).
703 // TODO We probably don't need this at all once we have a way to ensure that the
704 // current_art_method is never stashed in a (physical) register by the JIT and lost to the
705 // stack-walker.
706 EnsureObsoleteMethodsAreDeoptimized();
707 // TODO Verify the new Class.
708 // TODO Failure then undo updates to class
709 // TODO Shrink the obsolete method maps if possible?
710 // TODO find appropriate class loader.
Alex Lighta01de592016-11-15 10:43:06 -0800711 // TODO Put this into a scoped thing.
712 runtime_->GetThreadList()->ResumeAll();
713 // Get back shared mutator lock as expected for return.
714 self_->TransitionFromSuspendedToRunnable();
Alex Lightdba61482016-12-21 08:20:29 -0800715 // TODO Do the dex_file_ release at a more reasonable place. This works but it muddles who really
716 // owns the DexFile.
Alex Lighta01de592016-11-15 10:43:06 -0800717 dex_file_.release();
Alex Light6abd5392017-01-05 17:53:00 -0800718 if (heap->IsGcConcurrentAndMoving()) {
719 heap->DecrementDisableMovingGC(self_);
720 }
Alex Lighta01de592016-11-15 10:43:06 -0800721 return OK;
722}
723
Alex Light007ada22017-01-10 13:33:56 -0800724void Redefiner::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Alex Light200b9d72016-12-15 11:34:13 -0800725 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
726 const art::DexFile::ClassDef& class_def) {
Alex Lighta01de592016-11-15 10:43:06 -0800727 art::ClassLinker* linker = runtime_->GetClassLinker();
728 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Alex Light200b9d72016-12-15 11:34:13 -0800729 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -0800730 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -0800731 // Update methods.
Alex Lighta01de592016-11-15 10:43:06 -0800732 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) {
733 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
734 art::dex::TypeIndex method_return_idx =
735 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
736 const auto* old_type_list = method.GetParameterTypeList();
737 std::vector<art::dex::TypeIndex> new_type_list;
738 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
739 new_type_list.push_back(
740 dex_file_->GetIndexForTypeId(
741 *dex_file_->FindTypeId(
742 old_dex_file.GetTypeDescriptor(
743 old_dex_file.GetTypeId(
744 old_type_list->GetTypeItem(i).type_idx_)))));
745 }
746 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx,
747 new_type_list);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000748 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800749 CHECK(proto_id != nullptr || old_type_list == nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800750 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
751 *new_name_id,
752 *proto_id);
Nicolas Geoffrayf6abcda2016-12-21 09:26:18 +0000753 // TODO Return false, cleanup.
Alex Lightdba61482016-12-21 08:20:29 -0800754 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -0800755 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
756 method.SetDexMethodIndex(dex_method_idx);
757 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -0800758 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Lighta01de592016-11-15 10:43:06 -0800759 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size);
760 method.SetDexCacheResolvedTypes(new_dex_cache->GetResolvedTypes(), image_pointer_size);
Alex Lightdba61482016-12-21 08:20:29 -0800761 // Notify the jit that this method is redefined.
762 art::jit::Jit* jit = runtime_->GetJit();
763 if (jit != nullptr) {
764 jit->GetCodeCache()->NotifyMethodRedefined(&method);
765 }
Alex Lighta01de592016-11-15 10:43:06 -0800766 }
Alex Light200b9d72016-12-15 11:34:13 -0800767}
768
Alex Light007ada22017-01-10 13:33:56 -0800769void Redefiner::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -0800770 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
771 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
772 for (art::ArtField& field : fields_iter) {
773 std::string declaring_class_name;
774 const art::DexFile::TypeId* new_declaring_id =
775 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
776 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
777 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
778 // TODO Handle error, cleanup.
779 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
780 const art::DexFile::FieldId* new_field_id =
781 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
782 CHECK(new_field_id != nullptr);
783 // We only need to update the index since the other data in the ArtField cannot be updated.
784 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
785 }
786 }
Alex Light200b9d72016-12-15 11:34:13 -0800787}
788
789// Performs updates to class that will allow us to verify it.
Alex Light007ada22017-01-10 13:33:56 -0800790void Redefiner::UpdateClass(art::ObjPtr<art::mirror::Class> mclass,
Alex Light200b9d72016-12-15 11:34:13 -0800791 art::ObjPtr<art::mirror::DexCache> new_dex_cache) {
792 const art::DexFile::ClassDef* class_def = art::OatFile::OatDexFile::FindClassDef(
793 *dex_file_, class_sig_, art::ComputeModifiedUtf8Hash(class_sig_));
Alex Light007ada22017-01-10 13:33:56 -0800794 DCHECK(class_def != nullptr);
795 UpdateMethods(mclass, new_dex_cache, *class_def);
796 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -0800797
Alex Lighta01de592016-11-15 10:43:06 -0800798 // Update the class fields.
799 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
800 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
801 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Lighta01de592016-11-15 10:43:06 -0800802 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(*class_def));
803 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_)));
Alex Lighta01de592016-11-15 10:43:06 -0800804}
805
Alex Light007ada22017-01-10 13:33:56 -0800806void Redefiner::UpdateJavaDexFile(art::ObjPtr<art::mirror::Object> java_dex_file,
Alex Lighta01de592016-11-15 10:43:06 -0800807 art::ObjPtr<art::mirror::LongArray> new_cookie,
808 /*out*/art::ObjPtr<art::mirror::LongArray>* original_cookie) {
809 art::ArtField* internal_cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
810 "mInternalCookie", "Ljava/lang/Object;");
811 art::ArtField* cookie_field = java_dex_file->GetClass()->FindDeclaredInstanceField(
812 "mCookie", "Ljava/lang/Object;");
813 CHECK(internal_cookie_field != nullptr);
814 art::ObjPtr<art::mirror::LongArray> orig_internal_cookie(
815 internal_cookie_field->GetObject(java_dex_file)->AsLongArray());
816 art::ObjPtr<art::mirror::LongArray> orig_cookie(
817 cookie_field->GetObject(java_dex_file)->AsLongArray());
818 internal_cookie_field->SetObject<false>(java_dex_file, new_cookie);
819 *original_cookie = orig_internal_cookie;
820 if (!orig_cookie.IsNull()) {
821 cookie_field->SetObject<false>(java_dex_file, new_cookie);
822 }
Alex Lighta01de592016-11-15 10:43:06 -0800823}
824
825// This function does all (java) allocations we need to do for the Class being redefined.
826// TODO Change this name maybe?
827bool Redefiner::EnsureClassAllocationsFinished() {
828 art::StackHandleScope<2> hs(self_);
829 art::Handle<art::mirror::Class> klass(hs.NewHandle(self_->DecodeJObject(klass_)->AsClass()));
830 if (klass.Get() == nullptr) {
831 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
832 return false;
833 }
834 // Allocate the classExt
835 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self_)));
836 if (ext.Get() == nullptr) {
837 // No memory. Clear exception (it's not useful) and return error.
838 // TODO This doesn't need to be fatal. We could just not support obsolete methods after hitting
839 // this case.
840 self_->AssertPendingOOMException();
841 self_->ClearException();
842 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
843 return false;
844 }
845 // Allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
846 // are only modified when all threads (other than the modifying one) are suspended we don't need
847 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
848 // however, since that can happen at any time.
849 // TODO Clear these after we walk the stacks in order to free them in the (likely?) event there
850 // are no obsolete methods.
851 {
852 art::ObjectLock<art::mirror::ClassExt> lock(self_, ext);
853 if (!ext->ExtendObsoleteArrays(
854 self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
855 // OOM. Clear exception and return error.
856 self_->AssertPendingOOMException();
857 self_->ClearException();
858 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
859 return false;
860 }
861 }
862 return true;
863}
864
865} // namespace openjdkjvmti