blob: 907ab0252d8e2f8bb3d5614ccf2c61eff1b8c5c4 [file] [log] [blame]
Andreas Gampee492ae32016-10-28 19:34:57 -07001/* 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_class.h"
33
Alex Light440b5d92017-01-24 15:32:25 -080034#include "android-base/stringprintf.h"
35
Andreas Gampee6377462017-01-20 17:37:50 -080036#include <mutex>
37#include <unordered_set>
38
Andreas Gampee492ae32016-10-28 19:34:57 -070039#include "art_jvmti.h"
Andreas Gampee6377462017-01-20 17:37:50 -080040#include "base/macros.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080041#include "class_table-inl.h"
42#include "class_linker.h"
Alex Light440b5d92017-01-24 15:32:25 -080043#include "common_throws.h"
Andreas Gampe0eb36432017-02-15 18:36:14 -080044#include "dex_file_annotations.h"
Andreas Gampee6377462017-01-20 17:37:50 -080045#include "events-inl.h"
Alex Light40528472017-03-28 09:07:36 -070046#include "fixed_up_dex_file.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080047#include "gc/heap.h"
48#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080049#include "handle.h"
50#include "jni_env_ext-inl.h"
Andreas Gampeac587272017-01-05 15:21:34 -080051#include "jni_internal.h"
Alex Light440b5d92017-01-24 15:32:25 -080052#include "mirror/array-inl.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_ext.h"
Andreas Gampe0eb36432017-02-15 18:36:14 -080055#include "mirror/object_array-inl.h"
Andreas Gampea67354b2017-02-10 16:18:30 -080056#include "mirror/object_reference.h"
57#include "mirror/object-inl.h"
Andreas Gampe52784ac2017-02-13 18:10:09 -080058#include "mirror/reference.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080059#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080060#include "runtime_callbacks.h"
61#include "ScopedLocalRef.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070062#include "scoped_thread_state_change-inl.h"
63#include "thread-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080064#include "thread_list.h"
Alex Lighteb98b082017-01-25 13:02:32 -080065#include "ti_class_loader.h"
Alex Lightd8ce4e72017-02-27 10:52:29 -080066#include "ti_phase.h"
Alex Light440b5d92017-01-24 15:32:25 -080067#include "ti_redefine.h"
68#include "utils.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070069
70namespace openjdkjvmti {
71
Alex Light440b5d92017-01-24 15:32:25 -080072using android::base::StringPrintf;
73
74static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
75 const char* descriptor,
76 const std::string& orig_location,
77 jint final_len,
78 const unsigned char* final_dex_data)
79 REQUIRES_SHARED(art::Locks::mutator_lock_) {
80 // Make the mmap
81 std::string error_msg;
82 std::unique_ptr<art::MemMap> map(Redefiner::MoveDataToMemMap(orig_location,
83 final_len,
84 final_dex_data,
85 &error_msg));
86 if (map.get() == nullptr) {
87 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
88 self->ThrowOutOfMemoryError(StringPrintf(
89 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
90 return nullptr;
91 }
92
93 // Make a dex-file
94 if (map->Size() < sizeof(art::DexFile::Header)) {
95 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
96 art::ThrowClassFormatError(nullptr,
97 "Unable to read transformed dex file of %s",
98 descriptor);
99 return nullptr;
100 }
101 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
102 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
103 checksum,
104 std::move(map),
105 /*verify*/true,
106 /*verify_checksum*/true,
107 &error_msg));
108 if (dex_file.get() == nullptr) {
109 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
110 art::ThrowClassFormatError(nullptr,
111 "Unable to read transformed dex file of %s because %s",
112 descriptor,
113 error_msg.c_str());
114 return nullptr;
115 }
116 if (dex_file->NumClassDefs() != 1) {
117 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
118 // TODO Throw some other sort of error here maybe?
119 art::ThrowClassFormatError(
120 nullptr,
121 "Unable to use transformed dex file of %s because it contained too many classes",
122 descriptor);
123 return nullptr;
124 }
125 return dex_file;
126}
127
Andreas Gampee6377462017-01-20 17:37:50 -0800128struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800129 void ClassPreDefine(const char* descriptor,
130 art::Handle<art::mirror::Class> klass,
131 art::Handle<art::mirror::ClassLoader> class_loader,
132 const art::DexFile& initial_dex_file,
133 const art::DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
134 /*out*/art::DexFile const** final_dex_file,
135 /*out*/art::DexFile::ClassDef const** final_class_def)
136 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
137 bool is_enabled =
138 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
139 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
140 if (!is_enabled) {
141 return;
142 }
143 if (descriptor[0] != 'L') {
144 // It is a primitive or array. Just return
145 return;
146 }
Alex Lightd8ce4e72017-02-27 10:52:29 -0800147 jvmtiPhase phase = PhaseUtil::GetPhaseUnchecked();
148 if (UNLIKELY(phase != JVMTI_PHASE_START && phase != JVMTI_PHASE_LIVE)) {
149 // We want to wait until we are at least in the START phase so that all WellKnownClasses and
150 // mirror classes have been initialized and loaded. The runtime relies on these classes having
151 // specific fields and methods present. Since PreDefine hooks don't need to abide by this
152 // restriction we will simply not send the event for these classes.
153 LOG(WARNING) << "Ignoring load of class <" << descriptor << "> as it is being loaded during "
154 << "runtime initialization.";
155 return;
156 }
157
158 // Strip the 'L' and ';' from the descriptor
Alex Light28027122017-01-26 17:21:51 -0800159 std::string name(std::string(descriptor).substr(1, strlen(descriptor) - 2));
Alex Light440b5d92017-01-24 15:32:25 -0800160
161 art::Thread* self = art::Thread::Current();
162 art::JNIEnvExt* env = self->GetJniEnv();
163 ScopedLocalRef<jobject> loader(
164 env, class_loader.IsNull() ? nullptr : env->AddLocalReference<jobject>(class_loader.Get()));
Alex Light40528472017-03-28 09:07:36 -0700165 std::unique_ptr<FixedUpDexFile> dex_file_copy(FixedUpDexFile::Create(initial_dex_file));
166
Alex Light440b5d92017-01-24 15:32:25 -0800167 // Go back to native.
168 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
169 // Call all Non-retransformable agents.
170 jint post_no_redefine_len = 0;
171 unsigned char* post_no_redefine_dex_data = nullptr;
172 std::unique_ptr<const unsigned char> post_no_redefine_unique_ptr(nullptr);
173 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
174 self,
175 static_cast<JNIEnv*>(env),
176 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
177 loader.get(),
178 name.c_str(),
179 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
Alex Light40528472017-03-28 09:07:36 -0700180 static_cast<jint>(dex_file_copy->Size()),
181 static_cast<const unsigned char*>(dex_file_copy->Begin()),
Alex Light440b5d92017-01-24 15:32:25 -0800182 static_cast<jint*>(&post_no_redefine_len),
183 static_cast<unsigned char**>(&post_no_redefine_dex_data));
184 if (post_no_redefine_dex_data == nullptr) {
185 DCHECK_EQ(post_no_redefine_len, 0);
Alex Light40528472017-03-28 09:07:36 -0700186 post_no_redefine_dex_data = const_cast<unsigned char*>(dex_file_copy->Begin());
187 post_no_redefine_len = dex_file_copy->Size();
Alex Light440b5d92017-01-24 15:32:25 -0800188 } else {
189 post_no_redefine_unique_ptr = std::unique_ptr<const unsigned char>(post_no_redefine_dex_data);
190 DCHECK_GT(post_no_redefine_len, 0);
191 }
192 // Call all retransformable agents.
193 jint final_len = 0;
194 unsigned char* final_dex_data = nullptr;
195 std::unique_ptr<const unsigned char> final_dex_unique_ptr(nullptr);
196 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
197 self,
198 static_cast<JNIEnv*>(env),
199 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
200 loader.get(),
201 name.c_str(),
202 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
203 static_cast<jint>(post_no_redefine_len),
204 static_cast<const unsigned char*>(post_no_redefine_dex_data),
205 static_cast<jint*>(&final_len),
206 static_cast<unsigned char**>(&final_dex_data));
207 if (final_dex_data == nullptr) {
208 DCHECK_EQ(final_len, 0);
209 final_dex_data = post_no_redefine_dex_data;
210 final_len = post_no_redefine_len;
211 } else {
212 final_dex_unique_ptr = std::unique_ptr<const unsigned char>(final_dex_data);
213 DCHECK_GT(final_len, 0);
214 }
215
Alex Light40528472017-03-28 09:07:36 -0700216 if (final_dex_data != dex_file_copy->Begin()) {
Alex Light440b5d92017-01-24 15:32:25 -0800217 LOG(WARNING) << "Changing class " << descriptor;
218 art::ScopedObjectAccess soa(self);
219 art::StackHandleScope<2> hs(self);
220 // Save the results of all the non-retransformable agents.
221 // First allocate the ClassExt
222 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
223 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
224 // get copied.
225 if (ext.IsNull()) {
226 // We will just return failure if we fail to allocate
227 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
228 << "Aborting transformation since we will be unable to store it.";
229 self->AssertPendingOOMException();
230 return;
231 }
232
233 // Allocate the byte array to store the dex file bytes in.
234 art::Handle<art::mirror::ByteArray> arr(hs.NewHandle(
235 art::mirror::ByteArray::AllocateAndFill(
236 self,
237 reinterpret_cast<const signed char*>(post_no_redefine_dex_data),
238 post_no_redefine_len)));
239 if (arr.IsNull()) {
240 LOG(WARNING) << "Unable to allocate byte array for initial dex-file bytes. Aborting "
241 << "transformation";
242 self->AssertPendingOOMException();
243 return;
244 }
245
246 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
247 descriptor,
248 initial_dex_file.GetLocation(),
249 final_len,
250 final_dex_data));
251 if (dex_file.get() == nullptr) {
252 return;
253 }
254
Alex Lighteb98b082017-01-25 13:02:32 -0800255 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800256 LOG(WARNING) << "Dex file created by class-definition time transformation of "
257 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800258
259 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
260 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
261 return;
262 }
263
Alex Light440b5d92017-01-24 15:32:25 -0800264 // Actually set the ClassExt's original bytes once we have actually succeeded.
Alex Light2f814aa2017-03-24 15:21:34 +0000265 ext->SetOriginalDexFile(arr.Get());
Alex Light440b5d92017-01-24 15:32:25 -0800266 // Set the return values
267 *final_class_def = &dex_file->GetClassDef(0);
268 *final_dex_file = dex_file.release();
269 }
270 }
271
Andreas Gampee6377462017-01-20 17:37:50 -0800272 void ClassLoad(art::Handle<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
273 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
274 art::Thread* thread = art::Thread::Current();
275 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
276 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Andreas Gampe983c1752017-01-23 19:46:56 -0800277 ScopedLocalRef<jthread> thread_jni(
278 thread->GetJniEnv(), thread->GetJniEnv()->AddLocalReference<jthread>(thread->GetPeer()));
Andreas Gampee6377462017-01-20 17:37:50 -0800279 {
280 art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800281 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
282 thread,
283 static_cast<JNIEnv*>(thread->GetJniEnv()),
284 thread_jni.get(),
285 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800286 }
Andreas Gampe691051b2017-02-09 09:15:24 -0800287 if (klass->IsTemp()) {
288 AddTempClass(thread, jklass.get());
289 }
Andreas Gampee6377462017-01-20 17:37:50 -0800290 }
291 }
292
Andreas Gampe691051b2017-02-09 09:15:24 -0800293 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800294 art::Handle<art::mirror::Class> klass)
295 REQUIRES_SHARED(art::Locks::mutator_lock_) {
296 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
297 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800298 if (temp_klass.Get() != klass.Get()) {
299 DCHECK(temp_klass->IsTemp());
300 DCHECK(temp_klass->IsRetired());
301 HandleTempClass(thread, temp_klass, klass);
302 }
Andreas Gampee6377462017-01-20 17:37:50 -0800303 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
304 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Andreas Gampe983c1752017-01-23 19:46:56 -0800305 ScopedLocalRef<jthread> thread_jni(
306 thread->GetJniEnv(), thread->GetJniEnv()->AddLocalReference<jthread>(thread->GetPeer()));
Andreas Gampee6377462017-01-20 17:37:50 -0800307 art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800308 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
309 thread,
310 static_cast<JNIEnv*>(thread->GetJniEnv()),
311 thread_jni.get(),
312 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800313 }
314 }
315
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800316 // To support parallel class-loading, we need to perform some locking dances here. Namely,
317 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
318 // (as that requires suspending all mutators).
319
Andreas Gampee6377462017-01-20 17:37:50 -0800320 void AddTempClass(art::Thread* self, jclass klass) {
321 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800322 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
323 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800324 }
325
Andreas Gampe691051b2017-02-09 09:15:24 -0800326 void HandleTempClass(art::Thread* self,
327 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800328 art::Handle<art::mirror::Class> klass)
329 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800330 bool requires_fixup = false;
331 {
332 std::unique_lock<std::mutex> mu(temp_classes_lock);
333 if (temp_classes.empty()) {
334 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800335 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800336
337 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
338 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
339 self->GetJniEnv()->DeleteGlobalRef(*it);
340 temp_classes.erase(it);
341 requires_fixup = true;
342 break;
343 }
344 }
345 }
346 if (requires_fixup) {
347 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800348 }
349 }
350
Andreas Gampe691051b2017-02-09 09:15:24 -0800351 void FixupTempClass(art::Thread* self,
352 art::Handle<art::mirror::Class> temp_klass,
353 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800354 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800355 // Suspend everything.
356 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
357 if (heap->IsGcConcurrentAndMoving()) {
358 // Need to take a heap dump while GC isn't running. See the
359 // comment in Heap::VisitObjects().
360 heap->IncrementDisableMovingGC(self);
361 }
362 {
363 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
364 art::ScopedSuspendAll ssa("FixupTempClass");
365
366 art::mirror::Class* input = temp_klass.Get();
367 art::mirror::Class* output = klass.Get();
368
369 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800370 FixupLocalReferenceTables(self, input, output);
Andreas Gampea67354b2017-02-10 16:18:30 -0800371 FixupHeap(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800372 }
373 if (heap->IsGcConcurrentAndMoving()) {
374 heap->DecrementDisableMovingGC(self);
375 }
376 }
377
Andreas Gampe94dda932017-02-09 18:19:21 -0800378 class RootUpdater : public art::RootVisitor {
379 public:
380 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
381 : input_(input), output_(output) {}
382
383 void VisitRoots(art::mirror::Object*** roots,
384 size_t count,
385 const art::RootInfo& info ATTRIBUTE_UNUSED)
386 OVERRIDE {
387 for (size_t i = 0; i != count; ++i) {
388 if (*roots[i] == input_) {
389 *roots[i] = output_;
390 }
391 }
392 }
393
394 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
395 size_t count,
396 const art::RootInfo& info ATTRIBUTE_UNUSED)
397 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
398 for (size_t i = 0; i != count; ++i) {
399 if (roots[i]->AsMirrorPtr() == input_) {
400 roots[i]->Assign(output_);
401 }
402 }
403 }
404
405 private:
406 const art::mirror::Class* input_;
407 art::mirror::Class* output_;
408 };
409
Andreas Gampea67354b2017-02-10 16:18:30 -0800410 void FixupGlobalReferenceTables(art::mirror::Class* input, art::mirror::Class* output)
Andreas Gampe691051b2017-02-09 09:15:24 -0800411 REQUIRES(art::Locks::mutator_lock_) {
412 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
413
414 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800415 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800416 java_vm->VisitRoots(&global_update);
417
418 class WeakGlobalUpdate : public art::IsMarkedVisitor {
419 public:
420 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
421 : input_(root_input), output_(root_output) {}
422
423 art::mirror::Object* IsMarked(art::mirror::Object* obj) OVERRIDE {
424 if (obj == input_) {
425 return output_;
426 }
427 return obj;
428 }
429
430 private:
431 const art::mirror::Class* input_;
432 art::mirror::Class* output_;
433 };
434 WeakGlobalUpdate weak_global_update(input, output);
435 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800436 }
437
Andreas Gampe94dda932017-02-09 18:19:21 -0800438 void FixupLocalReferenceTables(art::Thread* self,
439 art::mirror::Class* input,
440 art::mirror::Class* output)
441 REQUIRES(art::Locks::mutator_lock_) {
442 class LocalUpdate {
443 public:
444 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
445 : input_(root_input), output_(root_output) {}
446
447 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
448 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
449
450 // Fix up the local table with a root visitor.
451 RootUpdater local_update(local->input_, local->output_);
452 t->GetJniEnv()->locals.VisitRoots(
453 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
454 }
455
456 private:
457 const art::mirror::Class* input_;
458 art::mirror::Class* output_;
459 };
460 LocalUpdate local_upd(input, output);
461 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
462 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
463 }
464
Andreas Gampea67354b2017-02-10 16:18:30 -0800465 void FixupHeap(art::mirror::Class* input, art::mirror::Class* output)
466 REQUIRES(art::Locks::mutator_lock_) {
467 class HeapFixupVisitor {
468 public:
469 HeapFixupVisitor(const art::mirror::Class* root_input, art::mirror::Class* root_output)
470 : input_(root_input), output_(root_output) {}
471
472 void operator()(art::mirror::Object* src,
473 art::MemberOffset field_offset,
474 bool is_static ATTRIBUTE_UNUSED) const
475 REQUIRES_SHARED(art::Locks::mutator_lock_) {
476 art::mirror::HeapReference<art::mirror::Object>* trg =
477 src->GetFieldObjectReferenceAddr(field_offset);
478 if (trg->AsMirrorPtr() == input_) {
479 DCHECK_NE(field_offset.Uint32Value(), 0u); // This shouldn't be the class field of
480 // an object.
481 trg->Assign(output_);
482 }
483 }
484
Andreas Gampe52784ac2017-02-13 18:10:09 -0800485 void operator()(art::ObjPtr<art::mirror::Class> klass ATTRIBUTE_UNUSED,
486 art::ObjPtr<art::mirror::Reference> reference) const
487 REQUIRES_SHARED(art::Locks::mutator_lock_) {
488 art::mirror::Object* val = reference->GetReferent();
489 if (val == input_) {
490 reference->SetReferent<false>(output_);
491 }
492 }
493
Andreas Gampea67354b2017-02-10 16:18:30 -0800494 void VisitRoot(art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED)
Andreas Gampe52784ac2017-02-13 18:10:09 -0800495 const {
Andreas Gampea67354b2017-02-10 16:18:30 -0800496 LOG(FATAL) << "Unreachable";
497 }
498
499 void VisitRootIfNonNull(
500 art::mirror::CompressedReference<art::mirror::Object>* root ATTRIBUTE_UNUSED) const {
501 LOG(FATAL) << "Unreachable";
502 }
503
504 static void AllObjectsCallback(art::mirror::Object* obj, void* arg)
505 REQUIRES_SHARED(art::Locks::mutator_lock_) {
506 HeapFixupVisitor* hfv = reinterpret_cast<HeapFixupVisitor*>(arg);
507
508 // Visit references, not native roots.
Andreas Gampe52784ac2017-02-13 18:10:09 -0800509 obj->VisitReferences<false>(*hfv, *hfv);
Andreas Gampea67354b2017-02-10 16:18:30 -0800510 }
511
512 private:
513 const art::mirror::Class* input_;
514 art::mirror::Class* output_;
515 };
516 HeapFixupVisitor hfv(input, output);
517 art::Runtime::Current()->GetHeap()->VisitObjectsPaused(HeapFixupVisitor::AllObjectsCallback,
518 &hfv);
519 }
520
Andreas Gampee6377462017-01-20 17:37:50 -0800521 // A set of all the temp classes we have handed out. We have to fix up references to these.
522 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
523 // Prepare event will closely follow, so the vector should be small.
524 std::mutex temp_classes_lock;
525 std::vector<jclass> temp_classes;
526
527 EventHandler* event_handler = nullptr;
528};
529
530ClassCallback gClassCallback;
531
532void ClassUtil::Register(EventHandler* handler) {
533 gClassCallback.event_handler = handler;
534 art::ScopedThreadStateChange stsc(art::Thread::Current(),
535 art::ThreadState::kWaitingForDebuggerToAttach);
536 art::ScopedSuspendAll ssa("Add load callback");
537 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
538}
539
540void ClassUtil::Unregister() {
541 art::ScopedThreadStateChange stsc(art::Thread::Current(),
542 art::ThreadState::kWaitingForDebuggerToAttach);
543 art::ScopedSuspendAll ssa("Remove thread callback");
544 art::Runtime* runtime = art::Runtime::Current();
545 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
546}
547
Andreas Gampeac587272017-01-05 15:21:34 -0800548jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
549 jclass jklass,
550 jint* field_count_ptr,
551 jfieldID** fields_ptr) {
552 art::ScopedObjectAccess soa(art::Thread::Current());
553 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
554 if (klass == nullptr) {
555 return ERR(INVALID_CLASS);
556 }
557
558 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
559 return ERR(NULL_POINTER);
560 }
561
Andreas Gampeac587272017-01-05 15:21:34 -0800562 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
563 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
564 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
565
566 unsigned char* out_ptr;
567 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
568 if (allocError != ERR(NONE)) {
569 return allocError;
570 }
571 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
572
573 size_t array_idx = 0;
574 for (art::ArtField& field : sfields) {
575 field_array[array_idx] = art::jni::EncodeArtField(&field);
576 ++array_idx;
577 }
578 for (art::ArtField& field : ifields) {
579 field_array[array_idx] = art::jni::EncodeArtField(&field);
580 ++array_idx;
581 }
582
583 *field_count_ptr = static_cast<jint>(array_size);
584 *fields_ptr = field_array;
585
586 return ERR(NONE);
587}
588
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800589jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
590 jclass jklass,
591 jint* method_count_ptr,
592 jmethodID** methods_ptr) {
593 art::ScopedObjectAccess soa(art::Thread::Current());
594 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
595 if (klass == nullptr) {
596 return ERR(INVALID_CLASS);
597 }
598
599 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
600 return ERR(NULL_POINTER);
601 }
602
603 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
604 unsigned char* out_ptr;
605 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
606 if (allocError != ERR(NONE)) {
607 return allocError;
608 }
609 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
610
611 if (art::kIsDebugBuild) {
612 size_t count = 0;
613 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
614 count++;
615 }
616 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
617 }
618
619 size_t array_idx = 0;
620 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
621 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
622 ++array_idx;
623 }
624
625 *method_count_ptr = static_cast<jint>(array_size);
626 *methods_ptr = method_array;
627
628 return ERR(NONE);
629}
630
Andreas Gampe8b07e472017-01-06 14:20:39 -0800631jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
632 jclass jklass,
633 jint* interface_count_ptr,
634 jclass** interfaces_ptr) {
635 art::ScopedObjectAccess soa(art::Thread::Current());
636 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
637 if (klass == nullptr) {
638 return ERR(INVALID_CLASS);
639 }
640
641 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
642 return ERR(NULL_POINTER);
643 }
644
645 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
646 // spec says these should not be reported.
647 if (klass->IsArrayClass()) {
648 *interface_count_ptr = 0;
649 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
650 return ERR(NONE);
651 }
652
653 size_t array_size = klass->NumDirectInterfaces();
654 unsigned char* out_ptr;
655 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
656 if (allocError != ERR(NONE)) {
657 return allocError;
658 }
659 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
660
661 art::StackHandleScope<1> hs(soa.Self());
662 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
663
664 for (uint32_t idx = 0; idx != array_size; ++idx) {
665 art::ObjPtr<art::mirror::Class> inf_klass =
666 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
667 if (inf_klass == nullptr) {
668 soa.Self()->ClearException();
669 env->Deallocate(out_ptr);
670 // TODO: What is the right error code here?
671 return ERR(INTERNAL);
672 }
673 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
674 }
675
676 *interface_count_ptr = static_cast<jint>(array_size);
677 *interfaces_ptr = interface_array;
678
679 return ERR(NONE);
680}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800681
Andreas Gampee492ae32016-10-28 19:34:57 -0700682jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
683 jclass jklass,
684 char** signature_ptr,
685 char** generic_ptr) {
686 art::ScopedObjectAccess soa(art::Thread::Current());
687 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
688 if (klass == nullptr) {
689 return ERR(INVALID_CLASS);
690 }
691
Andreas Gampe54711412017-02-21 12:41:43 -0800692 JvmtiUniquePtr<char[]> sig_copy;
Andreas Gampee492ae32016-10-28 19:34:57 -0700693 if (signature_ptr != nullptr) {
694 std::string storage;
695 const char* descriptor = klass->GetDescriptor(&storage);
696
Andreas Gampe54711412017-02-21 12:41:43 -0800697 jvmtiError ret;
698 sig_copy = CopyString(env, descriptor, &ret);
699 if (sig_copy == nullptr) {
Andreas Gampee492ae32016-10-28 19:34:57 -0700700 return ret;
701 }
Andreas Gampe54711412017-02-21 12:41:43 -0800702 *signature_ptr = sig_copy.get();
Andreas Gampee492ae32016-10-28 19:34:57 -0700703 }
704
Andreas Gampee6377462017-01-20 17:37:50 -0800705 if (generic_ptr != nullptr) {
706 *generic_ptr = nullptr;
Andreas Gampe0eb36432017-02-15 18:36:14 -0800707 if (!klass->IsProxyClass() && klass->GetDexCache() != nullptr) {
708 art::StackHandleScope<1> hs(soa.Self());
709 art::Handle<art::mirror::Class> h_klass = hs.NewHandle(klass);
710 art::mirror::ObjectArray<art::mirror::String>* str_array =
711 art::annotations::GetSignatureAnnotationForClass(h_klass);
712 if (str_array != nullptr) {
713 std::ostringstream oss;
714 for (int32_t i = 0; i != str_array->GetLength(); ++i) {
715 oss << str_array->Get(i)->ToModifiedUtf8();
716 }
717 std::string output_string = oss.str();
Andreas Gampe54711412017-02-21 12:41:43 -0800718 jvmtiError ret;
719 JvmtiUniquePtr<char[]> copy = CopyString(env, output_string.c_str(), &ret);
720 if (copy == nullptr) {
Andreas Gampe0eb36432017-02-15 18:36:14 -0800721 return ret;
722 }
Andreas Gampe54711412017-02-21 12:41:43 -0800723 *generic_ptr = copy.release();
Andreas Gampe0eb36432017-02-15 18:36:14 -0800724 } else if (soa.Self()->IsExceptionPending()) {
725 // TODO: Should we report an error here?
726 soa.Self()->ClearException();
727 }
728 }
Andreas Gampee6377462017-01-20 17:37:50 -0800729 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700730
731 // Everything is fine, release the buffers.
732 sig_copy.release();
733
734 return ERR(NONE);
735}
736
Andreas Gampeff9d2092017-01-06 09:12:49 -0800737jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
738 jclass jklass,
739 jint* status_ptr) {
740 art::ScopedObjectAccess soa(art::Thread::Current());
741 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
742 if (klass == nullptr) {
743 return ERR(INVALID_CLASS);
744 }
745
746 if (status_ptr == nullptr) {
747 return ERR(NULL_POINTER);
748 }
749
750 if (klass->IsArrayClass()) {
751 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
752 } else if (klass->IsPrimitive()) {
753 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
754 } else {
755 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
756 // This is finicky. If there's an error, we'll say it wasn't prepared.
757 if (klass->IsResolved()) {
758 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
759 }
760 if (klass->IsInitialized()) {
761 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
762 }
763 // Technically the class may be erroneous for other reasons, but we do not have enough info.
764 if (klass->IsErroneous()) {
765 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
766 }
767 }
768
769 return ERR(NONE);
770}
771
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800772template <typename T>
773static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
774 art::ScopedObjectAccess soa(art::Thread::Current());
775 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
776 if (klass == nullptr) {
777 return ERR(INVALID_CLASS);
778 }
779
780 if (is_t_ptr == nullptr) {
781 return ERR(NULL_POINTER);
782 }
783
784 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
785 return ERR(NONE);
786}
787
788jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
789 jclass jklass,
790 jboolean* is_interface_ptr) {
791 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
792 return klass->IsInterface();
793 };
794 return ClassIsT(jklass, test, is_interface_ptr);
795}
796
797jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
798 jclass jklass,
799 jboolean* is_array_class_ptr) {
800 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
801 return klass->IsArrayClass();
802 };
803 return ClassIsT(jklass, test, is_array_class_ptr);
804}
805
Andreas Gampe64013e52017-01-06 13:07:19 -0800806// Keep this in sync with Class.getModifiers().
807static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
808 REQUIRES_SHARED(art::Locks::mutator_lock_) {
809 if (klass->IsArrayClass()) {
810 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
811 if ((component_modifiers & art::kAccInterface) != 0) {
812 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
813 }
814 return art::kAccAbstract | art::kAccFinal | component_modifiers;
815 }
816
817 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
818
819 art::StackHandleScope<1> hs(self);
820 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
821 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
822}
823
824jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
825 jclass jklass,
826 jint* modifiers_ptr) {
827 art::ScopedObjectAccess soa(art::Thread::Current());
828 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
829 if (klass == nullptr) {
830 return ERR(INVALID_CLASS);
831 }
832
833 if (modifiers_ptr == nullptr) {
834 return ERR(NULL_POINTER);
835 }
836
837 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
838
839 return ERR(NONE);
840}
841
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800842jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
843 jclass jklass,
844 jobject* classloader_ptr) {
845 art::ScopedObjectAccess soa(art::Thread::Current());
846 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
847 if (klass == nullptr) {
848 return ERR(INVALID_CLASS);
849 }
850
851 if (classloader_ptr == nullptr) {
852 return ERR(NULL_POINTER);
853 }
854
855 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
856
857 return ERR(NONE);
858}
859
Andreas Gampe70f16392017-01-16 14:20:10 -0800860jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
861 jobject initiating_loader,
862 jint* class_count_ptr,
863 jclass** classes_ptr) {
864 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
865
866 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
867 return ERR(NULL_POINTER);
868 }
869 art::Thread* self = art::Thread::Current();
870 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
871 art::WellKnownClasses::java_lang_ClassLoader)) {
872 return ERR(ILLEGAL_ARGUMENT);
873 }
874 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
875 art::WellKnownClasses::java_lang_BootClassLoader)) {
876 // Need to use null for the BootClassLoader.
877 initiating_loader = nullptr;
878 }
879
880 art::ScopedObjectAccess soa(self);
881 art::ObjPtr<art::mirror::ClassLoader> class_loader =
882 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
883
884 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
885
886 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
887
888 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
889 if (class_table == nullptr) {
890 // Nothing loaded.
891 *class_count_ptr = 0;
892 *classes_ptr = nullptr;
893 return ERR(NONE);
894 }
895
896 struct ClassTableCount {
897 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
898 DCHECK(klass != nullptr);
899 ++count;
900 return true;
901 }
902
903 size_t count = 0;
904 };
905 ClassTableCount ctc;
906 class_table->Visit(ctc);
907
908 if (ctc.count == 0) {
909 // Nothing loaded.
910 *class_count_ptr = 0;
911 *classes_ptr = nullptr;
912 return ERR(NONE);
913 }
914
915 unsigned char* data;
916 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
917 if (data_result != ERR(NONE)) {
918 return data_result;
919 }
920 jclass* class_array = reinterpret_cast<jclass*>(data);
921
922 struct ClassTableFill {
923 bool operator()(art::ObjPtr<art::mirror::Class> klass)
924 REQUIRES_SHARED(art::Locks::mutator_lock_) {
925 DCHECK(klass != nullptr);
926 DCHECK_LT(count, ctc_ref.count);
927 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
928 return true;
929 }
930
931 jclass* local_class_array;
932 const ClassTableCount& ctc_ref;
933 art::ScopedObjectAccess* soa_ptr;
934 size_t count;
935 };
936 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
937 class_table->Visit(ctf);
938 DCHECK_EQ(ctc.count, ctf.count);
939
940 *class_count_ptr = ctc.count;
941 *classes_ptr = class_array;
942
943 return ERR(NONE);
944}
945
Andreas Gampe812a2442017-01-19 22:04:46 -0800946jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
947 jclass jklass,
948 jint* minor_version_ptr,
949 jint* major_version_ptr) {
950 art::ScopedObjectAccess soa(art::Thread::Current());
951 if (jklass == nullptr) {
952 return ERR(INVALID_CLASS);
953 }
954 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
955 if (!jklass_obj->IsClass()) {
956 return ERR(INVALID_CLASS);
957 }
958 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
959 if (klass->IsPrimitive() || klass->IsArrayClass()) {
960 return ERR(INVALID_CLASS);
961 }
962
963 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
964 return ERR(NULL_POINTER);
965 }
966
967 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
968 // what their dex cache copies from.
969 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
970
971 *major_version_ptr = static_cast<jint>(version);
972 *minor_version_ptr = 0;
973
974 return ERR(NONE);
975}
976
Andreas Gampee492ae32016-10-28 19:34:57 -0700977} // namespace openjdkjvmti