Skip to content

Commit

Permalink
Fallback to javaClass classloader for loading native lib in case of s…
Browse files Browse the repository at this point in the history
…ystem class loader failure (#328)
  • Loading branch information
DariusIMP authored Dec 20, 2024
1 parent 900a524 commit 91eb6be
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions zenoh-kotlin/src/jvmMain/kotlin/io/zenoh/Zenoh.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import java.util.zip.ZipInputStream
internal actual object ZenohLoad {
private const val ZENOH_LIB_NAME = "zenoh_jni"

init {
init {
// Try first to load the local native library for cases in which the module was built locally,
// otherwise try to load from the JAR.
if (tryLoadingLocalLibrary().isFailure) {
Expand All @@ -51,24 +51,30 @@ internal actual object ZenohLoad {
osName.contains("win") -> when {
osArch.contains("x86_64") || osArch.contains("amd64") || osArch.contains("x64") ->
Target.WINDOWS_X86_64_MSVC

osArch.contains("aarch64") || osArch.contains("arm64") ->
Target.WINDOWS_AARCH64_MSVC

else -> throw UnsupportedOperationException("Unsupported architecture on Windows: $osArch")
}

osName.contains("mac") || osName.contains("darwin") || osName.contains("os x") -> when {
osArch.contains("x86_64") || osArch.contains("amd64") || osArch.contains("x64") ->
Target.APPLE_X86_64

osArch.contains("aarch64") || osArch.contains("arm64") ->
Target.APPLE_AARCH64

else -> throw UnsupportedOperationException("Unsupported architecture on macOS: $osArch")
}

osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> when {
osArch.contains("x86_64") || osArch.contains("amd64") || osArch.contains("x64") ->
Target.LINUX_X86_64

osArch.contains("aarch64") || osArch.contains("arm64") ->
Target.LINUX_AARCH64

else -> throw UnsupportedOperationException("Unsupported architecture on Linux/Unix: $osArch")
}

Expand Down Expand Up @@ -115,7 +121,9 @@ internal actual object ZenohLoad {
}

private fun loadLibraryAsInputStream(target: Target): Result<InputStream> = runCatching {
val libUrl = ClassLoader.getSystemClassLoader().getResourceAsStream("$target/$target.zip")!!
val targetName = "$target/$target.zip"
val libUrl = ClassLoader.getSystemClassLoader().getResourceAsStream(targetName)
?: javaClass.classLoader.getResourceAsStream(targetName)!!
val uncompressedLibFile = unzipLibrary(libUrl)
return Result.success(FileInputStream(uncompressedLibFile.getOrThrow()))
}
Expand Down Expand Up @@ -152,6 +160,9 @@ internal actual object ZenohLoad {
*/
private fun tryLoadingLocalLibrary(): Result<Unit> = runCatching {
val lib = ClassLoader.getSystemClassLoader().findLibraryStream(ZENOH_LIB_NAME)
?: javaClass.classLoader.findLibraryStream(
ZENOH_LIB_NAME
)
if (lib != null) {
loadZenohJNI(lib)
} else {
Expand Down

0 comments on commit 91eb6be

Please sign in to comment.