Created
August 12, 2024 00:57
-
-
Save apangin/5554a85ba5e98b466d49dce15049e302 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright The async-profiler authors | |
* SPDX-License-Identifier: Apache-2.0 | |
*/ | |
#include <jvmti.h> | |
#include <dlfcn.h> | |
JNIEXPORT jlong JNICALL Java_Dlfcn_dlopen(JNIEnv* env, jclass cls, jstring libname) { | |
const char* libname_c = (*env)->GetStringUTFChars(env, libname, NULL); | |
void* ret = dlopen(libname_c, RTLD_NOW); | |
(*env)->ReleaseStringUTFChars(env, libname, libname_c); | |
return (jlong)ret; | |
} | |
JNIEXPORT jint JNICALL Java_Dlfcn_dlclose(JNIEnv* env, jclass cls, jlong handle) { | |
return dlclose((void*)handle); | |
} | |
JNIEXPORT jlong JNICALL Java_Dlfcn_dlsym(JNIEnv* env, jclass cls, jlong handle, jstring sym) { | |
const char* sym_c = (*env)->GetStringUTFChars(env, sym, NULL); | |
void* ret = dlsym((void*)handle, sym_c); | |
(*env)->ReleaseStringUTFChars(env, sym, sym_c); | |
return (jlong)ret; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright The async-profiler authors | |
* SPDX-License-Identifier: Apache-2.0 | |
*/ | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.concurrent.ThreadLocalRandom; | |
import java.util.stream.Stream; | |
public class Dlfcn { | |
private static final int THREADS = 4; | |
private static final int ITERATIONS = 100000; | |
static { | |
System.loadLibrary("dlfcn"); | |
} | |
public static void main(String[] args) throws Exception { | |
String[] libs; | |
try (Stream<Path> stream = Files.list(Paths.get(System.getProperty("java.home"), "lib"))) { | |
libs = stream.map(path -> path.getFileName().toString()) | |
.filter(filename -> filename.endsWith(".so")) | |
.toArray(String[]::new); | |
} | |
for (int i = 0; i < THREADS; i++) { | |
new Thread(() -> loop(libs)).start(); | |
} | |
} | |
private static void loop(String[] libs) { | |
for (int i = 0; i < ITERATIONS; i++) { | |
String lib = libs[ThreadLocalRandom.current().nextInt(libs.length)]; | |
long handle = dlopen(lib); | |
if (handle != 0) { | |
System.out.printf("[%s] %s = 0x%x\n", Thread.currentThread().getName(), lib, handle); | |
dlclose(handle); | |
} | |
} | |
} | |
public static native long dlopen(String libname); | |
public static native int dlclose(long handle); | |
public static native long dlsym(long handle, String sym); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment