MihonEmbeddedBridge.mm
iosApp/MihonEmbeddedBridge.mm
1#import "MihonEmbeddedBridge.h"2#import <TargetConditionals.h>34#if YOKAN_SIDELOAD_RUNTIME_ENABLED && !TARGET_OS_SIMULATOR5#include <jni.h>67#include <cstdio>8#include <cstdint>9#include <dlfcn.h>10#include <os/lock.h>11#include <string>12#include <vector>1314@interface YokanEmbeddedMihonThread : NSThread {15 NSCondition *_condition;16 NSMutableArray *_pendingBlocks;17}1819- (void)enqueueBlock:(dispatch_block_t)block;2021@end2223@implementation YokanEmbeddedMihonThread2425- (instancetype)init {26 self = [super init];27 if (self != nil) {28 _condition = [[NSCondition alloc] init];29 _pendingBlocks = [[NSMutableArray alloc] init];30 self.name = @"eu.friedcutlet.yokan.embedded-mihon";31 // The Zero interpreter divides the current native stack between its32 // Java operand stack and C/C++ calls. iOS dispatch workers only provide33 // a small implementation-defined stack, which can exhaust during34 // java.lang bootstrap. Give the embedded VM a stable, JVM-sized stack.35 self.stackSize = 8 * 1024 * 1024;36 }37 return self;38}3940- (void)enqueueBlock:(dispatch_block_t)block {41 [_condition lock];42 [_pendingBlocks addObject:[block copy]];43 [_condition signal];44 [_condition unlock];45}4647- (void)main {48 while (!self.cancelled) {49 dispatch_block_t block = nil;50 [_condition lock];51 while (_pendingBlocks.count == 0 && !self.cancelled) {52 [_condition wait];53 }54 if (_pendingBlocks.count > 0) {55 block = _pendingBlocks.firstObject;56 [_pendingBlocks removeObjectAtIndex:0];57 }58 [_condition unlock];5960 if (block != nil) {61 @autoreleasepool {62 block();63 }64 }65 }66}6768@end6970namespace {7172NSString *const kEmbeddedMihonErrorDomain =73 @"eu.friedcutlet.yokan.embedded_mihon";74const char *const kEmbeddedBridgeClassName =75 "mextensionserver/EmbeddedBridge";76const char *const kOpenJDKFrameworkRelativePath =77 "Frameworks/OpenJDKRuntime.framework/OpenJDKRuntime";7879using LoadFunctions = void (*)(void);80using CreateJavaVM = jint (*)(JavaVM **, void **, void *);8182JavaVM *gJavaVM = nullptr;83jclass gEmbeddedBridgeClass = nullptr;84jmethodID gStartMethod = nullptr;85jmethodID gPauseMethod = nullptr;86jmethodID gStopMethod = nullptr;87jmethodID gIsRunningMethod = nullptr;88void *gOpenJDKHandle = nullptr;89LoadFunctions gLoadFunctions = nullptr;90CreateJavaVM gCreateJavaVM = nullptr;91int32_t gLastStartedPort = 0;92os_unfair_lock gJavaVMLock = OS_UNFAIR_LOCK_INIT;9394class JavaVMLockGuard {95 public:96 JavaVMLockGuard() {97 os_unfair_lock_lock(&gJavaVMLock);98 }99100 ~JavaVMLockGuard() {101 os_unfair_lock_unlock(&gJavaVMLock);102 }103104 JavaVMLockGuard(const JavaVMLockGuard &) = delete;105 JavaVMLockGuard &operator=(const JavaVMLockGuard &) = delete;106};107108void TraceEmbeddedMihon(NSString *message) {109 const char *utf8 = message.UTF8String;110 fprintf(111 stderr,112 "Yokan EmbeddedMihon: %s\n",113 utf8 == nullptr ? "(null)" : utf8);114 fflush(stderr);115}116117YokanEmbeddedMihonThread *EmbeddedMihonThread() {118 static YokanEmbeddedMihonThread *thread;119 static dispatch_once_t onceToken;120 dispatch_once(&onceToken, ^{121 thread = [[YokanEmbeddedMihonThread alloc] init];122 [thread start];123 });124 return thread;125}126127NSError *EmbeddedMihonError(NSInteger code, NSString *message) {128 return [NSError errorWithDomain:kEmbeddedMihonErrorDomain129 code:code130 userInfo:@{NSLocalizedDescriptionKey : message}];131}132133NSString *OpenJDKRuntimePath() {134 NSString *relativePath =135 [NSString stringWithUTF8String:kOpenJDKFrameworkRelativePath];136 return [NSBundle.mainBundle.bundlePath137 stringByAppendingPathComponent:relativePath];138}139140NSString *OpenJDKRuntimeHome() {141 return [[OpenJDKRuntimePath() stringByDeletingLastPathComponent]142 stringByAppendingPathComponent:@"lib"];143}144145bool LoadOpenJDKRuntime(NSError **error) {146 if (gOpenJDKHandle != nullptr &&147 gLoadFunctions != nullptr &&148 gCreateJavaVM != nullptr) {149 return true;150 }151152 NSString *runtimePath = OpenJDKRuntimePath();153 dlerror();154 // The static OpenJDK build resolves its bundled JIMAGE and JDK native155 // functions through dlsym(RTLD_DEFAULT, ...). RTLD_GLOBAL is therefore156 // required even though the framework itself is loaded lazily.157 void *handle = dlopen(runtimePath.UTF8String, RTLD_NOW | RTLD_GLOBAL);158 if (handle == nullptr) {159 const char *details = dlerror();160 if (error != nullptr) {161 *error = EmbeddedMihonError(162 12,163 [NSString stringWithFormat:164 @"The on-device Mihon runtime could not be loaded: %s",165 details == nullptr ? "unknown dynamic loader error" : details]);166 }167 return false;168 }169170 const char *const requiredGlobalSymbols[] = {171 "JDK_Canonicalize",172 "JIMAGE_Open",173 "JIMAGE_Close",174 "JIMAGE_FindResource",175 "JIMAGE_GetResource",176 "VerifyClassForMajorVersion",177 };178 for (const char *symbol : requiredGlobalSymbols) {179 dlerror();180 if (dlsym(RTLD_DEFAULT, symbol) == nullptr) {181 if (error != nullptr) {182 *error = EmbeddedMihonError(183 14,184 [NSString stringWithFormat:185 @"The on-device Mihon runtime cannot expose %s.", symbol]);186 }187 dlclose(handle);188 return false;189 }190 }191192 dlerror();193 auto loadFunctions =194 reinterpret_cast<LoadFunctions>(195 dlsym(handle, "YokanOpenJDKLoadFunctions"));196 const char *loadFunctionsError = dlerror();197 dlerror();198 auto createJavaVM =199 reinterpret_cast<CreateJavaVM>(dlsym(handle, "JNI_CreateJavaVM"));200 const char *createJavaVMError = dlerror();201 if (loadFunctions == nullptr ||202 createJavaVM == nullptr ||203 loadFunctionsError != nullptr ||204 createJavaVMError != nullptr) {205 if (error != nullptr) {206 *error = EmbeddedMihonError(207 13,208 @"The on-device Mihon runtime is missing its JNI entry points.");209 }210 dlclose(handle);211 return false;212 }213214 gOpenJDKHandle = handle;215 gLoadFunctions = loadFunctions;216 gCreateJavaVM = createJavaVM;217 return true;218}219220NSString *JavaExceptionMessage(JNIEnv *env, NSString *fallback) {221 jthrowable exception = env->ExceptionOccurred();222 if (exception == nullptr) {223 return fallback;224 }225 env->ExceptionClear();226227 NSString *message = fallback;228 jclass throwableClass = env->FindClass("java/lang/Throwable");229 if (throwableClass != nullptr) {230 jmethodID toStringMethod =231 env->GetMethodID(throwableClass, "toString", "()Ljava/lang/String;");232 if (toStringMethod != nullptr) {233 auto text =234 static_cast<jstring>(env->CallObjectMethod(exception, toStringMethod));235 if (!env->ExceptionCheck() && text != nullptr) {236 const char *utf8 = env->GetStringUTFChars(text, nullptr);237 if (utf8 != nullptr) {238 message = [NSString stringWithUTF8String:utf8];239 env->ReleaseStringUTFChars(text, utf8);240 }241 env->DeleteLocalRef(text);242 } else {243 env->ExceptionClear();244 }245 }246 env->DeleteLocalRef(throwableClass);247 } else {248 env->ExceptionClear();249 }250 env->DeleteLocalRef(exception);251 return message;252}253254bool VerifyRuntimeFiles(255 NSString *resourcePath,256 NSString *runtimeHome,257 NSError **error) {258 NSArray<NSString *> *requiredFiles = @[259 @"lib/security/cacerts",260 @"MExtensionServer.jar",261 @"java-logging-shim.jar",262 ];263 NSFileManager *fileManager = NSFileManager.defaultManager;264 for (NSString *relativePath in requiredFiles) {265 NSString *path = [resourcePath stringByAppendingPathComponent:relativePath];266 if (![fileManager fileExistsAtPath:path]) {267 if (error != nullptr) {268 *error = EmbeddedMihonError(269 1,270 [NSString stringWithFormat:271 @"The embedded Mihon runtime is incomplete: %@ is missing.",272 relativePath]);273 }274 return false;275 }276 }277 NSString *bootModules =278 [runtimeHome stringByAppendingPathComponent:@"lib/modules"];279 if (![fileManager fileExistsAtPath:bootModules]) {280 if (error != nullptr) {281 *error = EmbeddedMihonError(282 1,283 @"The embedded Mihon runtime is incomplete: the framework-local "284 @"OpenJDK module image is missing.");285 }286 return false;287 }288 NSString *securityConfiguration =289 [runtimeHome stringByAppendingPathComponent:@"conf/security/java.security"];290 if (![fileManager fileExistsAtPath:securityConfiguration]) {291 if (error != nullptr) {292 *error = EmbeddedMihonError(293 1,294 @"The embedded Mihon runtime is incomplete: the framework-local "295 @"OpenJDK security configuration is missing.");296 }297 return false;298 }299 NSString *timezoneDatabase =300 [runtimeHome stringByAppendingPathComponent:@"lib/tzdb.dat"];301 if (![fileManager fileExistsAtPath:timezoneDatabase]) {302 if (error != nullptr) {303 *error = EmbeddedMihonError(304 1,305 @"The embedded Mihon runtime is incomplete: the framework-local "306 @"OpenJDK timezone database is missing.");307 }308 return false;309 }310 return true;311}312313NSString *CreateApplicationDirectory(NSError **error) {314 NSFileManager *fileManager = NSFileManager.defaultManager;315 NSURL *supportURL = [fileManager URLForDirectory:NSApplicationSupportDirectory316 inDomain:NSUserDomainMask317 appropriateForURL:nil318 create:YES319 error:error];320 if (supportURL == nil) {321 return nil;322 }323 NSURL *appURL = [supportURL URLByAppendingPathComponent:@"MihonExtensions"324 isDirectory:YES];325 if (![fileManager createDirectoryAtURL:appURL326 withIntermediateDirectories:YES327 attributes:nil328 error:error]) {329 return nil;330 }331 return appURL.path;332}333334bool CacheBridgeEntryPoints(JNIEnv *env, NSError **error) {335 TraceEmbeddedMihon(@"looking up mextensionserver/EmbeddedBridge");336 jclass localClass = env->FindClass(kEmbeddedBridgeClassName);337 if (localClass == nullptr) {338 TraceEmbeddedMihon(339 [NSString stringWithFormat:340 @"EmbeddedBridge lookup failed (exception=%@)",341 env->ExceptionCheck() ? @"yes" : @"no"]);342 if (error != nullptr) {343 *error = EmbeddedMihonError(344 3,345 JavaExceptionMessage(346 env, @"The embedded Mihon bridge class could not be loaded."));347 }348 return false;349 }350 TraceEmbeddedMihon(@"EmbeddedBridge class lookup succeeded");351352 gEmbeddedBridgeClass =353 static_cast<jclass>(env->NewGlobalRef(localClass));354 env->DeleteLocalRef(localClass);355 if (gEmbeddedBridgeClass == nullptr) {356 if (error != nullptr) {357 *error = EmbeddedMihonError(358 4, @"The embedded Mihon bridge class could not be retained.");359 }360 return false;361 }362 TraceEmbeddedMihon(@"EmbeddedBridge global reference retained");363364 gStartMethod = env->GetStaticMethodID(365 gEmbeddedBridgeClass, "start", "(ILjava/lang/String;)I");366 gPauseMethod =367 env->GetStaticMethodID(gEmbeddedBridgeClass, "pause", "()V");368 gStopMethod =369 env->GetStaticMethodID(gEmbeddedBridgeClass, "stop", "()V");370 gIsRunningMethod =371 env->GetStaticMethodID(gEmbeddedBridgeClass, "isRunning", "()Z");372 if (gStartMethod == nullptr ||373 gPauseMethod == nullptr ||374 gStopMethod == nullptr ||375 gIsRunningMethod == nullptr ||376 env->ExceptionCheck()) {377 if (error != nullptr) {378 *error = EmbeddedMihonError(379 5,380 JavaExceptionMessage(381 env, @"The embedded Mihon bridge entry points are invalid."));382 }383 return false;384 }385 TraceEmbeddedMihon(@"EmbeddedBridge JNI entry points cached");386 return true;387}388389bool CreateJavaVMIfNeeded(JNIEnv **environment, NSError **error) {390 JavaVMLockGuard guard;391 if (gJavaVM != nullptr) {392 if (gEmbeddedBridgeClass == nullptr ||393 gStartMethod == nullptr ||394 gPauseMethod == nullptr ||395 gStopMethod == nullptr ||396 gIsRunningMethod == nullptr) {397 if (error != nullptr) {398 *error = EmbeddedMihonError(399 2, @"The embedded Java runtime did not initialize completely.");400 }401 return false;402 }403 jint result = gJavaVM->AttachCurrentThread(404 reinterpret_cast<void **>(environment), nullptr);405 if (result != JNI_OK) {406 if (error != nullptr) {407 *error = EmbeddedMihonError(408 6, @"The embedded Java runtime could not attach its worker.");409 }410 return false;411 }412 return true;413 }414415 NSString *resourcePath = NSBundle.mainBundle.resourcePath;416 NSString *runtimeHome = OpenJDKRuntimeHome();417 if (!VerifyRuntimeFiles(resourcePath, runtimeHome, error)) {418 return false;419 }420 if (!LoadOpenJDKRuntime(error)) {421 return false;422 }423424 NSString *applicationDirectory = CreateApplicationDirectory(error);425 if (applicationDirectory == nil) {426 return false;427 }428 NSString *temporaryDirectory =429 [NSTemporaryDirectory() stringByAppendingPathComponent:@"MihonExtensions"];430 if (![NSFileManager.defaultManager431 createDirectoryAtPath:temporaryDirectory432 withIntermediateDirectories:YES433 attributes:nil434 error:error]) {435 return false;436 }437438 NSString *serverJar =439 [resourcePath stringByAppendingPathComponent:@"MExtensionServer.jar"];440 NSString *loggingShim =441 [resourcePath stringByAppendingPathComponent:@"java-logging-shim.jar"];442 NSString *trustStore =443 [resourcePath stringByAppendingPathComponent:@"lib/security/cacerts"];444445 std::vector<std::string> optionStrings = {446 std::string("-Djava.class.path=") + serverJar.UTF8String,447 std::string("-Xbootclasspath/a:") + loggingShim.UTF8String,448 std::string("-Djava.home=") + runtimeHome.UTF8String,449 std::string("-Djava.io.tmpdir=") + temporaryDirectory.UTF8String,450 std::string("-Duser.home=") + applicationDirectory.UTF8String,451 std::string("-Djavax.net.ssl.trustStore=") + trustStore.UTF8String,452 "-Djavax.net.ssl.trustStorePassword=changeit",453 "-Djava.awt.headless=true",454 "-Dfile.encoding=UTF-8",455 "-Djava.net.preferIPv4Stack=true",456 "-Dorg.slf4j.simpleLogger.defaultLogLevel=warn",457 // OpenJDK Zero uses Serial GC on iOS. Runtime v7 links java.lang.Class458 // before the first Java bytecode, so ordinary balanced generation459 // ceilings are sufficient without reserving an oversized heap.460 "-XX:+UseSerialGC",461 "-Xms128m",462 "-Xmx512m",463 "-XX:NewSize=64m",464 "-XX:MaxNewSize=256m",465 // The dedicated JNI bootstrap thread above has an 8 MiB stack, but466 // NanoHTTPD and the Android compatibility layer create ordinary Java467 // threads. BSD Zero otherwise gives those threads only 1536 KiB and its468 // stack-overflow signal path is not implemented, turning a deep request469 // into a process-fatal ShouldNotCall instead of StackOverflowError.470 "-Xss8m",471 };472 std::vector<JavaVMOption> options(optionStrings.size());473 for (size_t index = 0; index < optionStrings.size(); index++) {474 options[index].optionString =475 const_cast<char *>(optionStrings[index].c_str());476 options[index].extraInfo = nullptr;477 }478479 JavaVMInitArgs arguments = {};480 arguments.version = JNI_VERSION_1_8;481 arguments.nOptions = static_cast<jint>(options.size());482 arguments.options = options.data();483 arguments.ignoreUnrecognized = JNI_FALSE;484485 TraceEmbeddedMihon(@"calling JNI_CreateJavaVM");486 gLoadFunctions();487 // HotSpot must own SIGSEGV/SIGBUS while the VM is running. OpenJDK Zero488 // uses those signals internally on iOS, so an app-level handler here would489 // turn a recoverable VM signal into an app termination.490 jint result = gCreateJavaVM(491 &gJavaVM, reinterpret_cast<void **>(environment), &arguments);492 TraceEmbeddedMihon(493 [NSString stringWithFormat:494 @"JNI_CreateJavaVM returned %d (vm=%@, env=%@)",495 result,496 gJavaVM == nullptr ? @"null" : @"set",497 *environment == nullptr ? @"null" : @"set"]);498 if (result != JNI_OK || gJavaVM == nullptr || *environment == nullptr) {499 gJavaVM = nullptr;500 if (error != nullptr) {501 *error = EmbeddedMihonError(502 7,503 [NSString stringWithFormat:504 @"The embedded Java runtime could not start (JNI %d).",505 result]);506 }507 return false;508 }509 TraceEmbeddedMihon(@"JNI_CreateJavaVM succeeded");510 if (!CacheBridgeEntryPoints(*environment, error)) {511 TraceEmbeddedMihon(@"EmbeddedBridge JNI cache failed");512 return false;513 }514 TraceEmbeddedMihon(@"embedded Java runtime initialization completed");515 return true;516}517518void DetachCurrentWorker() {519 if (gJavaVM != nullptr) {520 gJavaVM->DetachCurrentThread();521 }522}523524} // namespace525526void YokanEmbeddedMihonStart(527 int32_t port,528 YokanEmbeddedMihonStartCompletion completion) {529 // Loading the framework and starting the VM are intentionally kept off the530 // app launch path and the UI thread. The framework remains loaded for the531 // lifetime of the process after the first Mihon request.532 [EmbeddedMihonThread() enqueueBlock:^{533 @autoreleasepool {534 NSError *error = nil;535 JNIEnv *environment = nullptr;536 int32_t startedPort = 0;537 TraceEmbeddedMihon(538 [NSString stringWithFormat:@"start requested on port %d", port]);539 if (CreateJavaVMIfNeeded(&environment, &error)) {540 NSString *applicationDirectory = CreateApplicationDirectory(&error);541 if (applicationDirectory != nil) {542 jstring appDirectory =543 environment->NewStringUTF(applicationDirectory.UTF8String);544 TraceEmbeddedMihon(@"calling EmbeddedBridge.start");545 jint result = environment->CallStaticIntMethod(546 gEmbeddedBridgeClass, gStartMethod, port, appDirectory);547 TraceEmbeddedMihon(548 [NSString stringWithFormat:549 @"EmbeddedBridge.start returned %d (exception=%@)",550 result,551 environment->ExceptionCheck() ? @"yes" : @"no"]);552 if (environment->ExceptionCheck()) {553 error = EmbeddedMihonError(554 8,555 JavaExceptionMessage(556 environment, @"The embedded Mihon bridge failed to start."));557 } else if (result <= 0 || result > UINT16_MAX) {558 error = EmbeddedMihonError(559 9, @"The embedded Mihon bridge returned an invalid port.");560 } else {561 startedPort = result;562 gLastStartedPort = result;563 }564 if (appDirectory != nullptr) {565 environment->DeleteLocalRef(appDirectory);566 }567 }568 DetachCurrentWorker();569 }570 if (error != nil) {571 TraceEmbeddedMihon(572 [NSString stringWithFormat:@"start failed: %@",573 error.localizedDescription]);574 } else {575 TraceEmbeddedMihon(576 [NSString stringWithFormat:@"start completed on port %d",577 startedPort]);578 }579 dispatch_async(dispatch_get_main_queue(), ^{580 completion(startedPort, error);581 });582 }583 }];584}585586void YokanEmbeddedMihonStop(587 YokanEmbeddedMihonCompletion completion) {588 [EmbeddedMihonThread() enqueueBlock:^{589 @autoreleasepool {590 NSError *error = nil;591 JNIEnv *environment = nullptr;592 if (gJavaVM != nullptr &&593 CreateJavaVMIfNeeded(&environment, &error)) {594 environment->CallStaticVoidMethod(595 gEmbeddedBridgeClass, gStopMethod);596 if (environment->ExceptionCheck()) {597 error = EmbeddedMihonError(598 10,599 JavaExceptionMessage(600 environment, @"The embedded Mihon bridge failed to stop."));601 } else {602 gLastStartedPort = 0;603 }604 DetachCurrentWorker();605 }606 dispatch_async(dispatch_get_main_queue(), ^{607 completion(error);608 });609 }610 }];611}612613void YokanEmbeddedMihonResume(614 YokanEmbeddedMihonCompletion completion) {615 const int32_t port = gLastStartedPort;616 if (port == 0) {617 completion(nil);618 return;619 }620 YokanEmbeddedMihonStart(port, ^(int32_t startedPort, NSError *error) {621 completion(error);622 });623}624625void YokanEmbeddedMihonPause(626 YokanEmbeddedMihonCompletion completion) {627 [EmbeddedMihonThread() enqueueBlock:^{628 @autoreleasepool {629 NSError *error = nil;630 JNIEnv *environment = nullptr;631 if (gJavaVM != nullptr &&632 CreateJavaVMIfNeeded(&environment, &error)) {633 environment->CallStaticVoidMethod(634 gEmbeddedBridgeClass, gPauseMethod);635 if (environment->ExceptionCheck()) {636 error = EmbeddedMihonError(637 12,638 JavaExceptionMessage(639 environment, @"The embedded Mihon bridge failed to pause."));640 }641 DetachCurrentWorker();642 }643 dispatch_async(dispatch_get_main_queue(), ^{644 completion(error);645 });646 }647 }];648}649650void YokanEmbeddedMihonIsRunning(651 YokanEmbeddedMihonStatusCompletion completion) {652 [EmbeddedMihonThread() enqueueBlock:^{653 @autoreleasepool {654 NSError *error = nil;655 JNIEnv *environment = nullptr;656 BOOL isRunning = NO;657 if (gJavaVM != nullptr &&658 CreateJavaVMIfNeeded(&environment, &error)) {659 jboolean result = environment->CallStaticBooleanMethod(660 gEmbeddedBridgeClass, gIsRunningMethod);661 if (environment->ExceptionCheck()) {662 error = EmbeddedMihonError(663 11,664 JavaExceptionMessage(665 environment,666 @"The embedded Mihon bridge status could not be read."));667 } else {668 isRunning = result == JNI_TRUE;669 }670 DetachCurrentWorker();671 }672 dispatch_async(dispatch_get_main_queue(), ^{673 completion(isRunning, error);674 });675 }676 }];677}678679#else680681namespace {682NSError *UnavailableRuntimeError() {683 return [NSError errorWithDomain:@"eu.friedcutlet.yokan.embedded_mihon"684 code:1685 userInfo:@{686 NSLocalizedDescriptionKey:687 @"This build does not include the sideloaded iOS Java runtime."688 }];689}690} // namespace691692void YokanEmbeddedMihonStart(693 int32_t port,694 YokanEmbeddedMihonStartCompletion completion) {695 completion(0, UnavailableRuntimeError());696}697698void YokanEmbeddedMihonPause(YokanEmbeddedMihonCompletion completion) {699 completion(nil);700}701702void YokanEmbeddedMihonResume(YokanEmbeddedMihonCompletion completion) {703 completion(nil);704}705706void YokanEmbeddedMihonStop(YokanEmbeddedMihonCompletion completion) {707 completion(nil);708}709710void YokanEmbeddedMihonIsRunning(711 YokanEmbeddedMihonStatusCompletion completion) {712 completion(NO, nil);713}714715#endif716