Question

How to get the name of the JVM TI _jclass? I want to display names of classes loaded in the JVMTI agent, however it is not obvious to me how to get the name of a class from a _jclass instance.

Was it helpful?

Solution

Is this what you want?

#include <stdlib.h>
#include "jvmti.h"

jvmtiEnv  *globalJVMTIInterface;

void JNICALL vmInit(jvmtiEnv *jvmti_env,JNIEnv* jni_env,jthread thread) {

    printf("VMStart\n");

    jint numberOfClasses;
    jclass *classes;

    jint returnCode =  (*globalJVMTIInterface)->GetLoadedClasses(globalJVMTIInterface, &numberOfClasses, &classes);
    if (returnCode != JVMTI_ERROR_NONE) {
        fprintf(stderr, "Unable to get a list of loaded classes (%d)\n", returnCode);
        exit(-1);
    }

    int i;

    for(i=0;i<numberOfClasses;i++) {

        char* signature = NULL;
        char* generic = NULL;

        (*globalJVMTIInterface)->GetClassSignature(globalJVMTIInterface, classes[i], &signature, &generic);

        printf("%d) %s %s\n", i+1, signature, generic);

        if(signature) {
            returnCode = (*globalJVMTIInterface)->Deallocate(globalJVMTIInterface, (unsigned char*) signature);
        }
        if(generic) {
            returnCode = (*globalJVMTIInterface)->Deallocate(globalJVMTIInterface, (unsigned char*) generic);
        }


    }


    if(classes) {
        returnCode = (*globalJVMTIInterface)->Deallocate(globalJVMTIInterface, (unsigned char*) classes);
    }

}

JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {

    jint returnCode = (*jvm)->GetEnv(jvm, (void **)&globalJVMTIInterface, JVMTI_VERSION_1_0);

    if (returnCode != JNI_OK) {
            fprintf(stderr, "The version of JVMTI requested (1.0) is not supported by this JVM.\n");
            return JVMTI_ERROR_UNSUPPORTED_VERSION;
    }


    jvmtiEventCallbacks *eventCallbacks;

    eventCallbacks = calloc(1, sizeof(jvmtiEventCallbacks));
    if (!eventCallbacks) {
            fprintf(stderr, "Unable to allocate memory\n");
            return JVMTI_ERROR_OUT_OF_MEMORY;
    }


    eventCallbacks->VMInit = &vmInit;


    returnCode = (*globalJVMTIInterface)->SetEventCallbacks(globalJVMTIInterface, eventCallbacks, (jint) sizeof(*eventCallbacks));
    if (returnCode != JNI_OK) {
        fprintf(stderr, "JVM does not have the required capabilities (%d)\n", returnCode);
        exit(-1);
    }


    returnCode = (*globalJVMTIInterface)->SetEventNotificationMode(globalJVMTIInterface, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, (jthread) NULL);
    if (returnCode != JNI_OK) {
        fprintf(stderr, "JVM does not have the required capabilities, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT (%d)\n", returnCode);
        exit(-1);
    }

    return JVMTI_ERROR_NONE;
}

OTHER TIPS

I believe you can determine it from GetClassSignature (not that I've tried it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top