blob: cf3cfa443155f6542977ce18392c405841cc05dc [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 Gampee6377462017-01-20 17:37:50 -080044#include "events-inl.h"
Andreas Gampe691051b2017-02-09 09:15:24 -080045#include "gc/heap.h"
46#include "gc_root.h"
Andreas Gampee6377462017-01-20 17:37:50 -080047#include "handle.h"
48#include "jni_env_ext-inl.h"
Andreas Gampeac587272017-01-05 15:21:34 -080049#include "jni_internal.h"
Alex Light440b5d92017-01-24 15:32:25 -080050#include "mirror/array-inl.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_ext.h"
Andreas Gampe70f16392017-01-16 14:20:10 -080053#include "runtime.h"
Andreas Gampee6377462017-01-20 17:37:50 -080054#include "runtime_callbacks.h"
55#include "ScopedLocalRef.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070056#include "scoped_thread_state_change-inl.h"
57#include "thread-inl.h"
Andreas Gampee6377462017-01-20 17:37:50 -080058#include "thread_list.h"
Alex Lighteb98b082017-01-25 13:02:32 -080059#include "ti_class_loader.h"
Alex Light440b5d92017-01-24 15:32:25 -080060#include "ti_redefine.h"
61#include "utils.h"
Andreas Gampee492ae32016-10-28 19:34:57 -070062
63namespace openjdkjvmti {
64
Alex Light440b5d92017-01-24 15:32:25 -080065using android::base::StringPrintf;
66
67static std::unique_ptr<const art::DexFile> MakeSingleDexFile(art::Thread* self,
68 const char* descriptor,
69 const std::string& orig_location,
70 jint final_len,
71 const unsigned char* final_dex_data)
72 REQUIRES_SHARED(art::Locks::mutator_lock_) {
73 // Make the mmap
74 std::string error_msg;
75 std::unique_ptr<art::MemMap> map(Redefiner::MoveDataToMemMap(orig_location,
76 final_len,
77 final_dex_data,
78 &error_msg));
79 if (map.get() == nullptr) {
80 LOG(WARNING) << "Unable to allocate mmap for redefined dex file! Error was: " << error_msg;
81 self->ThrowOutOfMemoryError(StringPrintf(
82 "Unable to allocate dex file for transformation of %s", descriptor).c_str());
83 return nullptr;
84 }
85
86 // Make a dex-file
87 if (map->Size() < sizeof(art::DexFile::Header)) {
88 LOG(WARNING) << "Could not read dex file header because dex_data was too short";
89 art::ThrowClassFormatError(nullptr,
90 "Unable to read transformed dex file of %s",
91 descriptor);
92 return nullptr;
93 }
94 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_;
95 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(),
96 checksum,
97 std::move(map),
98 /*verify*/true,
99 /*verify_checksum*/true,
100 &error_msg));
101 if (dex_file.get() == nullptr) {
102 LOG(WARNING) << "Unable to load modified dex file for " << descriptor << ": " << error_msg;
103 art::ThrowClassFormatError(nullptr,
104 "Unable to read transformed dex file of %s because %s",
105 descriptor,
106 error_msg.c_str());
107 return nullptr;
108 }
109 if (dex_file->NumClassDefs() != 1) {
110 LOG(WARNING) << "Dex file contains more than 1 class_def. Ignoring.";
111 // TODO Throw some other sort of error here maybe?
112 art::ThrowClassFormatError(
113 nullptr,
114 "Unable to use transformed dex file of %s because it contained too many classes",
115 descriptor);
116 return nullptr;
117 }
118 return dex_file;
119}
120
Andreas Gampee6377462017-01-20 17:37:50 -0800121struct ClassCallback : public art::ClassLoadCallback {
Alex Light440b5d92017-01-24 15:32:25 -0800122 void ClassPreDefine(const char* descriptor,
123 art::Handle<art::mirror::Class> klass,
124 art::Handle<art::mirror::ClassLoader> class_loader,
125 const art::DexFile& initial_dex_file,
126 const art::DexFile::ClassDef& initial_class_def ATTRIBUTE_UNUSED,
127 /*out*/art::DexFile const** final_dex_file,
128 /*out*/art::DexFile::ClassDef const** final_class_def)
129 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
130 bool is_enabled =
131 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookRetransformable) ||
132 event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassFileLoadHookNonRetransformable);
133 if (!is_enabled) {
134 return;
135 }
136 if (descriptor[0] != 'L') {
137 // It is a primitive or array. Just return
138 return;
139 }
Alex Light28027122017-01-26 17:21:51 -0800140 std::string name(std::string(descriptor).substr(1, strlen(descriptor) - 2));
Alex Light440b5d92017-01-24 15:32:25 -0800141
142 art::Thread* self = art::Thread::Current();
143 art::JNIEnvExt* env = self->GetJniEnv();
144 ScopedLocalRef<jobject> loader(
145 env, class_loader.IsNull() ? nullptr : env->AddLocalReference<jobject>(class_loader.Get()));
146 // Go back to native.
147 art::ScopedThreadSuspension sts(self, art::ThreadState::kNative);
148 // Call all Non-retransformable agents.
149 jint post_no_redefine_len = 0;
150 unsigned char* post_no_redefine_dex_data = nullptr;
151 std::unique_ptr<const unsigned char> post_no_redefine_unique_ptr(nullptr);
152 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookNonRetransformable>(
153 self,
154 static_cast<JNIEnv*>(env),
155 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
156 loader.get(),
157 name.c_str(),
158 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
159 static_cast<jint>(initial_dex_file.Size()),
160 static_cast<const unsigned char*>(initial_dex_file.Begin()),
161 static_cast<jint*>(&post_no_redefine_len),
162 static_cast<unsigned char**>(&post_no_redefine_dex_data));
163 if (post_no_redefine_dex_data == nullptr) {
164 DCHECK_EQ(post_no_redefine_len, 0);
165 post_no_redefine_dex_data = const_cast<unsigned char*>(initial_dex_file.Begin());
166 post_no_redefine_len = initial_dex_file.Size();
167 } else {
168 post_no_redefine_unique_ptr = std::unique_ptr<const unsigned char>(post_no_redefine_dex_data);
169 DCHECK_GT(post_no_redefine_len, 0);
170 }
171 // Call all retransformable agents.
172 jint final_len = 0;
173 unsigned char* final_dex_data = nullptr;
174 std::unique_ptr<const unsigned char> final_dex_unique_ptr(nullptr);
175 event_handler->DispatchEvent<ArtJvmtiEvent::kClassFileLoadHookRetransformable>(
176 self,
177 static_cast<JNIEnv*>(env),
178 static_cast<jclass>(nullptr), // The class doesn't really exist yet so send null.
179 loader.get(),
180 name.c_str(),
181 static_cast<jobject>(nullptr), // Android doesn't seem to have protection domains
182 static_cast<jint>(post_no_redefine_len),
183 static_cast<const unsigned char*>(post_no_redefine_dex_data),
184 static_cast<jint*>(&final_len),
185 static_cast<unsigned char**>(&final_dex_data));
186 if (final_dex_data == nullptr) {
187 DCHECK_EQ(final_len, 0);
188 final_dex_data = post_no_redefine_dex_data;
189 final_len = post_no_redefine_len;
190 } else {
191 final_dex_unique_ptr = std::unique_ptr<const unsigned char>(final_dex_data);
192 DCHECK_GT(final_len, 0);
193 }
194
195 if (final_dex_data != initial_dex_file.Begin()) {
196 LOG(WARNING) << "Changing class " << descriptor;
197 art::ScopedObjectAccess soa(self);
198 art::StackHandleScope<2> hs(self);
199 // Save the results of all the non-retransformable agents.
200 // First allocate the ClassExt
201 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(self)));
202 // Make sure we have a ClassExt. This is fine even though we are a temporary since it will
203 // get copied.
204 if (ext.IsNull()) {
205 // We will just return failure if we fail to allocate
206 LOG(WARNING) << "Could not allocate ext-data for class '" << descriptor << "'. "
207 << "Aborting transformation since we will be unable to store it.";
208 self->AssertPendingOOMException();
209 return;
210 }
211
212 // Allocate the byte array to store the dex file bytes in.
213 art::Handle<art::mirror::ByteArray> arr(hs.NewHandle(
214 art::mirror::ByteArray::AllocateAndFill(
215 self,
216 reinterpret_cast<const signed char*>(post_no_redefine_dex_data),
217 post_no_redefine_len)));
218 if (arr.IsNull()) {
219 LOG(WARNING) << "Unable to allocate byte array for initial dex-file bytes. Aborting "
220 << "transformation";
221 self->AssertPendingOOMException();
222 return;
223 }
224
225 std::unique_ptr<const art::DexFile> dex_file(MakeSingleDexFile(self,
226 descriptor,
227 initial_dex_file.GetLocation(),
228 final_len,
229 final_dex_data));
230 if (dex_file.get() == nullptr) {
231 return;
232 }
233
Alex Lighteb98b082017-01-25 13:02:32 -0800234 // TODO Check Redefined dex file for all invariants.
Alex Light440b5d92017-01-24 15:32:25 -0800235 LOG(WARNING) << "Dex file created by class-definition time transformation of "
236 << descriptor << " is not checked for all retransformation invariants.";
Alex Lighteb98b082017-01-25 13:02:32 -0800237
238 if (!ClassLoaderHelper::AddToClassLoader(self, class_loader, dex_file.get())) {
239 LOG(ERROR) << "Unable to add " << descriptor << " to class loader!";
240 return;
241 }
242
Alex Light440b5d92017-01-24 15:32:25 -0800243 // Actually set the ClassExt's original bytes once we have actually succeeded.
244 ext->SetOriginalDexFileBytes(arr.Get());
245 // Set the return values
246 *final_class_def = &dex_file->GetClassDef(0);
247 *final_dex_file = dex_file.release();
248 }
249 }
250
Andreas Gampee6377462017-01-20 17:37:50 -0800251 void ClassLoad(art::Handle<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
252 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassLoad)) {
253 art::Thread* thread = art::Thread::Current();
254 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
255 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Andreas Gampe983c1752017-01-23 19:46:56 -0800256 ScopedLocalRef<jthread> thread_jni(
257 thread->GetJniEnv(), thread->GetJniEnv()->AddLocalReference<jthread>(thread->GetPeer()));
Andreas Gampee6377462017-01-20 17:37:50 -0800258 {
259 art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800260 event_handler->DispatchEvent<ArtJvmtiEvent::kClassLoad>(
261 thread,
262 static_cast<JNIEnv*>(thread->GetJniEnv()),
263 thread_jni.get(),
264 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800265 }
Andreas Gampe691051b2017-02-09 09:15:24 -0800266 if (klass->IsTemp()) {
267 AddTempClass(thread, jklass.get());
268 }
Andreas Gampee6377462017-01-20 17:37:50 -0800269 }
270 }
271
Andreas Gampe691051b2017-02-09 09:15:24 -0800272 void ClassPrepare(art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800273 art::Handle<art::mirror::Class> klass)
274 REQUIRES_SHARED(art::Locks::mutator_lock_) {
275 if (event_handler->IsEventEnabledAnywhere(ArtJvmtiEvent::kClassPrepare)) {
276 art::Thread* thread = art::Thread::Current();
Andreas Gampe691051b2017-02-09 09:15:24 -0800277 if (temp_klass.Get() != klass.Get()) {
278 DCHECK(temp_klass->IsTemp());
279 DCHECK(temp_klass->IsRetired());
280 HandleTempClass(thread, temp_klass, klass);
281 }
Andreas Gampee6377462017-01-20 17:37:50 -0800282 ScopedLocalRef<jclass> jklass(thread->GetJniEnv(),
283 thread->GetJniEnv()->AddLocalReference<jclass>(klass.Get()));
Andreas Gampe983c1752017-01-23 19:46:56 -0800284 ScopedLocalRef<jthread> thread_jni(
285 thread->GetJniEnv(), thread->GetJniEnv()->AddLocalReference<jthread>(thread->GetPeer()));
Andreas Gampee6377462017-01-20 17:37:50 -0800286 art::ScopedThreadSuspension sts(thread, art::ThreadState::kNative);
Andreas Gampe983c1752017-01-23 19:46:56 -0800287 event_handler->DispatchEvent<ArtJvmtiEvent::kClassPrepare>(
288 thread,
289 static_cast<JNIEnv*>(thread->GetJniEnv()),
290 thread_jni.get(),
291 jklass.get());
Andreas Gampee6377462017-01-20 17:37:50 -0800292 }
293 }
294
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800295 // To support parallel class-loading, we need to perform some locking dances here. Namely,
296 // the fixup stage must not be holding the temp_classes lock when it fixes up the system
297 // (as that requires suspending all mutators).
298
Andreas Gampee6377462017-01-20 17:37:50 -0800299 void AddTempClass(art::Thread* self, jclass klass) {
300 std::unique_lock<std::mutex> mu(temp_classes_lock);
Andreas Gampe691051b2017-02-09 09:15:24 -0800301 jclass global_klass = reinterpret_cast<jclass>(self->GetJniEnv()->NewGlobalRef(klass));
302 temp_classes.push_back(global_klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800303 }
304
Andreas Gampe691051b2017-02-09 09:15:24 -0800305 void HandleTempClass(art::Thread* self,
306 art::Handle<art::mirror::Class> temp_klass,
Andreas Gampee6377462017-01-20 17:37:50 -0800307 art::Handle<art::mirror::Class> klass)
308 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800309 bool requires_fixup = false;
310 {
311 std::unique_lock<std::mutex> mu(temp_classes_lock);
312 if (temp_classes.empty()) {
313 return;
Andreas Gampee6377462017-01-20 17:37:50 -0800314 }
Andreas Gampe7619b5b2017-02-10 11:49:12 -0800315
316 for (auto it = temp_classes.begin(); it != temp_classes.end(); ++it) {
317 if (temp_klass.Get() == art::ObjPtr<art::mirror::Class>::DownCast(self->DecodeJObject(*it))) {
318 self->GetJniEnv()->DeleteGlobalRef(*it);
319 temp_classes.erase(it);
320 requires_fixup = true;
321 break;
322 }
323 }
324 }
325 if (requires_fixup) {
326 FixupTempClass(self, temp_klass, klass);
Andreas Gampee6377462017-01-20 17:37:50 -0800327 }
328 }
329
Andreas Gampe691051b2017-02-09 09:15:24 -0800330 void FixupTempClass(art::Thread* self,
331 art::Handle<art::mirror::Class> temp_klass,
332 art::Handle<art::mirror::Class> klass)
Andreas Gampee6377462017-01-20 17:37:50 -0800333 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Andreas Gampe691051b2017-02-09 09:15:24 -0800334 // Suspend everything.
335 art::gc::Heap* heap = art::Runtime::Current()->GetHeap();
336 if (heap->IsGcConcurrentAndMoving()) {
337 // Need to take a heap dump while GC isn't running. See the
338 // comment in Heap::VisitObjects().
339 heap->IncrementDisableMovingGC(self);
340 }
341 {
342 art::ScopedThreadSuspension sts(self, art::kWaitingForVisitObjects);
343 art::ScopedSuspendAll ssa("FixupTempClass");
344
345 art::mirror::Class* input = temp_klass.Get();
346 art::mirror::Class* output = klass.Get();
347
348 FixupGlobalReferenceTables(input, output);
Andreas Gampe94dda932017-02-09 18:19:21 -0800349 FixupLocalReferenceTables(self, input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800350 }
351 if (heap->IsGcConcurrentAndMoving()) {
352 heap->DecrementDisableMovingGC(self);
353 }
354 }
355
Andreas Gampe94dda932017-02-09 18:19:21 -0800356 class RootUpdater : public art::RootVisitor {
357 public:
358 RootUpdater(const art::mirror::Class* input, art::mirror::Class* output)
359 : input_(input), output_(output) {}
360
361 void VisitRoots(art::mirror::Object*** roots,
362 size_t count,
363 const art::RootInfo& info ATTRIBUTE_UNUSED)
364 OVERRIDE {
365 for (size_t i = 0; i != count; ++i) {
366 if (*roots[i] == input_) {
367 *roots[i] = output_;
368 }
369 }
370 }
371
372 void VisitRoots(art::mirror::CompressedReference<art::mirror::Object>** roots,
373 size_t count,
374 const art::RootInfo& info ATTRIBUTE_UNUSED)
375 OVERRIDE REQUIRES_SHARED(art::Locks::mutator_lock_) {
376 for (size_t i = 0; i != count; ++i) {
377 if (roots[i]->AsMirrorPtr() == input_) {
378 roots[i]->Assign(output_);
379 }
380 }
381 }
382
383 private:
384 const art::mirror::Class* input_;
385 art::mirror::Class* output_;
386 };
387
Andreas Gampe691051b2017-02-09 09:15:24 -0800388 void FixupGlobalReferenceTables(art::mirror::Class* input,
389 art::mirror::Class* output)
390 REQUIRES(art::Locks::mutator_lock_) {
391 art::JavaVMExt* java_vm = art::Runtime::Current()->GetJavaVM();
392
393 // Fix up the global table with a root visitor.
Andreas Gampe94dda932017-02-09 18:19:21 -0800394 RootUpdater global_update(input, output);
Andreas Gampe691051b2017-02-09 09:15:24 -0800395 java_vm->VisitRoots(&global_update);
396
397 class WeakGlobalUpdate : public art::IsMarkedVisitor {
398 public:
399 WeakGlobalUpdate(art::mirror::Class* root_input, art::mirror::Class* root_output)
400 : input_(root_input), output_(root_output) {}
401
402 art::mirror::Object* IsMarked(art::mirror::Object* obj) OVERRIDE {
403 if (obj == input_) {
404 return output_;
405 }
406 return obj;
407 }
408
409 private:
410 const art::mirror::Class* input_;
411 art::mirror::Class* output_;
412 };
413 WeakGlobalUpdate weak_global_update(input, output);
414 java_vm->SweepJniWeakGlobals(&weak_global_update);
Andreas Gampee6377462017-01-20 17:37:50 -0800415 }
416
Andreas Gampe94dda932017-02-09 18:19:21 -0800417 void FixupLocalReferenceTables(art::Thread* self,
418 art::mirror::Class* input,
419 art::mirror::Class* output)
420 REQUIRES(art::Locks::mutator_lock_) {
421 class LocalUpdate {
422 public:
423 LocalUpdate(const art::mirror::Class* root_input, art::mirror::Class* root_output)
424 : input_(root_input), output_(root_output) {}
425
426 static void Callback(art::Thread* t, void* arg) REQUIRES(art::Locks::mutator_lock_) {
427 LocalUpdate* local = reinterpret_cast<LocalUpdate*>(arg);
428
429 // Fix up the local table with a root visitor.
430 RootUpdater local_update(local->input_, local->output_);
431 t->GetJniEnv()->locals.VisitRoots(
432 &local_update, art::RootInfo(art::kRootJNILocal, t->GetThreadId()));
433 }
434
435 private:
436 const art::mirror::Class* input_;
437 art::mirror::Class* output_;
438 };
439 LocalUpdate local_upd(input, output);
440 art::MutexLock mu(self, *art::Locks::thread_list_lock_);
441 art::Runtime::Current()->GetThreadList()->ForEach(LocalUpdate::Callback, &local_upd);
442 }
443
Andreas Gampee6377462017-01-20 17:37:50 -0800444 // A set of all the temp classes we have handed out. We have to fix up references to these.
445 // For simplicity, we store the temp classes as JNI global references in a vector. Normally a
446 // Prepare event will closely follow, so the vector should be small.
447 std::mutex temp_classes_lock;
448 std::vector<jclass> temp_classes;
449
450 EventHandler* event_handler = nullptr;
451};
452
453ClassCallback gClassCallback;
454
455void ClassUtil::Register(EventHandler* handler) {
456 gClassCallback.event_handler = handler;
457 art::ScopedThreadStateChange stsc(art::Thread::Current(),
458 art::ThreadState::kWaitingForDebuggerToAttach);
459 art::ScopedSuspendAll ssa("Add load callback");
460 art::Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&gClassCallback);
461}
462
463void ClassUtil::Unregister() {
464 art::ScopedThreadStateChange stsc(art::Thread::Current(),
465 art::ThreadState::kWaitingForDebuggerToAttach);
466 art::ScopedSuspendAll ssa("Remove thread callback");
467 art::Runtime* runtime = art::Runtime::Current();
468 runtime->GetRuntimeCallbacks()->RemoveClassLoadCallback(&gClassCallback);
469}
470
Andreas Gampeac587272017-01-05 15:21:34 -0800471jvmtiError ClassUtil::GetClassFields(jvmtiEnv* env,
472 jclass jklass,
473 jint* field_count_ptr,
474 jfieldID** fields_ptr) {
475 art::ScopedObjectAccess soa(art::Thread::Current());
476 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
477 if (klass == nullptr) {
478 return ERR(INVALID_CLASS);
479 }
480
481 if (field_count_ptr == nullptr || fields_ptr == nullptr) {
482 return ERR(NULL_POINTER);
483 }
484
Andreas Gampeac587272017-01-05 15:21:34 -0800485 art::IterationRange<art::StrideIterator<art::ArtField>> ifields = klass->GetIFields();
486 art::IterationRange<art::StrideIterator<art::ArtField>> sfields = klass->GetSFields();
487 size_t array_size = klass->NumInstanceFields() + klass->NumStaticFields();
488
489 unsigned char* out_ptr;
490 jvmtiError allocError = env->Allocate(array_size * sizeof(jfieldID), &out_ptr);
491 if (allocError != ERR(NONE)) {
492 return allocError;
493 }
494 jfieldID* field_array = reinterpret_cast<jfieldID*>(out_ptr);
495
496 size_t array_idx = 0;
497 for (art::ArtField& field : sfields) {
498 field_array[array_idx] = art::jni::EncodeArtField(&field);
499 ++array_idx;
500 }
501 for (art::ArtField& field : ifields) {
502 field_array[array_idx] = art::jni::EncodeArtField(&field);
503 ++array_idx;
504 }
505
506 *field_count_ptr = static_cast<jint>(array_size);
507 *fields_ptr = field_array;
508
509 return ERR(NONE);
510}
511
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800512jvmtiError ClassUtil::GetClassMethods(jvmtiEnv* env,
513 jclass jklass,
514 jint* method_count_ptr,
515 jmethodID** methods_ptr) {
516 art::ScopedObjectAccess soa(art::Thread::Current());
517 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
518 if (klass == nullptr) {
519 return ERR(INVALID_CLASS);
520 }
521
522 if (method_count_ptr == nullptr || methods_ptr == nullptr) {
523 return ERR(NULL_POINTER);
524 }
525
526 size_t array_size = klass->NumDeclaredVirtualMethods() + klass->NumDirectMethods();
527 unsigned char* out_ptr;
528 jvmtiError allocError = env->Allocate(array_size * sizeof(jmethodID), &out_ptr);
529 if (allocError != ERR(NONE)) {
530 return allocError;
531 }
532 jmethodID* method_array = reinterpret_cast<jmethodID*>(out_ptr);
533
534 if (art::kIsDebugBuild) {
535 size_t count = 0;
536 for (auto& m ATTRIBUTE_UNUSED : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
537 count++;
538 }
539 CHECK_EQ(count, klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods());
540 }
541
542 size_t array_idx = 0;
543 for (auto& m : klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
544 method_array[array_idx] = art::jni::EncodeArtMethod(&m);
545 ++array_idx;
546 }
547
548 *method_count_ptr = static_cast<jint>(array_size);
549 *methods_ptr = method_array;
550
551 return ERR(NONE);
552}
553
Andreas Gampe8b07e472017-01-06 14:20:39 -0800554jvmtiError ClassUtil::GetImplementedInterfaces(jvmtiEnv* env,
555 jclass jklass,
556 jint* interface_count_ptr,
557 jclass** interfaces_ptr) {
558 art::ScopedObjectAccess soa(art::Thread::Current());
559 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
560 if (klass == nullptr) {
561 return ERR(INVALID_CLASS);
562 }
563
564 if (interface_count_ptr == nullptr || interfaces_ptr == nullptr) {
565 return ERR(NULL_POINTER);
566 }
567
568 // Need to handle array specifically. Arrays implement Serializable and Cloneable, but the
569 // spec says these should not be reported.
570 if (klass->IsArrayClass()) {
571 *interface_count_ptr = 0;
572 *interfaces_ptr = nullptr; // TODO: Should we allocate a dummy here?
573 return ERR(NONE);
574 }
575
576 size_t array_size = klass->NumDirectInterfaces();
577 unsigned char* out_ptr;
578 jvmtiError allocError = env->Allocate(array_size * sizeof(jclass), &out_ptr);
579 if (allocError != ERR(NONE)) {
580 return allocError;
581 }
582 jclass* interface_array = reinterpret_cast<jclass*>(out_ptr);
583
584 art::StackHandleScope<1> hs(soa.Self());
585 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
586
587 for (uint32_t idx = 0; idx != array_size; ++idx) {
588 art::ObjPtr<art::mirror::Class> inf_klass =
589 art::mirror::Class::ResolveDirectInterface(soa.Self(), h_klass, idx);
590 if (inf_klass == nullptr) {
591 soa.Self()->ClearException();
592 env->Deallocate(out_ptr);
593 // TODO: What is the right error code here?
594 return ERR(INTERNAL);
595 }
596 interface_array[idx] = soa.AddLocalReference<jclass>(inf_klass);
597 }
598
599 *interface_count_ptr = static_cast<jint>(array_size);
600 *interfaces_ptr = interface_array;
601
602 return ERR(NONE);
603}
Andreas Gampe18fee4d2017-01-06 11:36:35 -0800604
Andreas Gampee492ae32016-10-28 19:34:57 -0700605jvmtiError ClassUtil::GetClassSignature(jvmtiEnv* env,
606 jclass jklass,
607 char** signature_ptr,
608 char** generic_ptr) {
609 art::ScopedObjectAccess soa(art::Thread::Current());
610 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
611 if (klass == nullptr) {
612 return ERR(INVALID_CLASS);
613 }
614
615 JvmtiUniquePtr sig_copy;
616 if (signature_ptr != nullptr) {
617 std::string storage;
618 const char* descriptor = klass->GetDescriptor(&storage);
619
620 unsigned char* tmp;
621 jvmtiError ret = CopyString(env, descriptor, &tmp);
622 if (ret != ERR(NONE)) {
623 return ret;
624 }
625 sig_copy = MakeJvmtiUniquePtr(env, tmp);
626 *signature_ptr = reinterpret_cast<char*>(tmp);
627 }
628
629 // TODO: Support generic signature.
Andreas Gampee6377462017-01-20 17:37:50 -0800630 if (generic_ptr != nullptr) {
631 *generic_ptr = nullptr;
632 }
Andreas Gampee492ae32016-10-28 19:34:57 -0700633
634 // Everything is fine, release the buffers.
635 sig_copy.release();
636
637 return ERR(NONE);
638}
639
Andreas Gampeff9d2092017-01-06 09:12:49 -0800640jvmtiError ClassUtil::GetClassStatus(jvmtiEnv* env ATTRIBUTE_UNUSED,
641 jclass jklass,
642 jint* status_ptr) {
643 art::ScopedObjectAccess soa(art::Thread::Current());
644 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
645 if (klass == nullptr) {
646 return ERR(INVALID_CLASS);
647 }
648
649 if (status_ptr == nullptr) {
650 return ERR(NULL_POINTER);
651 }
652
653 if (klass->IsArrayClass()) {
654 *status_ptr = JVMTI_CLASS_STATUS_ARRAY;
655 } else if (klass->IsPrimitive()) {
656 *status_ptr = JVMTI_CLASS_STATUS_PRIMITIVE;
657 } else {
658 *status_ptr = JVMTI_CLASS_STATUS_VERIFIED; // All loaded classes are structurally verified.
659 // This is finicky. If there's an error, we'll say it wasn't prepared.
660 if (klass->IsResolved()) {
661 *status_ptr |= JVMTI_CLASS_STATUS_PREPARED;
662 }
663 if (klass->IsInitialized()) {
664 *status_ptr |= JVMTI_CLASS_STATUS_INITIALIZED;
665 }
666 // Technically the class may be erroneous for other reasons, but we do not have enough info.
667 if (klass->IsErroneous()) {
668 *status_ptr |= JVMTI_CLASS_STATUS_ERROR;
669 }
670 }
671
672 return ERR(NONE);
673}
674
Andreas Gampe4fd66ec2017-01-05 14:42:13 -0800675template <typename T>
676static jvmtiError ClassIsT(jclass jklass, T test, jboolean* is_t_ptr) {
677 art::ScopedObjectAccess soa(art::Thread::Current());
678 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
679 if (klass == nullptr) {
680 return ERR(INVALID_CLASS);
681 }
682
683 if (is_t_ptr == nullptr) {
684 return ERR(NULL_POINTER);
685 }
686
687 *is_t_ptr = test(klass) ? JNI_TRUE : JNI_FALSE;
688 return ERR(NONE);
689}
690
691jvmtiError ClassUtil::IsInterface(jvmtiEnv* env ATTRIBUTE_UNUSED,
692 jclass jklass,
693 jboolean* is_interface_ptr) {
694 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
695 return klass->IsInterface();
696 };
697 return ClassIsT(jklass, test, is_interface_ptr);
698}
699
700jvmtiError ClassUtil::IsArrayClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
701 jclass jklass,
702 jboolean* is_array_class_ptr) {
703 auto test = [](art::ObjPtr<art::mirror::Class> klass) REQUIRES_SHARED(art::Locks::mutator_lock_) {
704 return klass->IsArrayClass();
705 };
706 return ClassIsT(jklass, test, is_array_class_ptr);
707}
708
Andreas Gampe64013e52017-01-06 13:07:19 -0800709// Keep this in sync with Class.getModifiers().
710static uint32_t ClassGetModifiers(art::Thread* self, art::ObjPtr<art::mirror::Class> klass)
711 REQUIRES_SHARED(art::Locks::mutator_lock_) {
712 if (klass->IsArrayClass()) {
713 uint32_t component_modifiers = ClassGetModifiers(self, klass->GetComponentType());
714 if ((component_modifiers & art::kAccInterface) != 0) {
715 component_modifiers &= ~(art::kAccInterface | art::kAccStatic);
716 }
717 return art::kAccAbstract | art::kAccFinal | component_modifiers;
718 }
719
720 uint32_t modifiers = klass->GetAccessFlags() & art::kAccJavaFlagsMask;
721
722 art::StackHandleScope<1> hs(self);
723 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(klass));
724 return art::mirror::Class::GetInnerClassFlags(h_klass, modifiers);
725}
726
727jvmtiError ClassUtil::GetClassModifiers(jvmtiEnv* env ATTRIBUTE_UNUSED,
728 jclass jklass,
729 jint* modifiers_ptr) {
730 art::ScopedObjectAccess soa(art::Thread::Current());
731 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
732 if (klass == nullptr) {
733 return ERR(INVALID_CLASS);
734 }
735
736 if (modifiers_ptr == nullptr) {
737 return ERR(NULL_POINTER);
738 }
739
740 *modifiers_ptr = ClassGetModifiers(soa.Self(), klass);
741
742 return ERR(NONE);
743}
744
Andreas Gampe8f5b6032017-01-06 15:50:55 -0800745jvmtiError ClassUtil::GetClassLoader(jvmtiEnv* env ATTRIBUTE_UNUSED,
746 jclass jklass,
747 jobject* classloader_ptr) {
748 art::ScopedObjectAccess soa(art::Thread::Current());
749 art::ObjPtr<art::mirror::Class> klass = soa.Decode<art::mirror::Class>(jklass);
750 if (klass == nullptr) {
751 return ERR(INVALID_CLASS);
752 }
753
754 if (classloader_ptr == nullptr) {
755 return ERR(NULL_POINTER);
756 }
757
758 *classloader_ptr = soa.AddLocalReference<jobject>(klass->GetClassLoader());
759
760 return ERR(NONE);
761}
762
Andreas Gampe70f16392017-01-16 14:20:10 -0800763jvmtiError ClassUtil::GetClassLoaderClasses(jvmtiEnv* env,
764 jobject initiating_loader,
765 jint* class_count_ptr,
766 jclass** classes_ptr) {
767 UNUSED(env, initiating_loader, class_count_ptr, classes_ptr);
768
769 if (class_count_ptr == nullptr || classes_ptr == nullptr) {
770 return ERR(NULL_POINTER);
771 }
772 art::Thread* self = art::Thread::Current();
773 if (!self->GetJniEnv()->IsInstanceOf(initiating_loader,
774 art::WellKnownClasses::java_lang_ClassLoader)) {
775 return ERR(ILLEGAL_ARGUMENT);
776 }
777 if (self->GetJniEnv()->IsInstanceOf(initiating_loader,
778 art::WellKnownClasses::java_lang_BootClassLoader)) {
779 // Need to use null for the BootClassLoader.
780 initiating_loader = nullptr;
781 }
782
783 art::ScopedObjectAccess soa(self);
784 art::ObjPtr<art::mirror::ClassLoader> class_loader =
785 soa.Decode<art::mirror::ClassLoader>(initiating_loader);
786
787 art::ClassLinker* class_linker = art::Runtime::Current()->GetClassLinker();
788
789 art::ReaderMutexLock mu(self, *art::Locks::classlinker_classes_lock_);
790
791 art::ClassTable* class_table = class_linker->ClassTableForClassLoader(class_loader);
792 if (class_table == nullptr) {
793 // Nothing loaded.
794 *class_count_ptr = 0;
795 *classes_ptr = nullptr;
796 return ERR(NONE);
797 }
798
799 struct ClassTableCount {
800 bool operator()(art::ObjPtr<art::mirror::Class> klass) {
801 DCHECK(klass != nullptr);
802 ++count;
803 return true;
804 }
805
806 size_t count = 0;
807 };
808 ClassTableCount ctc;
809 class_table->Visit(ctc);
810
811 if (ctc.count == 0) {
812 // Nothing loaded.
813 *class_count_ptr = 0;
814 *classes_ptr = nullptr;
815 return ERR(NONE);
816 }
817
818 unsigned char* data;
819 jvmtiError data_result = env->Allocate(ctc.count * sizeof(jclass), &data);
820 if (data_result != ERR(NONE)) {
821 return data_result;
822 }
823 jclass* class_array = reinterpret_cast<jclass*>(data);
824
825 struct ClassTableFill {
826 bool operator()(art::ObjPtr<art::mirror::Class> klass)
827 REQUIRES_SHARED(art::Locks::mutator_lock_) {
828 DCHECK(klass != nullptr);
829 DCHECK_LT(count, ctc_ref.count);
830 local_class_array[count++] = soa_ptr->AddLocalReference<jclass>(klass);
831 return true;
832 }
833
834 jclass* local_class_array;
835 const ClassTableCount& ctc_ref;
836 art::ScopedObjectAccess* soa_ptr;
837 size_t count;
838 };
839 ClassTableFill ctf = { class_array, ctc, &soa, 0 };
840 class_table->Visit(ctf);
841 DCHECK_EQ(ctc.count, ctf.count);
842
843 *class_count_ptr = ctc.count;
844 *classes_ptr = class_array;
845
846 return ERR(NONE);
847}
848
Andreas Gampe812a2442017-01-19 22:04:46 -0800849jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
850 jclass jklass,
851 jint* minor_version_ptr,
852 jint* major_version_ptr) {
853 art::ScopedObjectAccess soa(art::Thread::Current());
854 if (jklass == nullptr) {
855 return ERR(INVALID_CLASS);
856 }
857 art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
858 if (!jklass_obj->IsClass()) {
859 return ERR(INVALID_CLASS);
860 }
861 art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
862 if (klass->IsPrimitive() || klass->IsArrayClass()) {
863 return ERR(INVALID_CLASS);
864 }
865
866 if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
867 return ERR(NULL_POINTER);
868 }
869
870 // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
871 // what their dex cache copies from.
872 uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
873
874 *major_version_ptr = static_cast<jint>(version);
875 *minor_version_ptr = 0;
876
877 return ERR(NONE);
878}
879
Andreas Gampee492ae32016-10-28 19:34:57 -0700880} // namespace openjdkjvmti