Skip to content

Instantly share code, notes, and snippets.

@apangin
Created July 2, 2019 16:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apangin/a1ffa97c8b5d448dc84a3bdd7eebb24e to your computer and use it in GitHub Desktop.
Save apangin/a1ffa97c8b5d448dc84a3bdd7eebb24e to your computer and use it in GitHub Desktop.
Example for the presentation about JVM TI
#include <jvmti.h>
#include <stdio.h>
static jvmtiIterationControl JNICALL
heap_callback(jlong class_tag, jlong size, jlong* tag_ptr, void* user_data) {
*tag_ptr = 1;
return JVMTI_ITERATION_CONTINUE;
}
JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
jvmtiEnv* jvmti;
vm->GetEnv((void**) &jvmti, JVMTI_VERSION_1_0);
jvmtiCapabilities capabilities = {0};
capabilities.can_tag_objects = 1;
jvmti->AddCapabilities(&capabilities);
JNIEnv* env;
vm->GetEnv((void**) &env, JNI_VERSION_1_6);
jclass AbstractButton = env->FindClass("javax/swing/AbstractButton");
if (AbstractButton != NULL) {
jclass Color = env->FindClass("java/awt/Color");
jmethodID Color_init = env->GetMethodID(Color, "<init>", "(III)V");
jobject red = options != NULL && options[0] == 'r'
? env->NewObject(Color, Color_init, 242, 242, 242)
: env->NewObject(Color, Color_init, 255, 0, 0);
jclass JComponent = env->FindClass("javax/swing/JComponent");
jmethodID setBackground = env->GetMethodID(JComponent, "setBackground", "(Ljava/awt/Color;)V");
jvmti->IterateOverInstancesOfClass(AbstractButton, JVMTI_HEAP_OBJECT_EITHER, heap_callback, NULL);
jlong tag = 1;
jint count = 0;
jobject* objects = NULL;
jvmti->GetObjectsWithTags(1, &tag, &count, &objects, NULL);
for (int i = 0; i < count; i++) {
env->CallVoidMethod(objects[i], setBackground, red);
}
jvmti->Deallocate((unsigned char*) objects);
}
jvmti->DisposeEnvironment();
return 0;
}
@tubaplayerdis
Copy link

This helped a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment