├── .gitignore ├── .gitmodules ├── LICENCE ├── build.gradle.kts ├── build.zig ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── readme.md ├── settings.gradle.kts └── src ├── main ├── java │ └── oolloo │ │ └── jlw │ │ ├── ArgParser.java │ │ ├── CimCommandLineLoader.java │ │ ├── ClassPathInjector.java │ │ ├── CommandLineLoader.java │ │ ├── NativeCommandLineLoader.java │ │ └── Wrapper.java └── zig │ └── wrapper.zig └── test └── java └── Test.java /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | /zig-cache/ 7 | /.zig-cache/ 8 | /zig-out/ 9 | /src/main/resources/ 10 | 11 | ### IntelliJ IDEA ### 12 | /.idea/ 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 44 | /cmake-build-debug/ 45 | /cmake-build-release/ 46 | /src/main/resources/libwrapper.dll 47 | /logs/ 48 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/jui"] 2 | path = lib/jui 3 | url = git@github.com:00ll00/jui.git 4 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 00ll00 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("java") 3 | } 4 | 5 | group = "oolloo" 6 | version = "1.4.3" 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | java { 13 | sourceCompatibility = JavaVersion.VERSION_1_6 14 | targetCompatibility = JavaVersion.VERSION_1_6 15 | } 16 | 17 | tasks.register("zigBuild") { 18 | mustRunAfter("clearLibs") 19 | commandLine("zig", "build", "--release=fast") 20 | } 21 | 22 | tasks.register("copyLibs") { 23 | mustRunAfter("zigBuild") 24 | from("zig-out/bin") 25 | include("**/*.dll") 26 | into("src/main/resources") 27 | } 28 | 29 | tasks.findByPath(":processResources")?.mustRunAfter("copyLibs") 30 | 31 | tasks.register("clearLibs") { 32 | delete("zig-out/lib", "zig-out/bin", "src/main/resources") 33 | } 34 | 35 | tasks.findByPath(":clean")?.dependsOn("clearLibs") 36 | 37 | tasks.jar { 38 | 39 | dependsOn("clearLibs", "zigBuild", "copyLibs") 40 | 41 | manifest { 42 | attributes ( mapOf ( 43 | "Main-Class" to "oolloo.jlw.Wrapper", 44 | "Add-Opens" to "java.base/jdk.internal.loader" 45 | ) ) 46 | } 47 | } -------------------------------------------------------------------------------- /build.zig: -------------------------------------------------------------------------------- 1 | //! zig version: 0.13.0 2 | 3 | const std = @import("std"); 4 | const Arch = std.Target.Cpu.Arch; 5 | 6 | const NATIVE_VERSION = "1.4.3"; 7 | 8 | const TARGET_ARCH = [_]Arch{ 9 | .x86, 10 | .x86_64, 11 | .aarch64, 12 | }; 13 | 14 | pub fn build(b: *std.Build) void { 15 | const optimize = b.standardOptimizeOption(.{}); 16 | 17 | const jui = b.createModule(.{ 18 | .root_source_file = b.path("lib/jui/src/jui.zig"), 19 | }); 20 | 21 | inline for (TARGET_ARCH) |arch| { 22 | const target = std.Target.Query{ .cpu_arch = arch, .os_tag = .windows, .abi = .msvc }; 23 | const lib = b.addSharedLibrary(.{ 24 | .name = "libjlw-" ++ @tagName(arch) ++ "-" ++ NATIVE_VERSION, 25 | .root_source_file = b.path("src/main/zig/wrapper.zig"), 26 | .target = b.resolveTargetQuery(target), 27 | .optimize = optimize, 28 | }); 29 | lib.root_module.addImport("jui", jui); 30 | b.installArtifact(lib); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/00ll00/java_launch_wrapper/05e78723cca4f14567062b44e061956d0a85c2be/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-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Java Launch Wrapper (v1.4.3) 2 | 3 | ## 有什么用? 4 | 5 | 如果你的 Windows 系统启用了 *Beta 版:使用Unicode UTF-8提供全球语言支持*,Java 可能会在读取命令行参数时使用错误的编码进行解码,导致一系列问题。 6 | 7 | Bug 参考 [JDK-8272352](https://bugs.openjdk.org/browse/JDK-8272352),已在 Java19 修复 8 | 9 | 使用此 Wrapper 可用于修复 **Class Path**, **-D 参数** 和 **App 参数** 中的乱码,解决大部分因此Bug无法运行的情况。 10 | 11 | ## 怎么用? 12 | 13 | 更改 Java 启动命令行,在 JVM 参数和主类之间插入`-jar java_launch_wrapper.jar`即可(需要 Java >= 1.6)。 14 | 15 | 例如: 16 | 17 | > 原命令行: 18 | > 19 | > java -cp "路径1";"路径2" MainClass 参数1 参数2 20 | > 21 | > 更改后: 22 | > 23 | > java -cp "路径1";"路径2" -jar "java_launch_wrapper.jar" MainClass 参数1 参数2 24 | 25 | **注意:** 26 | 27 | 1. 除`-jar`外原命令中的其他 jvm 选项可以直接保留,若原命令行中使用`-jar`则应该改为 ClassPath + MainClass 的形式。 28 | 2. Wrapper 会将动态链接库释放到系统临时目录,若系统的临时文件路径中也存在特殊字符,可以在 -jar 前添加 `-Doolloo.jlw.tmpdir="<自定义临时文件路径>"` 更改。 29 | 在这种情况下需要保证此路径存在且无特殊字符。 30 | 3. 仅在 Windows 平台可用,因为这个 Bug 是 Windows 独家。 31 | 32 | --- 33 | 34 | ## 更新记录 35 | 36 | ### V1.4 37 | 38 | - 修复未捕获`UnsatisfiedLinkError`未被捕获导致备用方案未被使用的问题 39 | - 支持 arm64 以及其他无法正确加载 native 库的情况(使用 powershell CIM cmdlet) 40 | - 解析 `-D 参数` 并覆盖到 JVM 的 System.Properties 41 | - 使用 zig 编译 native 库,去除无关依赖,减小库体积 42 | - 移除 dll 文件的 crc 校验 43 | - 移除 `-Doolloo.jlw.silent` 选项,改为设置 `-Doolloo.jlw.debug=true` 启用 wrapper 调试信息 44 | 45 | ### V1.3 46 | 47 | - 增加修改临时文件路径的启动参数 48 | - 修复 dll 被占用导致无法启动多个进程的问题 49 | - 增加 dll 文件校验 50 | - 增加必要的调试信息输出,可设置 `-Doolloo.jlw.silent=true` 关闭 51 | 52 | ### V1.2 53 | 54 | - 修复对std库的依赖问题 55 | - 修复字符编码问题 56 | - 将获取到的classpath写入jvm系统属性`java.class.path`以确保被包装应用能读取到正确的值 57 | 58 | ### V1.1 59 | 60 | - 修复对 Java9 - Java15 的支持。 61 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "java_launch_wrapper" 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/oolloo/jlw/ArgParser.java: -------------------------------------------------------------------------------- 1 | package oolloo.jlw; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class ArgParser { 6 | 7 | static String[] parse(String commandLine) { 8 | int pos = 0; 9 | int length = commandLine.length(); 10 | 11 | StringBuilder sb = new StringBuilder(); 12 | 13 | char[] chars = commandLine.toCharArray(); 14 | ArrayList res = new ArrayList(); 15 | 16 | boolean inStr = false; 17 | 18 | // TODO 19 | while (pos < length) { 20 | char c = chars[pos++]; 21 | switch (c) { 22 | case ' ': 23 | case '\t': 24 | if (inStr) { 25 | sb.append(c); 26 | } else if (sb.length() > 0) { 27 | res.add(sb.toString()); 28 | sb = new StringBuilder(); 29 | } 30 | break; 31 | case '\\': 32 | if (pos < length && (chars[pos] == '"' || chars[pos] == '\\')) { 33 | sb.append(chars[pos]); 34 | pos ++; 35 | } else { 36 | sb.append(c); 37 | } 38 | break; 39 | case '"': 40 | inStr = !inStr; 41 | break; 42 | default: 43 | sb.append(c); 44 | } 45 | } 46 | if (sb.length() > 0) { 47 | res.add(sb.toString()); 48 | } 49 | return res.toArray(new String[0]); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/oolloo/jlw/CimCommandLineLoader.java: -------------------------------------------------------------------------------- 1 | package oolloo.jlw; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | 6 | public class CimCommandLineLoader implements CommandLineLoader { 7 | 8 | @Override 9 | public String load() throws Exception { 10 | 11 | Process ps = Runtime.getRuntime().exec( 12 | "powershell -command \"(Get-CimInstance -classname win32_process -filter \"processid=$((Get-CimInstance -classname win32_process -filter \"processid=$PID\").parentprocessid)\").commandline\"" 13 | ); 14 | BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); 15 | return br.readLine(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/oolloo/jlw/ClassPathInjector.java: -------------------------------------------------------------------------------- 1 | package oolloo.jlw; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.InvocationTargetException; 6 | import java.lang.reflect.Method; 7 | import java.net.MalformedURLException; 8 | import java.net.URL; 9 | import java.net.URLClassLoader; 10 | 11 | public class ClassPathInjector { 12 | 13 | private static final int JAVA_VER; 14 | 15 | static { 16 | String ver = System.getProperty("java.specification.version"); 17 | int pos = ver.indexOf('.'); 18 | if (pos == -1) { 19 | JAVA_VER = Integer.parseInt(ver); 20 | } else { 21 | JAVA_VER = Integer.parseInt(ver.substring(pos + 1)); 22 | } 23 | } 24 | 25 | public static void appendClassPath(String path) throws MalformedURLException, InvocationTargetException, NoSuchMethodException, IllegalAccessException, ClassNotFoundException, NoSuchFieldException { 26 | if (JAVA_VER <= 8) { 27 | appendClassPath8(path); 28 | } else { 29 | appendClassPath9(path); 30 | } 31 | } 32 | 33 | private static void appendClassPath8(String path) throws NoSuchMethodException, MalformedURLException, InvocationTargetException, IllegalAccessException { 34 | URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); 35 | Method add = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); 36 | add.setAccessible(true); 37 | add.invoke(classLoader, new File(path).toURI().toURL()); 38 | } 39 | 40 | private static void appendClassPath9(String path) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, MalformedURLException, InvocationTargetException { 41 | ClassLoader classLoader = ClassLoader.getSystemClassLoader(); 42 | Class clazz = classLoader.loadClass("jdk.internal.loader.BuiltinClassLoader"); 43 | Class ucpCls = classLoader.loadClass("jdk.internal.loader.URLClassPath"); 44 | Field ucp = clazz.getDeclaredField("ucp"); 45 | ucp.setAccessible(true); 46 | Method add = ucpCls.getDeclaredMethod("addURL", URL.class); 47 | add.setAccessible(true); 48 | add.invoke(ucp.get(classLoader), new File(path).toURI().toURL()); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/oolloo/jlw/CommandLineLoader.java: -------------------------------------------------------------------------------- 1 | package oolloo.jlw; 2 | 3 | public interface CommandLineLoader { 4 | 5 | String load() throws Exception; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/oolloo/jlw/NativeCommandLineLoader.java: -------------------------------------------------------------------------------- 1 | package oolloo.jlw; 2 | 3 | import java.io.*; 4 | 5 | public class NativeCommandLineLoader implements CommandLineLoader { 6 | 7 | private static native String getCommandLine(); 8 | 9 | private static void loadNative() throws Exception { 10 | 11 | String os_arch = System.getProperty("os.arch"); 12 | String arch; 13 | 14 | if (os_arch.equals("x86") || os_arch.equals("i386")) { 15 | arch = "x86"; 16 | } else if (os_arch.equals("x86_64") || os_arch.equals("amd64")) { 17 | arch = "x86_64"; 18 | } else if (os_arch.equals("aarch64") || os_arch.equals("arm64")) { 19 | arch = "aarch64"; 20 | } else { 21 | throw new Exception("unknown os.arch: " + os_arch); 22 | } 23 | 24 | String lib_name = "libjlw-" + arch + "-" + Wrapper.NATIVE_VERSION + ".dll"; 25 | 26 | File tmp_dir = new File(System.getProperty("oolloo.jlw.tmpdir", System.getProperty("java.io.tmpdir", "."))); 27 | if (!tmp_dir.exists()) { 28 | tmp_dir = new File("."); 29 | } 30 | 31 | File lib = new File(tmp_dir, lib_name); 32 | 33 | if (lib.exists()) { 34 | Wrapper.debug(String.format("native file exists: '%s'.", lib.getAbsolutePath())); 35 | if (Wrapper.DEBUG) { 36 | Wrapper.debug("delete old native file."); 37 | if (!lib.delete()) throw new Exception(); 38 | } else { 39 | try { 40 | System.load(lib.getAbsolutePath()); 41 | return; // existing file is ok 42 | } catch (UnsatisfiedLinkError ignored) { 43 | Wrapper.debug(String.format("existing native file '%s' failed to load, trying to overwrite.", lib.getAbsolutePath())); 44 | } 45 | } 46 | } 47 | 48 | // release dll file 49 | Wrapper.debug(String.format("releasing native file to '%s'.", lib.getAbsolutePath())); 50 | 51 | InputStream is = NativeCommandLineLoader.class.getResourceAsStream("/" + lib_name); 52 | assert is != null; 53 | 54 | FileOutputStream os = new FileOutputStream(lib); 55 | 56 | try { 57 | byte[] buffer = new byte[1024]; 58 | int len; 59 | while ((len = is.read(buffer)) != -1) { 60 | os.write(buffer, 0, len); 61 | } 62 | } catch (IOException e) { 63 | throw new RuntimeException(e); 64 | } finally { 65 | is.close(); 66 | os.close(); 67 | } 68 | 69 | System.load(lib.getAbsolutePath()); 70 | } 71 | 72 | @Override 73 | public String load() throws Exception { 74 | 75 | loadNative(); 76 | Wrapper.debug("native file loaded."); 77 | 78 | return getCommandLine(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/oolloo/jlw/Wrapper.java: -------------------------------------------------------------------------------- 1 | package oolloo.jlw; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | import java.util.Arrays; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | import static java.lang.System.arraycopy; 11 | 12 | public class Wrapper { 13 | 14 | static final String NATIVE_VERSION = "1.4.3"; 15 | 16 | static final boolean DEBUG = System.getProperty("oolloo.jlw.debug", "").equals("true"); 17 | 18 | public static void main(String[] originArgs) throws Throwable { 19 | 20 | if (DEBUG) { 21 | debug("===== Origin ====="); 22 | debug(String.format("App Arguments: %s", Arrays.toString(originArgs))); 23 | debug("System Properties:"); 24 | 25 | Set> s = System.getProperties().entrySet(); 26 | 27 | for (Map.Entry e : s) { 28 | debug(String.format(" %s", e)); 29 | } 30 | 31 | debug("===================="); 32 | } 33 | 34 | String commandLine; 35 | 36 | try { 37 | commandLine = new NativeCommandLineLoader().load(); 38 | } catch (Throwable e1) { 39 | // Additionally captures UnsatisfiedLinkError. 40 | if (e1 instanceof Error && !(e1 instanceof UnsatisfiedLinkError)) throw e1; 41 | debug("native command line loader failed with exception:"); 42 | debug(e1.getMessage()); 43 | debug("try cim command line loader."); 44 | try { 45 | commandLine = new CimCommandLineLoader().load(); 46 | } catch (Exception e2) { 47 | debug("cim command line loader failed with exception:"); 48 | debug(e2.getMessage()); 49 | throw new Exception("All CommandLine Loaders Failed."); 50 | } 51 | } 52 | 53 | debug(String.format("got command line: %s", commandLine)); 54 | 55 | String[] args = ArgParser.parse(commandLine); 56 | 57 | debug(String.format("got raw args: %s", Arrays.toString(args))); 58 | 59 | int pos = 1; 60 | final int len = args.length; 61 | String clazzMain = null; 62 | String[] argsOut = null; 63 | do { 64 | String flag = args[pos++]; 65 | String arg = ""; 66 | if (flag.charAt(0) == '-') { 67 | int eqPos = flag.indexOf('='); 68 | if (eqPos > -1) { 69 | arg = flag.substring(eqPos + 1); 70 | flag = flag.substring(0, eqPos); 71 | } else if (args[pos].charAt(0) != '-') { 72 | arg = args[pos]; 73 | } 74 | if (flag.startsWith("-D")) { 75 | System.setProperty(flag.substring(2), arg); 76 | } else if ("-cp".equals(flag) || "--classpath".equals(flag) || "--class-path".equals(flag)) { 77 | System.setProperty("java.class.path", arg); 78 | for (String path : arg.split(File.pathSeparator)) ClassPathInjector.appendClassPath(path); 79 | } else if ("-jar".equals(flag)) { 80 | pos++; 81 | clazzMain = args[pos++]; 82 | int lenOut = len - pos; 83 | argsOut = new String[lenOut]; 84 | arraycopy(args, pos, argsOut, 0, lenOut); 85 | pos = len; 86 | } 87 | } 88 | } while (pos < len); 89 | 90 | if (DEBUG) { 91 | debug("===== Injected ====="); 92 | debug(String.format("Main Class: %s", clazzMain)); 93 | debug(String.format("App Arguments: %s", Arrays.toString(argsOut))); 94 | debug("System Properties:"); 95 | 96 | Set> s = System.getProperties().entrySet(); 97 | 98 | for (Map.Entry e : s) { 99 | debug(String.format(" %s", e)); 100 | } 101 | 102 | debug("===================="); 103 | } 104 | 105 | invokeMain(clazzMain, argsOut); 106 | } 107 | 108 | private static void invokeMain(String mainClass, String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { 109 | Class clazz = ClassLoader.getSystemClassLoader().loadClass(mainClass); 110 | Method main = clazz.getDeclaredMethod("main", String[].class); 111 | main.setAccessible(true); 112 | main.invoke(null, (Object) args); 113 | } 114 | 115 | static void debug(String msg) { 116 | if (DEBUG) System.out.println("jlw: " + msg); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/zig/wrapper.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const mem = std.mem; 3 | const k32 = std.os.windows.kernel32; 4 | const jui = @import("jui"); 5 | 6 | const jstring = jui.jstring; 7 | const jchar = jui.jchar; 8 | const jobject = jui.jobject; 9 | const JNIEnv = jui.JNIEnv; 10 | 11 | fn getCommandLine(jenv: *JNIEnv) !jstring { 12 | const cmd_line_w = k32.GetCommandLineW(); 13 | const utf16le_slice = mem.sliceTo(cmd_line_w, 0); 14 | return try jenv.newString(utf16le_slice); 15 | } 16 | 17 | comptime { 18 | const javaGetCommandLine = struct { 19 | fn inner(jenv: *JNIEnv, _: jobject) callconv(jui.JNICALL) jstring { 20 | return jui.wrapErrors(getCommandLine, .{jenv}); 21 | } 22 | }.inner; 23 | 24 | jui.exportAs("oolloo.jlw.NativeCommandLineLoader.getCommandLine", javaGetCommandLine); 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | 3 | public static void main(String[] args) { 4 | for (String arg: args) { 5 | System.out.println(arg); 6 | } 7 | } 8 | } 9 | --------------------------------------------------------------------------------