JvmBridge.h
vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.h
1#ifndef YOKAN_JVM_BRIDGE_H2#define YOKAN_JVM_BRIDGE_H34#include <dlfcn.h>5#include <TargetConditionals.h>6#include <jni.h>7#include <stdint.h>8#include <stdio.h>9#include <stdlib.h>10#include <string.h>11#include <sys/types.h>12#include <unistd.h>1314#define YOKAN_CS_OPS_STATUS 015#define YOKAN_CS_DEBUGGED 0x100000001617extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);1819static inline int32_t yokan_jvm_has_jit_permission(void) {20#if TARGET_OS_SIMULATOR21 return 1;22#else23 uint32_t flags = 0;24 return csops(getpid(), YOKAN_CS_OPS_STATUS, &flags, sizeof(flags)) == 0 &&25 (flags & YOKAN_CS_DEBUGGED) != 0;26#endif27}2829static inline void yokan_jvm_set_error(char *buffer, size_t capacity, const char *message) {30 if (buffer != NULL && capacity > 0) {31 snprintf(buffer, capacity, "%s", message != NULL ? message : "Unknown embedded JVM error");32 }33}3435static inline char *yokan_jvm_property(const char *name, const char *value) {36 const size_t size = strlen(name) + strlen(value) + 3;37 char *property = (char *)malloc(size);38 if (property != NULL) {39 snprintf(property, size, "-D%s=%s", name, value);40 }41 return property;42}4344static inline void yokan_jvm_set_pending_exception(45 JNIEnv *env,46 char *buffer,47 size_t capacity,48 const char *fallback49) {50 if (!(*env)->ExceptionCheck(env)) {51 yokan_jvm_set_error(buffer, capacity, fallback);52 return;53 }5455 jthrowable throwable = (*env)->ExceptionOccurred(env);56 (*env)->ExceptionClear(env);57 jclass throwable_class = throwable == NULL ? NULL :58 (jclass)(*env)->GetObjectClass(env, throwable);59 jmethodID to_string = throwable_class == NULL ? NULL :60 (*env)->GetMethodID(env, throwable_class, "toString", "()Ljava/lang/String;");61 jstring description = to_string == NULL ? NULL :62 (jstring)(*env)->CallObjectMethod(env, throwable, to_string);63 if ((*env)->ExceptionCheck(env)) {64 (*env)->ExceptionClear(env);65 description = NULL;66 }6768 int wrote_description = 0;69 if (description != NULL) {70 const char *utf = (*env)->GetStringUTFChars(env, description, NULL);71 if (utf != NULL) {72 yokan_jvm_set_error(buffer, capacity, utf);73 wrote_description = 1;74 (*env)->ReleaseStringUTFChars(env, description, utf);75 }76 }77 if ((*env)->ExceptionCheck(env)) {78 (*env)->ExceptionClear(env);79 }80 if (!wrote_description) {81 yokan_jvm_set_error(buffer, capacity, fallback);82 }83 if (description != NULL) (*env)->DeleteLocalRef(env, description);84 if (throwable_class != NULL) (*env)->DeleteLocalRef(env, throwable_class);85 if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable);86}8788static inline jclass yokan_jvm_load_class(89 JNIEnv *env,90 const char *jar_path,91 const char *class_name92) {93 jclass file_class = (*env)->FindClass(env, "java/io/File");94 jmethodID file_constructor = file_class == NULL ? NULL :95 (*env)->GetMethodID(env, file_class, "<init>", "(Ljava/lang/String;)V");96 jstring path = file_constructor == NULL ? NULL : (*env)->NewStringUTF(env, jar_path);97 jobject file = path == NULL ? NULL :98 (*env)->NewObject(env, file_class, file_constructor, path);99 jmethodID to_uri = file == NULL ? NULL :100 (*env)->GetMethodID(env, file_class, "toURI", "()Ljava/net/URI;");101 jobject uri = to_uri == NULL ? NULL : (*env)->CallObjectMethod(env, file, to_uri);102103 jclass uri_class = uri == NULL ? NULL : (*env)->FindClass(env, "java/net/URI");104 jmethodID to_url = uri_class == NULL ? NULL :105 (*env)->GetMethodID(env, uri_class, "toURL", "()Ljava/net/URL;");106 jobject url = to_url == NULL ? NULL : (*env)->CallObjectMethod(env, uri, to_url);107 jclass url_class = url == NULL ? NULL : (*env)->FindClass(env, "java/net/URL");108 jobjectArray urls = url_class == NULL ? NULL :109 (*env)->NewObjectArray(env, 1, url_class, url);110111 jclass loader_class = urls == NULL ? NULL :112 (*env)->FindClass(env, "java/net/URLClassLoader");113 jmethodID new_loader = loader_class == NULL ? NULL :114 (*env)->GetStaticMethodID(115 env,116 loader_class,117 "newInstance",118 "([Ljava/net/URL;)Ljava/net/URLClassLoader;"119 );120 jobject loader = new_loader == NULL ? NULL :121 (*env)->CallStaticObjectMethod(env, loader_class, new_loader, urls);122123 jclass thread_class = loader == NULL ? NULL : (*env)->FindClass(env, "java/lang/Thread");124 jmethodID current_thread = thread_class == NULL ? NULL :125 (*env)->GetStaticMethodID(env, thread_class, "currentThread", "()Ljava/lang/Thread;");126 jobject thread = current_thread == NULL ? NULL :127 (*env)->CallStaticObjectMethod(env, thread_class, current_thread);128 jmethodID set_context_loader = thread == NULL ? NULL :129 (*env)->GetMethodID(130 env,131 thread_class,132 "setContextClassLoader",133 "(Ljava/lang/ClassLoader;)V"134 );135 if (set_context_loader == NULL) {136 return NULL;137 }138 (*env)->CallVoidMethod(env, thread, set_context_loader, loader);139140 jclass class_loader_class = (*env)->FindClass(env, "java/lang/ClassLoader");141 jmethodID load_class = class_loader_class == NULL ? NULL :142 (*env)->GetMethodID(143 env,144 class_loader_class,145 "loadClass",146 "(Ljava/lang/String;)Ljava/lang/Class;"147 );148 jstring requested_class = load_class == NULL ? NULL :149 (*env)->NewStringUTF(env, class_name);150 jobject loaded_class = requested_class == NULL ? NULL :151 (*env)->CallObjectMethod(env, loader, load_class, requested_class);152 return (jclass)loaded_class;153}154155/*156 * Starts OpenJDK through the JNI invocation API and calls a static157 * main(String[]) method. JLI_Launch cannot be used inside an iOS host app:158 * Apple's libjli startup path resolves the process-wide `main` symbol and159 * would invoke the SwiftUI application entry point a second time.160 */161static inline int32_t yokan_jvm_launch_main(162 const char *jvm_path,163 const char *jar_path,164 const char *main_class_name,165 const char *port,166 const char *temporary_directory,167 const char *user_home,168 int32_t use_mirrored_code_cache,169 char *error_buffer,170 size_t error_capacity171) {172 void *handle = dlopen(jvm_path, RTLD_NOW | RTLD_GLOBAL);173 if (handle == NULL) {174 yokan_jvm_set_error(error_buffer, error_capacity, dlerror());175 return 1;176 }177178 typedef jint (*CreateJavaVm)(JavaVM **, void **, void *);179 CreateJavaVm create_vm = (CreateJavaVm)dlsym(handle, "JNI_CreateJavaVM");180 if (create_vm == NULL) {181 yokan_jvm_set_error(error_buffer, error_capacity, "libjvm.dylib does not export JNI_CreateJavaVM");182 return 2;183 }184185 char *class_path = yokan_jvm_property("java.class.path", jar_path);186 char *tmp_dir = yokan_jvm_property("java.io.tmpdir", temporary_directory);187 char *home = yokan_jvm_property("user.home", user_home);188 if (class_path == NULL || tmp_dir == NULL || home == NULL) {189 free(class_path);190 free(tmp_dir);191 free(home);192 yokan_jvm_set_error(error_buffer, error_capacity, "Could not allocate embedded JVM options");193 return 3;194 }195196 JavaVMOption options[12];197 jint option_count = 0;198 options[option_count++] = (JavaVMOption) { .optionString = "-Xint", .extraInfo = NULL };199 options[option_count++] = (JavaVMOption) { .optionString = "-Xms32m", .extraInfo = NULL };200 options[option_count++] = (JavaVMOption) { .optionString = "-Xmx512m", .extraInfo = NULL };201 /*202 * HotSpot's compressed class space requires an extended virtual address203 * range that ordinary sideloaded iOS processes do not receive.204 */205 options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UseCompressedClassPointers", .extraInfo = NULL };206 options[option_count++] = (JavaVMOption) { .optionString = "-XX:+UnlockExperimentalVMOptions", .extraInfo = NULL };207 if (use_mirrored_code_cache) {208 options[option_count++] = (JavaVMOption) { .optionString = "-XX:+MirrorMappedCodeCache", .extraInfo = NULL };209 }210 options[option_count++] = (JavaVMOption) { .optionString = "-Xrs", .extraInfo = NULL };211 options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UsePerfData", .extraInfo = NULL };212 options[option_count++] = (JavaVMOption) { .optionString = "-Djava.awt.headless=true", .extraInfo = NULL };213 options[option_count++] = (JavaVMOption) { .optionString = class_path, .extraInfo = NULL };214 options[option_count++] = (JavaVMOption) { .optionString = tmp_dir, .extraInfo = NULL };215 options[option_count++] = (JavaVMOption) { .optionString = home, .extraInfo = NULL };216 JavaVMInitArgs init_args = {217 .version = JNI_VERSION_1_8,218 .nOptions = option_count,219 .options = options,220 .ignoreUnrecognized = JNI_FALSE,221 };222 JavaVM *vm = NULL;223 JNIEnv *env = NULL;224 const jint create_result = create_vm(&vm, (void **)&env, &init_args);225 free(class_path);226 free(tmp_dir);227 free(home);228 if (create_result != JNI_OK || vm == NULL || env == NULL) {229 char message[128];230 snprintf(message, sizeof(message), "JNI_CreateJavaVM failed with code %d", create_result);231 yokan_jvm_set_error(error_buffer, error_capacity, message);232 return 4;233 }234235 jclass main_class = yokan_jvm_load_class(env, jar_path, main_class_name);236 if (main_class == NULL) {237 yokan_jvm_set_pending_exception(238 env,239 error_buffer,240 error_capacity,241 "Extension server main class was not found"242 );243 return 5;244 }245 jmethodID main_method = (*env)->GetStaticMethodID(env, main_class, "main", "([Ljava/lang/String;)V");246 if (main_method == NULL) {247 yokan_jvm_set_pending_exception(248 env,249 error_buffer,250 error_capacity,251 "Extension server main(String[]) method was not found"252 );253 return 6;254 }255 jclass string_class = (*env)->FindClass(env, "java/lang/String");256 jobjectArray arguments = string_class == NULL ? NULL : (*env)->NewObjectArray(env, 1, string_class, NULL);257 jstring port_argument = arguments == NULL ? NULL : (*env)->NewStringUTF(env, port);258 if (arguments == NULL || port_argument == NULL || (*env)->ExceptionCheck(env)) {259 yokan_jvm_set_pending_exception(260 env,261 error_buffer,262 error_capacity,263 "Could not create extension server arguments"264 );265 return 7;266 }267 (*env)->SetObjectArrayElement(env, arguments, 0, port_argument);268 if ((*env)->ExceptionCheck(env)) {269 yokan_jvm_set_pending_exception(270 env,271 error_buffer,272 error_capacity,273 "Could not populate extension server arguments"274 );275 return 7;276 }277 jvalue call_arguments[1];278 call_arguments[0].l = arguments;279 (*env)->CallStaticVoidMethodA(env, main_class, main_method, call_arguments);280 if ((*env)->ExceptionCheck(env)) {281 yokan_jvm_set_pending_exception(282 env,283 error_buffer,284 error_capacity,285 "Extension server main method failed"286 );287 return 8;288 }289 return 0;290}291292#endif293