├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── rust_lib ├── .gitignore ├── Cargo.toml ├── build.rs └── src │ └── lib.rs ├── settings.gradle.kts └── src └── nativeMain └── kotlin ├── Main.kt └── ReportedError.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .kotlin 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### IntelliJ IDEA ### 9 | .idea/modules.xml 10 | .idea/jarRepositories.xml 11 | .idea/compiler.xml 12 | .idea/libraries/ 13 | *.iws 14 | *.iml 15 | *.ipr 16 | out/ 17 | !**/src/main/**/out/ 18 | !**/src/test/**/out/ 19 | 20 | ### Eclipse ### 21 | .apt_generated 22 | .classpath 23 | .factorypath 24 | .project 25 | .settings 26 | .springBeans 27 | .sts4-cache 28 | bin/ 29 | !**/src/main/**/bin/ 30 | !**/src/test/**/bin/ 31 | 32 | ### NetBeans ### 33 | /nbproject/private/ 34 | /nbbuild/ 35 | /dist/ 36 | /nbdist/ 37 | /.nb-gradle/ 38 | 39 | ### VS Code ### 40 | .vscode/ 41 | 42 | ### Mac OS ### 43 | .DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin/Native & Rust interoperability 2 | 3 | ## Main goal 4 | 5 | We want to build an executable in Kotlin to use the language capabilities and our knowledge, but at 6 | the same time deliver fully independent of JVM solution, which can be as small as few megabytes. 7 | 8 | However, not every functionality can be easily handled in Kotlin, so sometimes it's just more convenient to 9 | prepare some external library, expose its symbols with C ABI and call them in expected places in Kotlin. 10 | We would prefer to build a static library, which can then be statically linked to the final executable, 11 | to make sure that the end user needs only a single binary to run our program. 12 | 13 | In our specific example, we see how to write a CLI tool in Kotlin/Native, but prepare an external library 14 | in Rust. The external library is responsible for unzipping the given file to a specific location. In Kotlin, 15 | we handle the rest of business logic, which (for the sake of simplicity) is just proper 16 | handling of program arguments and deleting some files, to see how the Kotlin/Native libraries can be used. 17 | 18 | ## Project configuration 19 | 20 | Let's start with having look at the project structure that's worth explaining what files 21 | and directories are responsible for which part of the project configuration. 22 | 23 | ``` 24 | ├── build.gradle.kts 25 | ├── gradle 26 | │   └── wrapper 27 | │   ├── gradle-wrapper.jar 28 | │   └── gradle-wrapper.properties 29 | ├── gradle.properties 30 | ├── gradlew 31 | ├── gradlew.bat 32 | ├── README.md 33 | ├── rust_lib 34 | │   ├── build.rs 35 | │   ├── Cargo.toml 36 | │   └── src 37 | │   └── lib.rs 38 | ├── settings.gradle.kts 39 | └── src 40 | ├── nativeInterop 41 | │   └── cinterop 42 | │   └── librust_lib.def 43 | └── nativeMain 44 | └── kotlin 45 | ├── Main.kt 46 | └── ReportedError.kt 47 | ``` 48 | 49 | ### Rust library 50 | 51 | First of all, we include the [rust_lib](./rust_lib) directory in our root. It contains the Rust project exporting static 52 | library. 53 | Its [Cargo.ml](./rust_lib/Cargo.toml) explicitly says that the build result is `staticlib`, for which release profile 54 | has multiple final binary size oriented optimizations enabled. It also declares two dependencies: 55 | 56 | - `zip` being our business-specific dependency that simplifies the implementation of unzipping files 57 | - `cbindgen` being must-have dependency, which is responsible for exporting the `.h` header file based on the 58 | definitions from our library. You 59 | can find a proper file [rust_lib.h](./rust_lib/target/rust_lib.h) after executing `buildRustLib` Gradle task. 60 | Additionally, in [build.rs](./rust_lib/build.rs) we include actual logics responsible for this process. 61 | 62 | The [lib.rs](./rust_lib/src/lib.rs) file contains, on the other hand, the actual definition of our 63 | exported library. We need to specify all the functions' symbols as `pub extern "C"` and add the 64 | `#[no_mangle]` macro to make them accessible via C ABI, as well as it's crucial to use a proper type 65 | for function arguments and returned value – they need to be compatible with the ones that C language would 66 | produce. 67 | 68 | That implies the proper conversion of arguments, to make them friendly to Rust. In our case we work 69 | with string values, which are passed as `char *out_path`. It's important to use `unsafe { CStr::from_ptr(chars) };` 70 | to convert them to `&str` – notice that using `unsafe { CString::from_raw(chars) };` is an incorrect approach as 71 | it leads to invalid free operation (we can find in `CString::from_raw` documentation that 72 | `If you need to borrow a string that was allocated by foreign code, use CStr.`) 73 | 74 | The final static library file, produced from our `rust_lib`, will be available in [release](./rust_lib/target/release) 75 | directory, and we're going to use it while compiling final binary, to find the symbols defined in 76 | header file. 77 | 78 | ### Gradle project 79 | 80 | We configure our root project with Gradle, using Kotlin Multiplatform Plugin to enable compilation to native 81 | targets. The main configuration file [build.gradle.kts](./build.gradle.kts) has a few, quite interesting definitions, 82 | that we've used to achieve our goal of building independent binary. 83 | 84 | We use `DefaultNativePlatform` helper to read current host OS and architecture and configure the 85 | compilation for our platform. Inside the `kotlin { ... }` block we configure the native target to 86 | `host` and then configure it inside the `target { ... }` block. There are two parts of the configuration that 87 | play the main role in our final result. 88 | 89 | The first part 90 | 91 | ```kotlin 92 | compilations.getByName("main").cinterops { 93 | create("librust_lib") { 94 | val buildRustLib by tasks.creating { 95 | exec { 96 | executable = cargoAbsolutePath 97 | args( 98 | "build", 99 | "--manifest-path", projectFile("rust_lib/Cargo.toml"), 100 | "--package", "rust_lib", 101 | "--lib", 102 | "--release" 103 | ) 104 | } 105 | } 106 | tasks.getByName(interopProcessingTaskName) { 107 | dependsOn(buildRustLib) 108 | } 109 | header(projectFile("rust_lib/target/rust_lib.h")) 110 | } 111 | } 112 | ``` 113 | 114 | is responsible for interoperability between Kotlin and C symbols. We create the `librust_lib` cinterop 115 | and configure the header location manually with `projectFile` function to get absolute path of the header, 116 | having the current location of project directory. Moreover, we add extra task named 117 | `buildRustLib`, which calls `cargo` command to build our Rust library before the cinterop task is executed. 118 | To make sure we have our header file available, we explicitly define the dependency on `interopProcessingTaskName`. 119 | It's worth mentioning here, that we include empty [librust_lib.def](./src/nativeInterop/cinterop/librust_lib.def) file 120 | in our project. It's required by project structure, as described in 121 | the [official documentation example](https://kotlinlang.org/docs/native-app-with-c-and-libcurl.html#add-interoperability-to-the-build-process). 122 | However, we want to define the required `header` relatively to project directory, and it seems that 123 | working and nice approach is to configure it directly in our build script. 124 | 125 | The second step — configuring final executable with 126 | 127 | ```kotlin 128 | binaries.executable { 129 | entryPoint = "main" 130 | baseName = "kotlin-tool" 131 | linkerOpts += rustLibAbsolutePath 132 | } 133 | ``` 134 | 135 | is essential to link our static library to the final compilation result from Kotlin. The value of `rustLibAbsolutePath` 136 | depends on current OS, as different systems support different types of static libraries. 137 | 138 | Additionally, we show how to add Kotlin/Native dependencies to some external libraries 139 | with source set dependencies as 140 | 141 | ```kotlin 142 | sourceSets { 143 | getByName("nativeMain").dependencies { 144 | implementation("org.jetbrains.kotlinx:kotlinx-io-core:0.3.0") 145 | } 146 | } 147 | ``` 148 | 149 | One last thing is including the definition of extra task named `binaries` to commonize 150 | the building process on all platforms. It calls the platform-specific task 151 | that builds the release and debug binaries for host architecture. 152 | 153 | ## Compilation 154 | 155 | We can easily compile the final binary by calling gradle task 156 | 157 | ```shell 158 | ./gradlew binaries 159 | ``` 160 | 161 | which produces `kotlin-tool` binary in a proper subdirectory of [bin](./build/bin/) build results. 162 | 163 | We can use it to unzip some zip file, just by passing our file's path as program argument. 164 | 165 | ## Conclusion 166 | 167 | Configuring the Kotlin/Native project in a basic scenario might not be so straightforward 168 | if we want to refer to some libraries built as a part of our project. Thanks to Gradle 169 | flexibility we can call `cargo`, build our Rust dependency and configure all the files 170 | relatively to our root project. In these few steps we get some reference project configuration 171 | that should work in most case and make our life simpler when we decide to build native binaries 172 | with Kotlin and glue them with some external Rust libraries. 173 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.nativeplatform.platform.internal.ArchitectureInternal 2 | import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform 3 | import org.gradle.nativeplatform.platform.internal.DefaultOperatingSystem 4 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetWithHostTests 5 | import java.lang.System.getenv 6 | 7 | plugins { 8 | kotlin("multiplatform") version "2.1.0" 9 | } 10 | 11 | group = "in.procyk" 12 | version = "1.0" 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | private val hostOs: DefaultOperatingSystem = DefaultNativePlatform.getCurrentOperatingSystem() 19 | private val hostArchitecture: ArchitectureInternal = DefaultNativePlatform.getCurrentArchitecture() 20 | 21 | private val exeExt: String get() = when { 22 | hostOs.isWindows -> ".exe" 23 | else -> "" 24 | } 25 | 26 | private val cargoAbsolutePath: String 27 | get() = when { 28 | hostOs.isWindows -> getenv("USERPROFILE") 29 | else -> getenv("HOME") 30 | } 31 | ?.let(::File) 32 | ?.resolve(".cargo/bin/cargo$exeExt") 33 | ?.takeIf { it.exists() } 34 | ?.absolutePath 35 | ?: throw GradleException("cargo binary is required to build project but it wasn't found") 36 | 37 | fun projectFile(path: String): String = projectDir.resolve(path).absolutePath 38 | 39 | private val rustLibAbsolutePath: String 40 | get() = projectFile( 41 | path = when { 42 | hostOs.isWindows -> "rust_lib/target/release/rust_lib.lib" 43 | else -> "rust_lib/target/release/librust_lib.a" 44 | } 45 | ) 46 | 47 | kotlin { 48 | applyDefaultHierarchyTemplate() 49 | 50 | val host = when { 51 | hostOs.isMacOsX && hostArchitecture.isAmd64 -> Host(macosX64()) 52 | hostOs.isMacOsX && hostArchitecture.isArm64 -> Host(macosArm64()) 53 | hostOs.isLinux && hostArchitecture.isAmd64 -> Host(linuxX64()) 54 | hostOs.isWindows && hostArchitecture.isAmd64 -> Host(mingwX64()) 55 | else -> throw GradleException("OS: $hostOs and architecture: $hostArchitecture is not supported in script configuration.") 56 | } 57 | tasks.create("binaries") { 58 | dependsOn("${host.targetName}Binaries") 59 | doLast { host.renameBinaries() } 60 | } 61 | host.target { 62 | compilations.getByName("main").cinterops { 63 | create("librust_lib") { 64 | val buildRustLib by tasks.creating { 65 | exec { 66 | executable = cargoAbsolutePath 67 | args( 68 | "build", 69 | "--manifest-path", projectFile("rust_lib/Cargo.toml"), 70 | "--package", "rust_lib", 71 | "--lib", 72 | "--release" 73 | ) 74 | } 75 | } 76 | tasks.getByName(interopProcessingTaskName) { 77 | dependsOn(buildRustLib) 78 | } 79 | packageName("librust_lib") 80 | header(projectFile("rust_lib/target/rust_lib.h")) 81 | } 82 | } 83 | binaries.executable { 84 | entryPoint = "main" 85 | baseName = "kotlin-tool" 86 | linkerOpts += rustLibAbsolutePath 87 | } 88 | } 89 | sourceSets { 90 | getByName("nativeMain").dependencies { 91 | implementation("org.jetbrains.kotlinx:kotlinx-io-core:0.6.0") 92 | } 93 | } 94 | } 95 | 96 | class Host( 97 | private val target: KotlinNativeTargetWithHostTests, 98 | ) { 99 | val targetName: String get() = target.targetName 100 | 101 | fun target(configure: KotlinNativeTargetWithHostTests.() -> Unit): Unit = target.run(configure) 102 | 103 | fun renameBinaries() { 104 | project.buildDir.resolve("bin/${target.name}").walkTopDown().forEach rename@{ 105 | if (it.extension != "kexe") return@rename 106 | val renamed = it.parentFile.resolve(it.nameWithoutExtension + exeExt) 107 | it.renameTo(renamed) 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | #Gradle 2 | org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\="-Xmx2048M" 3 | 4 | #Kotlin 5 | kotlin.code.style=official 6 | 7 | kotlin.native.cacheKind.mingwX64=none 8 | kotlin.native.cacheKind.linuxX64=none 9 | kotlin.native.cacheKind.macosX64=none 10 | kotlin.native.cacheKind.macosArm64=none 11 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/avan1235/kotlin-native-rust-interop/d0626e07b3a2b08fc2293bf4f4ce1f152a06c857/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /rust_lib/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /rust_lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_lib" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | crate-type = ["staticlib"] 8 | 9 | [profile.release] 10 | opt-level = "z" 11 | strip = true 12 | lto = true 13 | codegen-units = 1 14 | panic = "abort" 15 | 16 | [dependencies] 17 | zip = "2.2.2" 18 | 19 | [build-dependencies] 20 | cbindgen = "0.26.0" 21 | -------------------------------------------------------------------------------- /rust_lib/build.rs: -------------------------------------------------------------------------------- 1 | extern crate cbindgen; 2 | 3 | use std::env; 4 | 5 | fn main() { 6 | let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); 7 | let mut config: cbindgen::Config = Default::default(); 8 | config.language = cbindgen::Language::C; 9 | cbindgen::generate_with_config(&crate_dir, config) 10 | .unwrap() 11 | .write_to_file("target/rust_lib.h"); 12 | } 13 | -------------------------------------------------------------------------------- /rust_lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{c_char, c_int, CStr}; 2 | use std::fs; 3 | use std::io; 4 | use std::path::Path; 5 | 6 | pub const OK: c_int = 0; 7 | pub const FILE_OPEN_ERROR: c_int = 1; 8 | pub const CREATE_FILE_ERROR: c_int = 2; 9 | pub const SET_PERMISSION_ERROR: c_int = 3; 10 | pub const ZIP_ERROR: c_int = 4; 11 | pub const INVALID_STRING_CONVERSION_ERROR: c_int = 5; 12 | 13 | #[no_mangle] 14 | pub extern "C" fn unzip(in_path: *mut c_char, out_path: *mut c_char) -> c_int { 15 | match unzip_impl(in_path, out_path) { 16 | Ok(_) => OK, 17 | Err(code) => code 18 | } 19 | } 20 | 21 | type ResultExitCode = Result; 22 | 23 | fn unzip_impl(in_path: *mut c_char, out_path: *mut c_char) -> ResultExitCode<()> { 24 | let in_path = c_chars_to_path(in_path)?; 25 | let out_path = c_chars_to_path(out_path)?; 26 | let file = fs::File::open(in_path).map_err(|_| FILE_OPEN_ERROR)?; 27 | 28 | let mut archive = zip::ZipArchive::new(file).map_err(|_| ZIP_ERROR)?; 29 | 30 | for i in 0..archive.len() { 31 | let mut file = archive.by_index(i).map_err(|_| ZIP_ERROR)?; 32 | let out_path = match file.enclosed_name() { 33 | Some(path) => out_path.join(path).to_owned(), 34 | None => continue, 35 | }; 36 | 37 | if (*file.name()).ends_with('/') { 38 | fs::create_dir_all(&out_path).map_err(|_| CREATE_FILE_ERROR)?; 39 | } else { 40 | if let Some(p) = out_path.parent() { 41 | if !p.exists() { 42 | fs::create_dir_all(p).map_err(|_| CREATE_FILE_ERROR)?; 43 | } 44 | } 45 | let mut outfile = fs::File::create(&out_path).map_err(|_| CREATE_FILE_ERROR)?; 46 | io::copy(&mut file, &mut outfile).map_err(|_| CREATE_FILE_ERROR)?; 47 | } 48 | 49 | #[cfg(unix)] 50 | { 51 | use std::os::unix::fs::PermissionsExt; 52 | 53 | if let Some(mode) = file.unix_mode() { 54 | let permissions = fs::Permissions::from_mode(mode); 55 | fs::set_permissions(&out_path, permissions).map_err(|_| SET_PERMISSION_ERROR)?; 56 | } 57 | } 58 | } 59 | Ok(()) 60 | } 61 | 62 | fn c_chars_to_path<'a>(chars: *mut c_char) -> ResultExitCode<&'a Path> { 63 | let c_str = unsafe { CStr::from_ptr(chars) }; 64 | let str = c_str.to_str().map_err(|_| INVALID_STRING_CONVERSION_ERROR)?; 65 | Ok(Path::new(str)) 66 | } 67 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenCentral() 4 | gradlePluginPortal() 5 | } 6 | } 7 | 8 | rootProject.name = "kotlin-native-rust" -------------------------------------------------------------------------------- /src/nativeMain/kotlin/Main.kt: -------------------------------------------------------------------------------- 1 | import ReportedError.* 2 | import ReportedError.Companion.runReportingErrors 3 | import ReportedError.Companion.checkExitCode 4 | import kotlinx.cinterop.ExperimentalForeignApi 5 | import kotlinx.cinterop.cstr 6 | import kotlinx.io.files.Path 7 | import kotlinx.io.files.SystemFileSystem 8 | import librust_lib.unzip 9 | 10 | @OptIn(ExperimentalForeignApi::class) 11 | fun main(args: Array) = runReportingErrors { 12 | val inputFile = args.singleOrNull() ?: InvalidArgs.exit() 13 | 14 | if (!inputFile.endsWith(".zip")) InputFileNotZip.exit() 15 | 16 | val inputFilePath = Path(inputFile) 17 | if (!SystemFileSystem.exists(inputFilePath)) InputFileNotExists.exit() 18 | 19 | val inputFilePathParent = inputFilePath.parent ?: InputFileParentNotExists.exit() 20 | 21 | val inputPath = inputFilePath.toString() 22 | val outputPath = inputFilePathParent.toString() 23 | unzip(inputPath.cstr, outputPath.cstr).checkExitCode() 24 | } 25 | -------------------------------------------------------------------------------- /src/nativeMain/kotlin/ReportedError.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.cinterop.ExperimentalForeignApi 2 | import librust_lib.* 3 | import kotlin.system.exitProcess 4 | 5 | enum class ReportedError(private val message: String) { 6 | InvalidArgs("invalid arguments"), 7 | InputFileNotZip("input file is not a zip file"), 8 | InputFileNotExists("input file doesn't exist"), 9 | InputFileParentNotExists("input file parent doesn't exist"), 10 | FileOpenError("cannot open file"), 11 | FileCreateError("cannot create file"), 12 | FileSetPermissionError("cannot set permission on file"), 13 | ZipError("error when processing zip"), 14 | UnknownError("unknown error"), 15 | ; 16 | 17 | fun exit(): Nothing = throw ReportedErrorException(this) 18 | 19 | val status: Int get() = ordinal + 1 20 | 21 | companion object { 22 | private class ReportedErrorException(val error: ReportedError) : Exception(error.message) 23 | 24 | fun runReportingErrors(action: () -> Unit) { 25 | try { 26 | action() 27 | } catch (e: ReportedErrorException) { 28 | val error = e.error 29 | println("Error: ${error.message}") 30 | exitProcess(error.status) 31 | } 32 | } 33 | 34 | @OptIn(ExperimentalForeignApi::class) 35 | fun Int.checkExitCode(): Unit = when (this) { 36 | OK -> Unit 37 | FILE_OPEN_ERROR -> FileOpenError.exit() 38 | CREATE_FILE_ERROR -> FileCreateError.exit() 39 | SET_PERMISSION_ERROR -> FileSetPermissionError.exit() 40 | ZIP_ERROR -> ZipError.exit() 41 | INVALID_STRING_CONVERSION_ERROR -> UnknownError.exit() 42 | else -> UnknownError.exit() 43 | } 44 | } 45 | } 46 | --------------------------------------------------------------------------------