determine Java class size from JNI jclass

1.2k views Asked by At

I'm using JNI to analyze some program. I just wonder, after get jclass reference, how it is possible to find the size of the underlying class ?

for example: class cls = env->FindClass("Lee/Boehm/Test");

from here how can i evaluate the size of the class Lee.Boehm.Test inside hotspot's heap ?

Thank you Boehm

2

There are 2 answers

0
Paul Anderson On BEST ANSWER

Here you go

agent.c

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

jvmtiEnv *globalJVMTIInterface;

JNIEXPORT jlong JNICALL Java_util_Util_getObjectSize
  (JNIEnv *jni_env , jclass class , jobject object) {

    jlong objectSize;

     (*globalJVMTIInterface)->GetObjectSize(globalJVMTIInterface, object, &objectSize);

     return objectSize;
}

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;
    }

  return JVMTI_ERROR_NONE;
}

and ./util/Util.java

package util;

public class Util {
    public static final native long getObjectSize(Object obj);
}

and Test.java

public class Test {

   public static void main(String[] args) {

      System.out.println(util.Util.getObjectSize(new String()));

   }

}

gcc -I/opt/ibm-jdk-bin-1.6.0.9/include -shared -fPIC -o libagent.so agent.c

java -agentpath:./libagent.so Test

1
Paul Anderson On

hmmm.... if you mean the size of the class bytes then yes..... you would use jvmti to retransform the class in question which would generate a classloadhook event that you listen for and this could give you the class bytes and the size.... but they would be identical to the .class file on disk.... but if the class is dynamically generated and thats why you can't just look at the size of the .class file then this technique would work..... I can write the code for you if you want.