@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) package eu.friedcutlet.yokan.ext import eu.friedcutlet.yokan.ext.jvmbridge.yokan_jvm_launch_main import eu.friedcutlet.yokan.ext.jvmbridge.yokan_jvm_has_jit_permission import kotlinx.cinterop.ByteVar import kotlinx.cinterop.allocArray import kotlinx.cinterop.memScoped import kotlinx.cinterop.toKString import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import platform.Foundation.NSBundle import platform.Foundation.NSFileManager import platform.Foundation.NSHomeDirectory import platform.Foundation.NSTemporaryDirectory import platform.UIKit.UIDevice import platform.darwin.dispatch_async import platform.darwin.dispatch_get_global_queue import platform.posix.chdir import platform.posix.setenv /** * Embedded iOS runner. The signed OpenJDK runtime is loaded in-process. * JNI permits one JVM per process lifetime, so a running or exited JVM cannot be replaced. */ class IosExtensionServer : ExtensionServer { override val status: StateFlow = sharedStatus override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock { when (val current = sharedStatus.value.phase) { ExtensionServerPhase.Running -> { if (sharedStatus.value.port == config.port) return sharedStatus.value throw ExtensionServerException( "ALREADY_RUNNING", "The embedded iOS JVM is already running on port ${sharedStatus.value.port}; relaunch Yokan to change it", ) } ExtensionServerPhase.Stopped -> if (jvmWasStarted) { throw ExtensionServerException("JVM_EXITED", "The embedded iOS JVM already exited; relaunch Yokan to start it again") } ExtensionServerPhase.Starting, ExtensionServerPhase.Stopping -> { throw ExtensionServerException("BUSY", "The embedded iOS JVM is changing state") } ExtensionServerPhase.Failed -> if (jvmWasStarted) { throw ExtensionServerException("JVM_EXITED", "The embedded iOS JVM cannot be restarted; relaunch Yokan") } } val jar = normalizePath(config.serverJarPath) ?: throw ExtensionServerException("MISSING_JAR", "An extension server JAR is required on iOS") requireFile(jar, "MISSING_JAR", "Extension server JAR") val javaHome = resolveJavaHome(normalizePath(config.jvmPath)) val jvmPath = findLibrary(javaHome, "libjvm.dylib") ?: throw ExtensionServerException("MISSING_JAVA", "The signed iOS runtime has no libjvm.dylib: $javaHome") if (yokan_jvm_has_jit_permission() == 0) { throw ExtensionServerException( "JIT_UNAVAILABLE", "Enable JIT for Yokan with SideStore, AltStore, or StikDebug before starting the embedded server. " + "On iOS 26 or later, keep the debugger attached.", ) } val useMirroredCodeCache = UIDevice.currentDevice.systemVersion.substringBefore('.').toIntOrNull()?.let { it >= 26 } == true val mainClassName = "mextensionserver.MainKt" val temporaryDirectory = NSTemporaryDirectory() val userHome = NSHomeDirectory() setenv("JAVA_HOME", javaHome, 1) chdir(NSHomeDirectory()) jvmWasStarted = true sharedStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Launching embedded iOS JVM") dispatch_async(dispatch_get_global_queue(0, 0u)) { var errorMessage = "" val code = memScoped { val errorBuffer = allocArray(ErrorBufferSize) yokan_jvm_launch_main( jvm_path = jvmPath, jar_path = jar, main_class_name = mainClassName, port = config.port.toString(), temporary_directory = temporaryDirectory, user_home = userHome, use_mirrored_code_cache = if (useMirroredCodeCache) 1 else 0, error_buffer = errorBuffer, error_capacity = ErrorBufferSize.toULong(), ).also { result -> if (result != 0) errorMessage = errorBuffer.toKString() } } sharedStatus.value = ExtensionServerStatus( if (code == 0) ExtensionServerPhase.Stopped else ExtensionServerPhase.Failed, message = if (code == 0) { "Embedded iOS JVM exited" } else { errorMessage.ifBlank { "Embedded iOS JVM failed with code $code" } }, ) } ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Embedded iOS JVM started on port ${config.port}") .also { sharedStatus.value = it } } override suspend fun stop(): ExtensionServerStatus = lock.withLock { if (sharedStatus.value.phase == ExtensionServerPhase.Running) { throw ExtensionServerException( "STOP_UNSUPPORTED", "The embedded iOS JVM cannot stop without terminating Yokan", ) } sharedStatus.value } private fun resolveJavaHome(explicit: String?): String { val candidates = buildList { explicit?.let { add(if (it.endsWith("/bin/java")) it.removeSuffix("/bin/java") else it) } NSBundle.mainBundle.resourcePath?.let { add("$it/java_runtimes/java-21-openjdk") } } return candidates.firstOrNull { findLibrary(it, "libjvm.dylib") != null } ?: throw ExtensionServerException( "MISSING_JAVA", "No signed iOS OpenJDK runtime found; checked ${candidates.joinToString()}", ) } private fun findLibrary(home: String, name: String): String? { val relativePaths = listOf( "lib/$name", "lib/server/$name", "lib/zero/$name", "lib/client/$name", "lib/minimal/$name", "lib/jli/$name", "jre/lib/jli/$name", "jre/lib/server/$name", ) return relativePaths.asSequence().map { "$home/$it" }.firstOrNull(::fileExists) } private fun requireFile(path: String, code: String, label: String) { if (!fileExists(path)) throw ExtensionServerException(code, "$label does not exist: $path") } private fun fileExists(path: String): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path) private fun normalizePath(path: String?): String? = path?.trim()?.trim('"', '\'')?.removePrefix("file://")?.takeIf(String::isNotEmpty) private companion object { val lock = Mutex() val sharedStatus = MutableStateFlow(ExtensionServerStatus.Stopped) var jvmWasStarted = false const val ErrorBufferSize = 1_024 } }