Skip to content

Instantly share code, notes, and snippets.

@MattAlp
Forked from apangin/Bytecodes.java
Created October 27, 2018 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattAlp/84414ec428dd0827a95f97e0fcf3512a to your computer and use it in GitHub Desktop.
Save MattAlp/84414ec428dd0827a95f97e0fcf3512a to your computer and use it in GitHub Desktop.
Using JVMTI to obtain bytecodes of a Java method
#include <jvmti.h>
static jvmtiEnv* jvmti;
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM* vm, void* reserved) {
(*vm)->GetEnv(vm, (void**)&jvmti, JVMTI_VERSION_1_0);
jvmtiCapabilities capabilities = {0};
capabilities.can_get_bytecodes = 1;
capabilities.can_get_constant_pool = 1;
jvmtiError err = (*jvmti)->AddCapabilities(jvmti, &capabilities);
return JNI_VERSION_1_4;
}
JNIEXPORT jbyteArray JNICALL
Java_Bytecodes_getBytecodes(JNIEnv* env, jclass cls, jobject method) {
jmethodID methodID = (*env)->FromReflectedMethod(env, method);
jint bytecode_size;
unsigned char* bytecodes;
if ((*jvmti)->GetBytecodes(jvmti, methodID, &bytecode_size, &bytecodes) != 0) {
return NULL;
}
jbyteArray result = (*env)->NewByteArray(env, bytecode_size);
if (result != NULL) {
(*env)->SetByteArrayRegion(env, result, 0, bytecode_size, bytecodes);
}
(*jvmti)->Deallocate(jvmti, bytecodes);
return result;
}
import java.lang.reflect.Method;
import java.util.Arrays;
public class Bytecodes {
static {
System.loadLibrary("bytecodes");
}
private static native byte[] getBytecodes(Method method);
public static void main(String[] args) throws Exception {
Method m = Object.class.getDeclaredMethod("toString");
byte[] bytecode = getBytecodes(m);
System.out.println(Arrays.toString(bytecode));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment