added files.
This commit is contained in:
commit
b9a4fa717b
84 files changed
+7967
No files matched your search
+14
@@ -0,0 +1,14 @@
|
|||||||
|
.gradle/
|
||||||
|
build/
|
||||||
|
out/
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
.settings/
|
||||||
|
*.BACKUP
|
||||||
|
*.log
|
||||||
|
out.jar
|
||||||
|
*-out.jar
|
||||||
|
demo-out.jar
|
||||||
|
jnic-sources/
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<p align="center">
|
||||||
|
<img src="assets/ss.png" alt="Skid Solutions Banner" width="350" />
|
||||||
|
<br><br>
|
||||||
|
<a href="https://discord.gg/skidsolutions">
|
||||||
|
<img src="https://img.shields.io/badge/Discord-Skid%20Solutions-18181b?style=for-the-badge&logo=discord&logoColor=ffffff&labelColor=09090b" alt="Discord" />
|
||||||
|
</a>
|
||||||
|
<img src="https://img.shields.io/badge/Version-3.7.0-27272a?style=for-the-badge&labelColor=09090b" alt="Version 3.7.0" />
|
||||||
|
<img src="https://img.shields.io/badge/Java-17-3f3f46?style=for-the-badge&logo=openjdk&logoColor=ffffff&labelColor=09090b" alt="Java 17" />
|
||||||
|
<img src="https://img.shields.io/badge/Gradle-8.14.3-52525b?style=for-the-badge&logo=gradle&logoColor=ffffff&labelColor=09090b" alt="Gradle 8.14.3" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://discord.gg/skidsolutions">https://discord.gg/skidsolutions</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/divider.svg" alt="" width="720" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/jak.jpg" alt="jak" height="150" />
|
||||||
|
<img src="assets/hack.jpg" alt="hack" height="150" />
|
||||||
|
<img src="assets/deobf2.png" alt="deobf2" height="150" />
|
||||||
|
<img src="assets/deobf.jpg" alt="deobf" height="150" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/divider.svg" alt="" width="720" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## How to build
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
- **Java Development Kit**: JDK 17 (the Gradle wrapper 8.14.3 does not run on newer JDKs)
|
||||||
|
|
||||||
|
### Building OpenJNIC
|
||||||
|
|
||||||
|
Run from this folder:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:JAVA_HOME = "C:\Program Files\Java\jdk-17"
|
||||||
|
|
||||||
|
.\gradlew.bat clean build
|
||||||
|
```
|
||||||
|
|
||||||
|
Generated `build/libs/`:
|
||||||
|
- `OpenJNIC-3.7.0.jar`
|
||||||
|
- `OpenJNIC-3.7.0-sources.jar`
|
||||||
|
|
||||||
|
### Running
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
java -jar build\libs\OpenJNIC-3.7.0.jar <inputJAR> <outputJAR> <configFile> [-debug]
|
||||||
|
```
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 135 KiB |
@@ -0,0 +1,26 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 820 20" width="820" height="20" role="img" aria-hidden="true">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="baseLine" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#000000" stop-opacity="0" />
|
||||||
|
<stop offset="25%" stop-color="#404040" stop-opacity="0.7" />
|
||||||
|
<stop offset="50%" stop-color="#d4d4d4" stop-opacity="0.95" />
|
||||||
|
<stop offset="75%" stop-color="#404040" stop-opacity="0.7" />
|
||||||
|
<stop offset="100%" stop-color="#000000" stop-opacity="0" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="pulse" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#ffffff" stop-opacity="0" />
|
||||||
|
<stop offset="50%" stop-color="#ffffff" stop-opacity="1" />
|
||||||
|
<stop offset="100%" stop-color="#ffffff" stop-opacity="0" />
|
||||||
|
</linearGradient>
|
||||||
|
<clipPath id="lineClip">
|
||||||
|
<rect x="40" y="8" width="740" height="4" rx="2" />
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<rect x="40" y="9.25" width="740" height="1.5" rx="0.75" fill="url(#baseLine)" />
|
||||||
|
<g clip-path="url(#lineClip)">
|
||||||
|
<rect x="-120" y="8.5" width="140" height="3" rx="1.5" fill="url(#pulse)">
|
||||||
|
<animate attributeName="x" values="-120;820" dur="3.4s" repeatCount="indefinite" />
|
||||||
|
</rect>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 323 KiB |
+106
@@ -0,0 +1,106 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java'
|
||||||
|
id 'application'
|
||||||
|
id 'idea'
|
||||||
|
id 'eclipse'
|
||||||
|
}
|
||||||
|
|
||||||
|
group = 'dev.jnic'
|
||||||
|
version = '3.7.0'
|
||||||
|
|
||||||
|
def javaVersion = 17
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation 'org.ow2.asm:asm:9.11.1'
|
||||||
|
implementation 'org.ow2.asm:asm-tree:9.11.1'
|
||||||
|
implementation 'org.ow2.asm:asm-analysis:9.11.1'
|
||||||
|
implementation 'org.tukaani:xz:1.9'
|
||||||
|
implementation('org.simpleframework:simple-xml:2.7.1') {
|
||||||
|
exclude group: 'stax', module: 'stax-api'
|
||||||
|
exclude group: 'stax', module: 'stax'
|
||||||
|
exclude group: 'xpp3', module: 'xpp3'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain {
|
||||||
|
languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
}
|
||||||
|
withSourcesJar()
|
||||||
|
}
|
||||||
|
|
||||||
|
application {
|
||||||
|
applicationName = 'OpenJNIC'
|
||||||
|
mainClass = 'dev.jnic.JnicMain'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.release = javaVersion
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
options.compilerArgs += ['-parameters', '-Xlint:none', '-Xmaxerrs', '4096']
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(JavaExec).configureEach {
|
||||||
|
javaLauncher = javaToolchains.launcherFor {
|
||||||
|
languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(AbstractArchiveTask).configureEach {
|
||||||
|
preserveFileTimestamps = false
|
||||||
|
reproducibleFileOrder = true
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('jar', Jar) {
|
||||||
|
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||||
|
manifest {
|
||||||
|
attributes(
|
||||||
|
'Main-Class': 'dev.jnic.JnicMain',
|
||||||
|
'Implementation-Title': 'OpenJNIC',
|
||||||
|
'Implementation-Version': project.version)
|
||||||
|
}
|
||||||
|
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA'
|
||||||
|
from {
|
||||||
|
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register('translate', JavaExec) {
|
||||||
|
group = 'application'
|
||||||
|
description = 'Translates a jar: -Pinput=<in.jar> -Poutput=<out.jar> [-Pconfig=<file>] [-Pdebug]'
|
||||||
|
classpath = sourceSets.main.runtimeClasspath
|
||||||
|
mainClass = 'dev.jnic.JnicMain'
|
||||||
|
|
||||||
|
def inputJar = providers.gradleProperty('input')
|
||||||
|
def outputJar = providers.gradleProperty('output')
|
||||||
|
def configFile = providers.gradleProperty('config').orElse('config.xml')
|
||||||
|
|
||||||
|
doFirst {
|
||||||
|
if (!inputJar.isPresent() || !outputJar.isPresent()) {
|
||||||
|
throw new GradleException('translate needs -Pinput=<in.jar> and -Poutput=<out.jar>')
|
||||||
|
}
|
||||||
|
def cli = [inputJar.get(), outputJar.get(), configFile.get()]
|
||||||
|
if (project.hasProperty('debug')) {
|
||||||
|
cli << '-debug'
|
||||||
|
}
|
||||||
|
setArgs(cli)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idea {
|
||||||
|
module {
|
||||||
|
downloadSources = true
|
||||||
|
downloadJavadoc = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
eclipse {
|
||||||
|
classpath {
|
||||||
|
downloadSources = true
|
||||||
|
downloadJavadoc = true
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
<jnic>
|
||||||
|
<options>
|
||||||
|
<stringObf>true</stringObf>
|
||||||
|
<flowObf>true</flowObf>
|
||||||
|
<nativeIntegrity>true</nativeIntegrity>
|
||||||
|
<jarIntegrity>true</jarIntegrity>
|
||||||
|
<antiDebug>true</antiDebug>
|
||||||
|
<useIntrinsics>true</useIntrinsics>
|
||||||
|
<fastCompile>true</fastCompile>
|
||||||
|
</options>
|
||||||
|
<targets>
|
||||||
|
<target>WINDOWS_X86_64</target>
|
||||||
|
</targets>
|
||||||
|
<include>
|
||||||
|
<match>
|
||||||
|
<className>.*</className>
|
||||||
|
<methodName>.*</methodName>
|
||||||
|
<methodDesc>.*</methodDesc>
|
||||||
|
</match>
|
||||||
|
</include>
|
||||||
|
<exclude>
|
||||||
|
<match>
|
||||||
|
<className>.*\$.*</className>
|
||||||
|
<methodName>.*</methodName>
|
||||||
|
<methodDesc>.*</methodDesc>
|
||||||
|
</match>
|
||||||
|
</exclude>
|
||||||
|
</jnic>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
|
||||||
|
org.gradle.parallel=true
|
||||||
|
org.gradle.caching=true
|
||||||
Vendored
BIN
Binary file not shown.
+8
@@ -0,0 +1,8 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
|
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH="\\\"\\\""
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+94
@@ -0,0 +1,94 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rootProject.name = 'OpenJNIC'
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
package dev.jnic;
|
||||||
|
|
||||||
|
import dev.jnic.pipeline.Options;
|
||||||
|
import dev.jnic.pipeline.Rewriter;
|
||||||
|
import dev.jnic.util.Log;
|
||||||
|
import java.io.BufferedInputStream;
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import javax.xml.XMLConstants;
|
||||||
|
import javax.xml.parsers.DocumentBuilderFactory;
|
||||||
|
import org.w3c.dom.Element;
|
||||||
|
import org.w3c.dom.Node;
|
||||||
|
import org.w3c.dom.NodeList;
|
||||||
|
|
||||||
|
public final class JnicMain {
|
||||||
|
private static final String USAGE =
|
||||||
|
"java -jar OpenJNIC-3.7.0.jar <inputJAR> <outputJAR> <configFile> [-debug]";
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println();
|
||||||
|
System.out.println("JNIC Java Obfuscator 3.7.0");
|
||||||
|
System.out.println(" ~ (c) +Vincent Tang 2020-2023");
|
||||||
|
System.out.println();
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
if (args == null || (args.length != 3 && args.length != 4)) {
|
||||||
|
System.err.println("Incorrect number of arguments");
|
||||||
|
System.err.println(USAGE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (args.length == 4 && !"-debug".equals(args[3])) {
|
||||||
|
System.err.println("Unknown option: " + args[3]);
|
||||||
|
System.err.println(USAGE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.setDebug(args.length == 4);
|
||||||
|
|
||||||
|
Path input = Paths.get(args[0]).toAbsolutePath().normalize();
|
||||||
|
Path output = Paths.get(args[1]).toAbsolutePath().normalize();
|
||||||
|
Path config = Paths.get(args[2]).toAbsolutePath().normalize();
|
||||||
|
if (!Files.isRegularFile(input) || !Files.isReadable(input)) {
|
||||||
|
System.err.println("Input JAR is not readable: " + input);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Files.isRegularFile(config) || !Files.isReadable(config)) {
|
||||||
|
System.err.println("Configuration file is not readable: " + config);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (input.equals(output)) {
|
||||||
|
System.err.println("Input and output JAR must be different files");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Path outputParent = output.getParent();
|
||||||
|
if (outputParent != null && !Files.isDirectory(outputParent)) {
|
||||||
|
System.err.println("Output directory does not exist: " + outputParent);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Log.info("Licence: Skid Solutions");
|
||||||
|
Path compiler = findCompiler();
|
||||||
|
if (compiler == null) {
|
||||||
|
System.err.println("No usable compiler found.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.info("Found compiler: " + compiler);
|
||||||
|
Log.info("Reading input jar " + input);
|
||||||
|
Log.info("Reading configuration file " + config);
|
||||||
|
Log.info("Analysing classes...");
|
||||||
|
CliInspection inspection = inspect(input, config);
|
||||||
|
Log.info("Translating " + inspection.methodCount + " methods in "
|
||||||
|
+ inspection.selectedClassCount + " classes");
|
||||||
|
backupExisting(output);
|
||||||
|
Rewriter.rewrite(input, output, config, compiler, inspection.targets);
|
||||||
|
Log.info("Terminating normally.");
|
||||||
|
} catch (Exception failure) {
|
||||||
|
System.err.println("Failed to inspect input: " + failure.getMessage());
|
||||||
|
if (args.length == 4) {
|
||||||
|
failure.printStackTrace(System.err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void backupExisting(Path output) throws IOException {
|
||||||
|
if (!Files.exists(output)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Path backup = output.resolveSibling(output.getFileName() + ".BACKUP");
|
||||||
|
Files.deleteIfExists(backup);
|
||||||
|
Files.move(output, backup);
|
||||||
|
Log.warn(output + " already exists, renamed to " + backup);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CliInspection inspect(Path input, Path config) throws Exception {
|
||||||
|
int classes = 0;
|
||||||
|
int resources = 0;
|
||||||
|
int selectedClasses = 0;
|
||||||
|
int methods = 0;
|
||||||
|
try (JarFile jar = new JarFile(input.toFile())) {
|
||||||
|
Enumeration<JarEntry> entries = jar.entries();
|
||||||
|
while (entries.hasMoreElements()) {
|
||||||
|
JarEntry entry = entries.nextElement();
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (entry.getName().endsWith(".class")) {
|
||||||
|
classes++;
|
||||||
|
int selected = countTranslatableMethods(jar, entry);
|
||||||
|
if (selected > 0) {
|
||||||
|
selectedClasses++;
|
||||||
|
}
|
||||||
|
methods += selected;
|
||||||
|
} else {
|
||||||
|
resources++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||||
|
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||||
|
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||||
|
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||||
|
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||||
|
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||||
|
Element root = factory.newDocumentBuilder().parse(config.toFile()).getDocumentElement();
|
||||||
|
if (!"jnic".equals(root.getTagName())) {
|
||||||
|
throw new IllegalArgumentException("configuration root must be <jnic>");
|
||||||
|
}
|
||||||
|
ArrayList<String> targets = new ArrayList<>();
|
||||||
|
NodeList nodes = root.getElementsByTagName("target");
|
||||||
|
for (int index = 0; index < nodes.getLength(); index++) {
|
||||||
|
Node node = nodes.item(index);
|
||||||
|
String value = node.getTextContent().trim();
|
||||||
|
if (!value.isEmpty()) {
|
||||||
|
targets.add(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (targets.isEmpty()) {
|
||||||
|
targets.add(platformTarget());
|
||||||
|
}
|
||||||
|
|
||||||
|
Options options = Options.INSTANCE;
|
||||||
|
Element optionsElement = firstChild(root, "options");
|
||||||
|
if (optionsElement != null) {
|
||||||
|
options.setStringObfuscationEnabled(booleanElement(optionsElement, "stringObf", false));
|
||||||
|
options.setFlowObfuscationEnabled(booleanElement(optionsElement, "flowObf", false));
|
||||||
|
options.setNativeIntegrityEnabled(booleanElement(optionsElement, "nativeIntegrity", false));
|
||||||
|
options.setJarIntegrityEnabled(booleanElement(optionsElement, "jarIntegrity", false));
|
||||||
|
options.setAntiDebugEnabled(booleanElement(optionsElement, "antiDebug", false));
|
||||||
|
options.setUseIntrinsicsEnabled(booleanElement(optionsElement, "useIntrinsics", false));
|
||||||
|
options.setFastCompileEnabled(booleanElement(optionsElement, "fastCompile", false));
|
||||||
|
}
|
||||||
|
|
||||||
|
int generatedMethods = methods == 0 ? 0 : 1;
|
||||||
|
return new CliInspection(classes, resources, classes, methods + generatedMethods, targets);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Element firstChild(Element parent, String name) {
|
||||||
|
for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
|
||||||
|
if (child.getNodeType() == Node.ELEMENT_NODE && name.equals(child.getNodeName())) {
|
||||||
|
return (Element) child;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean booleanElement(Element parent, String name, boolean fallback) {
|
||||||
|
Element element = firstChild(parent, name);
|
||||||
|
if (element == null) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
String value = element.getTextContent().trim();
|
||||||
|
if (value.isEmpty()) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return Boolean.parseBoolean(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countTranslatableMethods(JarFile jar, JarEntry entry) throws IOException {
|
||||||
|
try (DataInputStream in = new DataInputStream(new BufferedInputStream(jar.getInputStream(entry)))) {
|
||||||
|
if (in.readInt() != 0xCAFEBABE) {
|
||||||
|
throw new IOException("invalid class: " + entry.getName());
|
||||||
|
}
|
||||||
|
in.readUnsignedShort();
|
||||||
|
in.readUnsignedShort();
|
||||||
|
int poolSize = in.readUnsignedShort();
|
||||||
|
String[] utf8 = new String[poolSize];
|
||||||
|
for (int index = 1; index < poolSize; index++) {
|
||||||
|
int tag = in.readUnsignedByte();
|
||||||
|
switch (tag) {
|
||||||
|
case 1:
|
||||||
|
utf8[index] = in.readUTF();
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
case 4:
|
||||||
|
in.skipBytes(4);
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
case 6:
|
||||||
|
in.skipBytes(8);
|
||||||
|
index++;
|
||||||
|
break;
|
||||||
|
case 7:
|
||||||
|
case 8:
|
||||||
|
case 16:
|
||||||
|
case 19:
|
||||||
|
case 20:
|
||||||
|
in.skipBytes(2);
|
||||||
|
break;
|
||||||
|
case 9:
|
||||||
|
case 10:
|
||||||
|
case 11:
|
||||||
|
case 12:
|
||||||
|
case 17:
|
||||||
|
case 18:
|
||||||
|
in.skipBytes(4);
|
||||||
|
break;
|
||||||
|
case 15:
|
||||||
|
in.skipBytes(3);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new IOException("unknown constant-pool tag " + tag + " in " + entry.getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
in.skipBytes(6);
|
||||||
|
int interfaces = in.readUnsignedShort();
|
||||||
|
in.skipBytes(interfaces * 2);
|
||||||
|
skipMembers(in);
|
||||||
|
int methodCount = in.readUnsignedShort();
|
||||||
|
int selected = 0;
|
||||||
|
for (int index = 0; index < methodCount; index++) {
|
||||||
|
int access = in.readUnsignedShort();
|
||||||
|
String name = utf8[in.readUnsignedShort()];
|
||||||
|
in.readUnsignedShort();
|
||||||
|
int attributes = in.readUnsignedShort();
|
||||||
|
boolean concrete = (access & (0x0100 | 0x0400)) == 0;
|
||||||
|
if (concrete && !"<init>".equals(name) && !"<clinit>".equals(name)) {
|
||||||
|
selected++;
|
||||||
|
}
|
||||||
|
skipAttributes(in, attributes);
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void skipMembers(DataInputStream in) throws IOException {
|
||||||
|
int count = in.readUnsignedShort();
|
||||||
|
for (int index = 0; index < count; index++) {
|
||||||
|
in.skipBytes(6);
|
||||||
|
skipAttributes(in, in.readUnsignedShort());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void skipAttributes(DataInputStream in, int count) throws IOException {
|
||||||
|
for (int index = 0; index < count; index++) {
|
||||||
|
in.readUnsignedShort();
|
||||||
|
long length = Integer.toUnsignedLong(in.readInt());
|
||||||
|
while (length > 0) {
|
||||||
|
int skipped = in.skipBytes((int) Math.min(length, 1 << 20));
|
||||||
|
if (skipped <= 0) {
|
||||||
|
throw new IOException("truncated class attribute");
|
||||||
|
}
|
||||||
|
length -= skipped;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path findCompiler() {
|
||||||
|
String configured = System.getenv("JNIC_ZIG");
|
||||||
|
if (configured != null && !configured.isBlank()) {
|
||||||
|
Path candidate = Paths.get(configured).toAbsolutePath().normalize();
|
||||||
|
if (Files.isRegularFile(candidate)) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Path current = Paths.get("").toAbsolutePath().normalize();
|
||||||
|
for (Path directory = current; directory != null; directory = directory.getParent()) {
|
||||||
|
Path bundled = directory.resolve("zig-x86_64-windows-0.17.1")
|
||||||
|
.resolve(isWindows() ? "zig.exe" : "zig");
|
||||||
|
if (Files.isRegularFile(bundled)) {
|
||||||
|
return bundled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String path = System.getenv("PATH");
|
||||||
|
if (path != null) {
|
||||||
|
for (String item : path.split(File.pathSeparator)) {
|
||||||
|
if (item.isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Path candidate = Paths.get(item).resolve(isWindows() ? "zig.exe" : "zig");
|
||||||
|
if (Files.isRegularFile(candidate)) {
|
||||||
|
return candidate.toAbsolutePath().normalize();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String platformTarget() {
|
||||||
|
String os = System.getProperty("os.name", "").toLowerCase();
|
||||||
|
String arch = System.getProperty("os.arch", "").toLowerCase();
|
||||||
|
String cpu = arch.contains("aarch64") || arch.contains("arm64") ? "AARCH64" : "X86_64";
|
||||||
|
if (os.contains("win")) {
|
||||||
|
return "WINDOWS_" + cpu;
|
||||||
|
}
|
||||||
|
if (os.contains("mac")) {
|
||||||
|
return "MACOS_" + cpu;
|
||||||
|
}
|
||||||
|
return "LINUX_" + cpu;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isWindows() {
|
||||||
|
return System.getProperty("os.name", "").toLowerCase().contains("win");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class CliInspection {
|
||||||
|
final int classCount;
|
||||||
|
final int resourceCount;
|
||||||
|
final int selectedClassCount;
|
||||||
|
final int methodCount;
|
||||||
|
final ArrayList<String> targets;
|
||||||
|
|
||||||
|
CliInspection(int classCount, int resourceCount, int selectedClassCount,
|
||||||
|
int methodCount, ArrayList<String> targets) {
|
||||||
|
this.classCount = classCount;
|
||||||
|
this.resourceCount = resourceCount;
|
||||||
|
this.selectedClassCount = selectedClassCount;
|
||||||
|
this.methodCount = methodCount;
|
||||||
|
this.targets = targets;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package dev.jnic.bignum;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
class BigIntMagnitude {
|
||||||
|
static final BigIntMagnitude ONE = new BigIntMagnitude(1);
|
||||||
|
static final int KNUTH_POW2_THRESH_LEN = 6;
|
||||||
|
static final int KNUTH_POW2_THRESH_ZEROS = 3;
|
||||||
|
|
||||||
|
int[] value;
|
||||||
|
int intLen;
|
||||||
|
int offset = 0;
|
||||||
|
|
||||||
|
BigIntMagnitude() {
|
||||||
|
this.value = new int[1];
|
||||||
|
this.intLen = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigIntMagnitude(int val) {
|
||||||
|
this.value = new int[]{val};
|
||||||
|
this.intLen = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigIntMagnitude(int[] val) {
|
||||||
|
this.value = val;
|
||||||
|
this.intLen = val.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigIntMagnitude(BigInteger b) {
|
||||||
|
this.intLen = b.mag.length;
|
||||||
|
this.value = Arrays.copyOf(b.mag, this.intLen);
|
||||||
|
}
|
||||||
|
|
||||||
|
BigIntMagnitude(BigIntMagnitude val) {
|
||||||
|
this.intLen = val.intLen;
|
||||||
|
this.value = Arrays.copyOfRange(val.value, val.offset, val.offset + this.intLen);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static java.math.BigInteger toJava(BigIntMagnitude v) {
|
||||||
|
java.math.BigInteger r = java.math.BigInteger.ZERO;
|
||||||
|
for (int i = 0; i < v.intLen; i++) {
|
||||||
|
r = r.shiftLeft(32).or(java.math.BigInteger.valueOf((long) v.value[v.offset + i] & BigInteger.LONG_MASK));
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setFromJava(java.math.BigInteger v) {
|
||||||
|
if (v.signum() < 0) {
|
||||||
|
v = v.negate();
|
||||||
|
}
|
||||||
|
int len = Math.max(1, (v.bitLength() + 31) / 32);
|
||||||
|
this.value = new int[len];
|
||||||
|
this.intLen = len;
|
||||||
|
this.offset = 0;
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
this.value[len - 1 - i] = v.shiftRight(i * 32).intValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BigIntMagnitude fromJava(java.math.BigInteger v) {
|
||||||
|
BigIntMagnitude r = new BigIntMagnitude(0);
|
||||||
|
r.setFromJava(v);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInteger toBigInteger(int sign) {
|
||||||
|
return BigInteger.fromJava(sign < 0 ? toJava(this).negate() : toJava(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInteger toBigInteger() {
|
||||||
|
return BigInteger.fromJava(toJava(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
long toLong() {
|
||||||
|
return toJava(this).longValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
void normalize() {
|
||||||
|
while (this.intLen > 0 && this.value[this.offset] == 0) {
|
||||||
|
this.offset++;
|
||||||
|
this.intLen--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear() {
|
||||||
|
this.offset = 0;
|
||||||
|
this.intLen = 0;
|
||||||
|
Arrays.fill(this.value, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
final int compare(BigIntMagnitude b) {
|
||||||
|
return toJava(this).compareTo(toJava(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
void copyValue(BigIntMagnitude src) {
|
||||||
|
this.value = src.value.clone();
|
||||||
|
this.intLen = src.intLen;
|
||||||
|
this.offset = src.offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
void copyValue(int[] val) {
|
||||||
|
this.value = val.clone();
|
||||||
|
this.intLen = val.length;
|
||||||
|
this.offset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setValue(int[] val, int length) {
|
||||||
|
this.value = val;
|
||||||
|
this.intLen = length;
|
||||||
|
this.offset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isZero() {
|
||||||
|
return toJava(this).signum() == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isOne() {
|
||||||
|
return toJava(this).equals(java.math.BigInteger.ONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isEven() {
|
||||||
|
return !toJava(this).testBit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isOdd() {
|
||||||
|
return toJava(this).testBit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isNormal() {
|
||||||
|
return this.intLen == 0 || this.value[this.offset] != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void leftShift(int n) {
|
||||||
|
setFromJava(toJava(this).shiftLeft(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
void rightShift(int n) {
|
||||||
|
setFromJava(toJava(this).shiftRight(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
void add(BigIntMagnitude addend) {
|
||||||
|
setFromJava(toJava(this).add(toJava(addend)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void add(int addend) {
|
||||||
|
setFromJava(toJava(this).add(java.math.BigInteger.valueOf(addend)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void mul(int y) {
|
||||||
|
setFromJava(toJava(this).multiply(java.math.BigInteger.valueOf(y)));
|
||||||
|
}
|
||||||
|
|
||||||
|
BigIntMagnitude divide(BigIntMagnitude b) {
|
||||||
|
java.math.BigInteger divisor = toJava(b);
|
||||||
|
return divisor.signum() == 0 ? fromJava(java.math.BigInteger.ZERO) : fromJava(toJava(this).divide(divisor));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return toJava(this).toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package dev.jnic.bignum;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class BigIntMath {
|
||||||
|
private BigInteger modulus;
|
||||||
|
private BigInteger exponent;
|
||||||
|
|
||||||
|
public void setParameters(BigInteger exponent, BigInteger modulus) {
|
||||||
|
this.exponent = exponent;
|
||||||
|
this.modulus = modulus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getExponentSignum() {
|
||||||
|
return this.exponent == null ? 0 : this.exponent.signum();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getModulusSignum() {
|
||||||
|
return this.modulus == null ? 0 : this.modulus.signum();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger fromBytes(byte[] bytes) {
|
||||||
|
return new BigInteger(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] toBytes(BigInteger value) {
|
||||||
|
return value == null ? new byte[0] : value.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger addInt(BigInteger value, int addend) {
|
||||||
|
return value.add(BigInteger.valueOf(addend));
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] slice(byte[] data, int offset, int length) {
|
||||||
|
return Arrays.copyOfRange(data, offset, offset + length);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
package dev.jnic.bignum;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class BigInteger {
|
||||||
|
static final long LONG_MASK = 0xFFFFFFFFL;
|
||||||
|
static final long SIGN_BIT_MASK = Long.MIN_VALUE;
|
||||||
|
private static final int MAX_MAG_LENGTH = 67108864;
|
||||||
|
|
||||||
|
public static final BigInteger ZERO = new BigInteger(new int[0], 0);
|
||||||
|
public static final BigInteger ONE = valueOf(1L);
|
||||||
|
public static final BigInteger TWO = valueOf(2L);
|
||||||
|
public static final BigInteger NEGATIVE_ONE = valueOf(-1L);
|
||||||
|
public static final BigInteger TEN = valueOf(10L);
|
||||||
|
|
||||||
|
int signum;
|
||||||
|
int[] mag;
|
||||||
|
|
||||||
|
public BigInteger(byte[] val) {
|
||||||
|
BigInteger converted = fromJava(new java.math.BigInteger(val));
|
||||||
|
this.signum = converted.signum;
|
||||||
|
this.mag = converted.mag;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger(int signum, byte[] magnitude) {
|
||||||
|
BigInteger converted = fromJava(new java.math.BigInteger(signum, magnitude));
|
||||||
|
this.signum = converted.signum;
|
||||||
|
this.mag = converted.mag;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger(String val, int radix) {
|
||||||
|
BigInteger converted = fromJava(new java.math.BigInteger(val, radix));
|
||||||
|
this.signum = converted.signum;
|
||||||
|
this.mag = converted.mag;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger(String val) {
|
||||||
|
this(val, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger(int numBits, Random rnd) {
|
||||||
|
BigInteger converted = fromJava(new java.math.BigInteger(numBits, rnd));
|
||||||
|
this.signum = converted.signum;
|
||||||
|
this.mag = converted.mag;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigInteger(int[] mag, int signum) {
|
||||||
|
this.signum = mag.length == 0 ? 0 : signum;
|
||||||
|
this.mag = mag;
|
||||||
|
if (this.mag.length >= MAX_MAG_LENGTH) {
|
||||||
|
checkRange();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigInteger(long val) {
|
||||||
|
if (val < 0L) {
|
||||||
|
val = -val;
|
||||||
|
this.signum = -1;
|
||||||
|
} else if (val == 0L) {
|
||||||
|
this.signum = 0;
|
||||||
|
this.mag = new int[0];
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.signum = 1;
|
||||||
|
}
|
||||||
|
int highWord = (int) (val >>> 32);
|
||||||
|
if (highWord == 0) {
|
||||||
|
this.mag = new int[]{(int) val};
|
||||||
|
} else {
|
||||||
|
this.mag = new int[]{highWord, (int) val};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkRange() {
|
||||||
|
if (this.mag.length > MAX_MAG_LENGTH || (this.mag.length == MAX_MAG_LENGTH && this.mag[0] < 0)) {
|
||||||
|
throw new ArithmeticException("BigInteger would overflow supported range");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static java.math.BigInteger toJava(BigInteger value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
java.math.BigInteger result = java.math.BigInteger.ZERO;
|
||||||
|
if (value.mag != null) {
|
||||||
|
for (int word : value.mag) {
|
||||||
|
result = result.shiftLeft(32).or(java.math.BigInteger.valueOf((long) word & LONG_MASK));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (value.signum < 0) {
|
||||||
|
result = result.negate();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static BigInteger fromJava(java.math.BigInteger value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (value.signum() == 0) {
|
||||||
|
return new BigInteger(new int[0], 0);
|
||||||
|
}
|
||||||
|
int sign = value.signum();
|
||||||
|
java.math.BigInteger abs = value.abs();
|
||||||
|
int len = Math.max(1, (abs.bitLength() + 31) / 32);
|
||||||
|
int[] words = new int[len];
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
words[len - 1 - i] = abs.shiftRight(i * 32).intValue();
|
||||||
|
}
|
||||||
|
return new BigInteger(words, sign);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int bitLengthForInt(int n) {
|
||||||
|
return 32 - Integer.numberOfLeadingZeros(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BigInteger valueOf(long val) {
|
||||||
|
return new BigInteger(val);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger add(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).add(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger subtract(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).subtract(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger multiply(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).multiply(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger divide(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).divide(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger[] divideAndRemainder(BigInteger val) {
|
||||||
|
java.math.BigInteger[] parts = toJava(this).divideAndRemainder(toJava(val));
|
||||||
|
return new BigInteger[]{fromJava(parts[0]), fromJava(parts[1])};
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger remainder(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).remainder(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger mod(BigInteger m) {
|
||||||
|
return fromJava(toJava(this).mod(toJava(m)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger and(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).and(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger or(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).or(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger xor(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).xor(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger andNot(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).andNot(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger not() {
|
||||||
|
return fromJava(toJava(this).not());
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger gcd(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).gcd(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger modInverse(BigInteger m) {
|
||||||
|
return fromJava(toJava(this).modInverse(toJava(m)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger min(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).min(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger max(BigInteger val) {
|
||||||
|
return fromJava(toJava(this).max(toJava(val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger negate() {
|
||||||
|
return fromJava(toJava(this).negate());
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger abs() {
|
||||||
|
return this.signum >= 0 ? this : this.negate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger shiftLeft(int n) {
|
||||||
|
return fromJava(toJava(this).shiftLeft(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigInteger shiftRight(int n) {
|
||||||
|
return fromJava(toJava(this).shiftRight(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
public int signum() {
|
||||||
|
return this.signum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int intValue() {
|
||||||
|
return toJava(this).intValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long longValue() {
|
||||||
|
return toJava(this).longValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int bitLength() {
|
||||||
|
return toJava(this).bitLength();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int bitCount() {
|
||||||
|
return toJava(this).bitCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int compareTo(BigInteger val) {
|
||||||
|
return toJava(this).compareTo(toJava(val));
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] toByteArray() {
|
||||||
|
return toJava(this).toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString(int radix) {
|
||||||
|
int r = (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) ? 10 : radix;
|
||||||
|
return toJava(this).toString(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return toJava(this).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object x) {
|
||||||
|
if (x == this) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!(x instanceof BigInteger)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
BigInteger other = (BigInteger) x;
|
||||||
|
return this.signum == other.signum && Arrays.equals(this.mag, other.mag);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return toJava(this).hashCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public class ClassCacheEntry {
|
||||||
|
private static final String ATTR = "__attribute__((const))static ";
|
||||||
|
|
||||||
|
private final AtomicInteger memberCounter = new AtomicInteger();
|
||||||
|
private final int classIndex;
|
||||||
|
private final String symbolName;
|
||||||
|
private final String internalName;
|
||||||
|
private final boolean hasLookup;
|
||||||
|
private final Map<MemberDescriptor, String> fields = new LinkedHashMap<>();
|
||||||
|
private final Map<MemberDescriptor, String> methods = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
ClassCacheEntry(int classIndex, String symbolName, String internalName, boolean hasLookup) {
|
||||||
|
this.classIndex = classIndex;
|
||||||
|
this.symbolName = symbolName;
|
||||||
|
this.internalName = internalName;
|
||||||
|
this.hasLookup = hasLookup;
|
||||||
|
}
|
||||||
|
|
||||||
|
String getFieldSymbol(MemberDescriptor descriptor) {
|
||||||
|
return this.fields.get(descriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
String getSymbolName() {
|
||||||
|
return this.symbolName;
|
||||||
|
}
|
||||||
|
|
||||||
|
String registerField(MemberDescriptor descriptor) {
|
||||||
|
return this.fields.computeIfAbsent(descriptor, k -> this.symbolName + "id_" + this.memberCounter.getAndIncrement());
|
||||||
|
}
|
||||||
|
|
||||||
|
String registerMethod(MemberDescriptor descriptor) {
|
||||||
|
return this.methods.computeIfAbsent(descriptor, k -> this.symbolName + "id_" + this.memberCounter.getAndIncrement());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String emitDeclaration() {
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
out.append(ATTR).append("jclass ").append(this.symbolName).append("(JNIEnv *env) {\n")
|
||||||
|
.append(" static _Atomic jclass clazz;\n")
|
||||||
|
.append(" jclass cached = atomic_load_explicit(&clazz, memory_order_relaxed);\n")
|
||||||
|
.append(" if (__builtin_expect(cached != 0, 1)) return cached;\n")
|
||||||
|
.append(" jclass loaded = (*env)->FindClass(env, \"").append(this.internalName).append("\");\n")
|
||||||
|
.append(" loaded = (*env)->NewGlobalRef(env, loaded);\n")
|
||||||
|
.append(" if (atomic_compare_exchange_strong_explicit(&clazz, &cached, loaded, memory_order_relaxed, memory_order_relaxed))\n")
|
||||||
|
.append(" return loaded;\n")
|
||||||
|
.append(" (*env)->DeleteGlobalRef(env, loaded);\n")
|
||||||
|
.append(" return cached;\n")
|
||||||
|
.append("}\n");
|
||||||
|
if (this.hasLookup) {
|
||||||
|
out.append(ATTR).append("jobject *").append(this.symbolName).append("l() {\n")
|
||||||
|
.append(" static jobject lookup; return &lookup;\n")
|
||||||
|
.append("}\n");
|
||||||
|
}
|
||||||
|
Map<Integer, Map.Entry<MemberDescriptor, Boolean>> ordered = new TreeMap<>();
|
||||||
|
for (Map.Entry<MemberDescriptor, String> entry : this.fields.entrySet()) {
|
||||||
|
ordered.put(parseSuffixIndex(entry.getValue()), Map.entry(entry.getKey(), true));
|
||||||
|
}
|
||||||
|
for (Map.Entry<MemberDescriptor, String> entry : this.methods.entrySet()) {
|
||||||
|
ordered.put(parseSuffixIndex(entry.getValue()), Map.entry(entry.getKey(), false));
|
||||||
|
}
|
||||||
|
for (Map.Entry<Integer, Map.Entry<MemberDescriptor, Boolean>> item : ordered.entrySet()) {
|
||||||
|
int idx = item.getKey();
|
||||||
|
MemberDescriptor member = item.getValue().getKey();
|
||||||
|
boolean isField = item.getValue().getValue();
|
||||||
|
boolean isStatic = member.isStatic();
|
||||||
|
String idType = isField ? "jfieldID" : "jmethodID";
|
||||||
|
String api = isField
|
||||||
|
? (isStatic ? "GetStaticFieldID" : "GetFieldID")
|
||||||
|
: (isStatic ? "GetStaticMethodID" : "GetMethodID");
|
||||||
|
String fn = this.symbolName + "id_" + idx;
|
||||||
|
out.append(ATTR).append(idType).append(" ").append(fn).append("(JNIEnv *env) {\n")
|
||||||
|
.append(" static _Atomic ").append(idType).append(" id;\n")
|
||||||
|
.append(" ").append(idType).append(" cached = atomic_load_explicit(&id, memory_order_relaxed);\n")
|
||||||
|
.append(" if (__builtin_expect(cached != 0, 1)) return cached;\n")
|
||||||
|
.append(" jclass clazz = ").append(this.symbolName).append("(env);\n")
|
||||||
|
.append(" cached = (*env)->").append(api).append("(env, clazz, \"")
|
||||||
|
.append(member.getName()).append("\", \"").append(member.getDescriptor()).append("\");\n")
|
||||||
|
.append(" atomic_store_explicit(&id, cached, memory_order_relaxed);\n")
|
||||||
|
.append(" return cached;\n")
|
||||||
|
.append("}\n");
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int parseSuffixIndex(String fn) {
|
||||||
|
int pos = fn.lastIndexOf('_');
|
||||||
|
if (pos < 0) return 0;
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(fn.substring(pos + 1));
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import dev.jnic.templates.State;
|
||||||
|
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
|
||||||
|
|
||||||
|
public class IndyEntry {
|
||||||
|
private final InvokeDynamicInsnNode insn;
|
||||||
|
private final String ownerName;
|
||||||
|
private String id;
|
||||||
|
private String symbolName;
|
||||||
|
|
||||||
|
public IndyEntry(InvokeDynamicInsnNode insn, String ownerName) {
|
||||||
|
this.insn = insn;
|
||||||
|
this.ownerName = ownerName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public InvokeDynamicInsnNode getInsn() {
|
||||||
|
return this.insn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOwnerName() {
|
||||||
|
return this.ownerName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return this.id != null ? this.id : "0";
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSymbolName() {
|
||||||
|
return this.symbolName != null ? this.symbolName : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSymbolName(String symbolName) {
|
||||||
|
this.symbolName = symbolName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String emitHelper(State ctx) {
|
||||||
|
String idValue = getId();
|
||||||
|
String fnName = "indy_" + idValue;
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("static jobject ").append(fnName).append("(JNIEnv *env) {\n");
|
||||||
|
sb.append(" static _Atomic jobject callSite;\n");
|
||||||
|
sb.append(" jobject cached = atomic_load_explicit(&callSite, memory_order_relaxed);\n");
|
||||||
|
sb.append(" if (__builtin_expect(cached != 0, 1)) return cached;\n");
|
||||||
|
sb.append(" return nullptr;\n");
|
||||||
|
sb.append("}\n");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import dev.jnic.templates.State;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
|
||||||
|
|
||||||
|
public class IndyRegistry {
|
||||||
|
private final AtomicInteger counter = new AtomicInteger();
|
||||||
|
private final Map<IndyEntry, String> entries = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
public String register(InvokeDynamicInsnNode indy, String ownerName) {
|
||||||
|
IndyEntry entry = new IndyEntry(indy, ownerName);
|
||||||
|
int id = this.counter.getAndIncrement();
|
||||||
|
String idStr = String.valueOf(id);
|
||||||
|
entry.setId(idStr);
|
||||||
|
this.entries.put(entry, idStr);
|
||||||
|
return "indy_" + idStr;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOrRegisterId(IndyEntry entry) {
|
||||||
|
if (entry == null) {
|
||||||
|
return "0";
|
||||||
|
}
|
||||||
|
return this.entries.computeIfAbsent(entry, k -> {
|
||||||
|
String id = String.valueOf(this.counter.getAndIncrement());
|
||||||
|
k.setId(id);
|
||||||
|
return id;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public String emitAllHelpers(State ctx) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (IndyEntry entry : this.entries.keySet()) {
|
||||||
|
sb.append(entry.emitHelper(ctx));
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import dev.jnic.crypto.ChaCha20Stream;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public class JniCacheRegistry {
|
||||||
|
private final AtomicInteger classCounter = new AtomicInteger();
|
||||||
|
private final Map<String, ClassCacheEntry> entries = new LinkedHashMap<>();
|
||||||
|
private final ChaCha20Stream stream;
|
||||||
|
|
||||||
|
public JniCacheRegistry(ChaCha20Stream stream) {
|
||||||
|
this.stream = stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerClass(String internalName) {
|
||||||
|
return getOrCreate(internalName, false).getSymbolName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerField(String owner, String name, String desc, boolean isStatic) {
|
||||||
|
ClassCacheEntry entry = getOrCreate(owner, false);
|
||||||
|
return entry.registerField(new MemberDescriptor(name, desc, isStatic));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerMethod(String owner, String name, String desc, boolean isStatic) {
|
||||||
|
ClassCacheEntry entry = getOrCreate(owner, false);
|
||||||
|
return entry.registerMethod(new MemberDescriptor(name, desc, isStatic));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerLookup(String internalName) {
|
||||||
|
ClassCacheEntry entry = getOrCreate(internalName, true);
|
||||||
|
return entry.getSymbolName() + "l";
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClassCacheEntry getOrCreate(String internalName, boolean withLookup) {
|
||||||
|
String normalized = internalName == null ? "java/lang/Object" : internalName;
|
||||||
|
ClassCacheEntry existing = this.entries.get(normalized);
|
||||||
|
if (existing != null) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
int id = this.classCounter.getAndIncrement();
|
||||||
|
ClassCacheEntry created = new ClassCacheEntry(id, "c_" + id, normalized, withLookup);
|
||||||
|
this.entries.put(normalized, created);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String emitAllDeclarations() {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (ClassCacheEntry entry : this.entries.values()) {
|
||||||
|
sb.append(entry.emitDeclaration());
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class MemberDescriptor {
|
||||||
|
private final String name;
|
||||||
|
private final String descriptor;
|
||||||
|
private final boolean isStatic;
|
||||||
|
|
||||||
|
MemberDescriptor(String name, String descriptor, boolean isStatic) {
|
||||||
|
this.name = name;
|
||||||
|
this.descriptor = descriptor;
|
||||||
|
this.isStatic = isStatic;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescriptor() {
|
||||||
|
return this.descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isStatic() {
|
||||||
|
return this.isStatic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (!(o instanceof MemberDescriptor)) return false;
|
||||||
|
MemberDescriptor that = (MemberDescriptor) o;
|
||||||
|
return this.isStatic == that.isStatic
|
||||||
|
&& Objects.equals(this.name, that.name)
|
||||||
|
&& Objects.equals(this.descriptor, that.descriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(this.name, this.descriptor, this.isStatic);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.name + ":" + this.descriptor + ":" + this.isStatic;
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public class MemberKey {
|
||||||
|
private final String owner;
|
||||||
|
private final String name;
|
||||||
|
private final String descriptor;
|
||||||
|
|
||||||
|
public MemberKey(String owner, String name, String descriptor) {
|
||||||
|
this.owner = owner;
|
||||||
|
this.name = name;
|
||||||
|
this.descriptor = descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MemberKey of(ClassNode owner, MethodNode method) {
|
||||||
|
return new MemberKey(
|
||||||
|
owner != null ? owner.name : "",
|
||||||
|
method != null ? method.name : "",
|
||||||
|
method != null ? method.desc : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (!(o instanceof MemberKey)) return false;
|
||||||
|
MemberKey that = (MemberKey) o;
|
||||||
|
return Objects.equals(this.owner, that.owner)
|
||||||
|
&& Objects.equals(this.name, that.name)
|
||||||
|
&& Objects.equals(this.descriptor, that.descriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(this.owner, this.name, this.descriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOwner() {
|
||||||
|
return this.owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescriptor() {
|
||||||
|
return this.descriptor;
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
public class MethodRef {
|
||||||
|
private final String owner;
|
||||||
|
private final String name;
|
||||||
|
private final String descriptor;
|
||||||
|
|
||||||
|
public MethodRef(String owner, String name, String descriptor) {
|
||||||
|
this.owner = owner;
|
||||||
|
this.name = name;
|
||||||
|
this.descriptor = descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static MethodRef of(String owner, String name, String descriptor) {
|
||||||
|
return new MethodRef(owner, name, descriptor);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOwner() {
|
||||||
|
return this.owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescriptor() {
|
||||||
|
return this.descriptor;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import dev.jnic.util.StringPair;
|
||||||
|
import dev.jnic.util.StringPairSet;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MethodRegistry {
|
||||||
|
private final Map<String, StringPairSet> entries = new HashMap<>();
|
||||||
|
|
||||||
|
public void add(String owner, String name, String descriptor) {
|
||||||
|
StringPairSet pairSet = this.entries.computeIfAbsent(owner, k -> new StringPairSet());
|
||||||
|
pairSet.add(new StringPair(name, descriptor));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean contains(String owner, String name, String descriptor) {
|
||||||
|
StringPairSet pairSet = this.entries.get(owner);
|
||||||
|
return pairSet != null && pairSet.contains(new StringPair(name, descriptor));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean containsOwner(String owner) {
|
||||||
|
return this.entries.containsKey(owner);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package dev.jnic.cache;
|
||||||
|
|
||||||
|
import dev.jnic.crypto.ChaCha20Stream;
|
||||||
|
import dev.jnic.pipeline.Entry;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public class StringPoolEmitter {
|
||||||
|
private final AtomicInteger counter = new AtomicInteger();
|
||||||
|
private final List<Entry> entries = new ArrayList<>();
|
||||||
|
private final ChaCha20Stream stream;
|
||||||
|
|
||||||
|
public StringPoolEmitter(ChaCha20Stream stream) {
|
||||||
|
this.stream = stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String register(byte[] data) {
|
||||||
|
int id = this.counter.getAndIncrement();
|
||||||
|
String name = "s_" + id;
|
||||||
|
this.entries.add(new Entry(name, "", data));
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String emitAll() {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package dev.jnic.crypto;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
|
||||||
|
public class ChaCha20Stream extends InputStream {
|
||||||
|
private final byte[] key;
|
||||||
|
private final byte[] nonce;
|
||||||
|
private final int[] state = new int[16];
|
||||||
|
private final byte[] buffer = new byte[64];
|
||||||
|
private int bufferIndex = 64;
|
||||||
|
|
||||||
|
private ChaCha20Stream(String constant, byte[] key, byte[] nonce) {
|
||||||
|
if (key.length != 32) {
|
||||||
|
throw new IllegalArgumentException("Key must be 32 bytes, got " + key.length);
|
||||||
|
}
|
||||||
|
if (nonce.length != 12) {
|
||||||
|
throw new IllegalArgumentException("Nonce must be 12 bytes, got " + nonce.length);
|
||||||
|
}
|
||||||
|
byte[] constantBytes = constant.getBytes(StandardCharsets.US_ASCII);
|
||||||
|
if (constantBytes.length != 16) {
|
||||||
|
throw new IllegalArgumentException("Constant must be 16 bytes, got " + constantBytes.length);
|
||||||
|
}
|
||||||
|
this.key = key;
|
||||||
|
this.nonce = nonce;
|
||||||
|
EndianUtils.readLittleEndianInts(constantBytes, 0, this.state, 0, 4);
|
||||||
|
EndianUtils.readLittleEndianInts(key, 0, this.state, 4, 8);
|
||||||
|
this.state[12] = 0;
|
||||||
|
EndianUtils.readLittleEndianInts(nonce, 0, this.state, 13, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ChaCha20Stream create(String constant, SecureRandom random) {
|
||||||
|
byte[] key = new byte[32];
|
||||||
|
byte[] nonce = new byte[12];
|
||||||
|
if (random != null) {
|
||||||
|
random.nextBytes(key);
|
||||||
|
random.nextBytes(nonce);
|
||||||
|
} else {
|
||||||
|
new SecureRandom().nextBytes(key);
|
||||||
|
new SecureRandom().nextBytes(nonce);
|
||||||
|
}
|
||||||
|
return new ChaCha20Stream(constant, key, nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getKey() {
|
||||||
|
return this.key.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getNonce() {
|
||||||
|
return this.nonce.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void generateBlock() {
|
||||||
|
int[] working = new int[16];
|
||||||
|
System.arraycopy(this.state, 0, working, 0, 16);
|
||||||
|
for (int i = 0; i < 10; ++i) {
|
||||||
|
quarterRound(working, 0, 4, 8, 12);
|
||||||
|
quarterRound(working, 1, 5, 9, 13);
|
||||||
|
quarterRound(working, 2, 6, 10, 14);
|
||||||
|
quarterRound(working, 3, 7, 11, 15);
|
||||||
|
quarterRound(working, 0, 5, 10, 15);
|
||||||
|
quarterRound(working, 1, 6, 11, 12);
|
||||||
|
quarterRound(working, 2, 7, 8, 13);
|
||||||
|
quarterRound(working, 3, 4, 9, 14);
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 16; ++i) {
|
||||||
|
int word = working[i] + this.state[i];
|
||||||
|
this.buffer[i * 4] = (byte) word;
|
||||||
|
this.buffer[i * 4 + 1] = (byte) (word >>> 8);
|
||||||
|
this.buffer[i * 4 + 2] = (byte) (word >>> 16);
|
||||||
|
this.buffer[i * 4 + 3] = (byte) (word >>> 24);
|
||||||
|
}
|
||||||
|
++this.state[12];
|
||||||
|
this.bufferIndex = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void quarterRound(int[] x, int a, int b, int c, int d) {
|
||||||
|
x[a] += x[b];
|
||||||
|
x[d] = Integer.rotateLeft(x[d] ^ x[a], 16);
|
||||||
|
x[c] += x[d];
|
||||||
|
x[b] = Integer.rotateLeft(x[b] ^ x[c], 12);
|
||||||
|
x[a] += x[b];
|
||||||
|
x[d] = Integer.rotateLeft(x[d] ^ x[a], 8);
|
||||||
|
x[c] += x[d];
|
||||||
|
x[b] = Integer.rotateLeft(x[b] ^ x[c], 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int read(byte[] dst, int off, int len) {
|
||||||
|
if (len <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < len; ++i) {
|
||||||
|
if (this.bufferIndex >= 64) {
|
||||||
|
this.generateBlock();
|
||||||
|
}
|
||||||
|
dst[off + i] = this.buffer[this.bufferIndex++];
|
||||||
|
}
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int read() {
|
||||||
|
if (this.bufferIndex >= 64) {
|
||||||
|
this.generateBlock();
|
||||||
|
}
|
||||||
|
return this.buffer[this.bufferIndex++] & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getBlockCounter() {
|
||||||
|
return this.state[12];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package dev.jnic.crypto;
|
||||||
|
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public abstract class DigestBase {
|
||||||
|
private static final Map<DigestBase, MessageDigest> DIGESTS = Collections.synchronizedMap(new IdentityHashMap<>());
|
||||||
|
|
||||||
|
protected DigestBase() {
|
||||||
|
}
|
||||||
|
|
||||||
|
final MessageDigest digest() {
|
||||||
|
MessageDigest digest = DIGESTS.get(this);
|
||||||
|
if (digest == null) {
|
||||||
|
try {
|
||||||
|
digest = MessageDigest.getInstance("SHA-1");
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new IllegalStateException(e);
|
||||||
|
}
|
||||||
|
DIGESTS.put(this, digest);
|
||||||
|
}
|
||||||
|
return digest;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(byte input) {
|
||||||
|
this.digest().update(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void update(byte[] input, int offset, int length) {
|
||||||
|
this.digest().update(input, offset, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void finish() {
|
||||||
|
this.digest().digest();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reset() {
|
||||||
|
this.digest().reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract void processBlock(byte[] input, int offset);
|
||||||
|
|
||||||
|
protected abstract void processLength(long bitLength);
|
||||||
|
|
||||||
|
protected abstract void processDigest();
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
package dev.jnic.crypto;
|
||||||
|
|
||||||
|
public abstract class EndianUtils {
|
||||||
|
public static short readLittleEndianShort(byte[] src, int offset) {
|
||||||
|
return (short) ((src[offset] & 0xFF) | ((src[offset + 1] & 0xFF) << 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int readLittleEndianInt(byte[] src, int offset) {
|
||||||
|
return (src[offset] & 0xFF)
|
||||||
|
| ((src[offset + 1] & 0xFF) << 8)
|
||||||
|
| ((src[offset + 2] & 0xFF) << 16)
|
||||||
|
| ((src[offset + 3] & 0xFF) << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readLittleEndianInts(byte[] src, int offset, int[] dst) {
|
||||||
|
for (int i = 0; i < dst.length; ++i) {
|
||||||
|
dst[i] = readLittleEndianInt(src, offset + i * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readBigEndianInts(byte[] src, int srcOff, int[] dst, int dstOff, int count) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
int pos = srcOff + i * 4;
|
||||||
|
dst[dstOff + i] = ((src[pos] & 0xFF) << 24)
|
||||||
|
| ((src[pos + 1] & 0xFF) << 16)
|
||||||
|
| ((src[pos + 2] & 0xFF) << 8)
|
||||||
|
| (src[pos + 3] & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toLittleEndianBytes(int value) {
|
||||||
|
byte[] dst = new byte[4];
|
||||||
|
writeLittleEndianInt(value, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianInt(int value, byte[] dst, int offset) {
|
||||||
|
dst[offset] = (byte) value;
|
||||||
|
dst[offset + 1] = (byte) (value >>> 8);
|
||||||
|
dst[offset + 2] = (byte) (value >>> 16);
|
||||||
|
dst[offset + 3] = (byte) (value >>> 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toLittleEndianBytes(int[] values) {
|
||||||
|
byte[] dst = new byte[values.length * 4];
|
||||||
|
writeLittleEndianInts(values, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianInts(int[] src, byte[] dst, int offset) {
|
||||||
|
for (int i = 0; i < src.length; ++i) {
|
||||||
|
writeLittleEndianInt(src[i], dst, offset + i * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianInts(int[] src, int srcOff, int count, byte[] dst, int dstOff) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
int pos = dstOff + i * 4;
|
||||||
|
int value = src[srcOff + i];
|
||||||
|
dst[pos] = (byte) (value >>> 24);
|
||||||
|
dst[pos + 1] = (byte) (value >>> 16);
|
||||||
|
dst[pos + 2] = (byte) (value >>> 8);
|
||||||
|
dst[pos + 3] = (byte) value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long readLittleEndianLong(byte[] src, int offset) {
|
||||||
|
return ((long) src[offset] & 0xFFL)
|
||||||
|
| (((long) src[offset + 1] & 0xFFL) << 8)
|
||||||
|
| (((long) src[offset + 2] & 0xFFL) << 16)
|
||||||
|
| (((long) src[offset + 3] & 0xFFL) << 24)
|
||||||
|
| (((long) src[offset + 4] & 0xFFL) << 32)
|
||||||
|
| (((long) src[offset + 5] & 0xFFL) << 40)
|
||||||
|
| (((long) src[offset + 6] & 0xFFL) << 48)
|
||||||
|
| (((long) src[offset + 7] & 0xFFL) << 56);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readBigEndianLongs(byte[] src, int offset, long[] dst) {
|
||||||
|
for (int i = 0; i < dst.length; ++i) {
|
||||||
|
int pos = offset + i * 8;
|
||||||
|
dst[i] = (((long) src[pos] & 0xFFL) << 56)
|
||||||
|
| (((long) src[pos + 1] & 0xFFL) << 48)
|
||||||
|
| (((long) src[pos + 2] & 0xFFL) << 40)
|
||||||
|
| (((long) src[pos + 3] & 0xFFL) << 32)
|
||||||
|
| (((long) src[pos + 4] & 0xFFL) << 24)
|
||||||
|
| (((long) src[pos + 5] & 0xFFL) << 16)
|
||||||
|
| (((long) src[pos + 6] & 0xFFL) << 8)
|
||||||
|
| ((long) src[pos + 7] & 0xFFL);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readLittleEndianLongs(byte[] src, int srcOff, long[] dst, int dstOff, int count) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
dst[dstOff + i] = readLittleEndianLong(src, srcOff + i * 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toBigEndianBytes(long value) {
|
||||||
|
byte[] dst = new byte[8];
|
||||||
|
writeBigEndianLong(value, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianLong(long value, byte[] dst, int offset) {
|
||||||
|
dst[offset] = (byte) (value >>> 56);
|
||||||
|
dst[offset + 1] = (byte) (value >>> 48);
|
||||||
|
dst[offset + 2] = (byte) (value >>> 40);
|
||||||
|
dst[offset + 3] = (byte) (value >>> 32);
|
||||||
|
dst[offset + 4] = (byte) (value >>> 24);
|
||||||
|
dst[offset + 5] = (byte) (value >>> 16);
|
||||||
|
dst[offset + 6] = (byte) (value >>> 8);
|
||||||
|
dst[offset + 7] = (byte) value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toBigEndianBytes(long[] values) {
|
||||||
|
byte[] dst = new byte[values.length * 8];
|
||||||
|
writeBigEndianLongs(values, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianLongs(long[] src, byte[] dst, int offset) {
|
||||||
|
for (int i = 0; i < src.length; ++i) {
|
||||||
|
writeLittleEndianLong(src[i], dst, offset + i * 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianLongs(long[] src, int srcOff, int count, byte[] dst, int dstOff) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
writeLittleEndianLong(src[srcOff + i], dst, dstOff + i * 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianLong(long value, byte[] dst, int offset, int byteCount) {
|
||||||
|
for (int i = 0; i < byteCount; ++i) {
|
||||||
|
dst[offset + i] = (byte) (value >>> (i * 8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static short readBigEndianShort(byte[] src, int offset) {
|
||||||
|
return (short) (((src[offset] & 0xFF) << 8) | (src[offset + 1] & 0xFF));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int readBigEndianInt(byte[] src, int offset) {
|
||||||
|
return ((src[offset] & 0xFF) << 24)
|
||||||
|
| ((src[offset + 1] & 0xFF) << 16)
|
||||||
|
| ((src[offset + 2] & 0xFF) << 8)
|
||||||
|
| (src[offset + 3] & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readBigEndianInts(byte[] src, int offset, int[] dst) {
|
||||||
|
for (int i = 0; i < dst.length; ++i) {
|
||||||
|
dst[i] = readBigEndianInt(src, offset + i * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readLittleEndianInts(byte[] src, int srcOff, int[] dst, int dstOff, int count) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
dst[dstOff + i] = readLittleEndianInt(src, srcOff + i * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int[] readLittleEndianInts(byte[] src, int offset, int byteLength) {
|
||||||
|
int[] dst = new int[byteLength / 4];
|
||||||
|
for (int i = 0; i < dst.length; ++i) {
|
||||||
|
dst[i] = readLittleEndianInt(src, offset + i * 4);
|
||||||
|
}
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toLittleEndianBytes(short value) {
|
||||||
|
return new byte[]{(byte) value, (byte) (value >>> 8)};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianShort(short value, byte[] dst, int offset) {
|
||||||
|
dst[offset] = (byte) value;
|
||||||
|
dst[offset + 1] = (byte) (value >>> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toBigEndianBytes(short value) {
|
||||||
|
return new byte[]{(byte) (value >>> 8), (byte) value};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianShort(short value, byte[] dst, int offset) {
|
||||||
|
dst[offset] = (byte) (value >>> 8);
|
||||||
|
dst[offset + 1] = (byte) value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toBigEndianBytes(int value) {
|
||||||
|
return new byte[]{(byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianInt(int value, byte[] dst, int offset) {
|
||||||
|
dst[offset] = (byte) (value >>> 24);
|
||||||
|
dst[offset + 1] = (byte) (value >>> 16);
|
||||||
|
dst[offset + 2] = (byte) (value >>> 8);
|
||||||
|
dst[offset + 3] = (byte) value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toBigEndianBytes(int[] values) {
|
||||||
|
byte[] dst = new byte[values.length * 4];
|
||||||
|
writeBigEndianInts(values, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianInts(int[] src, byte[] dst, int offset) {
|
||||||
|
writeBigEndianInts(src, 0, src.length, dst, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianInts(int[] src, int srcOff, int count, byte[] dst, int dstOff) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
writeLittleEndianInt(src[srcOff + i], dst, dstOff + i * 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long readBigEndianLong(byte[] src, int offset) {
|
||||||
|
return (((long) src[offset] & 0xFFL) << 56)
|
||||||
|
| (((long) src[offset + 1] & 0xFFL) << 48)
|
||||||
|
| (((long) src[offset + 2] & 0xFFL) << 40)
|
||||||
|
| (((long) src[offset + 3] & 0xFFL) << 32)
|
||||||
|
| (((long) src[offset + 4] & 0xFFL) << 24)
|
||||||
|
| (((long) src[offset + 5] & 0xFFL) << 16)
|
||||||
|
| (((long) src[offset + 6] & 0xFFL) << 8)
|
||||||
|
| ((long) src[offset + 7] & 0xFFL);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readLittleEndianLongs(byte[] src, int offset, long[] dst) {
|
||||||
|
for (int i = 0; i < dst.length; ++i) {
|
||||||
|
dst[i] = readLittleEndianLong(src, offset + i * 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void readBigEndianLongs(byte[] src, int srcOff, long[] dst, int dstOff, int count) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
dst[dstOff + i] = readBigEndianLong(src, srcOff + i * 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toLittleEndianBytes(long value) {
|
||||||
|
byte[] dst = new byte[8];
|
||||||
|
writeLittleEndianLong(value, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeLittleEndianLong(long value, byte[] dst, int offset) {
|
||||||
|
dst[offset] = (byte) value;
|
||||||
|
dst[offset + 1] = (byte) (value >>> 8);
|
||||||
|
dst[offset + 2] = (byte) (value >>> 16);
|
||||||
|
dst[offset + 3] = (byte) (value >>> 24);
|
||||||
|
dst[offset + 4] = (byte) (value >>> 32);
|
||||||
|
dst[offset + 5] = (byte) (value >>> 40);
|
||||||
|
dst[offset + 6] = (byte) (value >>> 48);
|
||||||
|
dst[offset + 7] = (byte) (value >>> 56);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] toLittleEndianBytes(long[] values) {
|
||||||
|
byte[] dst = new byte[values.length * 8];
|
||||||
|
writeLittleEndianLongs(values, dst, 0);
|
||||||
|
return dst;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianLongs(long[] src, byte[] dst, int offset) {
|
||||||
|
writeBigEndianLongs(src, 0, src.length, dst, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void writeBigEndianLongs(long[] src, int srcOff, int count, byte[] dst, int dstOff) {
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
writeBigEndianLong(src[srcOff + i], dst, dstOff + i * 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package dev.jnic.crypto;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class NoncePair {
|
||||||
|
private final long high;
|
||||||
|
private final long low;
|
||||||
|
private final byte[] seed;
|
||||||
|
|
||||||
|
public NoncePair(long high, long low, byte[] seed) {
|
||||||
|
this.high = high;
|
||||||
|
this.low = low;
|
||||||
|
this.seed = seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public NoncePair(long high, long low) {
|
||||||
|
this.high = high;
|
||||||
|
this.low = low;
|
||||||
|
this.seed = new byte[32];
|
||||||
|
ThreadLocalRandom.current().nextBytes(this.seed);
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getLow() {
|
||||||
|
return this.low;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getHigh() {
|
||||||
|
return this.high;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getSeed() {
|
||||||
|
return this.seed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package dev.jnic.crypto;
|
||||||
|
|
||||||
|
public class Sha1Digest extends DigestBase {
|
||||||
|
private static final int DIGEST_LENGTH = 20;
|
||||||
|
|
||||||
|
public Sha1Digest() {
|
||||||
|
this.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getDigestSize() {
|
||||||
|
return DIGEST_LENGTH;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void processBlock(byte[] input, int offset) {
|
||||||
|
int remaining = input.length - offset;
|
||||||
|
if (remaining > 0) {
|
||||||
|
this.digest().update(input, offset, remaining);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void processLength(long bitLength) {
|
||||||
|
this.digest().update((byte) (bitLength >>> 56));
|
||||||
|
this.digest().update((byte) (bitLength >>> 48));
|
||||||
|
this.digest().update((byte) (bitLength >>> 40));
|
||||||
|
this.digest().update((byte) (bitLength >>> 32));
|
||||||
|
this.digest().update((byte) (bitLength >>> 24));
|
||||||
|
this.digest().update((byte) (bitLength >>> 16));
|
||||||
|
this.digest().update((byte) (bitLength >>> 8));
|
||||||
|
this.digest().update((byte) bitLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int doFinal(byte[] out, int outOff) {
|
||||||
|
byte[] hash = this.digest().digest();
|
||||||
|
System.arraycopy(hash, 0, out, outOff, hash.length);
|
||||||
|
return hash.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
this.digest().reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void processDigest() {
|
||||||
|
this.digest().reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package dev.jnic.handler;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
|
||||||
|
public final class JvmOpcodeHandlers {
|
||||||
|
private JvmOpcodeHandlers() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String emit(AbstractInsnNode instruction, int pc) {
|
||||||
|
int op = instruction.getOpcode();
|
||||||
|
switch (op) {
|
||||||
|
case Opcodes.NOP:
|
||||||
|
return " /* nop */\n";
|
||||||
|
case Opcodes.ACONST_NULL:
|
||||||
|
return " stack0.l = nullptr;\n";
|
||||||
|
case Opcodes.ICONST_M1:
|
||||||
|
case Opcodes.ICONST_0:
|
||||||
|
case Opcodes.ICONST_1:
|
||||||
|
case Opcodes.ICONST_2:
|
||||||
|
case Opcodes.ICONST_3:
|
||||||
|
case Opcodes.ICONST_4:
|
||||||
|
case Opcodes.ICONST_5:
|
||||||
|
return " stack0.i = " + (op - Opcodes.ICONST_0) + ";\n";
|
||||||
|
case Opcodes.LCONST_0:
|
||||||
|
case Opcodes.LCONST_1:
|
||||||
|
return " stack0.j = " + (op - Opcodes.LCONST_0) + "LL;\n";
|
||||||
|
case Opcodes.FCONST_0:
|
||||||
|
case Opcodes.FCONST_1:
|
||||||
|
case Opcodes.FCONST_2:
|
||||||
|
return " stack0.f = " + (op - Opcodes.FCONST_0) + ".0f;\n";
|
||||||
|
case Opcodes.DCONST_0:
|
||||||
|
case Opcodes.DCONST_1:
|
||||||
|
return " stack0.d = " + (op - Opcodes.DCONST_0) + ".0;\n";
|
||||||
|
case Opcodes.IADD:
|
||||||
|
return " stack1.i += stack0.i;\n";
|
||||||
|
case Opcodes.ISUB:
|
||||||
|
return " stack1.i -= stack0.i;\n";
|
||||||
|
case Opcodes.IMUL:
|
||||||
|
return " stack1.i *= stack0.i;\n";
|
||||||
|
case Opcodes.IDIV:
|
||||||
|
return " stack1.i /= stack0.i;\n";
|
||||||
|
case Opcodes.IREM:
|
||||||
|
return " stack1.i %= stack0.i;\n";
|
||||||
|
case Opcodes.INEG:
|
||||||
|
return " stack0.i = -stack0.i;\n";
|
||||||
|
case Opcodes.IAND:
|
||||||
|
return " stack1.i &= stack0.i;\n";
|
||||||
|
case Opcodes.IOR:
|
||||||
|
return " stack1.i |= stack0.i;\n";
|
||||||
|
case Opcodes.IXOR:
|
||||||
|
return " stack1.i ^= stack0.i;\n";
|
||||||
|
case Opcodes.IRETURN:
|
||||||
|
return " return stack0.i;\n";
|
||||||
|
case Opcodes.LRETURN:
|
||||||
|
return " return stack0.j;\n";
|
||||||
|
case Opcodes.FRETURN:
|
||||||
|
return " return stack0.f;\n";
|
||||||
|
case Opcodes.DRETURN:
|
||||||
|
return " return stack0.d;\n";
|
||||||
|
case Opcodes.ARETURN:
|
||||||
|
return " return stack0.l;\n";
|
||||||
|
case Opcodes.RETURN:
|
||||||
|
return " return;\n";
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
package dev.jnic.handler;
|
||||||
|
|
||||||
|
import dev.jnic.templates.Labels;
|
||||||
|
import dev.jnic.templates.State;
|
||||||
|
import dev.jnic.type.StackFrame;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
|
||||||
|
public interface OpcodeHandler {
|
||||||
|
int NOP = 0;
|
||||||
|
int ACONST_NULL = 1;
|
||||||
|
int ICONST_M1 = 2;
|
||||||
|
int ICONST_0 = 3;
|
||||||
|
int ICONST_1 = 4;
|
||||||
|
int ICONST_2 = 5;
|
||||||
|
int ICONST_3 = 6;
|
||||||
|
int ICONST_4 = 7;
|
||||||
|
int ICONST_5 = 8;
|
||||||
|
int LCONST_0 = 9;
|
||||||
|
int LCONST_1 = 10;
|
||||||
|
int FCONST_0 = 11;
|
||||||
|
int FCONST_1 = 12;
|
||||||
|
int FCONST_2 = 13;
|
||||||
|
int DCONST_0 = 14;
|
||||||
|
int DCONST_1 = 15;
|
||||||
|
int BIPUSH = 16;
|
||||||
|
int SIPUSH = 17;
|
||||||
|
int LDC = 18;
|
||||||
|
int ILOAD = 21;
|
||||||
|
int LLOAD = 22;
|
||||||
|
int FLOAD = 23;
|
||||||
|
int DLOAD = 24;
|
||||||
|
int ALOAD = 25;
|
||||||
|
int IALOAD = 46;
|
||||||
|
int LALOAD = 47;
|
||||||
|
int FALOAD = 48;
|
||||||
|
int DALOAD = 49;
|
||||||
|
int AALOAD = 50;
|
||||||
|
int BALOAD = 51;
|
||||||
|
int CALOAD = 52;
|
||||||
|
int SALOAD = 53;
|
||||||
|
int ISTORE = 54;
|
||||||
|
int LSTORE = 55;
|
||||||
|
int FSTORE = 56;
|
||||||
|
int DSTORE = 57;
|
||||||
|
int ASTORE = 58;
|
||||||
|
int IASTORE = 79;
|
||||||
|
int LASTORE = 80;
|
||||||
|
int FASTORE = 81;
|
||||||
|
int DASTORE = 82;
|
||||||
|
int AASTORE = 83;
|
||||||
|
int BASTORE = 84;
|
||||||
|
int CASTORE = 85;
|
||||||
|
int SASTORE = 86;
|
||||||
|
int POP = 87;
|
||||||
|
int POP2 = 88;
|
||||||
|
int DUP = 89;
|
||||||
|
int DUP_X1 = 90;
|
||||||
|
int DUP_X2 = 91;
|
||||||
|
int DUP2 = 92;
|
||||||
|
int DUP2_X1 = 93;
|
||||||
|
int DUP2_X2 = 94;
|
||||||
|
int SWAP = 95;
|
||||||
|
int IADD = 96;
|
||||||
|
int LADD = 97;
|
||||||
|
int FADD = 98;
|
||||||
|
int DADD = 99;
|
||||||
|
int ISUB = 100;
|
||||||
|
int LSUB = 101;
|
||||||
|
int FSUB = 102;
|
||||||
|
int DSUB = 103;
|
||||||
|
int IMUL = 104;
|
||||||
|
int LMUL = 105;
|
||||||
|
int FMUL = 106;
|
||||||
|
int DMUL = 107;
|
||||||
|
int IDIV = 108;
|
||||||
|
int LDIV = 109;
|
||||||
|
int FDIV = 110;
|
||||||
|
int DDIV = 111;
|
||||||
|
int IREM = 112;
|
||||||
|
int LREM = 113;
|
||||||
|
int FREM = 114;
|
||||||
|
int DREM = 115;
|
||||||
|
int INEG = 116;
|
||||||
|
int LNEG = 117;
|
||||||
|
int FNEG = 118;
|
||||||
|
int DNEG = 119;
|
||||||
|
int ISHL = 120;
|
||||||
|
int LSHL = 121;
|
||||||
|
int ISHR = 122;
|
||||||
|
int LSHR = 123;
|
||||||
|
int IUSHR = 124;
|
||||||
|
int LUSHR = 125;
|
||||||
|
int IAND = 126;
|
||||||
|
int LAND = 127;
|
||||||
|
int IOR = 128;
|
||||||
|
int LOR = 129;
|
||||||
|
int IXOR = 130;
|
||||||
|
int LXOR = 131;
|
||||||
|
int IINC = 132;
|
||||||
|
int I2L = 133;
|
||||||
|
int I2F = 134;
|
||||||
|
int I2D = 135;
|
||||||
|
int L2I = 136;
|
||||||
|
int L2F = 137;
|
||||||
|
int L2D = 138;
|
||||||
|
int F2I = 139;
|
||||||
|
int F2L = 140;
|
||||||
|
int F2D = 141;
|
||||||
|
int D2I = 142;
|
||||||
|
int D2L = 143;
|
||||||
|
int D2F = 144;
|
||||||
|
int I2B = 145;
|
||||||
|
int I2C = 146;
|
||||||
|
int I2S = 147;
|
||||||
|
int LCMP = 148;
|
||||||
|
int FCMPL = 149;
|
||||||
|
int FCMPG = 150;
|
||||||
|
int DCMPL = 151;
|
||||||
|
int DCMPG = 152;
|
||||||
|
int IFEQ = 153;
|
||||||
|
int IFNE = 154;
|
||||||
|
int IFLT = 155;
|
||||||
|
int IFGE = 156;
|
||||||
|
int IFGT = 157;
|
||||||
|
int IFLE = 158;
|
||||||
|
int IF_ICMPEQ = 159;
|
||||||
|
int IF_ICMPNE = 160;
|
||||||
|
int IF_ICMPLT = 161;
|
||||||
|
int IF_ICMPGE = 162;
|
||||||
|
int IF_ICMPGT = 163;
|
||||||
|
int IF_ICMPLE = 164;
|
||||||
|
int IF_ACMPEQ = 165;
|
||||||
|
int IF_ACMPNE = 166;
|
||||||
|
int GOTO = 167;
|
||||||
|
int JSR = 168;
|
||||||
|
int RET = 169;
|
||||||
|
int TABLESWITCH = 170;
|
||||||
|
int LOOKUPSWITCH = 171;
|
||||||
|
int IRETURN = 172;
|
||||||
|
int LRETURN = 173;
|
||||||
|
int FRETURN = 174;
|
||||||
|
int DRETURN = 175;
|
||||||
|
int ARETURN = 176;
|
||||||
|
int RETURN = 177;
|
||||||
|
int GETSTATIC = 178;
|
||||||
|
int PUTSTATIC = 179;
|
||||||
|
int GETFIELD = 180;
|
||||||
|
int PUTFIELD = 181;
|
||||||
|
int INVOKEVIRTUAL = 182;
|
||||||
|
int INVOKESPECIAL = 183;
|
||||||
|
int INVOKESTATIC = 184;
|
||||||
|
int INVOKEINTERFACE = 185;
|
||||||
|
int INVOKEDYNAMIC = 186;
|
||||||
|
int NEW = 187;
|
||||||
|
int NEWARRAY = 188;
|
||||||
|
int ANEWARRAY = 189;
|
||||||
|
int ARRAYLENGTH = 190;
|
||||||
|
int ATHROW = 191;
|
||||||
|
int CHECKCAST = 192;
|
||||||
|
int INSTANCEOF = 193;
|
||||||
|
int MONITORENTER = 194;
|
||||||
|
int MONITOREXIT = 195;
|
||||||
|
int MULTIANEWARRAY = 197;
|
||||||
|
int IFNULL = 198;
|
||||||
|
int IFNONNULL = 199;
|
||||||
|
|
||||||
|
boolean matches(AbstractInsnNode insn);
|
||||||
|
|
||||||
|
String emit(State state, AbstractInsnNode insn, StackFrame frame, int pc, int nextPc, Labels labels, String returnType);
|
||||||
|
|
||||||
|
boolean isIntrinsic();
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package dev.jnic.handler;
|
||||||
|
|
||||||
|
import java.util.BitSet;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
|
||||||
|
public abstract class OpcodeHandlerBase implements OpcodeHandler {
|
||||||
|
private final boolean intrinsic;
|
||||||
|
private final BitSet opcodes = new BitSet();
|
||||||
|
|
||||||
|
public OpcodeHandlerBase(boolean intrinsic, int... opcodes) {
|
||||||
|
this.intrinsic = intrinsic;
|
||||||
|
if (opcodes != null) {
|
||||||
|
for (int opcode : opcodes) {
|
||||||
|
this.opcodes.set(opcode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(AbstractInsnNode insn) {
|
||||||
|
return insn != null && insn.getOpcode() >= 0 && this.opcodes.get(insn.getOpcode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isIntrinsic() {
|
||||||
|
return this.intrinsic;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package dev.jnic.intrinsic;
|
||||||
|
|
||||||
|
import dev.jnic.handler.OpcodeHandler;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.FieldInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
|
||||||
|
public abstract class IntrinsicHandlerBase implements OpcodeHandler {
|
||||||
|
private final int opcode;
|
||||||
|
private final String owner;
|
||||||
|
private final String name;
|
||||||
|
private final String descriptor;
|
||||||
|
|
||||||
|
protected IntrinsicHandlerBase(int opcode, String owner, String name, String descriptor) {
|
||||||
|
this.opcode = opcode;
|
||||||
|
this.owner = owner;
|
||||||
|
this.name = name;
|
||||||
|
this.descriptor = descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(AbstractInsnNode insn) {
|
||||||
|
if (insn == null || insn.getOpcode() != this.opcode) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (insn instanceof MethodInsnNode) {
|
||||||
|
MethodInsnNode methodInsn = (MethodInsnNode) insn;
|
||||||
|
return (this.owner == null || this.owner.equals(methodInsn.owner))
|
||||||
|
&& (this.name == null || this.name.equals(methodInsn.name))
|
||||||
|
&& (this.descriptor == null || this.descriptor.equals(methodInsn.desc));
|
||||||
|
}
|
||||||
|
if (insn instanceof FieldInsnNode) {
|
||||||
|
FieldInsnNode fieldInsn = (FieldInsnNode) insn;
|
||||||
|
return (this.owner == null || this.owner.equals(fieldInsn.owner))
|
||||||
|
&& (this.name == null || this.name.equals(fieldInsn.name))
|
||||||
|
&& (this.descriptor == null || this.descriptor.equals(fieldInsn.desc));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isIntrinsic() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package dev.jnic.jar;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
|
||||||
|
public class JarReader {
|
||||||
|
private final Collection<ClassReader> classReaders = new ArrayDeque<>();
|
||||||
|
private final Map<String, byte[]> classBytes = new HashMap<>();
|
||||||
|
|
||||||
|
public JarReader(String path) throws IOException {
|
||||||
|
try (JarFile jarFile = new JarFile(new File(path))) {
|
||||||
|
Enumeration<JarEntry> entries = jarFile.entries();
|
||||||
|
while (entries.hasMoreElements()) {
|
||||||
|
JarEntry entry = entries.nextElement();
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try (InputStream in = jarFile.getInputStream(entry)) {
|
||||||
|
byte[] bytes = in.readAllBytes();
|
||||||
|
this.readEntry(entry, bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void readEntry(JarEntry entry, byte[] bytes) {
|
||||||
|
String name = entry.getName();
|
||||||
|
if (name.endsWith(".class")) {
|
||||||
|
this.classBytes.put(name, bytes);
|
||||||
|
this.classReaders.add(new ClassReader(bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Collection<ClassReader> getClassReaders() {
|
||||||
|
return this.classReaders;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, byte[]> getClassBytes() {
|
||||||
|
return this.classBytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
final class BitTreeDecoder extends LiteralModel {
|
||||||
|
final DistanceDecoder parent;
|
||||||
|
|
||||||
|
BitTreeDecoder(DistanceDecoder parent) {
|
||||||
|
this.parent = parent;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public final class ByteBufferRangeSource extends RangeDecoder {
|
||||||
|
public final byte[] buf = new byte[65531];
|
||||||
|
public int pos = this.buf.length;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void normalize() throws IOException {
|
||||||
|
if ((this.range & 0xFF000000) == 0) {
|
||||||
|
try {
|
||||||
|
this.code = (this.code << 8) | (this.buf[this.pos++] & 0xFF);
|
||||||
|
this.range <<= 8;
|
||||||
|
} catch (ArrayIndexOutOfBoundsException e) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
final class DistanceDecoder extends DistanceParams {
|
||||||
|
final BitTreeDecoder[] subcoders;
|
||||||
|
final LzmaDecoder decoder;
|
||||||
|
|
||||||
|
DistanceDecoder(LzmaDecoder decoder, int lc, int lp) {
|
||||||
|
super(lc, lp);
|
||||||
|
this.decoder = decoder;
|
||||||
|
this.subcoders = new BitTreeDecoder[1 << (lc + lp)];
|
||||||
|
for (int i = 0; i < this.subcoders.length; ++i) {
|
||||||
|
this.subcoders[i] = new BitTreeDecoder(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final void reset() {
|
||||||
|
for (BitTreeDecoder subcoder : this.subcoders) {
|
||||||
|
subcoder.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
abstract class DistanceParams {
|
||||||
|
final int lc;
|
||||||
|
final int posMask;
|
||||||
|
|
||||||
|
DistanceParams(int lc, int lp) {
|
||||||
|
this.lc = lc;
|
||||||
|
this.posMask = (1 << lp) - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.ByteOrder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class JNICLoader extends InputStream {
|
||||||
|
public static ByteBuffer z;
|
||||||
|
private String version = "3.7.0";
|
||||||
|
private DataInputStream in;
|
||||||
|
private LzDictionary lz;
|
||||||
|
private ByteBufferRangeSource rc;
|
||||||
|
private LzmaDecoder lzma;
|
||||||
|
private int uncompressedSize = 0;
|
||||||
|
private boolean isLZMAChunk = false;
|
||||||
|
private boolean needDictReset = true;
|
||||||
|
private boolean needProps = true;
|
||||||
|
private boolean endReached = false;
|
||||||
|
private IOException exception = null;
|
||||||
|
private final byte[] tempBuf = new byte[1];
|
||||||
|
|
||||||
|
public JNICLoader(InputStream in) {
|
||||||
|
this(in, 0x1000000, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public JNICLoader(InputStream in, int dictSize, byte[] presetDict) {
|
||||||
|
if (in == null) {
|
||||||
|
throw new NullPointerException();
|
||||||
|
}
|
||||||
|
if (dictSize < 4096 || dictSize > 0x7FFFFFF0) {
|
||||||
|
throw new IllegalArgumentException();
|
||||||
|
}
|
||||||
|
this.in = new DataInputStream(in);
|
||||||
|
this.rc = new ByteBufferRangeSource();
|
||||||
|
this.lz = new LzDictionary((dictSize + 15) & 0xFFFFFFF0, presetDict);
|
||||||
|
if (presetDict != null && presetDict.length > 0) {
|
||||||
|
this.needDictReset = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int read() throws IOException {
|
||||||
|
if (this.read(this.tempBuf, 0, 1) == -1) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return this.tempBuf[0] & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int read(byte[] buf, int off, int len) throws IOException {
|
||||||
|
if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length) {
|
||||||
|
throw new IndexOutOfBoundsException();
|
||||||
|
}
|
||||||
|
if (len == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (this.in == null) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
if (this.exception != null) {
|
||||||
|
throw this.exception;
|
||||||
|
}
|
||||||
|
if (this.endReached) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
int size = 0;
|
||||||
|
while (len > 0) {
|
||||||
|
if (this.uncompressedSize == 0) {
|
||||||
|
this.decodeChunkHeader();
|
||||||
|
if (this.endReached) {
|
||||||
|
return size == 0 ? -1 : size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int copySizeMax = Math.min(this.uncompressedSize, len);
|
||||||
|
if (!this.isLZMAChunk) {
|
||||||
|
int n = Math.min(this.lz.size - this.lz.pos, copySizeMax);
|
||||||
|
this.in.readFully(this.lz.buf, this.lz.pos, n);
|
||||||
|
this.lz.pos += n;
|
||||||
|
if (this.lz.full < this.lz.pos) {
|
||||||
|
this.lz.full = this.lz.pos;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this.lz.size - this.lz.pos <= copySizeMax) {
|
||||||
|
this.lz.limit = this.lz.size;
|
||||||
|
} else {
|
||||||
|
this.lz.limit = this.lz.pos + copySizeMax;
|
||||||
|
}
|
||||||
|
this.lzma.decode();
|
||||||
|
}
|
||||||
|
int copied = this.lz.pos - this.lz.start;
|
||||||
|
if (this.lz.pos == this.lz.size) {
|
||||||
|
this.lz.pos = 0;
|
||||||
|
}
|
||||||
|
System.arraycopy(this.lz.buf, this.lz.start, buf, off, copied);
|
||||||
|
this.lz.start = this.lz.pos;
|
||||||
|
off += copied;
|
||||||
|
len -= copied;
|
||||||
|
size += copied;
|
||||||
|
this.uncompressedSize -= copied;
|
||||||
|
if (this.uncompressedSize == 0) {
|
||||||
|
if (this.rc.pos != this.rc.buf.length || this.rc.code != 0 || this.lz.pendingLen > 0) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
} catch (IOException e) {
|
||||||
|
this.exception = e;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void decodeChunkHeader() throws IOException {
|
||||||
|
int control = this.in.readUnsignedByte();
|
||||||
|
if (control == 0) {
|
||||||
|
this.endReached = true;
|
||||||
|
this.releaseResources();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (control >= 224 || control == 1) {
|
||||||
|
this.needProps = true;
|
||||||
|
this.needDictReset = false;
|
||||||
|
this.lz.start = 0;
|
||||||
|
this.lz.pos = 0;
|
||||||
|
this.lz.full = 0;
|
||||||
|
this.lz.limit = 0;
|
||||||
|
this.lz.buf[this.lz.size - 1] = 0;
|
||||||
|
} else if (this.needDictReset) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
if (control >= 128) {
|
||||||
|
this.isLZMAChunk = true;
|
||||||
|
this.uncompressedSize = (control & 0x1F) << 16;
|
||||||
|
this.uncompressedSize += this.in.readUnsignedShort() + 1;
|
||||||
|
int compressedSize = this.in.readUnsignedShort() + 1;
|
||||||
|
if (control >= 192) {
|
||||||
|
this.needProps = false;
|
||||||
|
this.decodeProps();
|
||||||
|
} else {
|
||||||
|
if (this.needProps) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
if (control >= 160) {
|
||||||
|
this.lzma.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (compressedSize < 5) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
if (this.in.readUnsignedByte() != 0) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
this.rc.code = this.in.readInt();
|
||||||
|
this.rc.range = -1;
|
||||||
|
int remaining = compressedSize - 5;
|
||||||
|
this.rc.pos = this.rc.buf.length - remaining;
|
||||||
|
this.in.readFully(this.rc.buf, this.rc.pos, remaining);
|
||||||
|
} else {
|
||||||
|
if (control > 2) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
this.isLZMAChunk = false;
|
||||||
|
this.uncompressedSize = this.in.readUnsignedShort() + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void decodeProps() throws IOException {
|
||||||
|
int props = this.in.readUnsignedByte();
|
||||||
|
if (props > 224) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
int pb = props / 45;
|
||||||
|
props -= pb * 9 * 5;
|
||||||
|
int lp = props / 9;
|
||||||
|
int lc = props - lp * 9;
|
||||||
|
if (lc + lp > 4) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
this.lzma = new LzmaDecoder(this.lz, this.rc, lc, lp, pb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int available() throws IOException {
|
||||||
|
if (this.in == null) {
|
||||||
|
throw new IOException("closed");
|
||||||
|
}
|
||||||
|
if (this.exception != null) {
|
||||||
|
throw this.exception;
|
||||||
|
}
|
||||||
|
return this.isLZMAChunk ? this.uncompressedSize : Math.min(this.uncompressedSize, this.in.available());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void releaseResources() {
|
||||||
|
if (this.lz != null) {
|
||||||
|
this.lz = null;
|
||||||
|
this.rc = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
if (this.in != null) {
|
||||||
|
this.releaseResources();
|
||||||
|
try {
|
||||||
|
this.in.close();
|
||||||
|
} finally {
|
||||||
|
this.in = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void init() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String platformKey(String os, String arch) {
|
||||||
|
boolean x86 = arch.equals("x86_64") || arch.equals("amd64") || arch.equals("x64");
|
||||||
|
boolean arm = arch.equals("aarch64") || arch.equals("arm64");
|
||||||
|
if (os.contains("win") && x86) return "WINDOWS_X86_64";
|
||||||
|
if (os.contains("win") && arm) return "WINDOWS_AARCH64";
|
||||||
|
if (os.contains("mac") && x86) return "MACOS_X86_64";
|
||||||
|
if (os.contains("mac") && arm) return "MACOS_AARCH64";
|
||||||
|
if (os.contains("lin") && x86) return "LINUX_X86_64";
|
||||||
|
if (os.contains("lin") && arm) return "LINUX_AARCH64";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long[] readLayout(String platform) {
|
||||||
|
try (InputStream layout = JNICLoader.class.getResourceAsStream("/dev/jnic/lib/layout.txt")) {
|
||||||
|
if (layout == null) return null;
|
||||||
|
String text = new String(layout.readAllBytes(), StandardCharsets.UTF_8);
|
||||||
|
for (String line : text.split("\\R")) {
|
||||||
|
String[] parts = line.trim().split("\\s+");
|
||||||
|
if (parts.length == 3 && parts[0].equals(platform)) {
|
||||||
|
return new long[]{Long.parseLong(parts[1]), Long.parseLong(parts[2])};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException | RuntimeException ignored) {
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static {
|
||||||
|
Stream<String> stream = ManagementFactory.getRuntimeMXBean().getInputArguments().stream();
|
||||||
|
List<String> list = Arrays.asList("-javaagent", "-agentlib");
|
||||||
|
Objects.requireNonNull(list);
|
||||||
|
if (!stream.anyMatch(list::contains)) {
|
||||||
|
z = ByteBuffer.allocateDirect(64).order(ByteOrder.LITTLE_ENDIAN);
|
||||||
|
String os = System.getProperty("os.name").toLowerCase();
|
||||||
|
String arch = System.getProperty("os.arch").toLowerCase();
|
||||||
|
long start = 0L;
|
||||||
|
long end = 0L;
|
||||||
|
String platform = platformKey(os, arch);
|
||||||
|
long[] range = platform == null ? null : readLayout(platform);
|
||||||
|
if (range != null) {
|
||||||
|
start = range[0];
|
||||||
|
end = range[1];
|
||||||
|
}
|
||||||
|
if (range == null && os.contains("lin") && (arch.equals("x86_64") || arch.equals("amd64"))) {
|
||||||
|
start = 22947080L;
|
||||||
|
end = 32608048L;
|
||||||
|
z.putInt(-567463365);
|
||||||
|
z.putInt(1401376760);
|
||||||
|
z.putInt(997729761);
|
||||||
|
z.putInt(1502854057);
|
||||||
|
z.putInt(1456950269);
|
||||||
|
z.putInt(2068781566);
|
||||||
|
z.putInt(-2074230231);
|
||||||
|
z.putInt(-877438771);
|
||||||
|
}
|
||||||
|
if (range == null && os.contains("mac") && arch.equals("aarch64")) {
|
||||||
|
start = 16419456L;
|
||||||
|
end = 22947080L;
|
||||||
|
z.putInt(1014097172);
|
||||||
|
z.putInt(-117690684);
|
||||||
|
z.putInt(820061173);
|
||||||
|
z.putInt(-1688620839);
|
||||||
|
z.putInt(-1273992576);
|
||||||
|
z.putInt(1914204887);
|
||||||
|
z.putInt(-1152264584);
|
||||||
|
z.putInt(-36053678);
|
||||||
|
}
|
||||||
|
if (range == null && os.contains("win") && (arch.equals("x86_64") || arch.equals("amd64"))) {
|
||||||
|
start = 0L;
|
||||||
|
end = 7558656L;
|
||||||
|
z.putInt(-1114421519);
|
||||||
|
z.putInt(457382690);
|
||||||
|
z.putInt(1129719259);
|
||||||
|
z.putInt(1518767796);
|
||||||
|
z.putInt(1901767710);
|
||||||
|
z.putInt(1310480474);
|
||||||
|
z.putInt(1420822585);
|
||||||
|
z.putInt(-1793329926);
|
||||||
|
}
|
||||||
|
if (range == null && os.contains("mac") && (arch.equals("x86_64") || arch.equals("amd64"))) {
|
||||||
|
start = 7558656L;
|
||||||
|
end = 16419456L;
|
||||||
|
z.putInt(1314687260);
|
||||||
|
z.putInt(-478689012);
|
||||||
|
z.putInt(-2086494599);
|
||||||
|
z.putInt(551956295);
|
||||||
|
z.putInt(410610689);
|
||||||
|
z.putInt(-1224114266);
|
||||||
|
z.putInt(-1353435766);
|
||||||
|
z.putInt(-1032801772);
|
||||||
|
}
|
||||||
|
if (start != end) {
|
||||||
|
InputStream resourceStream = JNICLoader.class.getResourceAsStream("/dev/jnic/lib/3273ada3-3474-4e4e-9623-319038d7e4bb.dat");
|
||||||
|
if (resourceStream != null) {
|
||||||
|
File file;
|
||||||
|
try {
|
||||||
|
file = File.createTempFile("lib", null);
|
||||||
|
file.deleteOnExit();
|
||||||
|
if (!file.exists()) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UnsatisfiedLinkError("Failed to create temp file");
|
||||||
|
}
|
||||||
|
byte[] buffer = new byte[2048];
|
||||||
|
try (JNICLoader decoder = new JNICLoader(resourceStream);
|
||||||
|
FileOutputStream out = new FileOutputStream(file)) {
|
||||||
|
long pos = 0L;
|
||||||
|
while (pos < start) {
|
||||||
|
long skipped = decoder.skip(start - pos);
|
||||||
|
if (skipped <= 0L) {
|
||||||
|
throw new IOException("failed to skip: " + pos);
|
||||||
|
}
|
||||||
|
pos += skipped;
|
||||||
|
}
|
||||||
|
while (pos < end) {
|
||||||
|
int n = decoder.read(buffer, 0, (int) Math.min(buffer.length, end - pos));
|
||||||
|
if (n < 0) break;
|
||||||
|
out.write(buffer, 0, n);
|
||||||
|
pos += n;
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UnsatisfiedLinkError("Failed to extract file: " + e.getMessage());
|
||||||
|
}
|
||||||
|
z.putInt(-1731935906);
|
||||||
|
z.putInt(-851835500);
|
||||||
|
z.putInt(-880934708);
|
||||||
|
System.load(file.getAbsolutePath());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
final class LengthDecoder extends LengthModel {
|
||||||
|
private final LzmaDecoder decoder;
|
||||||
|
|
||||||
|
LengthDecoder(LzmaDecoder decoder) {
|
||||||
|
this.decoder = decoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
final int decode(int posState) throws IOException {
|
||||||
|
if (this.decoder.rc.decodeBit(this.choice, 0) == 0) {
|
||||||
|
return this.decoder.rc.decodeBitTree(this.low[posState]) + 2;
|
||||||
|
}
|
||||||
|
if (this.decoder.rc.decodeBit(this.choice, 1) == 0) {
|
||||||
|
return this.decoder.rc.decodeBitTree(this.mid[posState]) + 2 + 8;
|
||||||
|
}
|
||||||
|
return this.decoder.rc.decodeBitTree(this.high) + 2 + 8 + 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
abstract class LengthModel {
|
||||||
|
final short[] choice = new short[2];
|
||||||
|
final short[][] low = new short[16][8];
|
||||||
|
final short[][] mid = new short[16][8];
|
||||||
|
final short[] high = new short[256];
|
||||||
|
|
||||||
|
LengthModel() {
|
||||||
|
}
|
||||||
|
|
||||||
|
final void reset() {
|
||||||
|
Arrays.fill(this.choice, (short) 1024);
|
||||||
|
for (short[] row : this.low) {
|
||||||
|
Arrays.fill(row, (short) 1024);
|
||||||
|
}
|
||||||
|
for (short[] row : this.mid) {
|
||||||
|
Arrays.fill(row, (short) 1024);
|
||||||
|
}
|
||||||
|
Arrays.fill(this.high, (short) 1024);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
abstract class LiteralModel {
|
||||||
|
final short[] probs = new short[768];
|
||||||
|
|
||||||
|
LiteralModel() {
|
||||||
|
}
|
||||||
|
|
||||||
|
final void reset() {
|
||||||
|
Arrays.fill(this.probs, (short) 1024);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public final class LzDictionary {
|
||||||
|
public final byte[] buf;
|
||||||
|
public final int size;
|
||||||
|
public int start = 0;
|
||||||
|
public int pos = 0;
|
||||||
|
public int full = 0;
|
||||||
|
public int limit = 0;
|
||||||
|
public int pendingLen = 0;
|
||||||
|
public int pendingDist = 0;
|
||||||
|
|
||||||
|
public LzDictionary(int dictSize, byte[] presetDict) {
|
||||||
|
this.size = dictSize;
|
||||||
|
this.buf = new byte[this.size];
|
||||||
|
if (presetDict != null) {
|
||||||
|
this.pos = Math.min(presetDict.length, dictSize);
|
||||||
|
this.full = this.pos;
|
||||||
|
this.start = this.pos;
|
||||||
|
System.arraycopy(presetDict, presetDict.length - this.pos, this.buf, 0, this.pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getByte(int dist) {
|
||||||
|
int offset = this.pos - dist - 1;
|
||||||
|
if (dist >= this.pos) {
|
||||||
|
offset += this.size;
|
||||||
|
}
|
||||||
|
return this.buf[offset] & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void repeat(int dist, int len) throws IOException {
|
||||||
|
if (dist < 0 || dist >= this.full) {
|
||||||
|
throw new IOException();
|
||||||
|
}
|
||||||
|
int left = Math.min(this.limit - this.pos, len);
|
||||||
|
this.pendingLen = len - left;
|
||||||
|
this.pendingDist = dist;
|
||||||
|
int back = this.pos - dist - 1;
|
||||||
|
if (back < 0) {
|
||||||
|
assert this.full == this.size;
|
||||||
|
back += this.size;
|
||||||
|
int copySize = Math.min(this.size - back, left);
|
||||||
|
assert copySize <= dist + 1;
|
||||||
|
System.arraycopy(this.buf, back, this.buf, this.pos, copySize);
|
||||||
|
this.pos += copySize;
|
||||||
|
back = 0;
|
||||||
|
left -= copySize;
|
||||||
|
if (left == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert back < this.pos;
|
||||||
|
assert left > 0;
|
||||||
|
do {
|
||||||
|
int copySize = Math.min(left, this.pos - back);
|
||||||
|
System.arraycopy(this.buf, back, this.buf, this.pos, copySize);
|
||||||
|
this.pos += copySize;
|
||||||
|
left -= copySize;
|
||||||
|
} while (left > 0);
|
||||||
|
if (this.full < this.pos) {
|
||||||
|
this.full = this.pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public final class LzmaDecoder extends LzmaState {
|
||||||
|
final LzDictionary dict;
|
||||||
|
final RangeDecoder rc;
|
||||||
|
private final DistanceDecoder literalDecoder;
|
||||||
|
private final LengthDecoder matchLenDecoder = new LengthDecoder(this);
|
||||||
|
private final LengthDecoder repLenDecoder = new LengthDecoder(this);
|
||||||
|
|
||||||
|
public LzmaDecoder(LzDictionary dict, RangeDecoder rc, int lc, int lp, int pb) {
|
||||||
|
super(pb);
|
||||||
|
this.dict = dict;
|
||||||
|
this.rc = rc;
|
||||||
|
this.literalDecoder = new DistanceDecoder(this, lc, lp);
|
||||||
|
this.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reset() {
|
||||||
|
super.reset();
|
||||||
|
this.literalDecoder.reset();
|
||||||
|
this.matchLenDecoder.reset();
|
||||||
|
this.repLenDecoder.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void decode() throws IOException {
|
||||||
|
if (this.dict.pendingLen > 0) {
|
||||||
|
this.dict.repeat(this.dict.pendingDist, this.dict.pendingLen);
|
||||||
|
}
|
||||||
|
while (this.dict.pos < this.dict.limit) {
|
||||||
|
int posState = this.dict.pos & this.posMask;
|
||||||
|
if (this.rc.decodeBit(this.isMatch[this.state.state], posState) == 0) {
|
||||||
|
this.decodeLiteral();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int len;
|
||||||
|
if (this.rc.decodeBit(this.isRep, this.state.state) == 0) {
|
||||||
|
len = this.decodeMatch(posState);
|
||||||
|
} else {
|
||||||
|
len = this.decodeRepMatch(posState);
|
||||||
|
}
|
||||||
|
this.dict.repeat(this.reps[0], len);
|
||||||
|
}
|
||||||
|
this.rc.normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void decodeLiteral() throws IOException {
|
||||||
|
int i = ((this.dict.getByte(0) >> (8 - this.literalDecoder.lc))
|
||||||
|
+ ((this.dict.pos & this.literalDecoder.posMask) << this.literalDecoder.lc));
|
||||||
|
BitTreeDecoder subcoder = this.literalDecoder.subcoders[i];
|
||||||
|
int symbol = 1;
|
||||||
|
if (this.state.state < 7) {
|
||||||
|
do {
|
||||||
|
symbol = (symbol << 1) | this.rc.decodeBit(subcoder.probs, symbol);
|
||||||
|
} while (symbol < 256);
|
||||||
|
} else {
|
||||||
|
int matchByte = this.dict.getByte(this.reps[0]);
|
||||||
|
int offset = 256;
|
||||||
|
do {
|
||||||
|
matchByte <<= 1;
|
||||||
|
int matchBit = matchByte & offset;
|
||||||
|
int bit = this.rc.decodeBit(subcoder.probs, offset + matchBit + symbol);
|
||||||
|
symbol = (symbol << 1) | bit;
|
||||||
|
offset &= (0 - bit) ^ ~matchBit;
|
||||||
|
} while (symbol < 256);
|
||||||
|
}
|
||||||
|
this.dict.buf[this.dict.pos++] = (byte) symbol;
|
||||||
|
if (this.dict.full < this.dict.pos) {
|
||||||
|
this.dict.full = this.dict.pos;
|
||||||
|
}
|
||||||
|
if (this.state.state <= 3) {
|
||||||
|
this.state.state = 0;
|
||||||
|
} else if (this.state.state <= 9) {
|
||||||
|
this.state.state -= 3;
|
||||||
|
} else {
|
||||||
|
this.state.state -= 6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int decodeMatch(int posState) throws IOException {
|
||||||
|
this.state.state = this.state.state < 7 ? 7 : 10;
|
||||||
|
this.reps[3] = this.reps[2];
|
||||||
|
this.reps[2] = this.reps[1];
|
||||||
|
this.reps[1] = this.reps[0];
|
||||||
|
int len = this.matchLenDecoder.decode(posState);
|
||||||
|
int distSlot = this.rc.decodeBitTree(this.distSlots[len < 6 ? len - 2 : 3]);
|
||||||
|
if (distSlot < 4) {
|
||||||
|
this.reps[0] = distSlot;
|
||||||
|
} else {
|
||||||
|
int limit = (distSlot >> 1) - 1;
|
||||||
|
this.reps[0] = (2 | (distSlot & 1)) << limit;
|
||||||
|
if (distSlot < 14) {
|
||||||
|
this.reps[0] |= this.rc.decodeReverseBitTree(this.distSpecial[distSlot - 4]);
|
||||||
|
} else {
|
||||||
|
int count = limit - 4;
|
||||||
|
int directBits = 0;
|
||||||
|
do {
|
||||||
|
this.rc.normalize();
|
||||||
|
this.rc.range >>>= 1;
|
||||||
|
int t = (this.rc.code - this.rc.range) >>> 31;
|
||||||
|
this.rc.code -= this.rc.range & (t - 1);
|
||||||
|
directBits = (directBits << 1) | (1 - t);
|
||||||
|
} while (--count != 0);
|
||||||
|
this.reps[0] |= directBits << 4;
|
||||||
|
this.reps[0] |= this.rc.decodeReverseBitTree(this.distAlign);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int decodeRepMatch(int posState) throws IOException {
|
||||||
|
if (this.rc.decodeBit(this.isRep0, this.state.state) == 0) {
|
||||||
|
if (this.rc.decodeBit(this.isRep0Long[this.state.state], posState) == 0) {
|
||||||
|
this.state.state = this.state.state < 7 ? 9 : 11;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int dist;
|
||||||
|
if (this.rc.decodeBit(this.isRep1, this.state.state) == 0) {
|
||||||
|
dist = this.reps[1];
|
||||||
|
} else {
|
||||||
|
if (this.rc.decodeBit(this.isRep2, this.state.state) == 0) {
|
||||||
|
dist = this.reps[2];
|
||||||
|
} else {
|
||||||
|
dist = this.reps[3];
|
||||||
|
this.reps[3] = this.reps[2];
|
||||||
|
}
|
||||||
|
this.reps[2] = this.reps[1];
|
||||||
|
}
|
||||||
|
this.reps[1] = this.reps[0];
|
||||||
|
this.reps[0] = dist;
|
||||||
|
}
|
||||||
|
this.state.state = this.state.state < 7 ? 8 : 11;
|
||||||
|
return this.repLenDecoder.decode(posState);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
abstract class LzmaState {
|
||||||
|
final int posMask;
|
||||||
|
final int[] reps = new int[4];
|
||||||
|
final LzmaStateBox state = new LzmaStateBox();
|
||||||
|
final short[][] isMatch = new short[12][16];
|
||||||
|
final short[] isRep = new short[12];
|
||||||
|
final short[] isRep0 = new short[12];
|
||||||
|
final short[] isRep1 = new short[12];
|
||||||
|
final short[] isRep2 = new short[12];
|
||||||
|
final short[][] isRep0Long = new short[12][16];
|
||||||
|
final short[][] distSlots = new short[4][64];
|
||||||
|
final short[][] distSpecial = new short[][]{
|
||||||
|
new short[2], new short[2], new short[4], new short[4],
|
||||||
|
new short[8], new short[8], new short[16], new short[16],
|
||||||
|
new short[32], new short[32]
|
||||||
|
};
|
||||||
|
final short[] distAlign = new short[16];
|
||||||
|
|
||||||
|
LzmaState(int pb) {
|
||||||
|
this.posMask = (1 << pb) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
Arrays.fill(this.reps, 0);
|
||||||
|
this.state.state = 0;
|
||||||
|
for (short[] row : this.isMatch) {
|
||||||
|
Arrays.fill(row, (short) 1024);
|
||||||
|
}
|
||||||
|
Arrays.fill(this.isRep, (short) 1024);
|
||||||
|
Arrays.fill(this.isRep0, (short) 1024);
|
||||||
|
Arrays.fill(this.isRep1, (short) 1024);
|
||||||
|
Arrays.fill(this.isRep2, (short) 1024);
|
||||||
|
for (short[] row : this.isRep0Long) {
|
||||||
|
Arrays.fill(row, (short) 1024);
|
||||||
|
}
|
||||||
|
for (short[] row : this.distSlots) {
|
||||||
|
Arrays.fill(row, (short) 1024);
|
||||||
|
}
|
||||||
|
for (short[] row : this.distSpecial) {
|
||||||
|
Arrays.fill(row, (short) 1024);
|
||||||
|
}
|
||||||
|
Arrays.fill(this.distAlign, (short) 1024);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
final class LzmaStateBox {
|
||||||
|
int state;
|
||||||
|
|
||||||
|
LzmaStateBox() {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package dev.jnic.loader;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public abstract class RangeDecoder {
|
||||||
|
public int range = 0;
|
||||||
|
public int code = 0;
|
||||||
|
|
||||||
|
public abstract void normalize() throws IOException;
|
||||||
|
|
||||||
|
public final int decodeBit(short[] probs, int index) throws IOException {
|
||||||
|
this.normalize();
|
||||||
|
short prob = probs[index];
|
||||||
|
int bound = (this.range >>> 11) * prob;
|
||||||
|
if ((this.code ^ Integer.MIN_VALUE) < (bound ^ Integer.MIN_VALUE)) {
|
||||||
|
this.range = bound;
|
||||||
|
probs[index] = (short) (prob + ((2048 - prob) >>> 5));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
this.range -= bound;
|
||||||
|
this.code -= bound;
|
||||||
|
probs[index] = (short) (prob - (prob >>> 5));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int decodeBitTree(short[] probs) throws IOException {
|
||||||
|
int symbol = 1;
|
||||||
|
do {
|
||||||
|
symbol = (symbol << 1) | this.decodeBit(probs, symbol);
|
||||||
|
} while (symbol < probs.length);
|
||||||
|
return symbol - probs.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public final int decodeReverseBitTree(short[] probs) throws IOException {
|
||||||
|
int symbol = 1;
|
||||||
|
int i = 0;
|
||||||
|
int result = 0;
|
||||||
|
do {
|
||||||
|
int bit = this.decodeBit(probs, symbol);
|
||||||
|
symbol = (symbol << 1) | bit;
|
||||||
|
result |= bit << i++;
|
||||||
|
} while (symbol < probs.length);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package dev.jnic.pipeline;
|
||||||
|
|
||||||
|
import dev.jnic.type.MethodMatcher;
|
||||||
|
import dev.jnic.util.Platform;
|
||||||
|
import java.util.List;
|
||||||
|
import org.objectweb.asm.tree.AnnotationNode;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
import org.simpleframework.xml.Element;
|
||||||
|
import org.simpleframework.xml.ElementList;
|
||||||
|
import org.simpleframework.xml.Root;
|
||||||
|
|
||||||
|
@Root(name = "jnic")
|
||||||
|
public class Config {
|
||||||
|
@Element(name = "options", required = false)
|
||||||
|
private Options options;
|
||||||
|
@ElementList(name = "targets", entry = "target", required = false)
|
||||||
|
private List<Platform> targets;
|
||||||
|
@Element(name = "includeAnnotation", required = false)
|
||||||
|
private String includeAnnotation;
|
||||||
|
@Element(name = "excludeAnnotation", required = false)
|
||||||
|
private String excludeAnnotation;
|
||||||
|
@ElementList(name = "include", required = false)
|
||||||
|
private List<MethodMatcher> include;
|
||||||
|
@ElementList(name = "exclude", required = false)
|
||||||
|
private List<MethodMatcher> exclude;
|
||||||
|
|
||||||
|
public Options getOptions() {
|
||||||
|
return this.options;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Platform> getTargets() {
|
||||||
|
return this.targets;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isIncluded(ClassNode classNode, MethodNode methodNode) {
|
||||||
|
if (this.includeAnnotation != null && !this.includeAnnotation.isEmpty()
|
||||||
|
&& (this.hasIncludeAnnotation(classNode) || this.hasIncludeAnnotation(methodNode))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (this.excludeAnnotation != null && !this.excludeAnnotation.isEmpty()
|
||||||
|
&& (this.hasExcludeAnnotation(classNode) || this.hasExcludeAnnotation(methodNode))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
boolean included = this.include == null || this.include.isEmpty();
|
||||||
|
if (!included) {
|
||||||
|
for (MethodMatcher matcher : this.include) {
|
||||||
|
if (matcher.matches(classNode.name, methodNode.name, methodNode.desc)) {
|
||||||
|
included = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!included) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (this.exclude != null) {
|
||||||
|
for (MethodMatcher matcher : this.exclude) {
|
||||||
|
if (matcher.matches(classNode.name, methodNode.name, methodNode.desc)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasAnnotation(List<AnnotationNode> annotations, String target) {
|
||||||
|
if (annotations == null || target == null || target.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (AnnotationNode annotation : annotations) {
|
||||||
|
if (annotation == null || annotation.desc == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String name = annotation.desc.replace('/', '.');
|
||||||
|
if (name.length() > 1 && name.charAt(0) == 'L' && name.endsWith(";")) {
|
||||||
|
name = name.substring(1, name.length() - 1);
|
||||||
|
}
|
||||||
|
if (name.equals(target)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasIncludeAnnotation(MethodNode methodNode) {
|
||||||
|
return hasAnnotation(methodNode.visibleAnnotations, this.includeAnnotation)
|
||||||
|
|| hasAnnotation(methodNode.invisibleAnnotations, this.includeAnnotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasExcludeAnnotation(MethodNode methodNode) {
|
||||||
|
return hasAnnotation(methodNode.visibleAnnotations, this.excludeAnnotation)
|
||||||
|
|| hasAnnotation(methodNode.invisibleAnnotations, this.excludeAnnotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasIncludeAnnotation(ClassNode classNode) {
|
||||||
|
return hasAnnotation(classNode.visibleAnnotations, this.includeAnnotation)
|
||||||
|
|| hasAnnotation(classNode.invisibleAnnotations, this.includeAnnotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasExcludeAnnotation(ClassNode classNode) {
|
||||||
|
return hasAnnotation(classNode.visibleAnnotations, this.excludeAnnotation)
|
||||||
|
|| hasAnnotation(classNode.invisibleAnnotations, this.excludeAnnotation);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package dev.jnic.pipeline;
|
||||||
|
|
||||||
|
public class Entry {
|
||||||
|
private final String name;
|
||||||
|
private final String descriptor;
|
||||||
|
private final byte[] data;
|
||||||
|
|
||||||
|
public Entry(String name, String descriptor, byte[] data) {
|
||||||
|
this.name = name;
|
||||||
|
this.descriptor = descriptor;
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescriptor() {
|
||||||
|
return this.descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getData() {
|
||||||
|
return this.data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package dev.jnic.pipeline;
|
||||||
|
|
||||||
|
import org.simpleframework.xml.Element;
|
||||||
|
import org.simpleframework.xml.Root;
|
||||||
|
|
||||||
|
@Root(name = "options")
|
||||||
|
public class Options {
|
||||||
|
public static final Options INSTANCE = new Options();
|
||||||
|
|
||||||
|
@Element(name = "stringObf", required = false)
|
||||||
|
private boolean stringObf;
|
||||||
|
@Element(name = "flowObf", required = false)
|
||||||
|
private boolean flowObf;
|
||||||
|
@Element(name = "nativeIntegrity", required = false)
|
||||||
|
private boolean nativeIntegrity;
|
||||||
|
@Element(name = "jarIntegrity", required = false)
|
||||||
|
private boolean jarIntegrity;
|
||||||
|
@Element(name = "antiDebug", required = false)
|
||||||
|
private boolean antiDebug;
|
||||||
|
@Element(name = "useIntrinsics", required = false)
|
||||||
|
private boolean useIntrinsics;
|
||||||
|
@Element(name = "fastCompile", required = false)
|
||||||
|
private boolean fastCompile;
|
||||||
|
|
||||||
|
public Options() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Options(Options source) {
|
||||||
|
this.stringObf = source.stringObf;
|
||||||
|
this.flowObf = source.flowObf;
|
||||||
|
this.nativeIntegrity = source.nativeIntegrity;
|
||||||
|
this.jarIntegrity = source.jarIntegrity;
|
||||||
|
this.antiDebug = source.antiDebug;
|
||||||
|
this.useIntrinsics = source.useIntrinsics;
|
||||||
|
this.fastCompile = source.fastCompile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isStringObfuscationEnabled() {
|
||||||
|
return this.stringObf;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFlowObfuscationEnabled() {
|
||||||
|
return this.flowObf;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isNativeIntegrityEnabled() {
|
||||||
|
return this.nativeIntegrity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isJarIntegrityEnabled() {
|
||||||
|
return this.jarIntegrity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isAntiDebugEnabled() {
|
||||||
|
return this.antiDebug;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUseIntrinsicsEnabled() {
|
||||||
|
return this.useIntrinsics;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFastCompileEnabled() {
|
||||||
|
return this.fastCompile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStringObfuscationEnabled(boolean value) {
|
||||||
|
this.stringObf = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFlowObfuscationEnabled(boolean value) {
|
||||||
|
this.flowObf = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNativeIntegrityEnabled(boolean value) {
|
||||||
|
this.nativeIntegrity = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setJarIntegrityEnabled(boolean value) {
|
||||||
|
this.jarIntegrity = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAntiDebugEnabled(boolean value) {
|
||||||
|
this.antiDebug = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUseIntrinsicsEnabled(boolean value) {
|
||||||
|
this.useIntrinsics = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFastCompileEnabled(boolean value) {
|
||||||
|
this.fastCompile = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Options{stringObf=" + this.stringObf
|
||||||
|
+ ", flowObf=" + this.flowObf
|
||||||
|
+ ", nativeIntegrity=" + this.nativeIntegrity
|
||||||
|
+ ", jarIntegrity=" + this.jarIntegrity
|
||||||
|
+ ", antiDebug=" + this.antiDebug
|
||||||
|
+ ", useIntrinsics=" + this.useIntrinsics
|
||||||
|
+ ", fastCompile=" + this.fastCompile + "}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
package dev.jnic.pipeline;
|
||||||
|
|
||||||
|
import dev.jnic.translate.CType;
|
||||||
|
import dev.jnic.translate.ClassNativizer;
|
||||||
|
import dev.jnic.translate.LoaderResources;
|
||||||
|
import dev.jnic.util.Log;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.jar.JarOutputStream;
|
||||||
|
import java.util.jar.Manifest;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import org.tukaani.xz.ArrayCache;
|
||||||
|
import org.tukaani.xz.FinishableOutputStream;
|
||||||
|
import org.tukaani.xz.FinishableWrapperOutputStream;
|
||||||
|
import org.tukaani.xz.LZMA2Options;
|
||||||
|
|
||||||
|
public final class Rewriter {
|
||||||
|
private static final String PAYLOAD_PATH = "dev/jnic/lib/3273ada3-3474-4e4e-9623-319038d7e4bb.dat";
|
||||||
|
private static final String LAYOUT_PATH = "dev/jnic/lib/layout.txt";
|
||||||
|
private static final String MANIFEST_PATH = "META-INF/MANIFEST.MF";
|
||||||
|
|
||||||
|
private Rewriter() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void rewrite(Path input, Path output, Path config, Path compiler, List<String> targets) throws IOException, InterruptedException {
|
||||||
|
Path sourcesDir = output.resolveSibling("jnic-sources");
|
||||||
|
Log.debug("Temporary files will be stored in " + sourcesDir);
|
||||||
|
Manifest manifest;
|
||||||
|
Map<String, byte[]> entries = new LinkedHashMap<>();
|
||||||
|
List<ClassUnit> units = new ArrayList<>();
|
||||||
|
int classIndex = 0;
|
||||||
|
try (JarFile jar = new JarFile(input.toFile())) {
|
||||||
|
manifest = jar.getManifest();
|
||||||
|
for (JarEntry entry : Collections.list(jar.entries())) {
|
||||||
|
String name = entry.getName();
|
||||||
|
if (entry.isDirectory() || MANIFEST_PATH.equalsIgnoreCase(name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
byte[] bytes = readAll(jar.getInputStream(entry));
|
||||||
|
if (name.endsWith(".class")) {
|
||||||
|
ClassNativizer.Result result = ClassNativizer.nativize(name, bytes, classIndex++);
|
||||||
|
entries.put(name, result.bytes);
|
||||||
|
if (!result.nativized() || result.internalName == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Log.debug("Processing class <" + result.internalName + ">");
|
||||||
|
for (ClassNativizer.Registration registration : result.registrations) {
|
||||||
|
Log.debug(" -> " + displayName(registration) + registration.descriptor);
|
||||||
|
}
|
||||||
|
units.add(new ClassUnit(result.internalName, result.registrations));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
entries.put(name, bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries.putAll(LoaderResources.load());
|
||||||
|
String source = emitSource(units);
|
||||||
|
Files.createDirectories(sourcesDir);
|
||||||
|
Path cFile = sourcesDir.resolve("jnic.c");
|
||||||
|
Files.write(cFile, source.getBytes(StandardCharsets.UTF_8));
|
||||||
|
Log.info("Saving translated sources");
|
||||||
|
Log.info("Compiling sources");
|
||||||
|
List<byte[]> libraries = new ArrayList<>();
|
||||||
|
StringBuilder layout = new StringBuilder();
|
||||||
|
long offset = 0L;
|
||||||
|
long total = 0L;
|
||||||
|
for (String target : targets) {
|
||||||
|
Log.debug(" -> " + target);
|
||||||
|
byte[] library = compile(compiler, cFile, sourcesDir, target);
|
||||||
|
layout.append(target).append(' ').append(offset).append(' ').append(offset + library.length).append('\n');
|
||||||
|
offset += library.length;
|
||||||
|
total += library.length;
|
||||||
|
libraries.add(library);
|
||||||
|
}
|
||||||
|
Log.info("Finished compilation");
|
||||||
|
Log.info("Compressing native libraries (total size: " + kib(total) + ") (preset: 6)");
|
||||||
|
byte[] payload = compress(concat(libraries));
|
||||||
|
Log.info("Compressed size: " + kib(payload.length) + " (ratio: " + ((float) payload.length / (float) total) + ")");
|
||||||
|
Log.info("Preparing output JAR file");
|
||||||
|
for (ClassUnit unit : units) {
|
||||||
|
for (ClassNativizer.Registration registration : unit.registrations) {
|
||||||
|
Log.debug("Deleted " + unit.internalName + "." + displayName(registration) + registration.descriptor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.info("Writing to file " + output);
|
||||||
|
repackage(output, entries, payload, layout.toString(), manifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String displayName(ClassNativizer.Registration registration) {
|
||||||
|
return "$jnicClinit".equals(registration.name) ? "<clinit>" : registration.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String kib(long bytes) {
|
||||||
|
return String.format(Locale.US, "%.1f KiB", (double) bytes / 1024.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String emitSource(List<ClassUnit> units) {
|
||||||
|
StringBuilder out = new StringBuilder(65536);
|
||||||
|
out.append("/* Auto-generated JNIC implementation file */\n")
|
||||||
|
.append("#include <jni.h>\n")
|
||||||
|
.append("#include <stdint.h>\n")
|
||||||
|
.append("#include <stdlib.h>\n")
|
||||||
|
.append("#include <string.h>\n")
|
||||||
|
.append("#include <math.h>\n\n")
|
||||||
|
.append("static jfloat jnic_f(uint32_t bits) { jfloat v; memcpy(&v, &bits, sizeof(v)); return v; }\n")
|
||||||
|
.append("static jdouble jnic_d(uint64_t bits) { jdouble v; memcpy(&v, &bits, sizeof(v)); return v; }\n\n");
|
||||||
|
for (ClassUnit unit : units) {
|
||||||
|
for (ClassNativizer.Registration registration : unit.registrations) {
|
||||||
|
out.append(registration.cSource).append('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (ClassUnit unit : units) {
|
||||||
|
out.append("JNIEXPORT void JNICALL ")
|
||||||
|
.append(CType.loaderSymbol(unit.internalName))
|
||||||
|
.append("(JNIEnv *env, jclass clazz) {\n")
|
||||||
|
.append(" static JNINativeMethod table[] = {\n");
|
||||||
|
for (ClassNativizer.Registration registration : unit.registrations) {
|
||||||
|
out.append(" {\"")
|
||||||
|
.append(escape(registration.name))
|
||||||
|
.append("\", \"")
|
||||||
|
.append(escape(registration.descriptor))
|
||||||
|
.append("\", (void *) &")
|
||||||
|
.append(registration.functionName)
|
||||||
|
.append("},\n");
|
||||||
|
}
|
||||||
|
out.append(" };\n")
|
||||||
|
.append(" (*env)->RegisterNatives(env, (*env)->FindClass(env, \"")
|
||||||
|
.append(escape(unit.internalName))
|
||||||
|
.append("\"), table, ")
|
||||||
|
.append(unit.registrations.size())
|
||||||
|
.append(");\n")
|
||||||
|
.append("}\n\n");
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String escape(String value) {
|
||||||
|
return value.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] compile(Path compiler, Path cFile, Path sourcesDir, String target) throws IOException, InterruptedException {
|
||||||
|
ZigTarget zig = ZigTarget.of(target);
|
||||||
|
Path library = sourcesDir.resolve(target.toLowerCase(Locale.ROOT) + zig.extension);
|
||||||
|
List<String> command = new ArrayList<>();
|
||||||
|
command.add(compiler.toString());
|
||||||
|
command.add("cc");
|
||||||
|
command.add("-shared");
|
||||||
|
command.add("-target");
|
||||||
|
command.add(zig.triple);
|
||||||
|
command.add(Options.INSTANCE.isFastCompileEnabled() ? "-Oz" : "-O2");
|
||||||
|
command.add("-Wl,-s");
|
||||||
|
command.add("-fPIC");
|
||||||
|
for (String include : jniIncludes()) {
|
||||||
|
command.add("-I");
|
||||||
|
command.add(include);
|
||||||
|
}
|
||||||
|
command.add(cFile.toString());
|
||||||
|
command.add("-o");
|
||||||
|
command.add(library.toString());
|
||||||
|
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||||
|
String log = new String(readAll(process.getInputStream()), StandardCharsets.UTF_8);
|
||||||
|
if (process.waitFor() != 0) {
|
||||||
|
throw new IOException("zig cc failed for " + target + ":\n" + log);
|
||||||
|
}
|
||||||
|
return Files.readAllBytes(library);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> jniIncludes() {
|
||||||
|
List<String> includes = new ArrayList<>();
|
||||||
|
String javaHome = System.getenv("JAVA_HOME");
|
||||||
|
if (javaHome == null || javaHome.isBlank()) {
|
||||||
|
javaHome = System.getProperty("java.home");
|
||||||
|
}
|
||||||
|
if (javaHome != null && !javaHome.isBlank()) {
|
||||||
|
Path base = Path.of(javaHome, "include");
|
||||||
|
includes.add(base.toString());
|
||||||
|
includes.add(base.resolve("win32").toString());
|
||||||
|
includes.add(base.resolve("linux").toString());
|
||||||
|
includes.add(base.resolve("darwin").toString());
|
||||||
|
}
|
||||||
|
return includes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] concat(List<byte[]> parts) {
|
||||||
|
int total = 0;
|
||||||
|
for (byte[] part : parts) {
|
||||||
|
total += part.length;
|
||||||
|
}
|
||||||
|
byte[] out = new byte[total];
|
||||||
|
int cursor = 0;
|
||||||
|
for (byte[] part : parts) {
|
||||||
|
System.arraycopy(part, 0, out, cursor, part.length);
|
||||||
|
cursor += part.length;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] compress(byte[] raw) throws IOException {
|
||||||
|
ByteArrayOutputStream sink = new ByteArrayOutputStream(raw.length / 2 + 64);
|
||||||
|
LZMA2Options options = new LZMA2Options(6);
|
||||||
|
FinishableOutputStream out = options.getOutputStream(
|
||||||
|
new FinishableWrapperOutputStream(sink),
|
||||||
|
ArrayCache.getDefaultCache());
|
||||||
|
out.write(raw);
|
||||||
|
out.finish();
|
||||||
|
return sink.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void repackage(Path output, Map<String, byte[]> entries, byte[] payload, String layout, Manifest manifest) throws IOException {
|
||||||
|
try (OutputStream file = Files.newOutputStream(output);
|
||||||
|
JarOutputStream jar = manifest != null ? new JarOutputStream(file, manifest) : new JarOutputStream(file)) {
|
||||||
|
for (Map.Entry<String, byte[]> entry : entries.entrySet()) {
|
||||||
|
if (entry.getKey().equals(PAYLOAD_PATH) || entry.getKey().equals(LAYOUT_PATH)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
writeEntry(jar, entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
writeEntry(jar, PAYLOAD_PATH, payload);
|
||||||
|
writeEntry(jar, LAYOUT_PATH, layout.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void writeEntry(JarOutputStream jar, String name, byte[] bytes) throws IOException {
|
||||||
|
ZipEntry entry = new ZipEntry(name);
|
||||||
|
jar.putNextEntry(entry);
|
||||||
|
jar.write(bytes);
|
||||||
|
jar.closeEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] readAll(InputStream in) throws IOException {
|
||||||
|
try (InputStream stream = in) {
|
||||||
|
return stream.readAllBytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class ClassUnit {
|
||||||
|
final String internalName;
|
||||||
|
final List<ClassNativizer.Registration> registrations;
|
||||||
|
|
||||||
|
ClassUnit(String internalName, List<ClassNativizer.Registration> registrations) {
|
||||||
|
this.internalName = internalName;
|
||||||
|
this.registrations = registrations;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum ZigTarget {
|
||||||
|
WINDOWS_X86_64("x86_64-windows-gnu", ".dll"),
|
||||||
|
WINDOWS_AARCH64("aarch64-windows-gnu", ".dll"),
|
||||||
|
MACOS_X86_64("x86_64-macos", ".dylib"),
|
||||||
|
MACOS_AARCH64("aarch64-macos", ".dylib"),
|
||||||
|
LINUX_X86_64("x86_64-linux-gnu", ".so"),
|
||||||
|
LINUX_AARCH64("aarch64-linux-gnu", ".so");
|
||||||
|
|
||||||
|
final String triple;
|
||||||
|
final String extension;
|
||||||
|
|
||||||
|
ZigTarget(String triple, String extension) {
|
||||||
|
this.triple = triple;
|
||||||
|
this.extension = extension;
|
||||||
|
}
|
||||||
|
|
||||||
|
static ZigTarget of(String target) {
|
||||||
|
try {
|
||||||
|
return ZigTarget.valueOf(target.toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException unknown) {
|
||||||
|
throw new IllegalArgumentException("Unsupported target: " + target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package dev.jnic.pipeline;
|
||||||
|
|
||||||
|
public class TranslateError extends RuntimeException {
|
||||||
|
public TranslateError(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TranslateError(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package dev.jnic.pipeline;
|
||||||
|
|
||||||
|
public class TranslateException extends Exception {
|
||||||
|
public TranslateException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TranslateException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public class Declarations implements Fragment {
|
||||||
|
private final Map<ClassNode, List<MethodNode>> classes;
|
||||||
|
private final int options;
|
||||||
|
|
||||||
|
public Declarations(Map<ClassNode, List<MethodNode>> classes, int options) {
|
||||||
|
this.classes = Objects.requireNonNull(classes, "classes");
|
||||||
|
this.options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String render(State context) {
|
||||||
|
StringBuilder out = new StringBuilder(4096);
|
||||||
|
out.append("/* \n")
|
||||||
|
.append(" * Auto-generated JNIC implementation file\n")
|
||||||
|
.append(" * \n * \n * \n * \n * \n * \n")
|
||||||
|
.append(" */\n\n")
|
||||||
|
.append("#include <jni.h>\n")
|
||||||
|
.append("#include <stdatomic.h>\n")
|
||||||
|
.append("#include <stdlib.h>\n")
|
||||||
|
.append("#include <string.h>\n")
|
||||||
|
.append("#include <stdarg.h>\n")
|
||||||
|
.append("#include <math.h>\n\n");
|
||||||
|
boolean first = true;
|
||||||
|
for (Map.Entry<ClassNode, List<MethodNode>> entry : this.classes.entrySet()) {
|
||||||
|
String owner = entry.getKey().name;
|
||||||
|
if (owner == null || entry.getValue() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (MethodNode method : entry.getValue()) {
|
||||||
|
if (method == null || method.name == null || method.desc == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!first) {
|
||||||
|
out.append('\n');
|
||||||
|
}
|
||||||
|
out.append(Transpiler.declaration(owner, method, true));
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.append("\n/* End JNIC implementation file */");
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public class Definition implements Fragment {
|
||||||
|
private final ClassNode owner;
|
||||||
|
private final MethodNode method;
|
||||||
|
private final String recoveredSourceFragment;
|
||||||
|
|
||||||
|
public Definition(ClassNode owner, MethodNode method, String recoveredSourceFragment) {
|
||||||
|
this.owner = Objects.requireNonNull(owner, "owner");
|
||||||
|
this.method = Objects.requireNonNull(method, "method");
|
||||||
|
this.recoveredSourceFragment = recoveredSourceFragment;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String render(State context) {
|
||||||
|
if (this.owner.name == null) {
|
||||||
|
throw new IllegalStateException("Class model has no internal name");
|
||||||
|
}
|
||||||
|
return Transpiler.safeDefinition(this.owner.name, this.method, this.recoveredSourceFragment);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String formatIdentifier(String prefix, String value, int index, String suffix) {
|
||||||
|
StringBuilder out = new StringBuilder();
|
||||||
|
if (prefix != null) {
|
||||||
|
out.append(prefix);
|
||||||
|
}
|
||||||
|
if (value != null) {
|
||||||
|
out.append(value);
|
||||||
|
}
|
||||||
|
if (index >= 0) {
|
||||||
|
out.append(index);
|
||||||
|
}
|
||||||
|
if (suffix != null) {
|
||||||
|
out.append(suffix);
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
public interface Fragment {
|
||||||
|
String render(State context);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public class Function implements Fragment {
|
||||||
|
private final String nativeFunctionName;
|
||||||
|
private final MethodNode method;
|
||||||
|
|
||||||
|
public Function(String nativeFunctionName, MethodNode method) {
|
||||||
|
this.nativeFunctionName = Objects.requireNonNull(nativeFunctionName, "nativeFunctionName");
|
||||||
|
this.method = Objects.requireNonNull(method, "method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String render(State context) {
|
||||||
|
return Transpiler.translatedFunction(this.nativeFunctionName, this.method);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String mangle(String value) {
|
||||||
|
return Transpiler.mangle(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import org.objectweb.asm.tree.LabelNode;
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Labels {
|
||||||
|
String resolve(String prefix, LabelNode label);
|
||||||
|
|
||||||
|
default String resolve(LabelNode label) {
|
||||||
|
return this.resolve("1", label);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.LabelNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
import org.objectweb.asm.tree.TryCatchBlockNode;
|
||||||
|
|
||||||
|
public class MethodSource implements Fragment {
|
||||||
|
private final ClassNode owner;
|
||||||
|
private final MethodNode method;
|
||||||
|
private final String recoveredSourceFragment;
|
||||||
|
|
||||||
|
public MethodSource(ClassNode owner, MethodNode method, String recoveredSourceFragment) {
|
||||||
|
this.owner = Objects.requireNonNull(owner, "owner");
|
||||||
|
this.method = Objects.requireNonNull(method, "method");
|
||||||
|
this.recoveredSourceFragment = recoveredSourceFragment;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String render(State context) {
|
||||||
|
if (this.owner.name == null) {
|
||||||
|
throw new IllegalStateException("Class model has no internal name");
|
||||||
|
}
|
||||||
|
String definition = Transpiler.safeDefinition(this.owner.name, this.method, this.recoveredSourceFragment);
|
||||||
|
Map<AbstractInsnNode, Integer> instructionIndexes = this.indexInstructions();
|
||||||
|
Map<LabelNode, String> labels = this.collectLabels();
|
||||||
|
StringBuilder metadata = new StringBuilder();
|
||||||
|
metadata.append("// recovered method model: ")
|
||||||
|
.append(instructionIndexes.size())
|
||||||
|
.append(" instructions, ")
|
||||||
|
.append(labels.size())
|
||||||
|
.append(" labels\n");
|
||||||
|
for (Map.Entry<LabelNode, String> entry : labels.entrySet()) {
|
||||||
|
metadata.append("// ")
|
||||||
|
.append(entry.getValue())
|
||||||
|
.append(" -> instruction ")
|
||||||
|
.append(instructionIndexes.getOrDefault(entry.getKey(), -1))
|
||||||
|
.append('\n');
|
||||||
|
}
|
||||||
|
return metadata.append(definition).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<AbstractInsnNode, Integer> indexInstructions() {
|
||||||
|
Map<AbstractInsnNode, Integer> indexes = new IdentityHashMap<>();
|
||||||
|
if (this.method.instructions == null) {
|
||||||
|
return indexes;
|
||||||
|
}
|
||||||
|
int index = 0;
|
||||||
|
for (AbstractInsnNode instruction : this.method.instructions) {
|
||||||
|
indexes.put(instruction, index++);
|
||||||
|
}
|
||||||
|
return indexes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<LabelNode, String> collectLabels() {
|
||||||
|
Map<LabelNode, String> labels = new LinkedHashMap<>();
|
||||||
|
if (this.method.instructions == null) {
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
|
int index = 0;
|
||||||
|
for (AbstractInsnNode instruction : this.method.instructions) {
|
||||||
|
if (instruction instanceof LabelNode) {
|
||||||
|
labels.put((LabelNode) instruction, "L" + index);
|
||||||
|
}
|
||||||
|
++index;
|
||||||
|
}
|
||||||
|
if (this.method.tryCatchBlocks != null) {
|
||||||
|
addTryCatchLabels(labels, this.method.tryCatchBlocks);
|
||||||
|
}
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addTryCatchLabels(Map<LabelNode, String> labels, List<TryCatchBlockNode> blocks) {
|
||||||
|
for (TryCatchBlockNode block : blocks) {
|
||||||
|
putLabel(labels, block.start);
|
||||||
|
putLabel(labels, block.end);
|
||||||
|
putLabel(labels, block.handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void putLabel(Map<LabelNode, String> labels, LabelNode label) {
|
||||||
|
if (label != null && !labels.containsKey(label)) {
|
||||||
|
labels.put(label, "L" + labels.size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public class Registration implements Fragment {
|
||||||
|
private final Map<ClassNode, List<MethodNode>> classes;
|
||||||
|
private final int options;
|
||||||
|
|
||||||
|
public Registration(Map<ClassNode, List<MethodNode>> classes, int options) {
|
||||||
|
this.classes = Objects.requireNonNull(classes, "classes");
|
||||||
|
this.options = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String render(State context) {
|
||||||
|
StringBuilder out = new StringBuilder(4096);
|
||||||
|
int nativeIndex = 0;
|
||||||
|
for (Map.Entry<ClassNode, List<MethodNode>> entry : this.classes.entrySet()) {
|
||||||
|
ClassNode type = entry.getKey();
|
||||||
|
List<MethodNode> methods = entry.getValue();
|
||||||
|
if (type == null || type.name == null || methods == null || methods.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.append("JNIEXPORT void JNICALL ")
|
||||||
|
.append(Transpiler.loaderSymbol(type.name))
|
||||||
|
.append("(JNIEnv *env, jclass clazz) {\n")
|
||||||
|
.append(" JNINativeMethod table[] = {\n");
|
||||||
|
for (MethodNode method : methods) {
|
||||||
|
if (method == null || method.name == null || method.desc == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.append(Transpiler.registrationEntry(method, nativeIndex++)).append(",\n");
|
||||||
|
}
|
||||||
|
out.append(" };\n")
|
||||||
|
.append(" (*env)->RegisterNatives(env, clazz, table, ")
|
||||||
|
.append(emittedCount(methods))
|
||||||
|
.append(");\n")
|
||||||
|
.append("}\n\n");
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int emittedCount(List<MethodNode> methods) {
|
||||||
|
int count = 0;
|
||||||
|
for (MethodNode method : methods) {
|
||||||
|
if (method != null && method.name != null && method.desc != null) {
|
||||||
|
++count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import dev.jnic.cache.IndyRegistry;
|
||||||
|
import dev.jnic.cache.JniCacheRegistry;
|
||||||
|
import dev.jnic.cache.MemberKey;
|
||||||
|
import dev.jnic.cache.StringPoolEmitter;
|
||||||
|
import dev.jnic.crypto.ChaCha20Stream;
|
||||||
|
import dev.jnic.pipeline.Options;
|
||||||
|
import dev.jnic.type.JniTypeUtils;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
|
||||||
|
|
||||||
|
public class State {
|
||||||
|
private final AtomicInteger methodCounter = new AtomicInteger();
|
||||||
|
private final Map<MemberKey, String> methodSymbols = new HashMap<>();
|
||||||
|
private final SecureRandom random;
|
||||||
|
private final JniCacheRegistry cacheRegistry;
|
||||||
|
private final IndyRegistry indyRegistry;
|
||||||
|
private final StringPoolEmitter stringPool;
|
||||||
|
private final Options options;
|
||||||
|
private final String moduleName;
|
||||||
|
private final String target;
|
||||||
|
private String currentOwner = "";
|
||||||
|
private String currentReturnJniType = "void";
|
||||||
|
private int currentMaxTempCount = 0;
|
||||||
|
private int currentExtraStackSlots = 0;
|
||||||
|
|
||||||
|
public State(SecureRandom random, String moduleName, String target, Options options) {
|
||||||
|
this.random = random != null ? random : new SecureRandom();
|
||||||
|
ChaCha20Stream stream = ChaCha20Stream.create("expand 32-byte k", this.random);
|
||||||
|
this.cacheRegistry = new JniCacheRegistry(stream);
|
||||||
|
this.indyRegistry = new IndyRegistry();
|
||||||
|
this.stringPool = new StringPoolEmitter(stream);
|
||||||
|
this.moduleName = moduleName != null ? moduleName : "";
|
||||||
|
this.target = target != null ? target : "";
|
||||||
|
this.options = options != null ? options : Options.INSTANCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getModuleName() {
|
||||||
|
return this.moduleName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTarget() {
|
||||||
|
return this.target;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Options getOptions() {
|
||||||
|
return this.options;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerMethodSymbol(MemberKey methodKey) {
|
||||||
|
return this.methodSymbols.computeIfAbsent(methodKey, k -> "jnic_" + this.methodCounter.getAndIncrement());
|
||||||
|
}
|
||||||
|
|
||||||
|
public SecureRandom getRandom() {
|
||||||
|
return this.random;
|
||||||
|
}
|
||||||
|
|
||||||
|
public JniCacheRegistry getCacheRegistry() {
|
||||||
|
return this.cacheRegistry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IndyRegistry getIndyRegistry() {
|
||||||
|
return this.indyRegistry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StringPoolEmitter getStringPool() {
|
||||||
|
return this.stringPool;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String cacheClass(String internalName) {
|
||||||
|
return this.cacheRegistry.registerClass(internalName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String cacheField(String owner, String name, String desc, boolean isStatic) {
|
||||||
|
return this.cacheRegistry.registerField(owner, name, desc, isStatic);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String cacheMethod(String owner, String name, String desc, boolean isStatic) {
|
||||||
|
return this.cacheRegistry.registerMethod(owner, name, desc, isStatic);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerLookup(String internalName) {
|
||||||
|
return this.cacheRegistry.registerLookup(internalName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String registerIndyHelper(InvokeDynamicInsnNode indy) {
|
||||||
|
return this.indyRegistry.register(indy, this.currentOwner);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void beginMethod(String ownerName, String returnJniType) {
|
||||||
|
this.currentOwner = ownerName != null ? ownerName : "";
|
||||||
|
this.currentReturnJniType = returnJniType != null ? returnJniType : "void";
|
||||||
|
this.currentMaxTempCount = 0;
|
||||||
|
this.currentExtraStackSlots = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String ownerName() {
|
||||||
|
return this.currentOwner;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String returnJniType() {
|
||||||
|
return this.currentReturnJniType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ensureTempCount(int count) {
|
||||||
|
if (count > this.currentMaxTempCount) {
|
||||||
|
this.currentMaxTempCount = count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int maxTempCount() {
|
||||||
|
return this.currentMaxTempCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ensureExtraStackSlots(int extra) {
|
||||||
|
if (extra > this.currentExtraStackSlots) {
|
||||||
|
this.currentExtraStackSlots = extra;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int extraStackSlots() {
|
||||||
|
return this.currentExtraStackSlots;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String jniCallType(Type type) {
|
||||||
|
return JniTypeUtils.jniCallType(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String callStaticMethod(String typeName, String owner, String name, String desc, String... args) {
|
||||||
|
String cVar = this.cacheClass(owner);
|
||||||
|
String mVar = this.cacheMethod(owner, name, desc != null ? desc : "", true);
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("(*env)->CallStatic").append(typeName).append("Method(env, ")
|
||||||
|
.append(cVar).append("(env), ").append(mVar).append("(env)");
|
||||||
|
if (args != null) {
|
||||||
|
for (String arg : args) {
|
||||||
|
sb.append(", ").append(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb.append(")");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String callVirtualMethod(String typeName, String objExpr, String owner, String name, String desc, String... args) {
|
||||||
|
String mVar = this.cacheMethod(owner, name, desc != null ? desc : "", false);
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("(*env)->Call").append(typeName).append("Method(env, ")
|
||||||
|
.append(objExpr).append(", ").append(mVar).append("(env)");
|
||||||
|
if (args != null) {
|
||||||
|
for (String arg : args) {
|
||||||
|
sb.append(", ").append(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb.append(")");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStaticField(String typeName, String owner, String name, String desc) {
|
||||||
|
String cVar = this.cacheClass(owner);
|
||||||
|
String fVar = this.cacheField(owner, name, desc, true);
|
||||||
|
return "(*env)->GetStatic" + typeName + "Field(env, " + cVar + "(env), " + fVar + "(env))";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getField(String typeName, String objExpr, String owner, String name, String desc) {
|
||||||
|
String fVar = this.cacheField(owner, name, desc, false);
|
||||||
|
return "(*env)->Get" + typeName + "Field(env, " + objExpr + ", " + fVar + "(env))";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String setStaticField(String typeName, String owner, String name, String desc, String valExpr) {
|
||||||
|
String cVar = this.cacheClass(owner);
|
||||||
|
String fVar = this.cacheField(owner, name, desc != null ? desc : "", true);
|
||||||
|
return "(*env)->SetStatic" + typeName + "Field(env, " + cVar + "(env), " + fVar + "(env), " + valExpr + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String isInstanceOf(String owner, Object valExpr) {
|
||||||
|
String cVar = this.cacheClass(owner);
|
||||||
|
return "(*env)->IsInstanceOf(env, " + valExpr + ", " + cVar + "(env))";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String newObject(String owner, String... args) {
|
||||||
|
String cVar = this.cacheClass(owner);
|
||||||
|
String mVar = this.cacheMethod(owner, "<init>", "()V", false);
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append("(*env)->NewObject(env, ").append(cVar).append("(env), ").append(mVar).append("(env)");
|
||||||
|
if (args != null) {
|
||||||
|
for (String arg : args) {
|
||||||
|
sb.append(", ").append(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sb.append(")");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
package dev.jnic.templates;
|
||||||
|
|
||||||
|
import dev.jnic.handler.JvmOpcodeHandlers;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public final class Transpiler {
|
||||||
|
private Transpiler() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static String declaration(String owner, MethodNode method, boolean semicolon) {
|
||||||
|
Descriptor descriptor = Descriptor.parse(method.desc);
|
||||||
|
StringBuilder out = new StringBuilder(192);
|
||||||
|
out.append("JNIEXPORT ")
|
||||||
|
.append(jniType(descriptor.result))
|
||||||
|
.append(" JNICALL ")
|
||||||
|
.append(symbol(owner, method))
|
||||||
|
.append("(JNIEnv *env, ")
|
||||||
|
.append((method.access & Opcodes.ACC_STATIC) != 0 ? "jclass clazz" : "jobject self");
|
||||||
|
for (int index = 0; index < descriptor.parameters.size(); ++index) {
|
||||||
|
out.append(", ").append(jniType(descriptor.parameters.get(index))).append(" arg").append(index);
|
||||||
|
}
|
||||||
|
out.append(')');
|
||||||
|
if (semicolon) {
|
||||||
|
out.append(';');
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String symbol(String owner, MethodNode method) {
|
||||||
|
return "Java_" + mangle(owner) + "_" + mangle(method.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String registrationEntry(String owner, MethodNode method) {
|
||||||
|
return " {\"" + cString(method.name) + "\", \"" + cString(method.desc)
|
||||||
|
+ "\", reinterpret_cast<void *>(&" + symbol(owner, method) + ")}";
|
||||||
|
}
|
||||||
|
|
||||||
|
static String registrationEntry(MethodNode method, int nativeIndex) {
|
||||||
|
return " {\"" + cString(method.name) + "\", \"" + cString(method.desc)
|
||||||
|
+ "\", (void *) &jnic_" + nativeIndex + "}";
|
||||||
|
}
|
||||||
|
|
||||||
|
static String loaderSymbol(String owner) {
|
||||||
|
return "Java_" + mangle(owner) + "__00024jnicLoader";
|
||||||
|
}
|
||||||
|
|
||||||
|
static String translatedFunction(String functionName, MethodNode method) {
|
||||||
|
Descriptor descriptor = Descriptor.parse(method.desc);
|
||||||
|
boolean isStatic = (method.access & Opcodes.ACC_STATIC) != 0;
|
||||||
|
StringBuilder out = new StringBuilder(1024);
|
||||||
|
out.append(jniType(descriptor.result))
|
||||||
|
.append(" JNICALL ")
|
||||||
|
.append(functionName)
|
||||||
|
.append("(JNIEnv *env, jobject thisObj");
|
||||||
|
for (int index = 0; index < descriptor.parameters.size(); ++index) {
|
||||||
|
out.append(", ").append(jniType(descriptor.parameters.get(index))).append(" arg").append(index);
|
||||||
|
}
|
||||||
|
out.append(") {\n");
|
||||||
|
int localCount = Math.max(method.maxLocals, initialLocalCount(descriptor, isStatic));
|
||||||
|
int stackCount = Math.max(method.maxStack, 0);
|
||||||
|
appendValues(out, "local", localCount);
|
||||||
|
if (localCount > 0) {
|
||||||
|
out.append('\n');
|
||||||
|
}
|
||||||
|
appendValues(out, "stack", stackCount);
|
||||||
|
if (stackCount > 0) {
|
||||||
|
out.append('\n');
|
||||||
|
}
|
||||||
|
appendValues(out, "temp", 4);
|
||||||
|
out.append('\n');
|
||||||
|
int local = 0;
|
||||||
|
if (!isStatic) {
|
||||||
|
out.append(" local0.l = thisObj;\n");
|
||||||
|
local = 1;
|
||||||
|
}
|
||||||
|
for (int index = 0; index < descriptor.parameters.size(); ++index) {
|
||||||
|
String parameter = descriptor.parameters.get(index);
|
||||||
|
out.append(" local").append(local).append('.').append(jvalueMember(parameter))
|
||||||
|
.append(" = arg").append(index).append(";\n");
|
||||||
|
local += slotWidth(parameter);
|
||||||
|
}
|
||||||
|
if (local > 0) {
|
||||||
|
out.append('\n');
|
||||||
|
}
|
||||||
|
if (method.instructions != null) {
|
||||||
|
int instructionIndex = 0;
|
||||||
|
for (AbstractInsnNode instruction : method.instructions) {
|
||||||
|
String emitted = JvmOpcodeHandlers.emit(instruction, instructionIndex++);
|
||||||
|
if (emitted == null) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Unsupported JVM instruction " + instruction.getClass().getName()
|
||||||
|
+ " (opcode " + instruction.getOpcode() + ")");
|
||||||
|
}
|
||||||
|
out.append(emitted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String fallback = fallbackReturn(descriptor.result);
|
||||||
|
if (!fallback.isEmpty()) {
|
||||||
|
out.append(" ").append(fallback).append('\n');
|
||||||
|
}
|
||||||
|
return out.append("}\n").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void appendValues(StringBuilder out, String prefix, int count) {
|
||||||
|
for (int index = 0; index < count; ++index) {
|
||||||
|
out.append(" jvalue ").append(prefix).append(index)
|
||||||
|
.append("; memset(&").append(prefix).append(index).append(", 0, sizeof(jvalue));\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int initialLocalCount(Descriptor descriptor, boolean isStatic) {
|
||||||
|
int count = isStatic ? 0 : 1;
|
||||||
|
for (String parameter : descriptor.parameters) {
|
||||||
|
count += slotWidth(parameter);
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int slotWidth(String descriptor) {
|
||||||
|
char type = descriptor.charAt(0);
|
||||||
|
return type == 'J' || type == 'D' ? 2 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String jvalueMember(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'Z':
|
||||||
|
return "z";
|
||||||
|
case 'B':
|
||||||
|
return "b";
|
||||||
|
case 'C':
|
||||||
|
return "c";
|
||||||
|
case 'S':
|
||||||
|
return "s";
|
||||||
|
case 'I':
|
||||||
|
return "i";
|
||||||
|
case 'J':
|
||||||
|
return "j";
|
||||||
|
case 'F':
|
||||||
|
return "f";
|
||||||
|
case 'D':
|
||||||
|
return "d";
|
||||||
|
default:
|
||||||
|
return "l";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String safeDefinition(String owner, MethodNode method, String recoveredFragment) {
|
||||||
|
Descriptor descriptor = Descriptor.parse(method.desc);
|
||||||
|
StringBuilder out = new StringBuilder(256);
|
||||||
|
out.append(declaration(owner, method, false)).append(" {\n");
|
||||||
|
if (looksLikeBody(recoveredFragment)) {
|
||||||
|
String body = recoveredFragment.trim();
|
||||||
|
if (body.startsWith("{") && body.endsWith("}")) {
|
||||||
|
body = body.substring(1, body.length() - 1).trim();
|
||||||
|
}
|
||||||
|
for (String line : body.split("\\R", -1)) {
|
||||||
|
out.append(" ").append(line).append('\n');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
out.append(" // Recovered source context: ").append(comment(recoveredFragment)).append("\n");
|
||||||
|
String fallback = fallbackReturn(descriptor.result);
|
||||||
|
if (!fallback.isEmpty()) {
|
||||||
|
out.append(" ").append(fallback).append('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.append('}').toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean looksLikeBody(String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String text = value.trim();
|
||||||
|
return text.indexOf(';') >= 0 || text.startsWith("{") || text.startsWith("return ");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String comment(String value) {
|
||||||
|
if (value == null) {
|
||||||
|
return "<none>";
|
||||||
|
}
|
||||||
|
return value.replace("\\", "\\\\").replace("\r", " ").replace("\n", " ").replace("*/", "* /");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String fallbackReturn(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'V':
|
||||||
|
return "";
|
||||||
|
case 'Z':
|
||||||
|
return "return JNI_FALSE;";
|
||||||
|
case 'B':
|
||||||
|
case 'C':
|
||||||
|
case 'I':
|
||||||
|
case 'J':
|
||||||
|
case 'S':
|
||||||
|
return "return 0;";
|
||||||
|
case 'F':
|
||||||
|
return "return 0.0f;";
|
||||||
|
case 'D':
|
||||||
|
return "return 0.0;";
|
||||||
|
default:
|
||||||
|
return "return NULL;";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String identifier(String value) {
|
||||||
|
String mangled = mangle(value);
|
||||||
|
return mangled.isEmpty() || Character.isDigit(mangled.charAt(0)) ? "_" + mangled : mangled;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String mangle(String value) {
|
||||||
|
StringBuilder result = new StringBuilder(value.length() + 16);
|
||||||
|
for (int index = 0; index < value.length(); ++index) {
|
||||||
|
char ch = value.charAt(index);
|
||||||
|
if (Character.isLetterOrDigit(ch)) {
|
||||||
|
result.append(ch);
|
||||||
|
} else if (ch == '_') {
|
||||||
|
result.append("_1");
|
||||||
|
} else if (ch == ';') {
|
||||||
|
result.append("_2");
|
||||||
|
} else if (ch == '[') {
|
||||||
|
result.append("_3");
|
||||||
|
} else if (ch == '/') {
|
||||||
|
result.append('_');
|
||||||
|
} else {
|
||||||
|
result.append("_0").append(String.format("%04x", (int) ch));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String cString(String value) {
|
||||||
|
return value.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String jniType(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'V':
|
||||||
|
return "void";
|
||||||
|
case 'Z':
|
||||||
|
return "jboolean";
|
||||||
|
case 'B':
|
||||||
|
return "jbyte";
|
||||||
|
case 'C':
|
||||||
|
return "jchar";
|
||||||
|
case 'S':
|
||||||
|
return "jshort";
|
||||||
|
case 'I':
|
||||||
|
return "jint";
|
||||||
|
case 'J':
|
||||||
|
return "jlong";
|
||||||
|
case 'F':
|
||||||
|
return "jfloat";
|
||||||
|
case 'D':
|
||||||
|
return "jdouble";
|
||||||
|
case 'L':
|
||||||
|
return "Ljava/lang/String;".equals(descriptor) ? "jstring" : "jobject";
|
||||||
|
case '[':
|
||||||
|
return arrayType(descriptor);
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("Bad JVM descriptor: " + descriptor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String arrayType(String descriptor) {
|
||||||
|
if (descriptor.length() != 2) {
|
||||||
|
return "jobjectArray";
|
||||||
|
}
|
||||||
|
switch (descriptor.charAt(1)) {
|
||||||
|
case 'Z':
|
||||||
|
return "jbooleanArray";
|
||||||
|
case 'B':
|
||||||
|
return "jbyteArray";
|
||||||
|
case 'C':
|
||||||
|
return "jcharArray";
|
||||||
|
case 'S':
|
||||||
|
return "jshortArray";
|
||||||
|
case 'I':
|
||||||
|
return "jintArray";
|
||||||
|
case 'J':
|
||||||
|
return "jlongArray";
|
||||||
|
case 'F':
|
||||||
|
return "jfloatArray";
|
||||||
|
case 'D':
|
||||||
|
return "jdoubleArray";
|
||||||
|
default:
|
||||||
|
return "jobjectArray";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Descriptor {
|
||||||
|
final List<String> parameters;
|
||||||
|
final String result;
|
||||||
|
|
||||||
|
Descriptor(List<String> parameters, String result) {
|
||||||
|
this.parameters = parameters;
|
||||||
|
this.result = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Descriptor parse(String value) {
|
||||||
|
if (value == null || value.length() < 3 || value.charAt(0) != '(') {
|
||||||
|
throw new IllegalArgumentException("Bad method descriptor: " + value);
|
||||||
|
}
|
||||||
|
List<String> parameters = new ArrayList<>();
|
||||||
|
int cursor = 1;
|
||||||
|
while (cursor < value.length() && value.charAt(cursor) != ')') {
|
||||||
|
int end = end(value, cursor);
|
||||||
|
parameters.add(value.substring(cursor, end));
|
||||||
|
cursor = end;
|
||||||
|
}
|
||||||
|
if (cursor >= value.length()) {
|
||||||
|
throw new IllegalArgumentException("Bad method descriptor: " + value);
|
||||||
|
}
|
||||||
|
int resultStart = cursor + 1;
|
||||||
|
int resultEnd = end(value, resultStart);
|
||||||
|
if (resultEnd != value.length()) {
|
||||||
|
throw new IllegalArgumentException("Trailing descriptor data: " + value);
|
||||||
|
}
|
||||||
|
return new Descriptor(parameters, value.substring(resultStart, resultEnd));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int end(String value, int start) {
|
||||||
|
if (start >= value.length()) {
|
||||||
|
throw new IllegalArgumentException("Truncated descriptor: " + value);
|
||||||
|
}
|
||||||
|
int cursor = start;
|
||||||
|
while (value.charAt(cursor) == '[') {
|
||||||
|
++cursor;
|
||||||
|
}
|
||||||
|
if (value.charAt(cursor) == 'L') {
|
||||||
|
int semicolon = value.indexOf(';', cursor);
|
||||||
|
if (semicolon < 0) {
|
||||||
|
throw new IllegalArgumentException("Unterminated descriptor: " + value);
|
||||||
|
}
|
||||||
|
return semicolon + 1;
|
||||||
|
}
|
||||||
|
if ("VZBCSIJFD".indexOf(value.charAt(cursor)) < 0) {
|
||||||
|
throw new IllegalArgumentException("Bad type descriptor: " + value);
|
||||||
|
}
|
||||||
|
return cursor + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package dev.jnic.translate;
|
||||||
|
|
||||||
|
public final class CType {
|
||||||
|
private CType() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static char slot(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'Z':
|
||||||
|
case 'B':
|
||||||
|
case 'C':
|
||||||
|
case 'S':
|
||||||
|
case 'I':
|
||||||
|
return 'i';
|
||||||
|
case 'J':
|
||||||
|
return 'j';
|
||||||
|
case 'F':
|
||||||
|
return 'f';
|
||||||
|
case 'D':
|
||||||
|
return 'd';
|
||||||
|
default:
|
||||||
|
return 'l';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String declare(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'V':
|
||||||
|
return "void";
|
||||||
|
case 'Z':
|
||||||
|
return "jboolean";
|
||||||
|
case 'B':
|
||||||
|
return "jbyte";
|
||||||
|
case 'C':
|
||||||
|
return "jchar";
|
||||||
|
case 'S':
|
||||||
|
return "jshort";
|
||||||
|
case 'I':
|
||||||
|
return "jint";
|
||||||
|
case 'J':
|
||||||
|
return "jlong";
|
||||||
|
case 'F':
|
||||||
|
return "jfloat";
|
||||||
|
case 'D':
|
||||||
|
return "jdouble";
|
||||||
|
case 'L':
|
||||||
|
return "Ljava/lang/String;".equals(descriptor) ? "jstring" : "jobject";
|
||||||
|
case '[':
|
||||||
|
return arrayType(descriptor);
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("Bad descriptor: " + descriptor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String accessor(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'V':
|
||||||
|
return "Void";
|
||||||
|
case 'Z':
|
||||||
|
return "Boolean";
|
||||||
|
case 'B':
|
||||||
|
return "Byte";
|
||||||
|
case 'C':
|
||||||
|
return "Char";
|
||||||
|
case 'S':
|
||||||
|
return "Short";
|
||||||
|
case 'I':
|
||||||
|
return "Int";
|
||||||
|
case 'J':
|
||||||
|
return "Long";
|
||||||
|
case 'F':
|
||||||
|
return "Float";
|
||||||
|
case 'D':
|
||||||
|
return "Double";
|
||||||
|
default:
|
||||||
|
return "Object";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String arrayType(String descriptor) {
|
||||||
|
if (descriptor.length() != 2) {
|
||||||
|
return "jobjectArray";
|
||||||
|
}
|
||||||
|
switch (descriptor.charAt(1)) {
|
||||||
|
case 'Z':
|
||||||
|
return "jbooleanArray";
|
||||||
|
case 'B':
|
||||||
|
return "jbyteArray";
|
||||||
|
case 'C':
|
||||||
|
return "jcharArray";
|
||||||
|
case 'S':
|
||||||
|
return "jshortArray";
|
||||||
|
case 'I':
|
||||||
|
return "jintArray";
|
||||||
|
case 'J':
|
||||||
|
return "jlongArray";
|
||||||
|
case 'F':
|
||||||
|
return "jfloatArray";
|
||||||
|
case 'D':
|
||||||
|
return "jdoubleArray";
|
||||||
|
default:
|
||||||
|
return "jobjectArray";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String internalName(String descriptor) {
|
||||||
|
if (descriptor == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (descriptor.startsWith("L") && descriptor.endsWith(";")) {
|
||||||
|
return descriptor.substring(1, descriptor.length() - 1);
|
||||||
|
}
|
||||||
|
if (descriptor.startsWith("[")) {
|
||||||
|
return descriptor;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String mangle(String value) {
|
||||||
|
StringBuilder result = new StringBuilder(value.length() + 16);
|
||||||
|
for (int index = 0; index < value.length(); index++) {
|
||||||
|
char ch = value.charAt(index);
|
||||||
|
if (Character.isLetterOrDigit(ch)) {
|
||||||
|
result.append(ch);
|
||||||
|
} else if (ch == '_') {
|
||||||
|
result.append("_1");
|
||||||
|
} else if (ch == ';') {
|
||||||
|
result.append("_2");
|
||||||
|
} else if (ch == '[') {
|
||||||
|
result.append("_3");
|
||||||
|
} else if (ch == '/') {
|
||||||
|
result.append('_');
|
||||||
|
} else {
|
||||||
|
result.append("_0").append(String.format("%04x", (int) ch));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String loaderSymbol(String internalName) {
|
||||||
|
return "Java_" + mangle(internalName) + "__00024jnicLoader";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String defaultReturn(String descriptor) {
|
||||||
|
switch (descriptor.charAt(0)) {
|
||||||
|
case 'V':
|
||||||
|
return "return;";
|
||||||
|
case 'Z':
|
||||||
|
return "return JNI_FALSE;";
|
||||||
|
case 'B':
|
||||||
|
case 'C':
|
||||||
|
case 'S':
|
||||||
|
case 'I':
|
||||||
|
case 'J':
|
||||||
|
return "return 0;";
|
||||||
|
case 'F':
|
||||||
|
return "return 0.0f;";
|
||||||
|
case 'D':
|
||||||
|
return "return 0.0;";
|
||||||
|
default:
|
||||||
|
return "return NULL;";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package dev.jnic.translate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.InsnList;
|
||||||
|
import org.objectweb.asm.tree.InsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public final class ClassNativizer {
|
||||||
|
private static final int ACC_PRIVATE = Opcodes.ACC_PRIVATE;
|
||||||
|
private static final int ACC_STATIC = Opcodes.ACC_STATIC;
|
||||||
|
private static final int ACC_NATIVE = Opcodes.ACC_NATIVE;
|
||||||
|
private static final int ACC_ABSTRACT = Opcodes.ACC_ABSTRACT;
|
||||||
|
private static final int ACC_INTERFACE = Opcodes.ACC_INTERFACE;
|
||||||
|
private static final int ACC_ANNOTATION = Opcodes.ACC_ANNOTATION;
|
||||||
|
private static final int ACC_MODULE = Opcodes.ACC_MODULE;
|
||||||
|
|
||||||
|
private static final String LOADER = "dev/jnic/loader/JNICLoader";
|
||||||
|
private static final String LOADER_PREFIX = "dev/jnic/loader/";
|
||||||
|
private static final String CLINIT = "<clinit>";
|
||||||
|
private static final String NATIVE_CLINIT = "$jnicClinit";
|
||||||
|
private static final String LOADER_METHOD = "$jnicLoader";
|
||||||
|
|
||||||
|
public static final class Registration {
|
||||||
|
public final String name;
|
||||||
|
public final String descriptor;
|
||||||
|
public final String functionName;
|
||||||
|
public final boolean isStatic;
|
||||||
|
public final String cSource;
|
||||||
|
|
||||||
|
Registration(String name, String descriptor, String functionName, boolean isStatic, String cSource) {
|
||||||
|
this.name = name;
|
||||||
|
this.descriptor = descriptor;
|
||||||
|
this.functionName = functionName;
|
||||||
|
this.isStatic = isStatic;
|
||||||
|
this.cSource = cSource;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class Result {
|
||||||
|
public final byte[] bytes;
|
||||||
|
public final String internalName;
|
||||||
|
public final List<Registration> registrations;
|
||||||
|
|
||||||
|
Result(byte[] bytes, String internalName, List<Registration> registrations) {
|
||||||
|
this.bytes = bytes;
|
||||||
|
this.internalName = internalName;
|
||||||
|
this.registrations = registrations;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean nativized() {
|
||||||
|
return !this.registrations.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClassNativizer() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Result nativize(String entryName, byte[] bytes, int classIndex) {
|
||||||
|
if (entryName.startsWith(LOADER_PREFIX) || entryName.endsWith("module-info.class")
|
||||||
|
|| entryName.endsWith("package-info.class")) {
|
||||||
|
return new Result(bytes, null, new ArrayList<>());
|
||||||
|
}
|
||||||
|
ClassNode node = new ClassNode();
|
||||||
|
try {
|
||||||
|
new ClassReader(bytes).accept(node, 0);
|
||||||
|
} catch (RuntimeException malformed) {
|
||||||
|
return new Result(bytes, null, new ArrayList<>());
|
||||||
|
}
|
||||||
|
if ((node.access & (ACC_INTERFACE | ACC_ANNOTATION | ACC_MODULE)) != 0) {
|
||||||
|
return new Result(bytes, node.name, new ArrayList<>());
|
||||||
|
}
|
||||||
|
if (node.name == null || node.name.startsWith(LOADER_PREFIX)) {
|
||||||
|
return new Result(bytes, node.name, new ArrayList<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Registration> registrations = new ArrayList<>();
|
||||||
|
int sequence = 0;
|
||||||
|
boolean clinitNativized = false;
|
||||||
|
|
||||||
|
for (MethodNode method : node.methods) {
|
||||||
|
if ("<init>".equals(method.name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!NativeMethodTranslator.canTranslate(method)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String functionName = "jnic_" + classIndex + "_" + sequence;
|
||||||
|
String cSource;
|
||||||
|
try {
|
||||||
|
cSource = NativeMethodTranslator.translate(functionName, node.name, method);
|
||||||
|
} catch (RuntimeException unsupported) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sequence++;
|
||||||
|
boolean isStatic = (method.access & ACC_STATIC) != 0;
|
||||||
|
if (CLINIT.equals(method.name)) {
|
||||||
|
method.name = NATIVE_CLINIT;
|
||||||
|
clinitNativized = true;
|
||||||
|
}
|
||||||
|
registrations.add(new Registration(method.name, method.desc, functionName, isStatic, cSource));
|
||||||
|
method.access |= ACC_NATIVE;
|
||||||
|
method.access &= ~ACC_ABSTRACT;
|
||||||
|
method.instructions.clear();
|
||||||
|
if (method.tryCatchBlocks != null) {
|
||||||
|
method.tryCatchBlocks.clear();
|
||||||
|
}
|
||||||
|
method.localVariables = null;
|
||||||
|
method.visibleLocalVariableAnnotations = null;
|
||||||
|
method.invisibleLocalVariableAnnotations = null;
|
||||||
|
method.maxStack = 0;
|
||||||
|
method.maxLocals = 0;
|
||||||
|
}
|
||||||
|
if (registrations.isEmpty()) {
|
||||||
|
return new Result(bytes, node.name, registrations);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean hasLoader = false;
|
||||||
|
for (MethodNode method : node.methods) {
|
||||||
|
if (LOADER_METHOD.equals(method.name) && "()V".equals(method.desc)) {
|
||||||
|
hasLoader = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasLoader) {
|
||||||
|
MethodNode loader = new MethodNode(
|
||||||
|
ACC_PRIVATE | ACC_STATIC | ACC_NATIVE, LOADER_METHOD, "()V", null, null);
|
||||||
|
node.methods.add(loader);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clinitNativized) {
|
||||||
|
MethodNode clinit = new MethodNode(ACC_STATIC, CLINIT, "()V", null, null);
|
||||||
|
InsnList body = clinit.instructions;
|
||||||
|
body.add(new MethodInsnNode(Opcodes.INVOKESTATIC, LOADER, "init", "()V", false));
|
||||||
|
body.add(new MethodInsnNode(Opcodes.INVOKESTATIC, node.name, LOADER_METHOD, "()V", false));
|
||||||
|
body.add(new MethodInsnNode(Opcodes.INVOKESTATIC, node.name, NATIVE_CLINIT, "()V", false));
|
||||||
|
body.add(new InsnNode(Opcodes.RETURN));
|
||||||
|
node.methods.add(clinit);
|
||||||
|
} else {
|
||||||
|
MethodNode clinit = null;
|
||||||
|
for (MethodNode method : node.methods) {
|
||||||
|
if (CLINIT.equals(method.name)) {
|
||||||
|
clinit = method;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (clinit == null) {
|
||||||
|
clinit = new MethodNode(ACC_STATIC, CLINIT, "()V", null, null);
|
||||||
|
clinit.instructions.add(new InsnNode(Opcodes.RETURN));
|
||||||
|
node.methods.add(clinit);
|
||||||
|
}
|
||||||
|
InsnList prefix = new InsnList();
|
||||||
|
prefix.add(new MethodInsnNode(Opcodes.INVOKESTATIC, LOADER, "init", "()V", false));
|
||||||
|
prefix.add(new MethodInsnNode(Opcodes.INVOKESTATIC, node.name, LOADER_METHOD, "()V", false));
|
||||||
|
clinit.instructions.insert(prefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||||
|
node.accept(writer);
|
||||||
|
return new Result(writer.toByteArray(), node.name, registrations);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package dev.jnic.translate;
|
||||||
|
|
||||||
|
import dev.jnic.pipeline.Options;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.InsnList;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
public final class LoaderResources {
|
||||||
|
private static final String PREFIX = "dev/jnic/loader/";
|
||||||
|
private static final String LOADER_CLASS = "JNICLoader";
|
||||||
|
private static final String CLINIT = "<clinit>";
|
||||||
|
private static final String STREAM = "java/util/stream/Stream";
|
||||||
|
private static final String ANY_MATCH = "anyMatch";
|
||||||
|
|
||||||
|
private static final String[] CLASSES = {
|
||||||
|
"BitTreeDecoder",
|
||||||
|
"ByteBufferRangeSource",
|
||||||
|
"DistanceDecoder",
|
||||||
|
"DistanceParams",
|
||||||
|
"JNICLoader",
|
||||||
|
"LengthDecoder",
|
||||||
|
"LengthModel",
|
||||||
|
"LiteralModel",
|
||||||
|
"LzDictionary",
|
||||||
|
"LzmaDecoder",
|
||||||
|
"LzmaState",
|
||||||
|
"LzmaStateBox",
|
||||||
|
"RangeDecoder",
|
||||||
|
};
|
||||||
|
|
||||||
|
private LoaderResources() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, byte[]> load() throws IOException {
|
||||||
|
Map<String, byte[]> resources = new LinkedHashMap<>();
|
||||||
|
for (String simple : CLASSES) {
|
||||||
|
String path = PREFIX + simple + ".class";
|
||||||
|
try (InputStream in = LoaderResources.class.getResourceAsStream("/" + path)) {
|
||||||
|
if (in == null) {
|
||||||
|
throw new IOException("loader resource not found on classpath: " + path);
|
||||||
|
}
|
||||||
|
byte[] bytes = in.readAllBytes();
|
||||||
|
if (LOADER_CLASS.equals(simple) && !Options.INSTANCE.isAntiDebugEnabled()) {
|
||||||
|
bytes = stripAntiDebugGuard(bytes);
|
||||||
|
}
|
||||||
|
resources.put(path, bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resources;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] stripAntiDebugGuard(byte[] bytes) {
|
||||||
|
ClassNode node = new ClassNode();
|
||||||
|
new ClassReader(bytes).accept(node, 0);
|
||||||
|
for (MethodNode method : node.methods) {
|
||||||
|
if (!CLINIT.equals(method.name)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
AbstractInsnNode guard = guardBranch(method.instructions);
|
||||||
|
if (guard == null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ArrayList<AbstractInsnNode> preamble = new ArrayList<>();
|
||||||
|
for (AbstractInsnNode current = method.instructions.getFirst(); current != null; current = current.getNext()) {
|
||||||
|
preamble.add(current);
|
||||||
|
if (current == guard) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (AbstractInsnNode instruction : preamble) {
|
||||||
|
method.instructions.remove(instruction);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
|
||||||
|
node.accept(writer);
|
||||||
|
return writer.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AbstractInsnNode guardBranch(InsnList instructions) {
|
||||||
|
for (AbstractInsnNode current = instructions.getFirst(); current != null; current = current.getNext()) {
|
||||||
|
if (current.getOpcode() != Opcodes.IFNE) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
AbstractInsnNode previous = current.getPrevious();
|
||||||
|
if (previous instanceof MethodInsnNode) {
|
||||||
|
MethodInsnNode call = (MethodInsnNode) previous;
|
||||||
|
if (STREAM.equals(call.owner) && ANY_MATCH.equals(call.name)) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,599 @@
|
|||||||
|
package dev.jnic.translate;
|
||||||
|
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
|
||||||
|
import org.objectweb.asm.tree.JumpInsnNode;
|
||||||
|
import org.objectweb.asm.tree.LabelNode;
|
||||||
|
import org.objectweb.asm.tree.LdcInsnNode;
|
||||||
|
import org.objectweb.asm.tree.LookupSwitchInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
import org.objectweb.asm.tree.MultiANewArrayInsnNode;
|
||||||
|
import org.objectweb.asm.tree.TableSwitchInsnNode;
|
||||||
|
import org.objectweb.asm.tree.TryCatchBlockNode;
|
||||||
|
|
||||||
|
public final class StackFlow {
|
||||||
|
public static final class State {
|
||||||
|
final int[] categories;
|
||||||
|
|
||||||
|
State(int[] categories) {
|
||||||
|
this.categories = categories;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int height() {
|
||||||
|
return this.categories.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int category(int offsetFromTop) {
|
||||||
|
int index = this.categories.length - 1 - offsetFromTop;
|
||||||
|
return index >= 0 && index < this.categories.length ? this.categories[index] : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
State with(int[] next) {
|
||||||
|
return new State(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private StackFlow() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static State[] analyze(MethodNode method) {
|
||||||
|
int size = method.instructions.size();
|
||||||
|
State[] states = new State[size];
|
||||||
|
if (size == 0) {
|
||||||
|
return states;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<AbstractInsnNode, Integer> indexes = new IdentityHashMap<>();
|
||||||
|
for (int index = 0; index < size; index++) {
|
||||||
|
indexes.put(method.instructions.get(index), index);
|
||||||
|
}
|
||||||
|
|
||||||
|
Deque<Integer> pending = new ArrayDeque<>();
|
||||||
|
seed(states, pending, 0, new State(new int[0]));
|
||||||
|
if (method.tryCatchBlocks != null) {
|
||||||
|
for (TryCatchBlockNode block : method.tryCatchBlocks) {
|
||||||
|
if (block.handler == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Integer index = indexes.get(block.handler);
|
||||||
|
if (index != null) {
|
||||||
|
seed(states, pending, index, new State(new int[]{1}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
while (!pending.isEmpty()) {
|
||||||
|
int index = pending.removeFirst();
|
||||||
|
State input = states[index];
|
||||||
|
if (input == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
AbstractInsnNode node = method.instructions.get(index);
|
||||||
|
if (node.getOpcode() < 0) {
|
||||||
|
merge(states, pending, index + 1, input);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
State output = step(node, input);
|
||||||
|
for (int next : successors(method, node, index, size)) {
|
||||||
|
merge(states, pending, next, output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return states;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void seed(State[] states, Deque<Integer> pending, int index, State state) {
|
||||||
|
if (index < 0 || index >= states.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
State existing = states[index];
|
||||||
|
State merged = existing == null ? state : mergeStates(existing, state);
|
||||||
|
if (existing == null || merged != existing) {
|
||||||
|
states[index] = merged;
|
||||||
|
pending.addLast(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void merge(State[] states, Deque<Integer> pending, int index, State incoming) {
|
||||||
|
if (index < 0 || index >= states.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
State existing = states[index];
|
||||||
|
if (existing == null) {
|
||||||
|
states[index] = incoming;
|
||||||
|
pending.addLast(index);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
State merged = mergeStates(existing, incoming);
|
||||||
|
if (merged != existing) {
|
||||||
|
states[index] = merged;
|
||||||
|
pending.addLast(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static State mergeStates(State left, State right) {
|
||||||
|
if (left.categories.length != right.categories.length) {
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
int[] merged = null;
|
||||||
|
for (int index = 0; index < left.categories.length; index++) {
|
||||||
|
int a = left.categories[index];
|
||||||
|
int b = right.categories[index];
|
||||||
|
int value = (a == 2 || b == 2) ? 2 : 1;
|
||||||
|
if (value != left.categories[index]) {
|
||||||
|
if (merged == null) {
|
||||||
|
merged = left.categories.clone();
|
||||||
|
}
|
||||||
|
merged[index] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return merged == null ? left : new State(merged);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Integer> successors(MethodNode method, AbstractInsnNode node, int index, int size) {
|
||||||
|
List<Integer> out = new ArrayList<>(2);
|
||||||
|
int op = node.getOpcode();
|
||||||
|
switch (op) {
|
||||||
|
case Opcodes.GOTO:
|
||||||
|
case Opcodes.JSR:
|
||||||
|
out.add(indexOf(method, ((JumpInsnNode) node).label));
|
||||||
|
return out;
|
||||||
|
case Opcodes.TABLESWITCH: {
|
||||||
|
TableSwitchInsnNode table = (TableSwitchInsnNode) node;
|
||||||
|
out.add(indexOf(method, table.dflt));
|
||||||
|
for (LabelNode label : table.labels) {
|
||||||
|
out.add(indexOf(method, label));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
case Opcodes.LOOKUPSWITCH: {
|
||||||
|
LookupSwitchInsnNode lookup = (LookupSwitchInsnNode) node;
|
||||||
|
out.add(indexOf(method, lookup.dflt));
|
||||||
|
for (LabelNode label : lookup.labels) {
|
||||||
|
out.add(indexOf(method, label));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
case Opcodes.IRETURN:
|
||||||
|
case Opcodes.LRETURN:
|
||||||
|
case Opcodes.FRETURN:
|
||||||
|
case Opcodes.DRETURN:
|
||||||
|
case Opcodes.ARETURN:
|
||||||
|
case Opcodes.RETURN:
|
||||||
|
case Opcodes.ATHROW:
|
||||||
|
case Opcodes.RET:
|
||||||
|
return out;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (isConditionalBranch(op)) {
|
||||||
|
out.add(indexOf(method, ((JumpInsnNode) node).label));
|
||||||
|
}
|
||||||
|
if (index + 1 < size) {
|
||||||
|
out.add(index + 1);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int indexOf(MethodNode method, AbstractInsnNode node) {
|
||||||
|
int size = method.instructions.size();
|
||||||
|
for (int index = 0; index < size; index++) {
|
||||||
|
if (method.instructions.get(index) == node) {
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isConditionalBranch(int op) {
|
||||||
|
return (op >= Opcodes.IFEQ && op <= Opcodes.IF_ACMPNE)
|
||||||
|
|| op == Opcodes.IFNULL
|
||||||
|
|| op == Opcodes.IFNONNULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static State step(AbstractInsnNode node, State input) {
|
||||||
|
int op = node.getOpcode();
|
||||||
|
List<Integer> stack = new ArrayList<>();
|
||||||
|
for (int category : input.categories) {
|
||||||
|
stack.add(category);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (op) {
|
||||||
|
case Opcodes.NOP:
|
||||||
|
break;
|
||||||
|
case Opcodes.ACONST_NULL:
|
||||||
|
case Opcodes.ICONST_M1:
|
||||||
|
case Opcodes.ICONST_0:
|
||||||
|
case Opcodes.ICONST_1:
|
||||||
|
case Opcodes.ICONST_2:
|
||||||
|
case Opcodes.ICONST_3:
|
||||||
|
case Opcodes.ICONST_4:
|
||||||
|
case Opcodes.ICONST_5:
|
||||||
|
case Opcodes.BIPUSH:
|
||||||
|
case Opcodes.SIPUSH:
|
||||||
|
case Opcodes.FCONST_0:
|
||||||
|
case Opcodes.FCONST_1:
|
||||||
|
case Opcodes.FCONST_2:
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.LCONST_0:
|
||||||
|
case Opcodes.LCONST_1:
|
||||||
|
case Opcodes.DCONST_0:
|
||||||
|
case Opcodes.DCONST_1:
|
||||||
|
stack.add(2);
|
||||||
|
break;
|
||||||
|
case Opcodes.LDC: {
|
||||||
|
Object constant = ((LdcInsnNode) node).cst;
|
||||||
|
stack.add(category(constant instanceof Long || constant instanceof Double ? "J" : "I"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.ILOAD:
|
||||||
|
case Opcodes.FLOAD:
|
||||||
|
case Opcodes.ALOAD:
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.LLOAD:
|
||||||
|
case Opcodes.DLOAD:
|
||||||
|
stack.add(2);
|
||||||
|
break;
|
||||||
|
case Opcodes.ISTORE:
|
||||||
|
case Opcodes.FSTORE:
|
||||||
|
case Opcodes.ASTORE:
|
||||||
|
case Opcodes.LSTORE:
|
||||||
|
case Opcodes.DSTORE:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.IALOAD:
|
||||||
|
case Opcodes.FALOAD:
|
||||||
|
case Opcodes.AALOAD:
|
||||||
|
case Opcodes.BALOAD:
|
||||||
|
case Opcodes.CALOAD:
|
||||||
|
case Opcodes.SALOAD:
|
||||||
|
pop(stack, 2);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.LALOAD:
|
||||||
|
case Opcodes.DALOAD:
|
||||||
|
pop(stack, 2);
|
||||||
|
stack.add(2);
|
||||||
|
break;
|
||||||
|
case Opcodes.IASTORE:
|
||||||
|
case Opcodes.LASTORE:
|
||||||
|
case Opcodes.FASTORE:
|
||||||
|
case Opcodes.DASTORE:
|
||||||
|
case Opcodes.AASTORE:
|
||||||
|
case Opcodes.BASTORE:
|
||||||
|
case Opcodes.CASTORE:
|
||||||
|
case Opcodes.SASTORE:
|
||||||
|
pop(stack, 3);
|
||||||
|
break;
|
||||||
|
case Opcodes.POP:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.POP2:
|
||||||
|
if (stack.isEmpty()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (stack.get(stack.size() - 1) == 2) {
|
||||||
|
pop(stack, 1);
|
||||||
|
} else {
|
||||||
|
pop(stack, 2);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case Opcodes.DUP:
|
||||||
|
stack.add(top(stack));
|
||||||
|
break;
|
||||||
|
case Opcodes.DUP_X1: {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.DUP_X2: {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
if (top(stack) == 2) {
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
} else {
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
int v3 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v3);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.DUP2: {
|
||||||
|
if (top(stack) == 2) {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v1);
|
||||||
|
} else {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.DUP2_X1: {
|
||||||
|
if (top(stack) == 2) {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
} else {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
int v3 = popValue(stack);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v3);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.DUP2_X2: {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
if (v1 == 2) {
|
||||||
|
if (top(stack) == 2) {
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
} else {
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
int v3 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v3);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
if (top(stack) == 2) {
|
||||||
|
int v3 = popValue(stack);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v3);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
} else {
|
||||||
|
int v3 = popValue(stack);
|
||||||
|
int v4 = popValue(stack);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v4);
|
||||||
|
stack.add(v3);
|
||||||
|
stack.add(v2);
|
||||||
|
stack.add(v1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.SWAP: {
|
||||||
|
int v1 = popValue(stack);
|
||||||
|
int v2 = popValue(stack);
|
||||||
|
stack.add(v1);
|
||||||
|
stack.add(v2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.IADD:
|
||||||
|
case Opcodes.ISUB:
|
||||||
|
case Opcodes.IMUL:
|
||||||
|
case Opcodes.IDIV:
|
||||||
|
case Opcodes.IREM:
|
||||||
|
case Opcodes.ISHL:
|
||||||
|
case Opcodes.ISHR:
|
||||||
|
case Opcodes.IUSHR:
|
||||||
|
case Opcodes.IAND:
|
||||||
|
case Opcodes.IOR:
|
||||||
|
case Opcodes.IXOR:
|
||||||
|
case Opcodes.FADD:
|
||||||
|
case Opcodes.FSUB:
|
||||||
|
case Opcodes.FMUL:
|
||||||
|
case Opcodes.FDIV:
|
||||||
|
case Opcodes.FREM:
|
||||||
|
case Opcodes.LCMP:
|
||||||
|
case Opcodes.FCMPL:
|
||||||
|
case Opcodes.FCMPG:
|
||||||
|
case Opcodes.DCMPL:
|
||||||
|
case Opcodes.DCMPG:
|
||||||
|
pop(stack, 2);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.LADD:
|
||||||
|
case Opcodes.LSUB:
|
||||||
|
case Opcodes.LMUL:
|
||||||
|
case Opcodes.LDIV:
|
||||||
|
case Opcodes.LREM:
|
||||||
|
case Opcodes.LSHL:
|
||||||
|
case Opcodes.LSHR:
|
||||||
|
case Opcodes.LUSHR:
|
||||||
|
case Opcodes.LAND:
|
||||||
|
case Opcodes.LOR:
|
||||||
|
case Opcodes.LXOR:
|
||||||
|
case Opcodes.DADD:
|
||||||
|
case Opcodes.DSUB:
|
||||||
|
case Opcodes.DMUL:
|
||||||
|
case Opcodes.DDIV:
|
||||||
|
case Opcodes.DREM:
|
||||||
|
pop(stack, 2);
|
||||||
|
stack.add(2);
|
||||||
|
break;
|
||||||
|
case Opcodes.INEG:
|
||||||
|
case Opcodes.FNEG:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.LNEG:
|
||||||
|
case Opcodes.DNEG:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(2);
|
||||||
|
break;
|
||||||
|
case Opcodes.IINC:
|
||||||
|
break;
|
||||||
|
case Opcodes.I2L:
|
||||||
|
case Opcodes.I2D:
|
||||||
|
case Opcodes.F2L:
|
||||||
|
case Opcodes.F2D:
|
||||||
|
case Opcodes.D2L:
|
||||||
|
case Opcodes.L2D:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(2);
|
||||||
|
break;
|
||||||
|
case Opcodes.I2F:
|
||||||
|
case Opcodes.L2I:
|
||||||
|
case Opcodes.L2F:
|
||||||
|
case Opcodes.F2I:
|
||||||
|
case Opcodes.D2I:
|
||||||
|
case Opcodes.D2F:
|
||||||
|
case Opcodes.I2B:
|
||||||
|
case Opcodes.I2C:
|
||||||
|
case Opcodes.I2S:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.IFEQ:
|
||||||
|
case Opcodes.IFNE:
|
||||||
|
case Opcodes.IFLT:
|
||||||
|
case Opcodes.IFGE:
|
||||||
|
case Opcodes.IFGT:
|
||||||
|
case Opcodes.IFLE:
|
||||||
|
case Opcodes.IFNULL:
|
||||||
|
case Opcodes.IFNONNULL:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.IF_ICMPEQ:
|
||||||
|
case Opcodes.IF_ICMPNE:
|
||||||
|
case Opcodes.IF_ICMPLT:
|
||||||
|
case Opcodes.IF_ICMPGE:
|
||||||
|
case Opcodes.IF_ICMPGT:
|
||||||
|
case Opcodes.IF_ICMPLE:
|
||||||
|
case Opcodes.IF_ACMPEQ:
|
||||||
|
case Opcodes.IF_ACMPNE:
|
||||||
|
pop(stack, 2);
|
||||||
|
break;
|
||||||
|
case Opcodes.GOTO:
|
||||||
|
break;
|
||||||
|
case Opcodes.JSR:
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.RET:
|
||||||
|
break;
|
||||||
|
case Opcodes.TABLESWITCH:
|
||||||
|
case Opcodes.LOOKUPSWITCH:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.IRETURN:
|
||||||
|
case Opcodes.LRETURN:
|
||||||
|
case Opcodes.FRETURN:
|
||||||
|
case Opcodes.DRETURN:
|
||||||
|
case Opcodes.ARETURN:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.RETURN:
|
||||||
|
break;
|
||||||
|
case Opcodes.GETSTATIC:
|
||||||
|
stack.add(category(((org.objectweb.asm.tree.FieldInsnNode) node).desc));
|
||||||
|
break;
|
||||||
|
case Opcodes.PUTSTATIC:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.GETFIELD:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(category(((org.objectweb.asm.tree.FieldInsnNode) node).desc));
|
||||||
|
break;
|
||||||
|
case Opcodes.PUTFIELD:
|
||||||
|
pop(stack, 2);
|
||||||
|
break;
|
||||||
|
case Opcodes.INVOKEVIRTUAL:
|
||||||
|
case Opcodes.INVOKESPECIAL:
|
||||||
|
case Opcodes.INVOKEINTERFACE:
|
||||||
|
case Opcodes.INVOKESTATIC:
|
||||||
|
case Opcodes.INVOKEDYNAMIC: {
|
||||||
|
String descriptor = op == Opcodes.INVOKEDYNAMIC
|
||||||
|
? ((InvokeDynamicInsnNode) node).desc
|
||||||
|
: ((MethodInsnNode) node).desc;
|
||||||
|
int arguments = Type.getArgumentTypes(descriptor).length;
|
||||||
|
pop(stack, arguments + (op == Opcodes.INVOKESTATIC || op == Opcodes.INVOKEDYNAMIC ? 0 : 1));
|
||||||
|
String result = Type.getReturnType(descriptor).getDescriptor();
|
||||||
|
if (!"V".equals(result)) {
|
||||||
|
stack.add(category(result));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case Opcodes.NEW:
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.NEWARRAY:
|
||||||
|
case Opcodes.ANEWARRAY:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.ARRAYLENGTH:
|
||||||
|
pop(stack, 1);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
case Opcodes.CHECKCAST:
|
||||||
|
case Opcodes.INSTANCEOF:
|
||||||
|
break;
|
||||||
|
case Opcodes.ATHROW:
|
||||||
|
case Opcodes.MONITORENTER:
|
||||||
|
case Opcodes.MONITOREXIT:
|
||||||
|
pop(stack, 1);
|
||||||
|
break;
|
||||||
|
case Opcodes.MULTIANEWARRAY:
|
||||||
|
pop(stack, ((MultiANewArrayInsnNode) node).dims);
|
||||||
|
stack.add(1);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new IllegalStateException("Unsupported opcode " + op + " in stack analysis");
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] categories = new int[stack.size()];
|
||||||
|
for (int index = 0; index < categories.length; index++) {
|
||||||
|
categories[index] = stack.get(index);
|
||||||
|
}
|
||||||
|
return new State(categories);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int category(String descriptor) {
|
||||||
|
if (descriptor == null || descriptor.isEmpty()) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
char first = descriptor.charAt(0);
|
||||||
|
return first == 'J' || first == 'D' ? 2 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int top(List<Integer> stack) {
|
||||||
|
return stack.isEmpty() ? 1 : stack.get(stack.size() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int popValue(List<Integer> stack) {
|
||||||
|
return stack.isEmpty() ? 1 : stack.remove(stack.size() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void pop(List<Integer> stack, int count) {
|
||||||
|
for (int index = 0; index < count && !stack.isEmpty(); index++) {
|
||||||
|
stack.remove(stack.size() - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import java.util.BitSet;
|
||||||
|
|
||||||
|
public class FlagSet {
|
||||||
|
private final BitSet bits;
|
||||||
|
|
||||||
|
public FlagSet(BitSet bits) {
|
||||||
|
this.bits = bits;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FlagSet() {
|
||||||
|
this(new BitSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FlagSet of(int flag) {
|
||||||
|
FlagSet flagSet = new FlagSet();
|
||||||
|
flagSet.bits.set(flag);
|
||||||
|
return flagSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
void set(int flag) {
|
||||||
|
this.bits.set(flag);
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear(int flag) {
|
||||||
|
this.bits.clear(flag);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean get(int flag) {
|
||||||
|
return this.bits.get(flag);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return this.bits.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int cardinality() {
|
||||||
|
return this.bits.cardinality();
|
||||||
|
}
|
||||||
|
|
||||||
|
public int nextSetBit(int fromIndex) {
|
||||||
|
return this.bits.nextSetBit(fromIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
FlagSet copy() {
|
||||||
|
return new FlagSet((BitSet) this.bits.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import dev.jnic.templates.State;
|
||||||
|
import org.objectweb.asm.ConstantDynamic;
|
||||||
|
import org.objectweb.asm.Handle;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
|
||||||
|
public class JniTypeUtils {
|
||||||
|
public static char slotChar(Type type) {
|
||||||
|
if (type == null) {
|
||||||
|
return 'l';
|
||||||
|
}
|
||||||
|
switch (type.getSort()) {
|
||||||
|
case Type.BOOLEAN:
|
||||||
|
return 'z';
|
||||||
|
case Type.CHAR:
|
||||||
|
return 'c';
|
||||||
|
case Type.BYTE:
|
||||||
|
return 'b';
|
||||||
|
case Type.SHORT:
|
||||||
|
return 's';
|
||||||
|
case Type.INT:
|
||||||
|
return 'i';
|
||||||
|
case Type.FLOAT:
|
||||||
|
return 'f';
|
||||||
|
case Type.LONG:
|
||||||
|
return 'j';
|
||||||
|
case Type.DOUBLE:
|
||||||
|
return 'd';
|
||||||
|
default:
|
||||||
|
return 'l';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String jniCallType(Type type) {
|
||||||
|
if (type == null) {
|
||||||
|
return "Object";
|
||||||
|
}
|
||||||
|
switch (type.getSort()) {
|
||||||
|
case Type.VOID:
|
||||||
|
return "Void";
|
||||||
|
case Type.BOOLEAN:
|
||||||
|
return "Boolean";
|
||||||
|
case Type.CHAR:
|
||||||
|
return "Char";
|
||||||
|
case Type.BYTE:
|
||||||
|
return "Byte";
|
||||||
|
case Type.SHORT:
|
||||||
|
return "Short";
|
||||||
|
case Type.INT:
|
||||||
|
return "Int";
|
||||||
|
case Type.FLOAT:
|
||||||
|
return "Float";
|
||||||
|
case Type.LONG:
|
||||||
|
return "Long";
|
||||||
|
case Type.DOUBLE:
|
||||||
|
return "Double";
|
||||||
|
default:
|
||||||
|
return "Object";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String jniArrayType(int atype) {
|
||||||
|
switch (atype) {
|
||||||
|
case 4:
|
||||||
|
return "jbooleanArray";
|
||||||
|
case 5:
|
||||||
|
return "jcharArray";
|
||||||
|
case 6:
|
||||||
|
return "jfloatArray";
|
||||||
|
case 7:
|
||||||
|
return "jdoubleArray";
|
||||||
|
case 8:
|
||||||
|
return "jbyteArray";
|
||||||
|
case 9:
|
||||||
|
return "jshortArray";
|
||||||
|
case 10:
|
||||||
|
return "jintArray";
|
||||||
|
case 11:
|
||||||
|
return "jlongArray";
|
||||||
|
default:
|
||||||
|
return "jarray";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String newArrayPrimitiveName(int atype) {
|
||||||
|
switch (atype) {
|
||||||
|
case 4:
|
||||||
|
return "Boolean";
|
||||||
|
case 5:
|
||||||
|
return "Char";
|
||||||
|
case 6:
|
||||||
|
return "Float";
|
||||||
|
case 7:
|
||||||
|
return "Double";
|
||||||
|
case 8:
|
||||||
|
return "Byte";
|
||||||
|
case 9:
|
||||||
|
return "Short";
|
||||||
|
case 10:
|
||||||
|
return "Int";
|
||||||
|
case 11:
|
||||||
|
return "Long";
|
||||||
|
default:
|
||||||
|
throw new IllegalArgumentException("Unknown array type: " + atype);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String jniType(Type type) {
|
||||||
|
if (type == null) {
|
||||||
|
return "jobject";
|
||||||
|
}
|
||||||
|
switch (type.getSort()) {
|
||||||
|
case Type.VOID:
|
||||||
|
return "void";
|
||||||
|
case Type.BOOLEAN:
|
||||||
|
return "jboolean";
|
||||||
|
case Type.CHAR:
|
||||||
|
return "jchar";
|
||||||
|
case Type.BYTE:
|
||||||
|
return "jbyte";
|
||||||
|
case Type.SHORT:
|
||||||
|
return "jshort";
|
||||||
|
case Type.INT:
|
||||||
|
return "jint";
|
||||||
|
case Type.FLOAT:
|
||||||
|
return "jfloat";
|
||||||
|
case Type.LONG:
|
||||||
|
return "jlong";
|
||||||
|
case Type.DOUBLE:
|
||||||
|
return "jdouble";
|
||||||
|
case Type.ARRAY: {
|
||||||
|
Type elem = type.getElementType();
|
||||||
|
if (elem != null && type.getDimensions() == 1) {
|
||||||
|
switch (elem.getSort()) {
|
||||||
|
case Type.BOOLEAN:
|
||||||
|
return "jbooleanArray";
|
||||||
|
case Type.CHAR:
|
||||||
|
return "jcharArray";
|
||||||
|
case Type.BYTE:
|
||||||
|
return "jbyteArray";
|
||||||
|
case Type.SHORT:
|
||||||
|
return "jshortArray";
|
||||||
|
case Type.INT:
|
||||||
|
return "jintArray";
|
||||||
|
case Type.FLOAT:
|
||||||
|
return "jfloatArray";
|
||||||
|
case Type.LONG:
|
||||||
|
return "jlongArray";
|
||||||
|
case Type.DOUBLE:
|
||||||
|
return "jdoubleArray";
|
||||||
|
default:
|
||||||
|
return "jobjectArray";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "jobjectArray";
|
||||||
|
}
|
||||||
|
case Type.OBJECT: {
|
||||||
|
String internal = type.getInternalName();
|
||||||
|
if ("java/lang/String".equals(internal)) {
|
||||||
|
return "jstring";
|
||||||
|
}
|
||||||
|
if ("java/lang/Class".equals(internal)) {
|
||||||
|
return "jclass";
|
||||||
|
}
|
||||||
|
if ("java/lang/Throwable".equals(internal)) {
|
||||||
|
return "jthrowable";
|
||||||
|
}
|
||||||
|
return "jobject";
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return "jobject";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String emitStringLiteral(int stackIdx, String str) {
|
||||||
|
if (str == null) {
|
||||||
|
return " stack" + stackIdx + ".l = nullptr;\n";
|
||||||
|
}
|
||||||
|
int len = str.length();
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append(" stack").append(stackIdx).append(".l = (*env)->NewString(env, (unsigned short[]) {");
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
if (i > 0) {
|
||||||
|
sb.append(", ");
|
||||||
|
}
|
||||||
|
sb.append((int) str.charAt(i));
|
||||||
|
}
|
||||||
|
if (len > 0) {
|
||||||
|
sb.append(", ");
|
||||||
|
}
|
||||||
|
sb.append("0}, ").append(len).append(");\n");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String emitLdcConstant(State ctx, Object cst, int stackIdx, int line, String ownerName) {
|
||||||
|
if (cst == null) {
|
||||||
|
return " stack" + stackIdx + ".l = nullptr;\n";
|
||||||
|
}
|
||||||
|
if (cst instanceof Integer) {
|
||||||
|
int val = (Integer) cst;
|
||||||
|
if (val == Integer.MIN_VALUE) {
|
||||||
|
return " stack" + stackIdx + ".i = (jint)0x80000000;\n";
|
||||||
|
}
|
||||||
|
return " stack" + stackIdx + ".i = " + val + ";\n";
|
||||||
|
}
|
||||||
|
if (cst instanceof Float) {
|
||||||
|
float val = (Float) cst;
|
||||||
|
if (Float.isNaN(val)) {
|
||||||
|
return " stack" + stackIdx + ".f = 0.0f / 0.0f;\n";
|
||||||
|
}
|
||||||
|
if (Float.isInfinite(val)) {
|
||||||
|
return " stack" + stackIdx + ".f = " + (val > 0 ? "1.0f / 0.0f" : "-1.0f / 0.0f") + ";\n";
|
||||||
|
}
|
||||||
|
return " stack" + stackIdx + ".f = " + val + "f;\n";
|
||||||
|
}
|
||||||
|
if (cst instanceof Long) {
|
||||||
|
long val = (Long) cst;
|
||||||
|
if (val == Long.MIN_VALUE) {
|
||||||
|
return " stack" + stackIdx + ".j = (jlong)0x8000000000000000ULL;\n";
|
||||||
|
}
|
||||||
|
return " stack" + stackIdx + ".j = " + val + "LL;\n";
|
||||||
|
}
|
||||||
|
if (cst instanceof Double) {
|
||||||
|
double val = (Double) cst;
|
||||||
|
if (Double.isNaN(val)) {
|
||||||
|
return " stack" + stackIdx + ".d = 0.0 / 0.0;\n";
|
||||||
|
}
|
||||||
|
if (Double.isInfinite(val)) {
|
||||||
|
return " stack" + stackIdx + ".d = " + (val > 0 ? "1.0 / 0.0" : "-1.0 / 0.0") + ";\n";
|
||||||
|
}
|
||||||
|
return " stack" + stackIdx + ".d = " + val + ";\n";
|
||||||
|
}
|
||||||
|
if (cst instanceof String) {
|
||||||
|
return emitStringLiteral(stackIdx, (String) cst);
|
||||||
|
}
|
||||||
|
if (cst instanceof Type) {
|
||||||
|
Type t = (Type) cst;
|
||||||
|
int sort = t.getSort();
|
||||||
|
if (sort == Type.OBJECT || sort == Type.ARRAY) {
|
||||||
|
String clsName = t.getInternalName();
|
||||||
|
String cVar = ctx != null ? ctx.cacheClass(clsName) : "nullptr";
|
||||||
|
return " stack" + stackIdx + ".l = " + cVar + "(env);\n";
|
||||||
|
}
|
||||||
|
if (sort == Type.METHOD) {
|
||||||
|
String desc = t.getDescriptor();
|
||||||
|
String mtCls = ctx != null ? ctx.cacheClass("java/lang/invoke/MethodType") : "c_mt";
|
||||||
|
String fromDesc = ctx != null
|
||||||
|
? ctx.cacheMethod("java/lang/invoke/MethodType", "fromMethodDescriptorString", "(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/invoke/MethodType;", true)
|
||||||
|
: "c_mt_id";
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append(emitStringLiteral(stackIdx, desc));
|
||||||
|
sb.append(" stack").append(stackIdx).append(".l = (*env)->CallStaticObjectMethod(env, ")
|
||||||
|
.append(mtCls).append("(env), ").append(fromDesc).append("(env), stack").append(stackIdx).append(".l, nullptr);\n");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cst instanceof Handle || cst instanceof ConstantDynamic) {
|
||||||
|
return " stack" + stackIdx + ".l = nullptr;\n";
|
||||||
|
}
|
||||||
|
return " stack" + stackIdx + ".l = nullptr;\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Type constantType(Object value) {
|
||||||
|
if (value instanceof Integer) return Type.INT_TYPE;
|
||||||
|
if (value instanceof Float) return Type.FLOAT_TYPE;
|
||||||
|
if (value instanceof Long) return Type.LONG_TYPE;
|
||||||
|
if (value instanceof Double) return Type.DOUBLE_TYPE;
|
||||||
|
if (value instanceof String) return Type.getType("Ljava/lang/String;");
|
||||||
|
if (value instanceof Type) {
|
||||||
|
Type t = (Type) value;
|
||||||
|
int s = t.getSort();
|
||||||
|
if (s == Type.OBJECT || s == Type.ARRAY) return Type.getType("Ljava/lang/Class;");
|
||||||
|
if (s == Type.METHOD) return Type.getType("Ljava/lang/invoke/MethodType;");
|
||||||
|
}
|
||||||
|
if (value instanceof Handle) return Type.getType("Ljava/lang/invoke/MethodHandle;");
|
||||||
|
if (value instanceof ConstantDynamic) return Type.getType(((ConstantDynamic) value).getDescriptor());
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
import org.objectweb.asm.tree.analysis.Analyzer;
|
||||||
|
import org.objectweb.asm.tree.analysis.AnalyzerException;
|
||||||
|
import org.objectweb.asm.tree.analysis.Frame;
|
||||||
|
|
||||||
|
public class MethodAnalysis {
|
||||||
|
private Frame<StackValueType>[] frames;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public MethodAnalysis(ClassNode classNode, MethodNode methodNode) throws AnalyzerException {
|
||||||
|
if (classNode != null && methodNode != null && methodNode.instructions != null && methodNode.instructions.size() > 0) {
|
||||||
|
try {
|
||||||
|
Analyzer<StackValueType> analyzer = new Analyzer<>(StackTypeInterpreter.INSTANCE);
|
||||||
|
this.frames = analyzer.analyze(classNode.name, methodNode);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
this.frames = new Frame[methodNode.instructions.size()];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.frames = new Frame[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Frame<StackValueType> getFrame(int index) {
|
||||||
|
if (this.frames == null || index < 0 || index >= this.frames.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.frames[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
public Frame<StackValueType>[] getFrames() {
|
||||||
|
return this.frames;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import dev.jnic.pipeline.TranslateException;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.regex.PatternSyntaxException;
|
||||||
|
import org.simpleframework.xml.Attribute;
|
||||||
|
import org.simpleframework.xml.Root;
|
||||||
|
import org.simpleframework.xml.core.Commit;
|
||||||
|
|
||||||
|
@Root(name = "match")
|
||||||
|
public class MethodMatcher {
|
||||||
|
@Attribute(name = "className", required = false)
|
||||||
|
private String className;
|
||||||
|
private Pattern classPattern;
|
||||||
|
@Attribute(name = "methodName", required = false)
|
||||||
|
private String methodName;
|
||||||
|
private Pattern methodPattern;
|
||||||
|
@Attribute(name = "methodDesc", required = false)
|
||||||
|
private String methodDesc;
|
||||||
|
private Pattern descPattern;
|
||||||
|
|
||||||
|
@Commit
|
||||||
|
private void compile() throws TranslateException {
|
||||||
|
try {
|
||||||
|
this.classPattern = this.className == null || this.className.isEmpty() ? null : Pattern.compile(this.className);
|
||||||
|
this.methodPattern = this.methodName == null || this.methodName.isEmpty() ? null : Pattern.compile(this.methodName);
|
||||||
|
this.descPattern = this.methodDesc == null || this.methodDesc.isEmpty() ? null : Pattern.compile(this.methodDesc);
|
||||||
|
} catch (PatternSyntaxException e) {
|
||||||
|
throw new TranslateException(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean matches(String className, String methodName, String methodDesc) {
|
||||||
|
if (this.classPattern != null && (className == null || !this.classPattern.matcher(className).matches())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (this.methodPattern != null && (methodName == null || !this.methodPattern.matcher(methodName).matches())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (this.descPattern != null && (methodDesc == null || !this.descPattern.matcher(methodDesc).matches())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.analysis.BasicValue;
|
||||||
|
import org.objectweb.asm.tree.analysis.Frame;
|
||||||
|
|
||||||
|
public class StackFrame {
|
||||||
|
private final Frame<BasicValue> inputFrame;
|
||||||
|
private final Frame<BasicValue> outputFrame;
|
||||||
|
private final MethodAnalysis analysis;
|
||||||
|
|
||||||
|
public StackFrame(Frame<BasicValue> inputFrame, Frame<BasicValue> outputFrame, MethodAnalysis analysis) {
|
||||||
|
this.inputFrame = inputFrame;
|
||||||
|
this.outputFrame = outputFrame;
|
||||||
|
this.analysis = analysis;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getInputStackSize() {
|
||||||
|
return this.inputFrame != null ? this.inputFrame.getStackSize() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getOutputStackSize() {
|
||||||
|
return this.outputFrame != null ? this.outputFrame.getStackSize() : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String topSlotChar(int offsetFromTop) {
|
||||||
|
Type t = this.getInputStackType(offsetFromTop);
|
||||||
|
return String.valueOf(JniTypeUtils.slotChar(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Type getInputStackType(int offsetFromTop) {
|
||||||
|
if (this.inputFrame == null) {
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
int size = this.inputFrame.getStackSize();
|
||||||
|
int idx = size - 1 - offsetFromTop;
|
||||||
|
if (idx < 0 || idx >= size) {
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
BasicValue val = this.inputFrame.getStack(idx);
|
||||||
|
if (val == null || val.getType() == null) {
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
return val.getType();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Type getOutputStackType(int offsetFromTop) {
|
||||||
|
if (this.outputFrame == null) {
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
int size = this.outputFrame.getStackSize();
|
||||||
|
int idx = size - 1 - offsetFromTop;
|
||||||
|
if (idx < 0 || idx >= size) {
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
BasicValue val = this.outputFrame.getStack(idx);
|
||||||
|
if (val == null || val.getType() == null) {
|
||||||
|
return Type.getType("Ljava/lang/Object;");
|
||||||
|
}
|
||||||
|
return val.getType();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPossiblyNull(int offsetFromTop) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Type topStackType(int offsetFromTop) {
|
||||||
|
return this.getInputStackType(offsetFromTop);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int topStackSize(int offsetFromTop) {
|
||||||
|
if (this.inputFrame != null) {
|
||||||
|
int size = this.inputFrame.getStackSize();
|
||||||
|
int idx = size - 1 - offsetFromTop;
|
||||||
|
if (idx >= 0 && idx < size) {
|
||||||
|
BasicValue val = this.inputFrame.getStack(idx);
|
||||||
|
if (val != null) {
|
||||||
|
return val.getSize();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Type t = this.getInputStackType(offsetFromTop);
|
||||||
|
if (t != null && (t.getSort() == Type.LONG || t.getSort() == Type.DOUBLE)) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.FieldInsnNode;
|
||||||
|
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
|
||||||
|
import org.objectweb.asm.tree.LdcInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
import org.objectweb.asm.tree.analysis.AnalyzerException;
|
||||||
|
import org.objectweb.asm.tree.analysis.Interpreter;
|
||||||
|
|
||||||
|
class StackTypeInterpreter extends Interpreter<StackValueType> {
|
||||||
|
public static final StackTypeInterpreter INSTANCE = new StackTypeInterpreter();
|
||||||
|
|
||||||
|
private StackTypeInterpreter() {
|
||||||
|
super(Opcodes.ASM9);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType newValue(Type type) {
|
||||||
|
return StackValueType.fromType(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType newParameterValue(boolean isInstanceMethod, int local, Type type) {
|
||||||
|
return StackValueType.fromType(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType newOperation(AbstractInsnNode insn) throws AnalyzerException {
|
||||||
|
if (insn == null) {
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
switch (insn.getOpcode()) {
|
||||||
|
case Opcodes.ACONST_NULL:
|
||||||
|
return StackValueType.NULL;
|
||||||
|
case Opcodes.ICONST_M1:
|
||||||
|
case Opcodes.ICONST_0:
|
||||||
|
case Opcodes.ICONST_1:
|
||||||
|
case Opcodes.ICONST_2:
|
||||||
|
case Opcodes.ICONST_3:
|
||||||
|
case Opcodes.ICONST_4:
|
||||||
|
case Opcodes.ICONST_5:
|
||||||
|
case Opcodes.FCONST_0:
|
||||||
|
case Opcodes.FCONST_1:
|
||||||
|
case Opcodes.FCONST_2:
|
||||||
|
case Opcodes.BIPUSH:
|
||||||
|
case Opcodes.SIPUSH:
|
||||||
|
return StackValueType.PRIMITIVE;
|
||||||
|
case Opcodes.LCONST_0:
|
||||||
|
case Opcodes.LCONST_1:
|
||||||
|
case Opcodes.DCONST_0:
|
||||||
|
case Opcodes.DCONST_1:
|
||||||
|
return StackValueType.WIDE;
|
||||||
|
case Opcodes.LDC: {
|
||||||
|
if (insn instanceof LdcInsnNode) {
|
||||||
|
Object cst = ((LdcInsnNode) insn).cst;
|
||||||
|
if (cst instanceof Long || cst instanceof Double) {
|
||||||
|
return StackValueType.WIDE;
|
||||||
|
}
|
||||||
|
if (cst instanceof Integer || cst instanceof Float) {
|
||||||
|
return StackValueType.PRIMITIVE;
|
||||||
|
}
|
||||||
|
return StackValueType.NON_NULL;
|
||||||
|
}
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
case Opcodes.GETSTATIC:
|
||||||
|
if (insn instanceof FieldInsnNode) {
|
||||||
|
return StackValueType.fromType(Type.getType(((FieldInsnNode) insn).desc));
|
||||||
|
}
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
case Opcodes.NEW:
|
||||||
|
return StackValueType.NON_NULL;
|
||||||
|
default:
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType copyOperation(AbstractInsnNode insn, StackValueType value) throws AnalyzerException {
|
||||||
|
return value != null ? value : StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType unaryOperation(AbstractInsnNode insn, StackValueType value) throws AnalyzerException {
|
||||||
|
if (insn == null) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
switch (insn.getOpcode()) {
|
||||||
|
case Opcodes.I2L:
|
||||||
|
case Opcodes.I2D:
|
||||||
|
case Opcodes.F2L:
|
||||||
|
case Opcodes.F2D:
|
||||||
|
case Opcodes.D2L:
|
||||||
|
return StackValueType.WIDE;
|
||||||
|
case Opcodes.L2I:
|
||||||
|
case Opcodes.L2F:
|
||||||
|
case Opcodes.F2I:
|
||||||
|
case Opcodes.D2I:
|
||||||
|
case Opcodes.D2F:
|
||||||
|
case Opcodes.ARRAYLENGTH:
|
||||||
|
case Opcodes.INSTANCEOF:
|
||||||
|
return StackValueType.PRIMITIVE;
|
||||||
|
case Opcodes.NEWARRAY:
|
||||||
|
case Opcodes.ANEWARRAY:
|
||||||
|
return StackValueType.NON_NULL;
|
||||||
|
case Opcodes.CHECKCAST:
|
||||||
|
return value != null ? value : StackValueType.REFERENCE;
|
||||||
|
case Opcodes.PUTSTATIC:
|
||||||
|
case Opcodes.IFEQ:
|
||||||
|
case Opcodes.IFNE:
|
||||||
|
case Opcodes.IFLT:
|
||||||
|
case Opcodes.IFGE:
|
||||||
|
case Opcodes.IFGT:
|
||||||
|
case Opcodes.IFLE:
|
||||||
|
case Opcodes.TABLESWITCH:
|
||||||
|
case Opcodes.LOOKUPSWITCH:
|
||||||
|
case Opcodes.IRETURN:
|
||||||
|
case Opcodes.LRETURN:
|
||||||
|
case Opcodes.FRETURN:
|
||||||
|
case Opcodes.DRETURN:
|
||||||
|
case Opcodes.ARETURN:
|
||||||
|
case Opcodes.ATHROW:
|
||||||
|
case Opcodes.MONITORENTER:
|
||||||
|
case Opcodes.MONITOREXIT:
|
||||||
|
case Opcodes.IFNULL:
|
||||||
|
case Opcodes.IFNONNULL:
|
||||||
|
return null;
|
||||||
|
case Opcodes.GETFIELD:
|
||||||
|
if (insn instanceof FieldInsnNode) {
|
||||||
|
return StackValueType.fromType(Type.getType(((FieldInsnNode) insn).desc));
|
||||||
|
}
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
default:
|
||||||
|
return value != null ? value : StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType binaryOperation(AbstractInsnNode insn, StackValueType value1, StackValueType value2) throws AnalyzerException {
|
||||||
|
if (insn == null) {
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
switch (insn.getOpcode()) {
|
||||||
|
case Opcodes.LALOAD:
|
||||||
|
case Opcodes.DALOAD:
|
||||||
|
case Opcodes.LADD:
|
||||||
|
case Opcodes.DADD:
|
||||||
|
case Opcodes.LSUB:
|
||||||
|
case Opcodes.DSUB:
|
||||||
|
case Opcodes.LMUL:
|
||||||
|
case Opcodes.DMUL:
|
||||||
|
case Opcodes.LDIV:
|
||||||
|
case Opcodes.DDIV:
|
||||||
|
case Opcodes.LREM:
|
||||||
|
case Opcodes.DREM:
|
||||||
|
case Opcodes.LSHL:
|
||||||
|
case Opcodes.LSHR:
|
||||||
|
case Opcodes.LUSHR:
|
||||||
|
case Opcodes.LAND:
|
||||||
|
case Opcodes.LOR:
|
||||||
|
case Opcodes.LXOR:
|
||||||
|
return StackValueType.WIDE;
|
||||||
|
case Opcodes.AALOAD:
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
case Opcodes.IF_ICMPEQ:
|
||||||
|
case Opcodes.IF_ICMPNE:
|
||||||
|
case Opcodes.IF_ICMPLT:
|
||||||
|
case Opcodes.IF_ICMPGE:
|
||||||
|
case Opcodes.IF_ICMPGT:
|
||||||
|
case Opcodes.IF_ICMPLE:
|
||||||
|
case Opcodes.IF_ACMPEQ:
|
||||||
|
case Opcodes.IF_ACMPNE:
|
||||||
|
case Opcodes.PUTFIELD:
|
||||||
|
return null;
|
||||||
|
default:
|
||||||
|
return StackValueType.PRIMITIVE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType ternaryOperation(AbstractInsnNode insn, StackValueType value1, StackValueType value2, StackValueType value3) throws AnalyzerException {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType naryOperation(AbstractInsnNode insn, List<? extends StackValueType> values) throws AnalyzerException {
|
||||||
|
if (insn == null) {
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
int op = insn.getOpcode();
|
||||||
|
if (op == Opcodes.MULTIANEWARRAY) {
|
||||||
|
return StackValueType.NON_NULL;
|
||||||
|
}
|
||||||
|
if (insn instanceof MethodInsnNode) {
|
||||||
|
MethodInsnNode methodInsn = (MethodInsnNode) insn;
|
||||||
|
if ("<init>".equals(methodInsn.name) && op == Opcodes.INVOKESPECIAL) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return StackValueType.fromType(Type.getReturnType(methodInsn.desc));
|
||||||
|
}
|
||||||
|
if (insn instanceof InvokeDynamicInsnNode) {
|
||||||
|
return StackValueType.fromType(Type.getReturnType(((InvokeDynamicInsnNode) insn).desc));
|
||||||
|
}
|
||||||
|
return StackValueType.REFERENCE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void returnOperation(AbstractInsnNode insn, StackValueType value, StackValueType expected) throws AnalyzerException {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public StackValueType merge(StackValueType value1, StackValueType value2) {
|
||||||
|
if (value1 == null) {
|
||||||
|
return value2;
|
||||||
|
}
|
||||||
|
return value1.merge(value2);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package dev.jnic.type;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.analysis.Value;
|
||||||
|
|
||||||
|
public enum StackValueType implements Value {
|
||||||
|
REFERENCE(1),
|
||||||
|
NULL(1),
|
||||||
|
NON_NULL(1),
|
||||||
|
PRIMITIVE(1),
|
||||||
|
WIDE(2);
|
||||||
|
|
||||||
|
private final int size;
|
||||||
|
|
||||||
|
StackValueType(int size) {
|
||||||
|
this.size = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static StackValueType fromType(Type type) {
|
||||||
|
if (type == null) {
|
||||||
|
return REFERENCE;
|
||||||
|
}
|
||||||
|
int sort = type.getSort();
|
||||||
|
if (sort == Type.VOID) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (sort == Type.LONG || sort == Type.DOUBLE) {
|
||||||
|
return WIDE;
|
||||||
|
}
|
||||||
|
if (sort == Type.ARRAY || sort == Type.OBJECT) {
|
||||||
|
return REFERENCE;
|
||||||
|
}
|
||||||
|
return PRIMITIVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getSize() {
|
||||||
|
return this.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StackValueType merge(StackValueType other) {
|
||||||
|
if (other == null || this == other) {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
if (this.size == 2 || other.size == 2) {
|
||||||
|
return WIDE;
|
||||||
|
}
|
||||||
|
if ((this == NON_NULL || this == NULL || this == REFERENCE)
|
||||||
|
&& (other == NON_NULL || other == NULL || other == REFERENCE)) {
|
||||||
|
return REFERENCE;
|
||||||
|
}
|
||||||
|
return PRIMITIVE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package dev.jnic.util;
|
||||||
|
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public final class Log {
|
||||||
|
private static final DateTimeFormatter TIME =
|
||||||
|
DateTimeFormatter.ofPattern("HH-mm-ss.SSS", Locale.ROOT);
|
||||||
|
private static boolean debug;
|
||||||
|
|
||||||
|
private Log() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setDebug(boolean value) {
|
||||||
|
debug = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isDebugEnabled() {
|
||||||
|
return debug;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void info(String message) {
|
||||||
|
write("INFO", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void debug(String message) {
|
||||||
|
if (debug) write("DEBUG", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void warn(String message) {
|
||||||
|
write("WARN", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void write(String level, String message) {
|
||||||
|
System.out.println(LocalTime.now().format(TIME) + " " + level + ": " + message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dev.jnic.util;
|
||||||
|
|
||||||
|
public enum LogLevel {
|
||||||
|
INSTANCE;
|
||||||
|
|
||||||
|
public static final int LEVEL_NONE = 6;
|
||||||
|
public static final int LEVEL_ERROR = 5;
|
||||||
|
public static final int LEVEL_WARN = 4;
|
||||||
|
public static final int LEVEL_INFO = 3;
|
||||||
|
public static final int LEVEL_DEBUG = 2;
|
||||||
|
public static final int LEVEL_TRACE = 1;
|
||||||
|
public static boolean ERROR;
|
||||||
|
public static boolean WARN;
|
||||||
|
public static boolean INFO;
|
||||||
|
public static boolean DEBUG;
|
||||||
|
public static boolean TRACE;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package dev.jnic.util;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public enum Platform {
|
||||||
|
WINDOWS_X86_64("windows", "x86_64", "amd64", "x86_64"),
|
||||||
|
WINDOWS_AARCH64("windows", "aarch64", "aarch64", "arm64"),
|
||||||
|
MACOS_X86_64("macos", "x86_64", "amd64", "x86_64"),
|
||||||
|
MACOS_AARCH64("macos", "aarch64", "aarch64", "arm64"),
|
||||||
|
LINUX_X86_64("linux", "x86_64", "amd64", "x86_64"),
|
||||||
|
LINUX_AARCH64("linux", "aarch64", "aarch64", "arm64");
|
||||||
|
|
||||||
|
private final String os;
|
||||||
|
private final String arch;
|
||||||
|
private final Set<String> aliases;
|
||||||
|
|
||||||
|
Platform(String os, String arch, String... aliases) {
|
||||||
|
this.os = os;
|
||||||
|
this.arch = arch;
|
||||||
|
this.aliases = new HashSet<>(Arrays.asList(aliases));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String targetName() {
|
||||||
|
return this.os + "-" + this.arch;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> getAliases() {
|
||||||
|
return this.aliases;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOs() {
|
||||||
|
return this.os;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getArch() {
|
||||||
|
return this.arch;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package dev.jnic.util;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
public class StringPair {
|
||||||
|
private final String first;
|
||||||
|
private final String second;
|
||||||
|
|
||||||
|
public StringPair(String first, String second) {
|
||||||
|
this.first = first;
|
||||||
|
this.second = second;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFirst() {
|
||||||
|
return this.first;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSecond() {
|
||||||
|
return this.second;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object other) {
|
||||||
|
if (this == other) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!(other instanceof StringPair)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
StringPair that = (StringPair) other;
|
||||||
|
return Objects.equals(this.first, that.first)
|
||||||
|
&& Objects.equals(this.second, that.second);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(this.first, this.second);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package dev.jnic.util;
|
||||||
|
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class StringPairSet {
|
||||||
|
private final Set<StringPair> pairs = new HashSet<>();
|
||||||
|
|
||||||
|
public void add(StringPair pair) {
|
||||||
|
this.pairs.add(pair);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean contains(StringPair pair) {
|
||||||
|
return this.pairs.contains(pair);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int size() {
|
||||||
|
return this.pairs.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user