Skip to content

[WIP] Android support #310

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// swift-tools-version: 6.0
// swift-tools-version: 6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.

import CompilerPluginSupport
import PackageDescription

Expand Down Expand Up @@ -226,7 +225,7 @@ let package = Package(
exclude: ["swift-java.config"],
swiftSettings: [
.swiftLanguageMode(.v5),
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"])
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"], .when(platforms: [.macOS, .linux, .windows]))
],
linkerSettings: [
.unsafeFlags(
Expand Down
4 changes: 4 additions & 0 deletions Sources/JavaKit/JavaEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@

import JavaRuntime

#if canImport(Android)
typealias JNINativeInterface_ = JNINativeInterface
#endif

extension UnsafeMutablePointer<JNIEnv?> {
var interface: JNINativeInterface_ { self.pointee!.pointee }
}
25 changes: 20 additions & 5 deletions Sources/JavaKit/JavaKitVM/JavaVirtualMachine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ import Foundation
#endif

public typealias JavaVMPointer = UnsafeMutablePointer<JavaVM?>
#if canImport(Android)
typealias JNIEnvPointer = UnsafeMutablePointer<JNIEnv?>
#else
typealias JNIEnvPointer = UnsafeMutableRawPointer
#endif

public final class JavaVirtualMachine: @unchecked Sendable {
/// The JNI version that we depend on.
Expand Down Expand Up @@ -61,7 +66,7 @@ public final class JavaVirtualMachine: @unchecked Sendable {
) throws {
self.classpath = classpath
var jvm: JavaVMPointer? = nil
var environment: UnsafeMutableRawPointer? = nil
var environment: JNIEnvPointer? = nil
var vmArgs = JavaVMInitArgs()
vmArgs.version = JavaVirtualMachine.jniVersion
vmArgs.ignoreUnrecognized = jboolean(ignoreUnrecognized ? JNI_TRUE : JNI_FALSE)
Expand Down Expand Up @@ -161,12 +166,18 @@ extension JavaVirtualMachine {
return environment.assumingMemoryBound(to: JNIEnv?.self)
}

#if canImport(Android)
var jniEnv = environment?.assumingMemoryBound(to: JNIEnv?.self)
#else
var jniEnv = environment
#endif

// Attach the current thread to the JVM.
let attachResult: jint
if asDaemon {
attachResult = jvm.pointee!.pointee.AttachCurrentThreadAsDaemon(jvm, &environment, nil)
attachResult = jvm.pointee!.pointee.AttachCurrentThreadAsDaemon(jvm, &jniEnv, nil)
} else {
attachResult = jvm.pointee!.pointee.AttachCurrentThread(jvm, &environment, nil)
attachResult = jvm.pointee!.pointee.AttachCurrentThread(jvm, &jniEnv, nil)
}

// If we failed to attach, report that.
Expand All @@ -175,9 +186,13 @@ extension JavaVirtualMachine {
throw attachError
}

JavaVirtualMachine.destroyTLS.set(environment!)
JavaVirtualMachine.destroyTLS.set(jniEnv!)

return environment!.assumingMemoryBound(to: JNIEnv?.self)
#if canImport(Android)
return jniEnv!
#else
return jniEnv!.assumingMemoryBound(to: JNIEnv?.self)
#endif
}

/// Detach the current thread from the Java Virtual Machine. All Java
Expand Down
8 changes: 8 additions & 0 deletions Sources/JavaKit/JavaObjectHolder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,21 @@ import JavaRuntime
/// while this instance is live.
public class JavaObjectHolder {
public private(set) var object: jobject?
#if canImport(Android)
public var environment: JNIEnvironment {
try! JavaVirtualMachine.shared().environment()
}
#else
public let environment: JNIEnvironment
#endif

/// Take a reference to a Java object and promote it to a global reference
/// so that the Java virtual machine will not garbage-collect it.
public init(object: jobject, environment: JNIEnvironment) {
self.object = environment.interface.NewGlobalRef(environment, object)
#if !canImport(Android)
self.environment = environment
#endif
}

/// Forget this Java object, meaning that it is no longer used from anywhere
Expand Down
98 changes: 98 additions & 0 deletions Sources/JavaRuntime/AndroidSupport.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

#ifdef __ANDROID__

#include <JavaRuntime.h>
#include <android/log.h>
#include <dlfcn.h>

// these are not exported by the Android SDK

extern "C" {
using JavaRuntime_GetDefaultJavaVMInitArgs_fn = jint (*)(void *vm_args);
using JavaRuntime_CreateJavaVM_fn = jint (*)(JavaVM **, JNIEnv **, void *);
using JavaRuntime_GetCreatedJavaVMs_fn = jint (*)(JavaVM **, jsize, jsize *);
}

static JavaRuntime_GetDefaultJavaVMInitArgs_fn
JavaRuntime_GetDefaultJavaVMInitArgs;
static JavaRuntime_CreateJavaVM_fn JavaRuntime_CreateJavaVM;
static JavaRuntime_GetCreatedJavaVMs_fn JavaRuntime_GetCreatedJavaVMs;

static void *JavaRuntime_dlhandle;

__attribute__((constructor)) static void JavaRuntime_init(void) {
JavaRuntime_dlhandle = dlopen("libnativehelper.so", RTLD_NOW | RTLD_LOCAL);
if (JavaRuntime_dlhandle == nullptr) {
__android_log_print(ANDROID_LOG_FATAL, "JavaRuntime",
"failed to open libnativehelper.so: %s", dlerror());
return;
}

JavaRuntime_GetDefaultJavaVMInitArgs =
reinterpret_cast<JavaRuntime_GetDefaultJavaVMInitArgs_fn>(
dlsym(JavaRuntime_dlhandle, "JNI_GetDefaultJavaVMInitArgs"));
if (JavaRuntime_GetDefaultJavaVMInitArgs == nullptr)
__android_log_print(ANDROID_LOG_FATAL, "JavaRuntime",
"JNI_GetDefaultJavaVMInitArgs not found: %s",
dlerror());

JavaRuntime_CreateJavaVM = reinterpret_cast<JavaRuntime_CreateJavaVM_fn>(
dlsym(JavaRuntime_dlhandle, "JNI_CreateJavaVM"));
if (JavaRuntime_CreateJavaVM == nullptr)
__android_log_print(ANDROID_LOG_FATAL, "JavaRuntime",
"JNI_CreateJavaVM not found: %s", dlerror());

JavaRuntime_GetCreatedJavaVMs =
reinterpret_cast<JavaRuntime_GetCreatedJavaVMs_fn>(
dlsym(JavaRuntime_dlhandle, "JNI_GetCreatedJavaVMs"));
if (JavaRuntime_GetCreatedJavaVMs == nullptr)
__android_log_print(ANDROID_LOG_FATAL, "JavaRuntime",
"JNI_GetCreatedJavaVMs not found: %s", dlerror());
}

__attribute__((destructor)) static void JavaRuntime_deinit(void) {
if (JavaRuntime_dlhandle) {
dlclose(JavaRuntime_dlhandle);
JavaRuntime_dlhandle = nullptr;
}

JavaRuntime_GetDefaultJavaVMInitArgs = nullptr;
JavaRuntime_CreateJavaVM = nullptr;
JavaRuntime_GetCreatedJavaVMs = nullptr;
}

jint JNI_GetDefaultJavaVMInitArgs(void *vm_args) {
if (JavaRuntime_GetDefaultJavaVMInitArgs == nullptr)
return JNI_ERR;

return (*JavaRuntime_GetDefaultJavaVMInitArgs)(vm_args);
}

jint JNI_CreateJavaVM(JavaVM **vm, JNIEnv **env, void *vm_args) {
if (JavaRuntime_CreateJavaVM == nullptr)
return JNI_ERR;

return (*JavaRuntime_CreateJavaVM)(vm, env, vm_args);
}

jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs) {
if (JavaRuntime_GetCreatedJavaVMs == nullptr)
return JNI_ERR;

return (*JavaRuntime_GetCreatedJavaVMs)(vmBuf, bufLen, nVMs);
}

#endif