commit 09aab327eacbdacb3f732323343caaf6b5d0c829
Author: nitrogenoliquido <203537016+nitrogenoliquido@users.noreply.github.com>
Date: Fri Nov 27 10:00:18 2026 -0500
added files.
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..bede429
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,14 @@
+.gradle/
+.kotlin/
+build/
+out/
+.idea/
+*.iml
+.classpath
+.project
+.settings/
+*.log
+*.BACKUP
+*.obf.jar
+out.jar
+*-out.jar
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..bf0b4cd
--- /dev/null
+++ b/README.md
@@ -0,0 +1,58 @@
+
+
+
+
+
+
+
+
+
+
+
+
+ https://discord.gg/skidsolutions
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ This is not a reconstruction nor a remake.
+
+
+
+
+
+
+## How to build
+
+### Prerequisites
+- **Java Development Kit**: JDK 17 (the Gradle wrapper 8.14.3 does not run on newer JDKs)
+
+### Building OpenParamorphism
+
+Run from this folder:
+
+```powershell
+$env:JAVA_HOME = "C:\Program Files\Java\jdk-17"
+
+.\gradlew.bat clean build
+```
+
+Generated `build/libs/`:
+- `OpenParamorphism-1.3-beta-hotfix.jar`
+- `OpenParamorphism-1.3-beta-hotfix-sources.jar`
+
+### Running
+
+```powershell
+java -jar build\libs\OpenParamorphism-1.3-beta-hotfix.jar
+```
diff --git a/assets/deobf.jpg b/assets/deobf.jpg
new file mode 100644
index 0000000..fa8dbde
Binary files /dev/null and b/assets/deobf.jpg differ
diff --git a/assets/deobf2.png b/assets/deobf2.png
new file mode 100644
index 0000000..1d4014d
Binary files /dev/null and b/assets/deobf2.png differ
diff --git a/assets/divider.svg b/assets/divider.svg
new file mode 100644
index 0000000..f473231
--- /dev/null
+++ b/assets/divider.svg
@@ -0,0 +1,26 @@
+
diff --git a/assets/hack.jpg b/assets/hack.jpg
new file mode 100644
index 0000000..c4252ef
Binary files /dev/null and b/assets/hack.jpg differ
diff --git a/assets/jak.jpg b/assets/jak.jpg
new file mode 100644
index 0000000..162bfe5
Binary files /dev/null and b/assets/jak.jpg differ
diff --git a/assets/ss.png b/assets/ss.png
new file mode 100644
index 0000000..041b33a
Binary files /dev/null and b/assets/ss.png differ
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..0153844
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,101 @@
+plugins {
+ id 'org.jetbrains.kotlin.jvm' version '2.4.21'
+ id 'java'
+ id 'application'
+ id 'idea'
+ id 'eclipse'
+}
+
+group = 'site.hackery.paramorphism'
+version = '1.3-beta-hotfix'
+
+def javaVersion = 17
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation 'org.jetbrains.kotlin:kotlin-stdlib'
+ implementation 'org.ow2.asm:asm:9.8'
+ implementation 'org.ow2.asm:asm-tree:9.8'
+ implementation 'org.ow2.asm:asm-commons:9.8'
+ implementation 'org.ow2.asm:asm-analysis:9.8'
+ implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2'
+ implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2'
+ implementation 'org.apache.maven:maven-aether-provider:3.3.9'
+ implementation 'org.eclipse.aether:aether-connector-basic:1.0.2.v20150114'
+ implementation 'org.eclipse.aether:aether-transport-file:1.0.2.v20150114'
+
+ testImplementation 'org.junit.jupiter:junit-jupiter:5.11.4'
+ testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
+}
+
+java {
+ toolchain {
+ languageVersion = JavaLanguageVersion.of(javaVersion)
+ }
+ withSourcesJar()
+}
+
+kotlin {
+ jvmToolchain(javaVersion)
+}
+
+application {
+ applicationName = 'OpenParamorphism'
+ mainClass = 'site.hackery.paramorphism.ParamorphismMain'
+}
+
+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('test', Test) {
+ useJUnitPlatform()
+}
+
+tasks.named('jar', Jar) {
+ duplicatesStrategy = DuplicatesStrategy.EXCLUDE
+ manifest {
+ attributes(
+ 'Main-Class': 'site.hackery.paramorphism.ParamorphismMain',
+ 'Implementation-Title': 'OpenParamorphism',
+ 'Implementation-Version': project.version)
+ }
+ exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA'
+ from {
+ configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
+ }
+}
+
+tasks.named('sourcesJar', Jar) {
+ duplicatesStrategy = DuplicatesStrategy.EXCLUDE
+}
+
+idea {
+ module {
+ downloadSources = true
+ downloadJavadoc = true
+ }
+}
+
+eclipse {
+ classpath {
+ downloadSources = true
+ downloadJavadoc = true
+ }
+}
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..e05d1fe
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,5 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+org.gradle.parallel=true
+org.gradle.caching=true
+kotlin.code.style=official
+kotlin.suppressGradlePluginWarnings=DeprecatedGradleVersionWarning
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..1b33c55
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..9251069
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -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
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..23d15a9
--- /dev/null
+++ b/gradlew
@@ -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" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..db3a6ac
--- /dev/null
+++ b/gradlew.bat
@@ -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
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..d8ce4de
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1,7 @@
+pluginManagement {
+ repositories {
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+rootProject.name = 'OpenParamorphism'
diff --git a/src/main/java/site/hackery/paramorphism/runtime/PackedFileClassLoader.java b/src/main/java/site/hackery/paramorphism/runtime/PackedFileClassLoader.java
new file mode 100644
index 0000000..85fd386
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/runtime/PackedFileClassLoader.java
@@ -0,0 +1,42 @@
+package site.hackery.paramorphism.runtime;
+
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.io.InputStream;
+import java.util.zip.GZIPInputStream;
+
+public class PackedFileClassLoader extends ClassLoader {
+ private static final long GZIP_HEADER_MAGIC = 0x1F8B080000000000L;
+ private byte[] packedBytes;
+
+ public PackedFileClassLoader(ClassLoader parent, String resourceName, int unpackedSize) {
+ super(parent);
+ try {
+ InputStream stream = parent.getResourceAsStream(resourceName);
+ DataInputStream dataInputStream = new DataInputStream(stream);
+ this.packedBytes = new byte[unpackedSize];
+ dataInputStream.readFully(this.packedBytes, 0, stream.available());
+
+ for (int i = 7; i >= 0; i--) {
+ this.packedBytes[7 - i] = (byte) ((GZIP_HEADER_MAGIC >> (8 * i)) & 0xFFL);
+ }
+
+ stream.close();
+ GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(this.packedBytes.clone()));
+ dataInputStream = new DataInputStream(gzipInputStream);
+ dataInputStream.readFully(this.packedBytes);
+ gzipInputStream.close();
+ } catch (Exception ignored) {
+ while (true) {
+ }
+ }
+ }
+
+ public Class> createClass(String name) throws ClassNotFoundException {
+ try {
+ return super.defineClass(name, this.packedBytes, 0, this.packedBytes.length);
+ } catch (Exception ignored) {
+ return super.findClass(name);
+ }
+ }
+}
diff --git a/src/main/java/site/hackery/paramorphism/strategy/controlflow/graph/IntPair.java b/src/main/java/site/hackery/paramorphism/strategy/controlflow/graph/IntPair.java
new file mode 100644
index 0000000..e410026
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/strategy/controlflow/graph/IntPair.java
@@ -0,0 +1,19 @@
+package site.hackery.paramorphism.strategy.controlflow.graph;
+
+public final class IntPair {
+ private final int first;
+ private final int second;
+
+ public IntPair(int first, int second) {
+ this.first = first;
+ this.second = second;
+ }
+
+ public int getFirst() {
+ return this.first;
+ }
+
+ public int getSecond() {
+ return this.second;
+ }
+}
diff --git a/src/main/java/site/hackery/paramorphism/strategy/renaming/tree/MappingElementKind.java b/src/main/java/site/hackery/paramorphism/strategy/renaming/tree/MappingElementKind.java
new file mode 100644
index 0000000..2f1dd66
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/strategy/renaming/tree/MappingElementKind.java
@@ -0,0 +1,8 @@
+package site.hackery.paramorphism.strategy.renaming.tree;
+
+public enum MappingElementKind {
+ PACKAGE,
+ CLASS,
+ FIELD,
+ METHOD
+}
diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipCoder.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipCoder.java
new file mode 100644
index 0000000..f907a5d
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipCoder.java
@@ -0,0 +1,59 @@
+package site.hackery.paramorphism.util.zip;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+public class ZipCoder {
+ private final Charset charset;
+ private final boolean utf8;
+ private CharsetEncoder encoder;
+
+ private ZipCoder(Charset charset) {
+ this.charset = charset;
+ this.utf8 = charset.name().equals(StandardCharsets.UTF_8.name());
+ }
+
+ static ZipCoder forCharset(Charset charset) {
+ return new ZipCoder(charset);
+ }
+
+ byte[] encode(String text) {
+ CharsetEncoder charsetEncoder = getEncoder().reset();
+ char[] chars = text.toCharArray();
+ int maxBytes = (int) ((float) chars.length * charsetEncoder.maxBytesPerChar());
+ byte[] output = new byte[maxBytes];
+ if (maxBytes == 0) {
+ return output;
+ }
+ ByteBuffer byteBuffer = ByteBuffer.wrap(output);
+ CharBuffer charBuffer = CharBuffer.wrap(chars);
+ CoderResult result = charsetEncoder.encode(charBuffer, byteBuffer, true);
+ if (!result.isUnderflow()) {
+ throw new IllegalArgumentException(result.toString());
+ }
+ result = charsetEncoder.flush(byteBuffer);
+ if (!result.isUnderflow()) {
+ throw new IllegalArgumentException(result.toString());
+ }
+ return byteBuffer.position() == output.length ? output : Arrays.copyOf(output, byteBuffer.position());
+ }
+
+ boolean isUtf8() {
+ return this.utf8;
+ }
+
+ private CharsetEncoder getEncoder() {
+ if (this.encoder == null) {
+ this.encoder = this.charset.newEncoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT);
+ }
+ return this.encoder;
+ }
+}
diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants.java
new file mode 100644
index 0000000..d162907
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants.java
@@ -0,0 +1,8 @@
+package site.hackery.paramorphism.util.zip;
+
+public interface ZipConstants {
+ long LOCAL_HEADER_SIGNATURE = 0x04034B50L;
+ long DATA_DESCRIPTOR_SIGNATURE = 0x08074B50L;
+ long CENTRAL_DIRECTORY_SIGNATURE = 0x02014B50L;
+ long END_RECORD_SIGNATURE = 0x06054B50L;
+}
diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants64.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants64.java
new file mode 100644
index 0000000..42a4c2a
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants64.java
@@ -0,0 +1,17 @@
+package site.hackery.paramorphism.util.zip;
+
+public interface ZipConstants64 {
+ long ZIP64_END_SIGNATURE = 0x06064B50L;
+ long ZIP64_LOCATOR_SIGNATURE = 0x07064B50L;
+ int ZIP64_END_HEADER_SIZE = 56;
+ int ZIP64_EXTRA_ID = 1;
+ int ZIP64_ENTRY_COUNT_SENTINEL = 0xFFFF;
+ long ZIP64_SIZE_SENTINEL = 0xFFFFFFFFL;
+ int UTF8_FLAG = 2048;
+ int ZIP64_TAG = 1;
+ int NTFS_EXTRA_ID = 10;
+ int EXTENDED_TIMESTAMP_EXTRA_ID = 21589;
+ int MODIFIED_TIME_FLAG = 1;
+ int ACCESS_TIME_FLAG = 2;
+ int CREATION_TIME_FLAG = 4;
+}
diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipEntry.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipEntry.java
new file mode 100644
index 0000000..c1cd1bd
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipEntry.java
@@ -0,0 +1,241 @@
+package site.hackery.paramorphism.util.zip;
+
+import java.nio.file.attribute.FileTime;
+import java.util.Objects;
+import java.util.concurrent.TimeUnit;
+
+public class ZipEntry implements ZipConstants, Cloneable {
+ public static final int STORED = 0;
+ public static final int DEFLATED = 8;
+ static final long DOS_TIME_BEFORE_1980 = (1L << 21) | (1L << 16);
+ private static final long UPPER_DOS_TIME_BOUND = 4036608000000L;
+
+ String name;
+ long extendedDosTime = -1L;
+ FileTime modifiedTime;
+ FileTime accessTime;
+ FileTime creationTime;
+ long crc = -1L;
+ long size = -1L;
+ long compressedSize = -1L;
+ int method = -1;
+ int flags = 0;
+ byte[] extra;
+ String comment;
+
+ public ZipEntry(String name) {
+ Objects.requireNonNull(name, "name");
+ if (name.length() > 0xFFFF) {
+ throw new IllegalArgumentException("entry name too long");
+ }
+ this.name = name;
+ }
+
+ public ZipEntry(ZipEntry entry) {
+ Objects.requireNonNull(entry, "entry");
+ this.name = entry.name;
+ this.extendedDosTime = entry.extendedDosTime;
+ this.modifiedTime = entry.modifiedTime;
+ this.accessTime = entry.accessTime;
+ this.creationTime = entry.creationTime;
+ this.crc = entry.crc;
+ this.size = entry.size;
+ this.compressedSize = entry.compressedSize;
+ this.method = entry.method;
+ this.flags = entry.flags;
+ this.extra = entry.extra;
+ this.comment = entry.comment;
+ }
+
+ ZipEntry() {
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setTime(long time) {
+ this.extendedDosTime = ZipUtils.javaToExtendedDosTime(time);
+ if (this.extendedDosTime != DOS_TIME_BEFORE_1980 && time <= UPPER_DOS_TIME_BOUND) {
+ this.modifiedTime = null;
+ } else {
+ this.modifiedTime = FileTime.from(time, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ public long getTime() {
+ if (this.modifiedTime != null) {
+ return this.modifiedTime.toMillis();
+ }
+ return this.extendedDosTime != -1L ? ZipUtils.extendedDosToJavaTime(this.extendedDosTime) : -1L;
+ }
+
+ public ZipEntry setLastModifiedTime(FileTime fileTime) {
+ this.modifiedTime = Objects.requireNonNull(fileTime, "lastModifiedTime");
+ this.extendedDosTime = ZipUtils.javaToExtendedDosTime(fileTime.to(TimeUnit.MILLISECONDS));
+ return this;
+ }
+
+ public FileTime getLastModifiedTime() {
+ if (this.modifiedTime != null) {
+ return this.modifiedTime;
+ }
+ return this.extendedDosTime == -1L ? null : FileTime.from(this.getTime(), TimeUnit.MILLISECONDS);
+ }
+
+ public ZipEntry setLastAccessTime(FileTime fileTime) {
+ this.accessTime = Objects.requireNonNull(fileTime, "lastAccessTime");
+ return this;
+ }
+
+ public FileTime getLastAccessTime() {
+ return this.accessTime;
+ }
+
+ public ZipEntry setCreationTime(FileTime fileTime) {
+ this.creationTime = Objects.requireNonNull(fileTime, "creationTime");
+ return this;
+ }
+
+ public FileTime getCreationTime() {
+ return this.creationTime;
+ }
+
+ public void setSize(long size) {
+ if (size < 0L) {
+ throw new IllegalArgumentException("invalid entry size");
+ }
+ this.size = size;
+ }
+
+ public long getSize() {
+ return this.size;
+ }
+
+ public long getCompressedSize() {
+ return this.compressedSize;
+ }
+
+ public void setCompressedSize(long compressedSize) {
+ this.compressedSize = compressedSize;
+ }
+
+ public void setCrc(long crc) {
+ if (crc < 0L || crc > 0xFFFFFFFFL) {
+ throw new IllegalArgumentException("invalid entry crc-32");
+ }
+ this.crc = crc;
+ }
+
+ public long getCrc() {
+ return this.crc;
+ }
+
+ public void setMethod(int method) {
+ if (method != STORED && method != DEFLATED) {
+ throw new IllegalArgumentException("invalid compression method");
+ }
+ this.method = method;
+ }
+
+ public int getMethod() {
+ return this.method;
+ }
+
+ public void setExtra(byte[] extra) {
+ this.setExtraFields(extra, false);
+ }
+
+ void setExtraFields(byte[] extra, boolean applyZip64Sizes) {
+ if (extra != null) {
+ if (extra.length > 0xFFFF) {
+ throw new IllegalArgumentException("invalid extra field length");
+ }
+ int offset = 0;
+ int length = extra.length;
+ while (offset + 4 < length) {
+ int tag = ZipUtils.readUnsignedShort(extra, offset);
+ int fieldSize = ZipUtils.readUnsignedShort(extra, offset + 2);
+ offset += 4;
+ if (offset + fieldSize > length) {
+ break;
+ }
+ switch (tag) {
+ case ZipConstants64.ZIP64_EXTRA_ID:
+ if (applyZip64Sizes && fieldSize >= 16) {
+ this.size = ZipUtils.readLong(extra, offset);
+ this.compressedSize = ZipUtils.readLong(extra, offset + 8);
+ }
+ break;
+ case ZipConstants64.NTFS_EXTRA_ID:
+ if (fieldSize >= 32) {
+ int ntfsOffset = offset + 4;
+ if (ZipUtils.readUnsignedShort(extra, ntfsOffset) == ZipConstants64.ZIP64_TAG
+ && ZipUtils.readUnsignedShort(extra, ntfsOffset + 2) == 24) {
+ this.modifiedTime = ZipUtils.windowsTimeToFileTime(ZipUtils.readLong(extra, ntfsOffset + 4));
+ this.accessTime = ZipUtils.windowsTimeToFileTime(ZipUtils.readLong(extra, ntfsOffset + 12));
+ this.creationTime = ZipUtils.windowsTimeToFileTime(ZipUtils.readLong(extra, ntfsOffset + 20));
+ }
+ }
+ break;
+ case ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID:
+ int flags = Byte.toUnsignedInt(extra[offset]);
+ int pos = 1;
+ if ((flags & ZipConstants64.MODIFIED_TIME_FLAG) != 0 && 5 <= fieldSize) {
+ this.modifiedTime = ZipUtils.unixTimeToFileTime(ZipUtils.readUnsignedInt(extra, offset + 1));
+ pos += 4;
+ }
+ if ((flags & ZipConstants64.ACCESS_TIME_FLAG) != 0 && pos + 4 <= fieldSize) {
+ this.accessTime = ZipUtils.unixTimeToFileTime(ZipUtils.readUnsignedInt(extra, offset + pos));
+ pos += 4;
+ }
+ if ((flags & ZipConstants64.CREATION_TIME_FLAG) != 0 && pos + 4 <= fieldSize) {
+ this.creationTime = ZipUtils.unixTimeToFileTime(ZipUtils.readUnsignedInt(extra, offset + pos));
+ }
+ break;
+ default:
+ break;
+ }
+ offset += fieldSize;
+ }
+ }
+ this.extra = extra;
+ }
+
+ public byte[] getExtra() {
+ return this.extra;
+ }
+
+ public void setComment(String comment) {
+ this.comment = comment;
+ }
+
+ public String getComment() {
+ return this.comment;
+ }
+
+ public boolean isDirectory() {
+ return this.name.endsWith("/");
+ }
+
+ @Override
+ public String toString() {
+ return this.getName();
+ }
+
+ @Override
+ public int hashCode() {
+ return this.name.hashCode();
+ }
+
+ @Override
+ public Object clone() {
+ try {
+ ZipEntry copy = (ZipEntry) super.clone();
+ copy.extra = this.extra == null ? null : this.extra.clone();
+ return copy;
+ } catch (CloneNotSupportedException ex) {
+ throw new InternalError(ex);
+ }
+ }
+}
diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipOutputStream.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipOutputStream.java
new file mode 100644
index 0000000..f9607f9
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipOutputStream.java
@@ -0,0 +1,615 @@
+package site.hackery.paramorphism.util.zip;
+
+import org.jetbrains.annotations.Nullable;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.HashSet;
+import java.util.Vector;
+import java.util.zip.CRC32;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.ZipException;
+
+public class ZipOutputStream extends DeflaterOutputStream implements ZipConstants {
+ public static final int STORED = 0;
+ public static final int DEFLATED = 8;
+
+ private static final boolean inhibitZip64 =
+ Boolean.parseBoolean(System.getProperty("jdk.util.zip.inhibitZip64", "false"));
+
+ private EntryRecord currentEntry;
+ private final Vector entries = new Vector<>();
+ private final HashSet entryNames = new HashSet<>();
+ private final CRC32 crc = new CRC32();
+ private long writtenBytes = 0L;
+ private long entryDataOffset = 0L;
+ private byte[] comment;
+ private int defaultMethod = DEFLATED;
+ private boolean finished;
+ private boolean closed = false;
+ private final ZipCoder coder;
+ private ZipDataDescriptorTransformers dataDescriptorTransformers;
+
+ public ZipOutputStream(OutputStream outputStream) {
+ this(outputStream, StandardCharsets.UTF_8);
+ }
+
+ public ZipOutputStream(OutputStream outputStream, Charset charset) {
+ super(outputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true));
+ if (charset == null) {
+ throw new NullPointerException("charset is null");
+ }
+ this.coder = ZipCoder.forCharset(charset);
+ }
+
+ private static int versionNeeded(ZipEntry entry) throws ZipException {
+ switch (entry.method) {
+ case STORED:
+ return 10;
+ case DEFLATED:
+ return 20;
+ default:
+ throw new ZipException("unsupported compression method");
+ }
+ }
+
+ private void ensureOpen() throws IOException {
+ if (this.closed) {
+ throw new IOException("Stream closed");
+ }
+ }
+
+ public void setComment(String comment) {
+ if (comment != null) {
+ this.comment = this.coder.encode(comment);
+ if (this.comment.length > 0xFFFF) {
+ throw new IllegalArgumentException("ZIP file comment too long.");
+ }
+ }
+ }
+
+ public void setMethod(int defaultMethod) {
+ if (defaultMethod != DEFLATED && defaultMethod != STORED) {
+ throw new IllegalArgumentException("invalid compression method");
+ }
+ this.defaultMethod = defaultMethod;
+ }
+
+ public void setLevel(int level) {
+ this.def.setLevel(level);
+ }
+
+ public void putNextEntry(ZipEntry entry) throws IOException {
+ this.ensureOpen();
+ if (this.currentEntry != null) {
+ this.closeEntry();
+ }
+ if (entry.extendedDosTime == -1L) {
+ entry.setTime(System.currentTimeMillis());
+ }
+ if (entry.method == -1) {
+ entry.method = this.defaultMethod;
+ }
+ entry.flags = 0;
+ switch (entry.method) {
+ case STORED:
+ if (entry.size == -1L) {
+ entry.size = entry.compressedSize;
+ } else if (entry.compressedSize == -1L) {
+ entry.compressedSize = entry.size;
+ } else if (entry.size != entry.compressedSize) {
+ throw new ZipException("STORED entry where compressed != uncompressed size");
+ }
+ if (entry.size == -1L || entry.crc == -1L) {
+ throw new ZipException("STORED entry missing size, compressed size, or crc-32");
+ }
+ break;
+ case DEFLATED:
+ if (entry.size == -1L || entry.compressedSize == -1L || entry.crc == -1L) {
+ entry.flags = 8;
+ }
+ break;
+ default:
+ throw new ZipException("unsupported compression method");
+ }
+ if (!this.entryNames.add(entry.name)) {
+ throw new ZipException("duplicate entry: " + entry.name);
+ }
+ if (this.coder.isUtf8()) {
+ entry.flags |= ZipConstants64.UTF8_FLAG;
+ }
+ this.currentEntry = new EntryRecord(entry, this.writtenBytes);
+ this.entries.add(this.currentEntry);
+ this.writeLocalHeader(this.currentEntry);
+ }
+
+ public void closeEntry() throws IOException {
+ this.ensureOpen();
+ if (this.currentEntry == null) {
+ return;
+ }
+ ZipEntry entry = this.currentEntry.entry;
+ switch (entry.method) {
+ case STORED:
+ if (entry.size != this.writtenBytes - this.entryDataOffset) {
+ throw new ZipException("invalid entry size (expected " + entry.size + " but got "
+ + (this.writtenBytes - this.entryDataOffset) + " bytes)");
+ }
+ if (entry.crc != this.crc.getValue()) {
+ throw new ZipException("invalid entry crc-32 (expected 0x" + Long.toHexString(entry.crc)
+ + " but got 0x" + Long.toHexString(this.crc.getValue()) + ")");
+ }
+ break;
+ case DEFLATED:
+ this.def.finish();
+ while (!this.def.finished()) {
+ this.deflate();
+ }
+ if ((entry.flags & 8) == 0) {
+ if (entry.size != this.def.getBytesRead()) {
+ throw new ZipException("invalid entry size (expected " + entry.size
+ + " but got " + this.def.getBytesRead() + " bytes)");
+ }
+ if (entry.compressedSize != this.def.getBytesWritten()) {
+ throw new ZipException("invalid entry compressed size (expected " + entry.compressedSize
+ + " but got " + this.def.getBytesWritten() + " bytes)");
+ }
+ if (entry.crc != this.crc.getValue()) {
+ throw new ZipException("invalid entry CRC-32 (expected 0x" + Long.toHexString(entry.crc)
+ + " but got 0x" + Long.toHexString(this.crc.getValue()) + ")");
+ }
+ } else {
+ entry.size = this.def.getBytesRead();
+ entry.compressedSize = this.def.getBytesWritten();
+ entry.crc = this.crc.getValue();
+ this.writeDataDescriptor(entry);
+ }
+ this.def.reset();
+ this.writtenBytes += entry.compressedSize;
+ break;
+ default:
+ throw new ZipException("invalid compression method");
+ }
+ this.crc.reset();
+ this.currentEntry = null;
+ }
+
+ @Override
+ public synchronized void write(byte[] bytes, int off, int len) throws IOException {
+ this.ensureOpen();
+ if (off < 0 || len < 0 || off > bytes.length - len) {
+ throw new IndexOutOfBoundsException();
+ }
+ if (len == 0) {
+ return;
+ }
+ if (this.currentEntry == null) {
+ throw new ZipException("no current ZIP entry");
+ }
+ ZipEntry entry = this.currentEntry.entry;
+ switch (entry.method) {
+ case STORED:
+ this.writtenBytes += len;
+ if (this.writtenBytes - this.entryDataOffset > entry.size) {
+ throw new ZipException("attempt to write past end of STORED entry");
+ }
+ this.out.write(bytes, off, len);
+ break;
+ case DEFLATED:
+ super.write(bytes, off, len);
+ break;
+ default:
+ throw new ZipException("invalid compression method");
+ }
+ this.crc.update(bytes, off, len);
+ }
+
+ @Override
+ public void finish() throws IOException {
+ this.ensureOpen();
+ if (this.finished) {
+ return;
+ }
+ if (this.currentEntry != null) {
+ this.closeEntry();
+ }
+ long centralDirectoryOffset = this.writtenBytes;
+ for (EntryRecord record : this.entries) {
+ this.writeCentralHeader(record);
+ }
+ this.writeEndRecord(centralDirectoryOffset, this.writtenBytes - centralDirectoryOffset);
+ this.finished = true;
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (!this.closed) {
+ try {
+ super.close();
+ } finally {
+ this.def.end();
+ this.closed = true;
+ }
+ }
+ }
+
+ private void writeLocalHeader(EntryRecord record) throws IOException {
+ ZipEntry entry = record.entry;
+ int flags = entry.flags;
+ boolean zip64 = false;
+ int extraLength = this.getExtraLength(entry.extra);
+
+ this.writeInt(LOCAL_HEADER_SIGNATURE);
+ if ((flags & 8) == 8) {
+ this.writeShort(versionNeeded(entry));
+ this.writeShort(flags);
+ this.writeShort(entry.method);
+ this.writeInt(entry.extendedDosTime);
+ this.writeInt(0L);
+ this.writeInt(0L);
+ this.writeInt(0L);
+ } else {
+ if (entry.compressedSize < ZipConstants64.ZIP64_SIZE_SENTINEL
+ && entry.size < ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ this.writeShort(versionNeeded(entry));
+ } else {
+ zip64 = true;
+ this.writeShort(45);
+ }
+ this.writeShort(flags);
+ this.writeShort(entry.method);
+ this.writeInt(entry.extendedDosTime);
+ this.writeInt(entry.crc);
+ if (zip64) {
+ this.writeInt(ZipConstants64.ZIP64_SIZE_SENTINEL);
+ this.writeInt(ZipConstants64.ZIP64_SIZE_SENTINEL);
+ extraLength += 20;
+ } else {
+ this.writeInt(entry.compressedSize);
+ this.writeInt(entry.size);
+ }
+ }
+
+ byte[] encodedName = this.coder.encode(entry.name);
+ this.writeShort(encodedName.length);
+
+ int timestampBytes = 0;
+ int timestampFlags = 0;
+ if (entry.modifiedTime != null) {
+ timestampBytes += 4;
+ timestampFlags |= ZipConstants64.MODIFIED_TIME_FLAG;
+ }
+ if (entry.accessTime != null) {
+ timestampBytes += 4;
+ timestampFlags |= ZipConstants64.ACCESS_TIME_FLAG;
+ }
+ if (entry.creationTime != null) {
+ timestampBytes += 4;
+ timestampFlags |= ZipConstants64.CREATION_TIME_FLAG;
+ }
+ if (timestampFlags != 0) {
+ extraLength += timestampBytes + 5;
+ }
+
+ this.writeShort(extraLength);
+ this.writeBytes(encodedName, 0, encodedName.length);
+
+ if (zip64) {
+ this.writeShort(ZipConstants64.ZIP64_EXTRA_ID);
+ this.writeShort(16);
+ this.writeLong(entry.size);
+ this.writeLong(entry.compressedSize);
+ }
+
+ if (timestampFlags != 0) {
+ this.writeShort(ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID);
+ this.writeShort(timestampBytes + 1);
+ this.writeByte(timestampFlags);
+ if (entry.modifiedTime != null) {
+ this.writeInt(ZipUtils.fileTimeToUnixTime(entry.modifiedTime));
+ }
+ if (entry.accessTime != null) {
+ this.writeInt(ZipUtils.fileTimeToUnixTime(entry.accessTime));
+ }
+ if (entry.creationTime != null) {
+ this.writeInt(ZipUtils.fileTimeToUnixTime(entry.creationTime));
+ }
+ }
+
+ this.writeExtra(entry.extra);
+ this.entryDataOffset = this.writtenBytes;
+ }
+
+ public void setDataDescriptorTransformers(@Nullable ZipDataDescriptorTransformers dataDescriptorTransformers) {
+ this.dataDescriptorTransformers = dataDescriptorTransformers;
+ }
+
+ public ZipDataDescriptorTransformers getDataDescriptorTransformers() {
+ return this.dataDescriptorTransformers;
+ }
+
+ private void writeDataDescriptor(ZipEntry entry) throws IOException {
+ if (this.dataDescriptorTransformers != null) {
+ if (this.dataDescriptorTransformers.getCrcTransformer() != null) {
+ entry.crc = this.dataDescriptorTransformers.getCrcTransformer().invoke(entry.crc);
+ }
+ if (this.dataDescriptorTransformers.getCompressedSizeTransformer() != null) {
+ entry.compressedSize = this.dataDescriptorTransformers.getCompressedSizeTransformer().invoke(entry.compressedSize);
+ }
+ if (this.dataDescriptorTransformers.getSizeTransformer() != null) {
+ entry.size = this.dataDescriptorTransformers.getSizeTransformer().invoke(entry.size);
+ }
+ }
+
+ this.writeInt(DATA_DESCRIPTOR_SIGNATURE);
+ this.writeInt(entry.crc);
+ if (entry.compressedSize < ZipConstants64.ZIP64_SIZE_SENTINEL
+ && entry.size < ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ this.writeInt(entry.compressedSize);
+ this.writeInt(entry.size);
+ } else {
+ this.writeLong(entry.compressedSize);
+ this.writeLong(entry.size);
+ }
+ }
+
+ private void writeCentralHeader(EntryRecord record) throws IOException {
+ ZipEntry entry = record.entry;
+ int flags = entry.flags;
+ int versionNeeded = versionNeeded(entry);
+ long compressedSize = entry.compressedSize;
+ long size = entry.size;
+ long offset = record.offset;
+ int zip64ExtraSize = 0;
+ boolean zip64 = false;
+
+ if (entry.compressedSize >= ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ compressedSize = ZipConstants64.ZIP64_SIZE_SENTINEL;
+ zip64ExtraSize += 8;
+ zip64 = true;
+ }
+ if (entry.size >= ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ size = ZipConstants64.ZIP64_SIZE_SENTINEL;
+ zip64ExtraSize += 8;
+ zip64 = true;
+ }
+ if (record.offset >= ZipConstants64.ZIP64_SIZE_SENTINEL || record.offset < 0L) {
+ offset = ZipConstants64.ZIP64_SIZE_SENTINEL;
+ zip64ExtraSize += 8;
+ zip64 = true;
+ }
+
+ this.writeInt(CENTRAL_DIRECTORY_SIGNATURE);
+ if (zip64) {
+ this.writeShort(45);
+ this.writeShort(45);
+ } else {
+ this.writeShort(versionNeeded);
+ this.writeShort(versionNeeded);
+ }
+
+ this.writeShort(flags);
+ this.writeShort(entry.method);
+ this.writeInt(entry.extendedDosTime);
+ this.writeInt(entry.crc);
+ this.writeInt(compressedSize);
+ this.writeInt(size);
+
+ byte[] encodedName = this.coder.encode(entry.name);
+ this.writeShort(encodedName.length);
+
+ int extraLength = this.getExtraLength(entry.extra);
+ if (zip64) {
+ extraLength += zip64ExtraSize + 4;
+ }
+
+ int timestampFlags = 0;
+ if (entry.modifiedTime != null) {
+ extraLength += 4;
+ timestampFlags = ZipConstants64.MODIFIED_TIME_FLAG;
+ }
+ if (entry.accessTime != null) {
+ timestampFlags |= ZipConstants64.ACCESS_TIME_FLAG;
+ }
+ if (entry.creationTime != null) {
+ timestampFlags |= ZipConstants64.CREATION_TIME_FLAG;
+ }
+ if (timestampFlags != 0) {
+ extraLength += 5;
+ }
+
+ this.writeShort(extraLength);
+ byte[] encodedComment;
+ if (entry.comment != null) {
+ encodedComment = this.coder.encode(entry.comment);
+ this.writeShort(Math.min(encodedComment.length, 0xFFFF));
+ } else {
+ encodedComment = null;
+ this.writeShort(0);
+ }
+
+ this.writeShort(0);
+ this.writeShort(0);
+ this.writeInt(0L);
+ this.writeInt(offset);
+ this.writeBytes(encodedName, 0, encodedName.length);
+
+ if (zip64) {
+ this.writeShort(ZipConstants64.ZIP64_EXTRA_ID);
+ this.writeShort(zip64ExtraSize);
+ if (size == ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ this.writeLong(entry.size);
+ }
+ if (compressedSize == ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ this.writeLong(entry.compressedSize);
+ }
+ if (offset == ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ this.writeLong(record.offset);
+ }
+ }
+
+ if (timestampFlags != 0) {
+ this.writeShort(ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID);
+ if (entry.modifiedTime != null) {
+ this.writeShort(5);
+ this.writeByte(timestampFlags);
+ this.writeInt(ZipUtils.fileTimeToUnixTime(entry.modifiedTime));
+ } else {
+ this.writeShort(1);
+ this.writeByte(timestampFlags);
+ }
+ }
+
+ this.writeExtra(entry.extra);
+ if (encodedComment != null) {
+ this.writeBytes(encodedComment, 0, Math.min(encodedComment.length, 0xFFFF));
+ }
+ }
+
+ private void writeEndRecord(long centralOffset, long centralSize) throws IOException {
+ boolean zip64 = false;
+ long recordedSize = centralSize;
+ long recordedOffset = centralOffset;
+ if (centralSize >= ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ recordedSize = ZipConstants64.ZIP64_SIZE_SENTINEL;
+ zip64 = true;
+ }
+ if (centralOffset >= ZipConstants64.ZIP64_SIZE_SENTINEL) {
+ recordedOffset = ZipConstants64.ZIP64_SIZE_SENTINEL;
+ zip64 = true;
+ }
+
+ int entryCount = this.entries.size();
+ if (entryCount >= ZipConstants64.ZIP64_ENTRY_COUNT_SENTINEL) {
+ zip64 |= !inhibitZip64;
+ if (zip64) {
+ entryCount = ZipConstants64.ZIP64_ENTRY_COUNT_SENTINEL;
+ }
+ }
+
+ if (zip64) {
+ long zip64EndOffset = this.writtenBytes;
+ this.writeInt(ZipConstants64.ZIP64_END_SIGNATURE);
+ this.writeLong(44L);
+ this.writeShort(45);
+ this.writeShort(45);
+ this.writeInt(0L);
+ this.writeInt(0L);
+ this.writeLong(this.entries.size());
+ this.writeLong(this.entries.size());
+ this.writeLong(centralSize);
+ this.writeLong(centralOffset);
+ this.writeInt(ZipConstants64.ZIP64_LOCATOR_SIGNATURE);
+ this.writeInt(0L);
+ this.writeLong(zip64EndOffset);
+ this.writeInt(1L);
+ }
+
+ this.writeInt(END_RECORD_SIGNATURE);
+ this.writeShort(0);
+ this.writeShort(0);
+ this.writeShort(entryCount);
+ this.writeShort(entryCount);
+ this.writeInt(recordedSize);
+ this.writeInt(recordedOffset);
+ if (this.comment != null) {
+ this.writeShort(this.comment.length);
+ this.writeBytes(this.comment, 0, this.comment.length);
+ } else {
+ this.writeShort(0);
+ }
+ }
+
+ private int getExtraLength(byte[] extra) {
+ if (extra == null) {
+ return 0;
+ }
+ int skipped = 0;
+ int totalLength = extra.length;
+ int offset = 0;
+ while (offset + 4 <= totalLength) {
+ int tag = ZipUtils.readUnsignedShort(extra, offset);
+ int fieldSize = ZipUtils.readUnsignedShort(extra, offset + 2);
+ if (fieldSize < 0 || offset + 4 + fieldSize > totalLength) {
+ break;
+ }
+ if (tag == ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID || tag == ZipConstants64.ZIP64_EXTRA_ID) {
+ skipped += fieldSize + 4;
+ }
+ offset += fieldSize + 4;
+ }
+ return totalLength - skipped;
+ }
+
+ private void writeExtra(byte[] extra) throws IOException {
+ if (extra == null) {
+ return;
+ }
+ int totalLength = extra.length;
+ int offset = 0;
+ while (offset + 4 <= totalLength) {
+ int tag = ZipUtils.readUnsignedShort(extra, offset);
+ int fieldSize = ZipUtils.readUnsignedShort(extra, offset + 2);
+ if (fieldSize < 0 || offset + 4 + fieldSize > totalLength) {
+ this.writeBytes(extra, offset, totalLength - offset);
+ return;
+ }
+ if (tag != ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID && tag != ZipConstants64.ZIP64_EXTRA_ID) {
+ this.writeBytes(extra, offset, fieldSize + 4);
+ }
+ offset += fieldSize + 4;
+ }
+ if (offset < totalLength) {
+ this.writeBytes(extra, offset, totalLength - offset);
+ }
+ }
+
+ private void writeByte(int value) throws IOException {
+ this.out.write(value & 0xFF);
+ this.writtenBytes++;
+ }
+
+ private void writeShort(int value) throws IOException {
+ this.out.write(value & 0xFF);
+ this.out.write((value >>> 8) & 0xFF);
+ this.writtenBytes += 2L;
+ }
+
+ private void writeInt(long value) throws IOException {
+ this.out.write((int) (value & 0xFFL));
+ this.out.write((int) ((value >>> 8) & 0xFFL));
+ this.out.write((int) ((value >>> 16) & 0xFFL));
+ this.out.write((int) ((value >>> 24) & 0xFFL));
+ this.writtenBytes += 4L;
+ }
+
+ private void writeLong(long value) throws IOException {
+ this.out.write((int) (value & 0xFFL));
+ this.out.write((int) ((value >>> 8) & 0xFFL));
+ this.out.write((int) ((value >>> 16) & 0xFFL));
+ this.out.write((int) ((value >>> 24) & 0xFFL));
+ this.out.write((int) ((value >>> 32) & 0xFFL));
+ this.out.write((int) ((value >>> 40) & 0xFFL));
+ this.out.write((int) ((value >>> 48) & 0xFFL));
+ this.out.write((int) ((value >>> 56) & 0xFFL));
+ this.writtenBytes += 8L;
+ }
+
+ private void writeBytes(byte[] bytes, int off, int len) throws IOException {
+ super.out.write(bytes, off, len);
+ this.writtenBytes += len;
+ }
+
+ private static class EntryRecord {
+ final ZipEntry entry;
+ final long offset;
+
+ EntryRecord(ZipEntry entry, long offset) {
+ this.entry = entry;
+ this.offset = offset;
+ }
+ }
+}
diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipUtils.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipUtils.java
new file mode 100644
index 0000000..4206802
--- /dev/null
+++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipUtils.java
@@ -0,0 +1,79 @@
+package site.hackery.paramorphism.util.zip;
+
+import java.nio.file.attribute.FileTime;
+import java.util.Date;
+import java.util.concurrent.TimeUnit;
+
+public class ZipUtils {
+ private static final long DOS_TIME_BEFORE_1980 = (1L << 21) | (1L << 16);
+ private static final long WINDOWS_EPOCH_MICROSECONDS = -11644473600000000L;
+
+ public static FileTime windowsTimeToFileTime(long windowsTime) {
+ return FileTime.from(windowsTime / 10L + WINDOWS_EPOCH_MICROSECONDS, TimeUnit.MICROSECONDS);
+ }
+
+ public static long fileTimeToWindowsTime(FileTime fileTime) {
+ return (fileTime.to(TimeUnit.MICROSECONDS) - WINDOWS_EPOCH_MICROSECONDS) * 10L;
+ }
+
+ public static FileTime unixTimeToFileTime(long unixSeconds) {
+ return FileTime.from(unixSeconds, TimeUnit.SECONDS);
+ }
+
+ public static long fileTimeToUnixTime(FileTime fileTime) {
+ return fileTime.to(TimeUnit.SECONDS);
+ }
+
+ @SuppressWarnings("deprecation")
+ private static long dosToJavaTime(long dosTime) {
+ Date date = new Date(
+ (int) (((dosTime >> 25) & 0x7FL) + 80L),
+ (int) (((dosTime >> 21) & 0x0FL) - 1L),
+ (int) ((dosTime >> 16) & 0x1FL),
+ (int) ((dosTime >> 11) & 0x1FL),
+ (int) ((dosTime >> 5) & 0x3FL),
+ (int) ((dosTime << 1) & 0x3EL)
+ );
+ return date.getTime();
+ }
+
+ public static long extendedDosToJavaTime(long extendedDosTime) {
+ long time = dosToJavaTime(extendedDosTime);
+ return time + (extendedDosTime >> 32);
+ }
+
+ @SuppressWarnings("deprecation")
+ private static long javaToDosTime(long time) {
+ Date date = new Date(time);
+ int year = date.getYear() + 1900;
+ if (year < 1980) {
+ return DOS_TIME_BEFORE_1980;
+ }
+ return (long) ((year - 1980) << 25
+ | (date.getMonth() + 1) << 21
+ | date.getDate() << 16
+ | date.getHours() << 11
+ | date.getMinutes() << 5
+ | (date.getSeconds() >> 1));
+ }
+
+ public static long javaToExtendedDosTime(long time) {
+ if (time < 0L) {
+ return DOS_TIME_BEFORE_1980;
+ }
+ long dosTime = javaToDosTime(time);
+ return dosTime != DOS_TIME_BEFORE_1980 ? dosTime + ((time % 2000L) << 32) : DOS_TIME_BEFORE_1980;
+ }
+
+ public static int readUnsignedShort(byte[] bytes, int offset) {
+ return Byte.toUnsignedInt(bytes[offset]) | (Byte.toUnsignedInt(bytes[offset + 1]) << 8);
+ }
+
+ public static long readUnsignedInt(byte[] bytes, int offset) {
+ return ((long) readUnsignedShort(bytes, offset) | ((long) readUnsignedShort(bytes, offset + 2) << 16)) & 0xFFFFFFFFL;
+ }
+
+ public static long readLong(byte[] bytes, int offset) {
+ return readUnsignedInt(bytes, offset) | (readUnsignedInt(bytes, offset + 4) << 32);
+ }
+}
diff --git a/src/main/kotlin/site/hackery/paramorphism/ConfigurationGenerator.kt b/src/main/kotlin/site/hackery/paramorphism/ConfigurationGenerator.kt
new file mode 100644
index 0000000..8c9e519
--- /dev/null
+++ b/src/main/kotlin/site/hackery/paramorphism/ConfigurationGenerator.kt
@@ -0,0 +1,39 @@
+package site.hackery.paramorphism
+
+import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
+import com.fasterxml.jackson.dataformat.yaml.YAMLMapper
+import site.hackery.paramorphism.config.ElementMask
+import site.hackery.paramorphism.resources.io.ZipResourceSet
+import site.hackery.paramorphism.resources.masking.MaskedClassSet
+import site.hackery.paramorphism.resources.views.ResourceBackedClassSet
+import site.hackery.paramorphism.util.logging.LogLevel
+import site.hackery.paramorphism.util.logging.Logger
+import java.io.File
+
+object ConfigurationGenerator {
+ fun generateConfiguration(jarFile: File, mask: ElementMask) {
+ val zipResources = ZipResourceSet(jarFile)
+ val classes = MaskedClassSet(mask, ResourceBackedClassSet(zipResources))
+ val yamlMapper = YAMLMapper(YAMLFactory())
+
+ val configMap = LinkedHashMap()
+ configMap["input"] = jarFile.path
+ val flags = LinkedHashMap()
+ configMap["flags"] = flags
+
+ for ((_, classNode) in classes.entries()) {
+ val hasKotlinMetadata = classNode.visibleAnnotations?.any { it.desc == "Lkotlin/Metadata;" } == true
+ if (hasKotlinMetadata && flags["kotlin"] != true) {
+ Logger.log(LogLevel.INFO, "Kotlin class detected: ${classNode.name}")
+ Logger.log(LogLevel.INFO, "Suggesting the 'kotlin' flag be set to true")
+ flags["kotlin"] = true
+ }
+ }
+
+ if (flags.isEmpty()) {
+ configMap.remove("flags")
+ }
+
+ println("Config:\n${yamlMapper.writeValueAsString(configMap)}")
+ }
+}
diff --git a/src/main/kotlin/site/hackery/paramorphism/ObfuscationPipeline.kt b/src/main/kotlin/site/hackery/paramorphism/ObfuscationPipeline.kt
new file mode 100644
index 0000000..4570440
--- /dev/null
+++ b/src/main/kotlin/site/hackery/paramorphism/ObfuscationPipeline.kt
@@ -0,0 +1,281 @@
+package site.hackery.paramorphism
+
+import org.objectweb.asm.ClassReader
+import org.objectweb.asm.ClassWriter
+import site.hackery.paramorphism.config.ElementMask
+import site.hackery.paramorphism.config.ParamorphismConfig
+import site.hackery.paramorphism.resources.ClassSet
+import site.hackery.paramorphism.resources.ClassSetGroup
+import site.hackery.paramorphism.resources.LazyResource
+import site.hackery.paramorphism.resources.ManifestResource
+import site.hackery.paramorphism.resources.ResourceSet
+import site.hackery.paramorphism.resources.TaggedResource
+import site.hackery.paramorphism.resources.io.ZipResourceSet
+import site.hackery.paramorphism.resources.masking.IncludedClassSet
+import site.hackery.paramorphism.resources.masking.MaskedClassSet
+import site.hackery.paramorphism.resources.overlay.OverlayClassSet
+import site.hackery.paramorphism.resources.overlay.OverlayResourceSet
+import site.hackery.paramorphism.resources.views.NonClassResourceSet
+import site.hackery.paramorphism.resources.views.ResourceBackedClassSet
+import site.hackery.paramorphism.strategy.StrategyPipeline
+import site.hackery.paramorphism.util.RandomContext
+import site.hackery.paramorphism.util.context.ContextStore
+import site.hackery.paramorphism.util.context.MutableObfuscationContext
+import site.hackery.paramorphism.util.context.ObfuscationContext
+import site.hackery.paramorphism.util.logging.LogLevel
+import site.hackery.paramorphism.util.logging.Logger
+import site.hackery.paramorphism.util.logging.PerformanceProfiler
+import site.hackery.paramorphism.util.manifest.ManifestAttributes
+import site.hackery.paramorphism.util.runtime.JavaRuntimeClassSet
+import site.hackery.paramorphism.util.zip.ZipDataDescriptorTransformers
+import site.hackery.paramorphism.util.zip.ZipEntry
+import site.hackery.paramorphism.util.zip.ZipOutputStream
+import java.io.ByteArrayInputStream
+import java.io.Closeable
+import java.io.File
+import java.io.FileFilter
+import java.io.FileOutputStream
+import java.math.BigInteger
+import java.security.MessageDigest
+import java.util.jar.Attributes
+import java.util.jar.Manifest
+
+object ObfuscationPipeline {
+ fun run(config: ParamorphismConfig) {
+ var inputArchive: ZipResourceSet? = null
+ var classSet: ClassSet? = null
+ var resourceSet: ResourceSet? = null
+ var libraries: ClassSetGroup? = null
+ try {
+ PerformanceProfiler.beginPhase("Initialize")
+ val store = ContextStore()
+ val context = ObfuscationContext(store)
+ val mutableContext = MutableObfuscationContext(store)
+ mutableContext.config = config
+
+ val (resolvedInput, outputFile) = resolveInputOutput(config)
+ inputArchive = ZipResourceSet(resolvedInput)
+ val randomContext = createRandomContext(config, inputArchive)
+ mutableContext.putService(RandomContext::class.java, randomContext)
+
+ val shadedMask = config.shadedLibraries.get()
+ classSet = createClassSet(inputArchive, shadedMask)
+ resourceSet = createResourceSet(inputArchive)
+ libraries = loadLibraries(inputArchive, config, shadedMask)
+ mutableContext.classes = classSet
+ mutableContext.resources = resourceSet
+ mutableContext.libraries = libraries
+ mutableContext.globalMask = config.mask.getOrDefault(ElementMask(emptyArray(), emptyArray()))
+ mutableContext.nameGenerator = config.nameGeneration.get()!!
+ context.nameGenerator.random = randomContext.getRandom()
+
+ val flags = config.flags.get()!!
+ mutableContext.putService(site.hackery.paramorphism.config.ConfigFlags::class.java, flags)
+
+ flags["anti_decompression"]?.let { context.nameGenerator.prefixClassNamesWithNul = it }
+
+ try {
+ val manifestResource = context.resources.get("META-INF/MANIFEST.MF")
+ if (manifestResource != null) {
+ mutableContext.manifest = Manifest(ByteArrayInputStream(manifestResource.getBytes()))
+ } else {
+ mutableContext.manifest = Manifest()
+ context.manifest.mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0"
+ }
+ } catch (_: Exception) {
+ Logger.log(LogLevel.WARNING, "Error parsing MANIFEST.MF - It will be overwritten")
+ mutableContext.manifest = Manifest()
+ context.manifest.mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0"
+ }
+
+ context.resources.put("META-INF/MANIFEST.MF", ManifestResource(context.manifest, -999))
+ if (config.branding.getOrDefault(true)) {
+ context.manifest.mainAttributes[ManifestAttributes.OBFUSCATED_BY] = "Paramorphism"
+ }
+
+ val pipeline = StrategyPipeline(context)
+ val initMillis = PerformanceProfiler.endPhase()
+
+ PerformanceProfiler.beginPhase("Obfuscate")
+ pipeline.run(context, mutableContext)
+ val obfuscateMillis = PerformanceProfiler.endPhase()
+
+ PerformanceProfiler.beginPhase("Write")
+ val classes = context.classes
+ val resources = context.resources
+
+ PerformanceProfiler.measurePhase("Assemble Classes") {
+ for ((_, classNode) in classes.entries()) {
+ resources.put(
+ "${classNode.name}.class",
+ TaggedResource(
+ "assembled_class",
+ LazyResource({
+ val writer = ClassWriter(ClassWriter.COMPUTE_MAXS)
+ classNode.accept(writer)
+ writer.toByteArray()
+ }, 0)
+ )
+ )
+ }
+ }
+
+ shadedMask?.let { mask ->
+ PerformanceProfiler.measurePhase("Shade Library Resources") {
+ inputArchive.names()
+ .filter { mask.matches(it) }
+ .map { it to inputArchive.get(it)!! }
+ .forEach { (name, resource) -> resources.put(name, resource) }
+ }
+ }
+
+ PerformanceProfiler.measurePhase("Write Resources") {
+ if (outputFile.exists()) {
+ outputFile.delete()
+ }
+
+ ZipOutputStream(FileOutputStream(outputFile)).use { zipOut ->
+ val corruptArchive = flags["corruption"] ?: false
+ if (corruptArchive) {
+ zipOut.dataDescriptorTransformers = ZipDataDescriptorTransformers(
+ crcTransformer = { -1L },
+ compressedSizeTransformer = null,
+ sizeTransformer = { -1L }
+ )
+ zipOut.putNextEntry(ZipEntry("//\u0000//.class"))
+ zipOut.write('i'.code)
+ zipOut.closeEntry()
+ zipOut.dataDescriptorTransformers = null
+ }
+
+ val writeRandom = randomContext.getRandom()
+ val groupedByPriority = resources.entries()
+ .filter { (name, _) -> !name.endsWith(".SF") && !name.endsWith(".RSA") }
+ .distinctBy { (name, _) -> name }
+ .groupBy { (_, resource) -> resource.writePriority }
+ .toSortedMap()
+
+ for (group in groupedByPriority.values) {
+ for ((name, resource) in group.shuffled(writeRandom)) {
+ val isClassEntry = name.endsWith(".class")
+ val corruptEntry = corruptArchive &&
+ isClassEntry &&
+ resource is TaggedResource &&
+ resource.tag == "assembled_class"
+ val entryName = if (corruptEntry) "$name/" else name
+
+ zipOut.putNextEntry(ZipEntry(entryName))
+ zipOut.write(resource.getBytes())
+ zipOut.closeEntry()
+
+ if (corruptEntry) {
+ zipOut.dataDescriptorTransformers = ZipDataDescriptorTransformers(
+ crcTransformer = { writeRandom.nextLong() },
+ compressedSizeTransformer = null,
+ sizeTransformer = { resource.getBytes().size.toLong() }
+ )
+ zipOut.putNextEntry(ZipEntry("$name/encrypted_data"))
+ zipOut.write('i'.code)
+ zipOut.closeEntry()
+ zipOut.dataDescriptorTransformers = null
+
+ zipOut.putNextEntry(ZipEntry("$name/name"))
+ zipOut.write(name.dropLast(".class".length).toByteArray(Charsets.UTF_8))
+ zipOut.closeEntry()
+ }
+ }
+ }
+ }
+ }
+ val writeMillis = PerformanceProfiler.endPhase()
+
+ val totalMillis = initMillis + obfuscateMillis + writeMillis
+ val formatMs: (Double) -> String = { "%.2fms".format(it) }
+ Logger.log(
+ "Finished in ${formatMs(totalMillis)} (init: ${formatMs(initMillis)}, obfuscate: ${formatMs(obfuscateMillis)}, write: ${formatMs(writeMillis)})"
+ )
+
+ try {
+ val relativeOut = outputFile.absoluteFile.toRelativeString(config.file.absoluteFile.parentFile)
+ Logger.log("Saved output to: $relativeOut")
+ } catch (_: Exception) {
+ Logger.log("Saved output to: ${outputFile.absolutePath}")
+ }
+ } catch (ex: Exception) {
+ Logger.log(LogLevel.ERROR, "An error occurred during obfuscation: ${ex.message ?: ex}")
+ Logger.writer.flush()
+ ex.printStackTrace()
+ } finally {
+ closeQuietly(libraries)
+ closeQuietly(classSet)
+ closeQuietly(resourceSet)
+ closeQuietly(inputArchive)
+ }
+ }
+
+ private fun closeQuietly(closeable: Closeable?) {
+ if (closeable != null) {
+ runCatching { closeable.close() }
+ }
+ }
+
+ private fun resolveInputOutput(config: ParamorphismConfig): Pair {
+ val input = config.input.get() ?: error("Input JAR file was not defined")
+ val output = config.output.get() ?: File("${input.absolutePath.substringBeforeLast('.')}.obf.jar")
+ if (!input.exists()) {
+ error("Input JAR file does not exist")
+ }
+ return input to output
+ }
+
+ private fun createRandomContext(config: ParamorphismConfig, resources: ResourceSet): RandomContext {
+ val digest = MessageDigest.getInstance("SHA-256")
+ for ((_, resource) in resources.entries()) {
+ digest.update(resource.getBytes())
+ }
+ val hashSeed = BigInteger(digest.digest()).toLong()
+ return RandomContext(hashSeed + config.randomOffset.getOrDefault(0).toLong())
+ }
+
+ private fun createClassSet(resources: ResourceSet, shadedLibraries: ElementMask?): ClassSet {
+ val classSet: ClassSet = ResourceBackedClassSet(resources)
+ val filtered: ClassSet = if (shadedLibraries != null) MaskedClassSet(shadedLibraries, classSet) else classSet
+ return OverlayClassSet(filtered)
+ }
+
+ private fun createResourceSet(resources: ResourceSet): ResourceSet =
+ OverlayResourceSet(NonClassResourceSet(resources))
+
+ private fun loadLibraries(
+ resources: ResourceSet,
+ config: ParamorphismConfig,
+ shadedLibraries: ElementMask?
+ ): ClassSetGroup {
+ val configuredFiles = config.libraries.getOrDefault(emptyArray()).flatMap { file ->
+ if (file.isDirectory) {
+ file.listFiles(FileFilter { it.extension.equals("jar", ignoreCase = true) })?.toList() ?: emptyList()
+ } else {
+ listOf(file)
+ }
+ }
+
+ val classSets = configuredFiles
+ .map { ResourceBackedClassSet(ZipResourceSet(it), ClassReader.SKIP_CODE) as ClassSet }
+ .toMutableList()
+
+ if (shadedLibraries != null) {
+ classSets.add(0, IncludedClassSet(shadedLibraries, ResourceBackedClassSet(resources, ClassReader.SKIP_CODE)))
+ }
+ if (config.addJavaRuntime.getOrDefault(true)) {
+ classSets.add(0, JavaRuntimeClassSet.locateRuntimeClasses())
+ }
+ classSets.addAll(loadMavenLibraries(config))
+
+ return ClassSetGroup(classSets.toTypedArray())
+ }
+
+ private fun loadMavenLibraries(config: ParamorphismConfig): List =
+ config.mavenLibraries.getOrDefault(emptyArray()).map { file ->
+ ResourceBackedClassSet(ZipResourceSet(file), ClassReader.SKIP_CODE)
+ }
+}
diff --git a/src/main/kotlin/site/hackery/paramorphism/ParamorphismMain.kt b/src/main/kotlin/site/hackery/paramorphism/ParamorphismMain.kt
new file mode 100644
index 0000000..a767231
--- /dev/null
+++ b/src/main/kotlin/site/hackery/paramorphism/ParamorphismMain.kt
@@ -0,0 +1,54 @@
+@file:JvmName("ParamorphismMain")
+
+package site.hackery.paramorphism
+
+import com.fasterxml.jackson.core.JsonParseException
+import site.hackery.paramorphism.config.ParamorphismConfig
+import site.hackery.paramorphism.update.UpdateCheckThread
+import site.hackery.paramorphism.util.logging.LogLevel
+import site.hackery.paramorphism.util.logging.Logger
+import java.io.File
+import java.io.InputStreamReader
+
+const val VERSION: String = "1.3-beta-hotfix"
+
+fun main(args: Array) {
+ val updateThread = UpdateCheckThread()
+ updateThread.start()
+ runCommandLine(args)
+ updateThread.join()
+
+ val updateInfo = updateThread.updateInformation ?: return
+ val latestVersion = updateInfo.last()
+ val currentIndex = updateInfo.indexOf(VERSION)
+ if (currentIndex != -1 && currentIndex < updateInfo.lastIndex) {
+ println()
+ Logger.log(LogLevel.WARNING, "Your current version is outdated!")
+ Logger.log(LogLevel.WARNING, "Your version: $VERSION, new version: $latestVersion")
+ Logger.log(LogLevel.WARNING, "Download the new version at: https://paramorphism.serenity.enterprises/")
+ if (System.getProperty("os.name").contains("Windows")) {
+ print("\nPress return to exit...")
+ InputStreamReader(System.`in`, Charsets.UTF_8).read()
+ }
+ }
+}
+
+private fun runCommandLine(args: Array) {
+ if (args.isEmpty()) {
+ println("Usage:")
+ println("\tparamorphism.jar [config]")
+ return
+ }
+ val configFile = File(args.joinToString(" "))
+ if (!configFile.exists()) {
+ println("Config file was not found: ${configFile.absolutePath}")
+ return
+ }
+ try {
+ val config = ParamorphismConfig(configFile)
+ ObfuscationPipeline.run(config)
+ } catch (ex: JsonParseException) {
+ System.err.println("There was an error parsing the configuration file:")
+ System.err.println(ex.message)
+ }
+}
diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigAccess.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigAccess.kt
new file mode 100644
index 0000000..3a918f8
--- /dev/null
+++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigAccess.kt
@@ -0,0 +1,12 @@
+@file:JvmName("ConfigAccess")
+
+package site.hackery.paramorphism.config
+
+inline fun ConfigDocument.getTyped(key: String): T? =
+ getValue(key, T::class.java)
+
+inline fun ConfigDocument.getOrDefault(key: String, defaultValue: T): T =
+ getValue(key, T::class.java) ?: defaultValue
+
+inline fun ConfigDocument.getArray(key: String): Array? =
+ getValue(key, Array::class.java)
diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigDecoder.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigDecoder.kt
new file mode 100644
index 0000000..a368e49
--- /dev/null
+++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigDecoder.kt
@@ -0,0 +1,103 @@
+package site.hackery.paramorphism.config
+
+import com.fasterxml.jackson.core.type.TypeReference
+import site.hackery.paramorphism.util.maven.MavenLibraryResolver
+import site.hackery.paramorphism.util.naming.NameDictionaries
+import site.hackery.paramorphism.util.naming.NameDictionary
+import site.hackery.paramorphism.util.naming.NameGenerator
+import java.io.File
+
+interface ConfigDecoder {
+ fun decode(document: ConfigDocument, key: String): T?
+
+ companion object {
+ val stringDecoder: ScalarConfigDecoder = ScalarConfigDecoder(String::class)
+ val stringArrayDecoder: ScalarConfigDecoder> = ScalarConfigDecoder(Array::class)
+ val integerDecoder: ScalarConfigDecoder = ScalarConfigDecoder(Int::class)
+ val booleanDecoder: ScalarConfigDecoder = ScalarConfigDecoder(Boolean::class)
+
+ val fileDecoder: ConfigDecoder = object : ConfigDecoder {
+ override fun decode(document: ConfigDocument, key: String): File? =
+ document.getValue(key, String::class.java)?.let { document.resolvePath(it) }
+ }
+
+ val fileArrayDecoder: ConfigDecoder> = object : ConfigDecoder> {
+ override fun decode(document: ConfigDocument, key: String): Array? {
+ val paths = document.getValue(key, Array::class.java) ?: return null
+ return paths.map { document.resolvePath(it) }.toTypedArray()
+ }
+ }
+
+ val elementMaskDecoder: ConfigDecoder = object : ConfigDecoder {
+ override fun decode(document: ConfigDocument, key: String): ElementMask? {
+ val includes = stringArrayDecoder.decode(document, "$key.include") ?: emptyArray()
+ val excludes = stringArrayDecoder.decode(document, "$key.exclude") ?: emptyArray()
+ return if (includes.isEmpty() && excludes.isEmpty()) null else ElementMask(includes, excludes)
+ }
+ }
+
+ val nameAffixDecoder: ConfigDecoder> = object : ConfigDecoder> {
+ override fun decode(document: ConfigDocument, key: String): Array? {
+ val map = document.getValue(key, object : TypeReference