|
| 1 | +// Native agent that nREPL uses for deeply buried JDK functionality. |
| 2 | +// Currently it is used to bring back Thread.stop() that was lost in JDK20+. |
| 3 | + |
| 4 | +#include <jvmti.h> |
| 5 | +#include <stdio.h> |
| 6 | + |
| 7 | +static jvmtiEnv* jvmti_env; |
| 8 | + |
| 9 | +// https://docs.oracle.com/en/java/javase/21/docs/specs/jvmti.html#StopThread |
| 10 | +JNIEXPORT void JNICALL Java_dt_JvmtiAgent_stopThread |
| 11 | +(JNIEnv* env, jclass cls, jthread thread, jobject throwable) { |
| 12 | + jvmtiError err; |
| 13 | + jvmtiThreadInfo threadInfo; |
| 14 | + |
| 15 | + err = (*jvmti_env)->GetThreadInfo(jvmti_env, thread, &threadInfo); |
| 16 | + if (err != JVMTI_ERROR_NONE) { |
| 17 | + printf("Error getting thread info: %d\n", err); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + //printf("Stopping thread \"%s\" using JVMTI...\n", threadInfo.name); |
| 22 | + |
| 23 | + err = (*jvmti_env)->StopThread(jvmti_env, thread, throwable); |
| 24 | + if (err != JVMTI_ERROR_NONE) { |
| 25 | + printf("Error stopping thread: %d\n", err); |
| 26 | + return; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* _) { |
| 31 | + //printf("nREPL native agent loaded\n"); |
| 32 | + |
| 33 | + // Initialize JVMTI environment. |
| 34 | + jint res = (*vm)->GetEnv(vm, (void**)&jvmti_env, JVMTI_VERSION_1_2); |
| 35 | + if (res != JNI_OK) { |
| 36 | + fprintf(stderr, "Failed to get JVMTI environment\n"); |
| 37 | + return JNI_ERR; |
| 38 | + } |
| 39 | + |
| 40 | + // Request capabilities for StopThread |
| 41 | + jvmtiCapabilities capabilities = {0}; |
| 42 | + capabilities.can_signal_thread = 1; |
| 43 | + (*jvmti_env)->AddCapabilities(jvmti_env, &capabilities); |
| 44 | + |
| 45 | + return JNI_OK; |
| 46 | +} |
0 commit comments