Search code examples
javacjava-native-interfacejvmti

Java JVMTI Agent crashes on GetEnv()


I'm at a total loss here. I'm trying to get a JVMTI agent library running but it keeps crashing for some reason.

I've narrowed it down this line:

(*jvm)->GetEnv(jvm, (void**)jvmti, JVMTI_VERSION_1_0);

this is the full code of the agent lib (in C):

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


jvmtiEnv* jvmti = NULL;


JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
{
    printf("Agent started.\n");
    _flushall();
    jint err = (*jvm)->GetEnv(jvm, (void**)jvmti, JVMTI_VERSION_1_0);
    if (err != JNI_OK)
    {
        printf("Failed to get JVMTI env!\n");
        _flushall();
        return err;
    }

    return JNI_OK;
}

JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved)
{
    return JNI_OK;
}

JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm)
{
}

As I tried to isolate what the issue was I wrote a very simple java app to test this with:

public class Test
{
    public static void main(String[] args)
    {
        System.out.println("Hello from java!");

    }
}

If I run this from netbeans with the VM arg -agentpath set to my .dllcontaining the code above, the app seems to crash when it tries to call GetEnv().

I've made sure of the following things: - The JVM and the dll are both 64bit. - The library is most definitely being found and loaded (the printf output is visible before the crash.)

I don't know what else could probably be causing this, do I have to link against some JVMTI API lib that I don't know about?

Or could this be an issue with the java installation on my PC?

Thanks


Solution

  • You should be passing address of jvmti to GetEnv() as in:

    jint err = (*jvm)->GetEnv(jvm, (void**) &jvmti, JVMTI_VERSION_1_0);