xref: /aosp_15_r20/cts/hostsidetests/jvmti/base/jni/tracking.cpp (revision b7c941bb3fa97aba169d73cee0bed2de8ac964bf)
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <mutex>
18 
19 #include "jni.h"
20 #include "jvmti.h"
21 
22 #include "android-base/logging.h"
23 #include "android-base/stringprintf.h"
24 #include "jni_binder.h"
25 #include "jvmti_helper.h"
26 #include "scoped_local_ref.h"
27 #include "scoped_utf_chars.h"
28 #include "test_env.h"
29 
30 namespace art {
31 
GetClassName(JNIEnv * jni_env,jclass cls)32 static std::string GetClassName(JNIEnv* jni_env, jclass cls) {
33   ScopedLocalRef<jclass> class_class(jni_env, jni_env->GetObjectClass(cls));
34   jmethodID mid = jni_env->GetMethodID(class_class.get(), "getName", "()Ljava/lang/String;");
35   ScopedLocalRef<jstring> str(
36       jni_env, reinterpret_cast<jstring>(jni_env->CallObjectMethod(cls, mid)));
37   ScopedUtfChars utf_chars(jni_env, str.get());
38   return utf_chars.c_str();
39 }
40 
41 static std::mutex gLock;
42 static std::string gCollection;
43 static jthread gExpectedThread = nullptr;
44 
RecordAllocationEvent(JNIEnv * jni_env,jobject object,jclass object_klass,jlong size)45 static void RecordAllocationEvent(JNIEnv* jni_env, jobject object, jclass object_klass,
46                                   jlong size) {
47   std::string object_klass_descriptor = GetClassName(jni_env, object_klass);
48   ScopedLocalRef<jclass> object_klass2(jni_env, jni_env->GetObjectClass(object));
49   std::string object_klass_descriptor2 = GetClassName(jni_env, object_klass2.get());
50   std::string result = android::base::StringPrintf("ObjectAllocated type %s/%s size %zu",
51                                                    object_klass_descriptor.c_str(),
52                                                    object_klass_descriptor2.c_str(),
53                                                    static_cast<size_t>(size));
54   std::unique_lock<std::mutex> mu(gLock);
55   gCollection += result + "#";
56 }
57 
ObjectAllocatedGlobal(jvmtiEnv * ti_env ATTRIBUTE_UNUSED,JNIEnv * jni_env,jthread thread,jobject object,jclass object_klass,jlong size)58 static void JNICALL ObjectAllocatedGlobal(jvmtiEnv* ti_env ATTRIBUTE_UNUSED, JNIEnv* jni_env,
59                                           jthread thread, jobject object, jclass object_klass,
60                                           jlong size) {
61   // Ignore events from threads other than the test thread. It is not possible
62   // to make sure that we don't receive any outstanding callbacks after
63   // disabling the allocation events. So just ignore events from other threads
64   // to make the test stable.
65   if (!jni_env->IsSameObject(thread, gExpectedThread)) {
66     return;
67   }
68   RecordAllocationEvent(jni_env, object, object_klass, size);
69 }
70 
ObjectAllocatedThread(jvmtiEnv * ti_env ATTRIBUTE_UNUSED,JNIEnv * jni_env,jthread thread,jobject object,jclass object_klass,jlong size)71 static void JNICALL ObjectAllocatedThread(jvmtiEnv* ti_env ATTRIBUTE_UNUSED, JNIEnv* jni_env,
72                                           jthread thread, jobject object, jclass object_klass,
73                                           jlong size) {
74   CHECK(jni_env->IsSameObject(thread, gExpectedThread));
75   RecordAllocationEvent(jni_env, object, object_klass, size);
76 }
77 
Java_android_jvmti_cts_JvmtiTrackingTest_setupObjectAllocCallback(JNIEnv * env,jclass klass ATTRIBUTE_UNUSED,jboolean enable,jboolean global)78 extern "C" JNIEXPORT void JNICALL Java_android_jvmti_cts_JvmtiTrackingTest_setupObjectAllocCallback(
79         JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jboolean enable, jboolean global) {
80   jvmtiEventCallbacks callbacks;
81   memset(&callbacks, 0, sizeof(jvmtiEventCallbacks));
82   if (enable) {
83     callbacks.VMObjectAlloc = global ? ObjectAllocatedGlobal : ObjectAllocatedThread;
84   } else {
85     callbacks.VMObjectAlloc = nullptr;
86   }
87 
88   jvmtiError ret = jvmti_env->SetEventCallbacks(&callbacks, sizeof(callbacks));
89   JvmtiErrorToException(env, jvmti_env, ret);
90 }
91 
Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking(JNIEnv * env,jclass klass ATTRIBUTE_UNUSED,jthread thread,jboolean enable)92 extern "C" JNIEXPORT void JNICALL Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking(
93     JNIEnv* env, jclass klass ATTRIBUTE_UNUSED, jthread thread, jboolean enable) {
94   jvmtiError ret = jvmti_env->SetEventNotificationMode(
95       enable ? JVMTI_ENABLE : JVMTI_DISABLE,
96       JVMTI_EVENT_VM_OBJECT_ALLOC,
97       thread);
98   if (enable) {
99     if (thread == nullptr) {
100       // We are enabling the allocation events globally but can only deterministically check the
101       // ones on the current thread.
102       jthread curr_thread;
103       jvmti_env->GetCurrentThread(&curr_thread);
104       gExpectedThread = env->NewGlobalRef(curr_thread);
105     } else {
106       gExpectedThread = env->NewGlobalRef(thread);
107     }
108   } else if (gExpectedThread != nullptr) {
109     env->DeleteGlobalRef(gExpectedThread);
110     gExpectedThread = nullptr;
111   }
112   JvmtiErrorToException(env, jvmti_env, ret);
113 }
114 
115 extern "C" JNIEXPORT
Java_android_jvmti_cts_JvmtiTrackingTest_getAndResetAllocationTrackingString(JNIEnv * env,jclass klass ATTRIBUTE_UNUSED)116 jstring JNICALL Java_android_jvmti_cts_JvmtiTrackingTest_getAndResetAllocationTrackingString(
117     JNIEnv* env, jclass klass ATTRIBUTE_UNUSED) {
118   // We will have a string allocation. So only do the C++ string retrieval under lock.
119   std::string result;
120   {
121     std::unique_lock<std::mutex> mu(gLock);
122     result.swap(gCollection);
123   }
124   // Make sure we give any other threads that might have been waiting to get a last crack time to
125   // run. We will ignore their additions however.
126   bool is_empty = false;
127   do {
128     {
129       std::unique_lock<std::mutex> mu(gLock);
130       is_empty = gCollection.empty();
131       gCollection.clear();
132     }
133     sched_yield();
134   } while (!is_empty);
135 
136   if (result.empty()) {
137     return nullptr;
138   }
139 
140   return env->NewStringUTF(result.c_str());
141 }
142 
143 static JNINativeMethod gMethods[] = {
144   { "setupObjectAllocCallback", "(Z;Z)V",
145           (void*)Java_android_jvmti_cts_JvmtiTrackingTest_setupObjectAllocCallback},
146 
147   { "enableAllocationTracking", "(Ljava/lang/Thread;Z)V",
148           (void*)Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking },
149 
150   { "getAndResetAllocationTrackingString", "()Ljava/lang/String;",
151           (void*)Java_android_jvmti_cts_JvmtiTrackingTest_getAndResetAllocationTrackingString },
152 };
153 
register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv * jenv,JNIEnv * env)154 void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv* jenv, JNIEnv* env) {
155   ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
156           "android/jvmti/cts/JvmtiTrackingTest", nullptr));
157   if (klass.get() == nullptr) {
158     env->ExceptionClear();
159     return;
160   }
161 
162   env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
163   if (env->ExceptionCheck()) {
164     env->ExceptionClear();
165     LOG(ERROR) << "Could not register natives for JvmtiTrackingTest class";
166   }
167 }
168 
169 }  // namespace art
170