added files.

This commit is contained in:
nitrogenoliquido committed 2026-11-27 10:00:18 -05:00
commit 09aab327ea
109 files changed
+5269

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
.gradle/
.kotlin/
build/
out/
.idea/
*.iml
.classpath
.project
.settings/
*.log
*.BACKUP
*.obf.jar
out.jar
*-out.jar
+58
View File
@@ -0,0 +1,58 @@
<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-1.3--beta--hotfix-27272a?style=for-the-badge&labelColor=09090b" alt="Version 1.3-beta-hotfix" />
<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">
<sub>This is not a reconstruction nor a remake.</sub>
</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 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 <configFile>
```
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

+26
View File
@@ -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

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

+101
View File
@@ -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
}
}
+5
View File
@@ -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
Binary file not shown.
+8
View File
@@ -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
Vendored Executable
+251
View File
@@ -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
View File
@@ -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
+7
View File
@@ -0,0 +1,7 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
rootProject.name = 'OpenParamorphism'
@@ -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);
}
}
}
@@ -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;
}
}
@@ -0,0 +1,8 @@
package site.hackery.paramorphism.strategy.renaming.tree;
public enum MappingElementKind {
PACKAGE,
CLASS,
FIELD,
METHOD
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
@@ -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);
}
}
}
@@ -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<EntryRecord> entries = new Vector<>();
private final HashSet<String> 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;
}
}
}
@@ -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);
}
}
@@ -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<String, Any>()
configMap["input"] = jarFile.path
val flags = LinkedHashMap<String, Boolean>()
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)}")
}
}
@@ -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<File, File> {
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<ClassSet> =
config.mavenLibraries.getOrDefault(emptyArray()).map { file ->
ResourceBackedClassSet(ZipResourceSet(file), ClassReader.SKIP_CODE)
}
}
@@ -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<String>) {
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<String>) {
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)
}
}
@@ -0,0 +1,12 @@
@file:JvmName("ConfigAccess")
package site.hackery.paramorphism.config
inline fun <reified T : Any> ConfigDocument.getTyped(key: String): T? =
getValue(key, T::class.java)
inline fun <reified T : Any> ConfigDocument.getOrDefault(key: String, defaultValue: T): T =
getValue(key, T::class.java) ?: defaultValue
inline fun <reified T : Any> ConfigDocument.getArray(key: String): Array<T>? =
getValue(key, Array<T>::class.java)
@@ -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<T> {
fun decode(document: ConfigDocument, key: String): T?
companion object {
val stringDecoder: ScalarConfigDecoder<String> = ScalarConfigDecoder(String::class)
val stringArrayDecoder: ScalarConfigDecoder<Array<String>> = ScalarConfigDecoder(Array<String>::class)
val integerDecoder: ScalarConfigDecoder<Int> = ScalarConfigDecoder(Int::class)
val booleanDecoder: ScalarConfigDecoder<Boolean> = ScalarConfigDecoder(Boolean::class)
val fileDecoder: ConfigDecoder<File> = object : ConfigDecoder<File> {
override fun decode(document: ConfigDocument, key: String): File? =
document.getValue(key, String::class.java)?.let { document.resolvePath(it) }
}
val fileArrayDecoder: ConfigDecoder<Array<File>> = object : ConfigDecoder<Array<File>> {
override fun decode(document: ConfigDocument, key: String): Array<File>? {
val paths = document.getValue(key, Array<String>::class.java) ?: return null
return paths.map { document.resolvePath(it) }.toTypedArray()
}
}
val elementMaskDecoder: ConfigDecoder<ElementMask> = object : ConfigDecoder<ElementMask> {
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<Array<String?>> = object : ConfigDecoder<Array<String?>> {
override fun decode(document: ConfigDocument, key: String): Array<String?>? {
val map = document.getValue(key, object : TypeReference<Map<String, String>>() {}) ?: return null
val defaultAffix = map["all"]
val scopes = arrayOf("packages", "classes", "fields", "methods")
return Array(scopes.size) { index -> map[scopes[index]] ?: defaultAffix }
}
}
val dictionaryArrayDecoder: ConfigDecoder<Array<NameDictionary>> = object : ConfigDecoder<Array<NameDictionary>> {
override fun decode(document: ConfigDocument, key: String): Array<NameDictionary> {
val result = Array(4) { NameDictionaries.ALPHABET }
val map = document.getValue(key, object : TypeReference<Map<String, String>>() {}) ?: return result
fun resolve(scopeKey: String): NameDictionary? {
val spec = map[scopeKey] ?: return null
return NameDictionaries.dictionaries[spec]
?: error("Invalid dictionary specifier: $spec")
}
val defaultDict = resolve("all")
val scopes = arrayOf("packages", "classes", "fields", "methods")
for (i in scopes.indices) {
val selected = resolve(scopes[i]) ?: defaultDict
if (selected != null) {
result[i] = selected
}
}
return result
}
}
val nameGeneratorDecoder: ConfigDecoder<NameGenerator> = object : ConfigDecoder<NameGenerator> {
override fun decode(document: ConfigDocument, key: String): NameGenerator {
val dictionaries = dictionaryArrayDecoder.decode(document, "$key.dictionaries")
?: Array(4) { NameDictionaries.ALPHABET }
val inflation = document.getValue("$key.inflation", Int::class.javaObjectType)
val prefixes = nameAffixDecoder.decode(document, "$key.prefixes") ?: arrayOfNulls(4)
val suffixes = nameAffixDecoder.decode(document, "$key.suffixes") ?: arrayOfNulls(4)
val shuffle = document.getValue("$key.shuffle", Boolean::class.javaObjectType) ?: true
return NameGenerator(dictionaries, inflation, prefixes, suffixes, shuffle)
}
}
val flagsDecoder: ConfigDecoder<ConfigFlags> = object : ConfigDecoder<ConfigFlags> {
override fun decode(document: ConfigDocument, key: String): ConfigFlags {
val map = document.getValue(key, object : TypeReference<Map<String, Boolean>>() {}) ?: emptyMap()
return ConfigFlags(map)
}
}
val mavenLibrariesDecoder: ConfigDecoder<Array<File>> = object : ConfigDecoder<Array<File>> {
override fun decode(document: ConfigDocument, key: String): Array<File>? {
val repos = document.getValue(key, object : TypeReference<Map<String, List<String>>>() {}) ?: return null
val resolvedFiles = ArrayList<File>()
for ((repoPath, coordinates) in repos) {
val resolver = MavenLibraryResolver(document.resolvePath(repoPath))
for (coord in coordinates) {
resolver.resolveArtifact(coord)?.let { resolvedFiles.add(it) }
}
}
return resolvedFiles.toTypedArray()
}
}
}
}
@@ -0,0 +1,58 @@
package site.hackery.paramorphism.config
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.databind.node.MissingNode
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper
import java.io.File
abstract class ConfigDocument(val file: File) {
private val mapper: ObjectMapper = when (file.extension.lowercase()) {
"json" -> JsonMapper.builder().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS).build()
else -> YAMLMapper.builder().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS).build()
}
private val rootNode: JsonNode = mapper.readTree(file)
private fun <T> convertValue(node: JsonNode, type: Class<T>): T? {
if (node.isMissingNode || node.isNull) {
return null
}
return try {
mapper.treeToValue(node, type)
} catch (_: Exception) {
null
}
}
private fun <T> convertValue(node: JsonNode, typeReference: TypeReference<T>): T? {
if (node.isMissingNode || node.isNull) {
return null
}
return try {
mapper.convertValue(node, typeReference)
} catch (_: Exception) {
null
}
}
private fun findNode(key: String): JsonNode {
var current: JsonNode? = rootNode
for (segment in key.split('.')) {
current = current?.get(segment)
}
return current ?: MissingNode.getInstance()
}
fun <T> getValue(key: String, type: Class<T>): T? = convertValue(findNode(key), type)
fun <T> getValue(key: String, typeReference: TypeReference<T>): T? = convertValue(findNode(key), typeReference)
fun resolvePath(path: String): File {
val candidate = File(path)
return if (candidate.isAbsolute) candidate else File(file.parentFile, path)
}
}
@@ -0,0 +1,5 @@
package site.hackery.paramorphism.config
class ConfigFlags(private val flags: Map<String, Boolean>) {
operator fun get(flag: String): Boolean? = flags[flag]
}
@@ -0,0 +1,12 @@
package site.hackery.paramorphism.config
class ConfigValue<T>(
private val document: ConfigDocument,
private val key: String,
private val decoder: ConfigDecoder<T>,
private val defaultValue: T? = null
) {
fun get(): T? = decoder.decode(document, key) ?: defaultValue
fun getOrDefault(fallback: T): T = decoder.decode(document, key) ?: fallback
}
@@ -0,0 +1,24 @@
package site.hackery.paramorphism.config
class ElementMask(
private val includes: Array<String>,
private val excludes: Array<String>
) {
fun matches(target: String): Boolean {
var matched = if (includes.isNotEmpty()) {
includes.any { matchesPattern(it, target) }
} else {
true
}
if (excludes.any { matchesPattern(it, target) }) {
matched = false
}
return matched
}
private fun matchesPattern(pattern: String, target: String): Boolean = when {
pattern.last() == '/' -> target.startsWith(pattern)
pattern.last() == '*' -> target.startsWith(pattern.substring(0, pattern.lastIndex))
else -> pattern == target
}
}
@@ -0,0 +1,18 @@
package site.hackery.paramorphism.config
import site.hackery.paramorphism.util.naming.NameGenerator
import java.io.File
class ParamorphismConfig(file: File) : ConfigDocument(file) {
val input: ConfigValue<File> = ConfigValue(this, "input", ConfigDecoder.fileDecoder)
val output: ConfigValue<File> = ConfigValue(this, "output", ConfigDecoder.fileDecoder)
val libraries: ConfigValue<Array<File>> = ConfigValue(this, "libraries", ConfigDecoder.fileArrayDecoder)
val mavenLibraries: ConfigValue<Array<File>> = ConfigValue(this, "maven_libraries", ConfigDecoder.mavenLibrariesDecoder)
val addJavaRuntime: ConfigValue<Boolean> = ConfigValue(this, "add_java_runtime", ConfigDecoder.booleanDecoder)
val shadedLibraries: ConfigValue<ElementMask> = ConfigValue(this, "shaded_libraries", ConfigDecoder.elementMaskDecoder)
val mask: ConfigValue<ElementMask> = ConfigValue(this, "mask", ConfigDecoder.elementMaskDecoder)
val flags: ConfigValue<ConfigFlags> = ConfigValue(this, "flags", ConfigDecoder.flagsDecoder)
val nameGeneration: ConfigValue<NameGenerator> = ConfigValue(this, "name_generation", ConfigDecoder.nameGeneratorDecoder)
val randomOffset: ConfigValue<Int> = ConfigValue(this, "random_offset", ConfigDecoder.integerDecoder)
val branding: ConfigValue<Boolean> = ConfigValue(this, "branding", ConfigDecoder.booleanDecoder)
}
@@ -0,0 +1,8 @@
package site.hackery.paramorphism.config
import kotlin.reflect.KClass
class ScalarConfigDecoder<T : Any>(private val type: KClass<T>) : ConfigDecoder<T> {
override fun decode(document: ConfigDocument, key: String): T? =
document.getValue(key, type.java)
}
@@ -0,0 +1,8 @@
package site.hackery.paramorphism.resources
class ByteArrayResource(
private val data: ByteArray,
writePriority: Int = 1
) : Resource(writePriority) {
override fun getBytes(): ByteArray = data
}
@@ -0,0 +1,16 @@
package site.hackery.paramorphism.resources
import org.objectweb.asm.tree.ClassNode
import java.io.Closeable
interface ClassSet : Closeable {
fun get(name: String): ClassNode?
fun put(name: String, classNode: ClassNode)
fun contains(name: String): Boolean
fun entries(): Sequence<Pair<String, ClassNode>>
fun names(): Sequence<String>
}
@@ -0,0 +1,37 @@
package site.hackery.paramorphism.resources
import org.objectweb.asm.tree.ClassNode
import java.io.Closeable
class ClassSetGroup(val classSets: Array<ClassSet>) : Closeable {
private val classSetIndices = LinkedHashMap<String, Int>()
private fun findClassSet(name: String): ClassSet? {
val cachedIndex = classSetIndices[name]
if (cachedIndex != null) {
return if (cachedIndex < 0) null else classSets[cachedIndex]
}
for (i in classSets.indices) {
val classSet = classSets[i]
if (classSet.contains(name)) {
classSetIndices[name] = i
return classSet
}
}
classSetIndices[name] = -1
return null
}
fun get(name: String): ClassNode? = findClassSet(name)?.get(name)
fun contains(name: String): Boolean = findClassSet(name) != null
fun entries(): Sequence<Pair<String, ClassNode>> =
classSets.asSequence().flatMap { it.entries() }
override fun close() {
for (classSet in classSets) {
runCatching { classSet.close() }
}
}
}
@@ -0,0 +1,8 @@
package site.hackery.paramorphism.resources
class LazyResource(
val supplier: () -> ByteArray,
writePriority: Int = 1
) : Resource(writePriority) {
override fun getBytes(): ByteArray = supplier()
}
@@ -0,0 +1,12 @@
package site.hackery.paramorphism.resources
import java.io.ByteArrayOutputStream
import java.util.jar.Manifest
class ManifestResource(
val manifest: Manifest,
writePriority: Int
) : Resource(writePriority) {
override fun getBytes(): ByteArray =
ByteArrayOutputStream().also { manifest.write(it) }.toByteArray()
}
@@ -0,0 +1,5 @@
package site.hackery.paramorphism.resources
sealed class Resource(val writePriority: Int) {
abstract fun getBytes(): ByteArray
}
@@ -0,0 +1,15 @@
package site.hackery.paramorphism.resources
import java.io.Closeable
interface ResourceSet : Closeable {
fun get(name: String): Resource?
fun put(name: String, resource: Resource?)
fun contains(name: String): Boolean
fun entries(): Sequence<Pair<String, Resource>>
fun names(): Sequence<String>
}
@@ -0,0 +1,8 @@
package site.hackery.paramorphism.resources
class TaggedResource(
val tag: String,
val delegate: Resource
) : Resource(delegate.writePriority) {
override fun getBytes(): ByteArray = delegate.getBytes()
}
@@ -0,0 +1,83 @@
package site.hackery.paramorphism.resources.io
import site.hackery.paramorphism.resources.LazyResource
import site.hackery.paramorphism.resources.Resource
import site.hackery.paramorphism.resources.ResourceSet
import java.nio.file.FileSystem
import java.nio.file.Files
import java.nio.file.Path
import kotlin.streams.asSequence
class FileSystemResourceSet(private val fileSystem: FileSystem) : ResourceSet {
private val moduleRoots: List<Path> by lazy {
val modulesDir = fileSystem.getPath("/modules")
if (!Files.isDirectory(modulesDir)) {
emptyList()
} else {
Files.list(modulesDir).use { stream ->
stream.filter { Files.isDirectory(it) }
.toList()
.sortedByDescending { it.fileName?.toString() == "java.base" }
}
}
}
private fun resolvePath(name: String): Path? {
val direct = fileSystem.getPath(name)
if (Files.isRegularFile(direct)) {
return direct
}
for (moduleRoot in moduleRoots) {
val candidate = moduleRoot.resolve(name)
if (Files.isRegularFile(candidate)) {
return candidate
}
}
return null
}
override fun get(name: String): Resource? {
val path = resolvePath(name) ?: return null
return LazyResource({ Files.readAllBytes(path) })
}
override fun put(name: String, resource: Resource?) {
throw UnsupportedOperationException()
}
override fun contains(name: String): Boolean = resolvePath(name) != null
private fun walkRoot(): Path {
val modulesDir = fileSystem.getPath("/modules")
return if (Files.isDirectory(modulesDir)) modulesDir else fileSystem.getPath("/")
}
private fun normalizeEntryName(path: Path): String {
val modulesDir = fileSystem.getPath("/modules")
return if (Files.isDirectory(modulesDir) && path.startsWith(modulesDir) && path.nameCount > 2) {
path.subpath(2, path.nameCount).toString()
} else {
path.toString().drop(1)
}
}
override fun entries(): Sequence<Pair<String, Resource>> =
Files.walk(walkRoot())
.asSequence()
.filter { Files.isRegularFile(it) }
.map { path -> normalizeEntryName(path) to LazyResource({ Files.readAllBytes(path) }) }
override fun names(): Sequence<String> =
Files.walk(walkRoot())
.asSequence()
.filter { Files.isRegularFile(it) }
.map { path -> normalizeEntryName(path) }
override fun close() {
try {
fileSystem.close()
} catch (_: UnsupportedOperationException) {
// Built-in jrt:/ FileSystem instances cannot be closed.
}
}
}
@@ -0,0 +1,41 @@
package site.hackery.paramorphism.resources.io
import site.hackery.paramorphism.resources.ByteArrayResource
import site.hackery.paramorphism.resources.Resource
import site.hackery.paramorphism.resources.ResourceSet
import java.io.File
import java.util.zip.ZipFile
import kotlin.streams.asSequence
class ZipResourceSet(file: File) : ResourceSet {
private val zipFile = ZipFile(file)
override fun get(name: String): Resource? {
val entry = zipFile.getEntry(name) ?: return null
val bytes = zipFile.getInputStream(entry).use { it.readBytes() }
return ByteArrayResource(bytes)
}
override fun put(name: String, resource: Resource?) {
throw UnsupportedOperationException()
}
override fun contains(name: String): Boolean = zipFile.getEntry(name) != null
override fun entries(): Sequence<Pair<String, Resource>> =
zipFile.stream()
.asSequence()
.map { entry -> entry.name to zipFile.getInputStream(entry) }
.filter { (_, stream) -> stream.available() > 0 }
.map { (name, stream) ->
val bytes = stream.use { it.readBytes() }
name to ByteArrayResource(bytes)
}
override fun names(): Sequence<String> =
zipFile.stream().asSequence().map { it.name }
override fun close() {
zipFile.close()
}
}
@@ -0,0 +1,30 @@
package site.hackery.paramorphism.resources.masking
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.config.ElementMask
import site.hackery.paramorphism.resources.ClassSet
class IncludedClassSet(
private val mask: ElementMask,
private val delegate: ClassSet
) : ClassSet {
override fun get(name: String): ClassNode? =
if (!mask.matches(name)) null else delegate.get(name)
override fun put(name: String, classNode: ClassNode) {
throw UnsupportedOperationException()
}
override fun contains(name: String): Boolean =
mask.matches(name) && delegate.contains(name)
override fun entries(): Sequence<Pair<String, ClassNode>> =
delegate.entries().filter { (name, _) -> mask.matches(name) }
override fun names(): Sequence<String> =
delegate.names().filter { mask.matches(it) }
override fun close() {
delegate.close()
}
}
@@ -0,0 +1,30 @@
package site.hackery.paramorphism.resources.masking
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.config.ElementMask
import site.hackery.paramorphism.resources.ClassSet
class MaskedClassSet(
private val mask: ElementMask,
private val delegate: ClassSet
) : ClassSet {
override fun get(name: String): ClassNode? =
if (mask.matches(name)) null else delegate.get(name)
override fun put(name: String, classNode: ClassNode) {
throw UnsupportedOperationException()
}
override fun contains(name: String): Boolean =
!mask.matches(name) && delegate.contains(name)
override fun entries(): Sequence<Pair<String, ClassNode>> =
delegate.entries().filter { (name, _) -> !mask.matches(name) }
override fun names(): Sequence<String> =
delegate.names().filter { !mask.matches(it) }
override fun close() {
delegate.close()
}
}
@@ -0,0 +1,34 @@
package site.hackery.paramorphism.resources.overlay
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.resources.ClassSet
class OverlayClassSet(val parent: ClassSet?) : ClassSet {
val overrides: MutableMap<String, ClassNode> = LinkedHashMap()
override fun get(name: String): ClassNode? =
if (overrides.containsKey(name)) overrides[name] else parent?.get(name)
override fun put(name: String, classNode: ClassNode) {
overrides[name] = classNode
}
override fun contains(name: String): Boolean =
overrides.containsKey(name) || (parent?.contains(name) == true)
override fun entries(): Sequence<Pair<String, ClassNode>> {
val localEntries = overrides.entries.asSequence().map { it.key to it.value }
val parentEntries = parent?.entries()?.filter { (name, _) -> !overrides.containsKey(name) } ?: emptySequence()
return localEntries + parentEntries
}
override fun names(): Sequence<String> {
val localNames = overrides.keys.asSequence()
val parentNames = parent?.names()?.filter { !overrides.containsKey(it) } ?: emptySequence()
return localNames + parentNames
}
override fun close() {
parent?.close()
}
}
@@ -0,0 +1,36 @@
package site.hackery.paramorphism.resources.overlay
import site.hackery.paramorphism.resources.Resource
import site.hackery.paramorphism.resources.ResourceSet
class OverlayResourceSet(val parent: ResourceSet?) : ResourceSet {
val overrides: MutableMap<String, Resource?> = LinkedHashMap()
override fun get(name: String): Resource? =
if (overrides.containsKey(name)) overrides[name] else parent?.get(name)
override fun put(name: String, resource: Resource?) {
overrides[name] = resource
}
override fun contains(name: String): Boolean =
overrides.containsKey(name) || (parent?.contains(name) == true)
override fun entries(): Sequence<Pair<String, Resource>> {
val localEntries = overrides.entries.asSequence().mapNotNull { (key, value) ->
value?.let { key to it }
}
val parentEntries = parent?.entries()?.filter { (name, _) -> !overrides.containsKey(name) } ?: emptySequence()
return localEntries + parentEntries
}
override fun names(): Sequence<String> {
val localNames = overrides.keys.asSequence()
val parentNames = parent?.names()?.filter { !overrides.containsKey(it) } ?: emptySequence()
return localNames + parentNames
}
override fun close() {
parent?.close()
}
}
@@ -0,0 +1,26 @@
package site.hackery.paramorphism.resources.views
import site.hackery.paramorphism.resources.Resource
import site.hackery.paramorphism.resources.ResourceSet
class NonClassResourceSet(private val delegate: ResourceSet) : ResourceSet {
override fun get(name: String): Resource? =
if (name.endsWith(".class")) null else delegate.get(name)
override fun put(name: String, resource: Resource?) {
delegate.put(name, resource)
}
override fun contains(name: String): Boolean =
!name.endsWith(".class") && delegate.contains(name)
override fun entries(): Sequence<Pair<String, Resource>> =
delegate.entries().filter { (name, _) -> !name.endsWith(".class") }
override fun names(): Sequence<String> =
delegate.names().filter { !it.endsWith(".class") }
override fun close() {
delegate.close()
}
}
@@ -0,0 +1,37 @@
package site.hackery.paramorphism.resources.views
import org.objectweb.asm.ClassReader
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.resources.ResourceSet
class ResourceBackedClassSet(
private val resources: ResourceSet,
private val classReaderFlags: Int = ClassReader.EXPAND_FRAMES
) : ClassSet {
override fun get(name: String): ClassNode? =
resources.get("$name.class")?.let { readClass(it.getBytes()) }
override fun put(name: String, classNode: ClassNode) {
throw UnsupportedOperationException()
}
override fun contains(name: String): Boolean = resources.contains("$name.class")
override fun entries(): Sequence<Pair<String, ClassNode>> =
resources.entries()
.filter { (name, _) -> name.endsWith(".class") }
.map { (name, resource) -> name.dropLast(".class".length) to readClass(resource.getBytes()) }
override fun names(): Sequence<String> =
resources.entries()
.filter { (name, _) -> name.endsWith(".class") }
.map { (name, _) -> name.dropLast(".class".length) }
override fun close() {
resources.close()
}
private fun readClass(bytes: ByteArray): ClassNode =
ClassNode().also { ClassReader(bytes).accept(it, classReaderFlags) }
}
@@ -0,0 +1,18 @@
package site.hackery.paramorphism.strategy
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.util.context.ObfuscationContext
interface Strategy {
val name: String
fun runsOnExcludedClasses(): Boolean = false
fun initialize(context: ObfuscationContext) {
}
fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode = classNode
fun finish(context: ObfuscationContext) {
}
}
@@ -0,0 +1,6 @@
package site.hackery.paramorphism.strategy
class StrategyPass(
val name: String,
private val strategies: MutableList<Strategy>
) : MutableList<Strategy> by strategies
@@ -0,0 +1,120 @@
package site.hackery.paramorphism.strategy
import site.hackery.paramorphism.config.ConfigDecoder
import site.hackery.paramorphism.config.ElementMask
import site.hackery.paramorphism.config.ParamorphismConfig
import site.hackery.paramorphism.strategy.debug.DebugInfoScrubbingStrategy
import site.hackery.paramorphism.strategy.indirection.FieldAccessIndirectionStrategy
import site.hackery.paramorphism.strategy.indirection.MethodCallIndirectionStrategy
import site.hackery.paramorphism.strategy.indirection.StringIndirectionStrategy
import site.hackery.paramorphism.strategy.kotlin.KotlinIntrinsicsConcealmentStrategy
import site.hackery.paramorphism.strategy.kotlin.KotlinMetadataScrubbingStrategy
import site.hackery.paramorphism.strategy.renaming.RenamingStrategy
import site.hackery.paramorphism.util.RandomContext
import site.hackery.paramorphism.util.context.MutableObfuscationContext
import site.hackery.paramorphism.util.context.ObfuscationContext
import site.hackery.paramorphism.util.logging.PerformanceProfiler
class StrategyPipeline(context: ObfuscationContext) {
private val config: ParamorphismConfig = context.config
private val randomProvider: RandomContext = context.getService(RandomContext::class.java)
private val strategyMasks = LinkedHashMap<Strategy, ElementMask>()
private val passes: List<StrategyPass>
init {
val flags = config.flags.get()!!
val builtPasses = ArrayList<StrategyPass>()
fun addPass(name: String, configure: StrategyPass.() -> Unit) {
val pass = StrategyPass(name, ArrayList())
pass.configure()
builtPasses.add(pass)
}
fun StrategyPass.appendIfEnabled(strategy: Strategy, defaultEnabled: Boolean = true) {
val enabled = config.getValue("${strategy.configurationKey()}.enabled", Boolean::class.javaObjectType)
?: defaultEnabled
if (enabled) {
add(strategy)
}
}
addPass("Metadata Scrubbing") {
appendIfEnabled(DebugInfoScrubbingStrategy(randomProvider.getRandom()))
val kotlinEnabled = flags["kotlin"] ?: false
appendIfEnabled(KotlinMetadataScrubbingStrategy(), kotlinEnabled)
appendIfEnabled(KotlinIntrinsicsConcealmentStrategy(), kotlinEnabled)
}
addPass("Remapper") {
appendIfEnabled(RenamingStrategy())
}
addPass("Indirection") {
appendIfEnabled(MethodCallIndirectionStrategy(randomProvider.getRandom()))
appendIfEnabled(FieldAccessIndirectionStrategy(randomProvider.getRandom()))
appendIfEnabled(StringIndirectionStrategy(randomProvider.getRandom()))
}
builtPasses.removeIf { it.isEmpty() }
this.passes = builtPasses
}
fun run(context: ObfuscationContext, mutableContext: MutableObfuscationContext) {
for (strategy in passes.flatten()) {
ConfigDecoder.elementMaskDecoder.decode(config, "${strategy.configurationKey()}.mask")?.let { mask ->
strategyMasks[strategy] = mask
}
}
var passNumber = 0
for (pass in passes) {
if (passes.size != 1) {
PerformanceProfiler.beginPhase("Pass #${++passNumber}: ${pass.name}")
}
PerformanceProfiler.measurePhase("Setup") {
for (strategy in pass) {
PerformanceProfiler.measurePhase(strategy.name) {
mutableContext.localMask = strategyMasks[strategy]
strategy.initialize(context)
}
}
}
PerformanceProfiler.measurePhase("Processing") {
PerformanceProfiler.measureSections {
for ((className, initialNode) in context.classes.entries().toList()) {
var currentNode = initialNode
for (strategy in pass) {
val localMask = strategyMasks[strategy]
val matchesMasks = context.globalMask.matches(className) &&
(localMask?.matches(className) ?: true)
if (strategy.runsOnExcludedClasses() || matchesMasks) {
PerformanceProfiler.switchSection(strategy.name)
mutableContext.localMask = localMask
currentNode = strategy.transform(currentNode, context)
}
}
context.classes.put(className, currentNode)
}
}
}
PerformanceProfiler.measurePhase("Finalization") {
for (strategy in pass) {
PerformanceProfiler.measurePhase(strategy.name) {
mutableContext.localMask = strategyMasks[strategy]
strategy.finish(context)
}
}
}
if (passes.size != 1) {
PerformanceProfiler.endPhase()
}
}
strategyMasks.clear()
}
}
@@ -0,0 +1,13 @@
@file:JvmName("StrategyUtils")
package site.hackery.paramorphism.strategy
fun Strategy.configurationKey(): String = buildString {
for (ch in name) {
if (ch == '-' || ch == ' ' || ch == '.') {
append('_')
} else {
append(ch.lowercaseChar())
}
}
}
@@ -0,0 +1,13 @@
package site.hackery.paramorphism.strategy.controlflow
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.util.context.ObfuscationContext
class ControlFlowManglingStrategy : Strategy {
override val name: String = "Control Flow Mangling"
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
TODO("Control flow mangling is not implemented in this version")
}
}
@@ -0,0 +1,10 @@
package site.hackery.paramorphism.strategy.controlflow.graph
import org.objectweb.asm.tree.AbstractInsnNode
class BasicBlock(
val firstInstruction: AbstractInsnNode,
val lastInstruction: AbstractInsnNode
) {
val successors: MutableList<BasicBlock> = ArrayList()
}
@@ -0,0 +1,9 @@
package site.hackery.paramorphism.strategy.controlflow.graph
import org.objectweb.asm.tree.AbstractInsnNode
internal class BasicBlockBuilder {
var firstIndex: Int? = null
var lastIndex: Int? = null
val successorInstructions: MutableList<AbstractInsnNode> = ArrayList()
}
@@ -0,0 +1,19 @@
package site.hackery.paramorphism.strategy.controlflow.graph
import org.objectweb.asm.tree.analysis.Analyzer
import org.objectweb.asm.tree.analysis.Interpreter
import org.objectweb.asm.tree.analysis.Value
class ControlFlowAnalyzer<V : Value>(interpreter: Interpreter<V>) : Analyzer<V>(interpreter) {
val successors: MutableMap<Int, MutableSet<Int>> = LinkedHashMap()
override fun newControlFlowEdge(insnIndex: Int, successorIndex: Int) {
successors.getOrPut(insnIndex) { LinkedHashSet() }.add(successorIndex)
super.newControlFlowEdge(insnIndex, successorIndex)
}
override fun newControlFlowExceptionEdge(insnIndex: Int, successorIndex: Int): Boolean {
successors.getOrPut(insnIndex) { LinkedHashSet() }.add(successorIndex)
return super.newControlFlowExceptionEdge(insnIndex, successorIndex)
}
}
@@ -0,0 +1,85 @@
@file:JvmName("ControlFlowGraphUtils")
package site.hackery.paramorphism.strategy.controlflow.graph
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.analysis.BasicInterpreter
private fun reverseEdges(edges: Map<Int, Set<Int>>): Map<Int, Set<Int>> {
val reversed = LinkedHashMap<Int, MutableSet<Int>>()
for ((source, targets) in edges) {
for (target in targets) {
reversed.getOrPut(target) { LinkedHashSet() }.add(source)
}
}
return reversed
}
fun buildBlocks(classNode: ClassNode, methodNode: MethodNode): Set<BasicBlock> {
if (methodNode.instructions.size() == 0) {
return emptySet()
}
val analyzer = ControlFlowAnalyzer(BasicInterpreter())
analyzer.analyze(classNode.name, methodNode)
val successors = analyzer.successors
val predecessors = reverseEdges(successors)
val builders = ArrayList<BasicBlockBuilder>()
var previousEnd = -1
for ((index, insn) in methodNode.instructions.iterator().withIndex()) {
if (insn.next == null) {
builders.add(
BasicBlockBuilder().apply {
firstIndex = previousEnd + 1
lastIndex = index
}
)
previousEnd = index
} else {
val insnSuccessors = successors[index] ?: continue
if (insnSuccessors.size == 1) {
val targetIndex = insnSuccessors.first()
val targetPredCount = predecessors[targetIndex]?.size ?: 1
if (targetPredCount == 1) {
continue
}
}
builders.add(
BasicBlockBuilder().apply {
firstIndex = previousEnd + 1
lastIndex = index
successorInstructions.addAll(insnSuccessors.map { methodNode.instructions[it] })
}
)
previousEnd = index
}
}
val resolvedBlocks = LinkedHashMap<BasicBlockBuilder, BasicBlock>()
fun resolveBlock(builder: BasicBlockBuilder): BasicBlock {
resolvedBlocks[builder]?.let { return it }
val block = BasicBlock(
methodNode.instructions[builder.firstIndex!!],
methodNode.instructions[builder.lastIndex!!]
)
resolvedBlocks[builder] = block
val successorBuilders = builder.successorInstructions.map { targetInsn ->
val targetIndex = methodNode.instructions.indexOf(targetInsn)
builders.first { it.firstIndex == targetIndex }
}
block.successors.addAll(successorBuilders.map { resolveBlock(it) })
return block
}
for (builder in builders) {
resolveBlock(builder)
}
return resolvedBlocks.values.toSet()
}
@@ -0,0 +1,36 @@
package site.hackery.paramorphism.strategy.debug
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.LineNumberNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.strategy.configurationKey
import site.hackery.paramorphism.util.context.ObfuscationContext
import java.util.Random
class DebugInfoScrubbingStrategy(val random: Random) : Strategy {
override val name: String = "Debug Info Scrubbing"
lateinit var localVariableName: String
override fun initialize(context: ObfuscationContext) {
localVariableName = context.config.getValue("${configurationKey()}.local_variable_name", String::class.java)
?: "v"
}
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
classNode.sourceFile = ""
classNode.sourceDebug = ""
for (method in classNode.methods) {
method.localVariables?.forEach { localVar ->
localVar.name = localVariableName
}
for (insn in method.instructions) {
if (insn is LineNumberNode) {
insn.line = random.nextInt(65335)
}
}
}
return super.transform(classNode, context)
}
}
@@ -0,0 +1,86 @@
package site.hackery.paramorphism.strategy.indirection
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FieldInsnNode
import org.objectweb.asm.tree.MethodInsnNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethod
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethodFactory
import site.hackery.paramorphism.strategy.indirection.generation.buildIndirectionPackagePrefix
import site.hackery.paramorphism.strategy.indirection.generation.impl.PackedMethodGenerator
import site.hackery.paramorphism.strategy.indirection.generation.loadArguments
import site.hackery.paramorphism.strategy.indirection.generation.returnInstruction
import site.hackery.paramorphism.util.context.ObfuscationContext
import java.util.Random
class FieldAccessIndirectionStrategy(private val random: Random) : Strategy {
override val name: String = "Field Access Indirection"
private lateinit var packagePrefix: String
private lateinit var methodFactory: GeneratedMethodFactory
private val fieldWrappers = LinkedHashMap<String, GeneratedMethod>()
override fun initialize(context: ObfuscationContext) {
packagePrefix = buildIndirectionPackagePrefix(context, random, rootPackageIndex = 2)
methodFactory = PackedMethodGenerator(packagePrefix, context.nameGenerator, random)
methodFactory.initialize(context.classes, context.resources)
}
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
val lookupClass: (String) -> ClassNode? = { name ->
if (context.classes.contains(name)) context.classes.get(name) else context.libraries.get(name)
}
for (method in classNode.methods) {
for (insn in method.instructions.toArray()) {
if (insn !is FieldInsnNode) {
continue
}
if (context.classes.get(insn.owner) != null) {
continue
}
val ownerClass = context.libraries.get(insn.owner) ?: continue
val fieldAccess = findField(lookupClass, ownerClass, insn.name, insn.desc)?.access
if ((ownerClass.access and Opcodes.ACC_PUBLIC) == 0) {
continue
}
if (fieldAccess != null && (fieldAccess and Opcodes.ACC_PUBLIC) == 0) {
continue
}
val isInstance = insn.opcode != Opcodes.GETSTATIC && insn.opcode != Opcodes.PUTSTATIC
val isGet = insn.opcode == Opcodes.GETSTATIC || insn.opcode == Opcodes.GETFIELD
val cacheKey = "${if (isGet) "get" else "set"} ${insn.owner} ${insn.name} ${insn.desc}"
val wrapper = fieldWrappers.getOrPut(cacheKey) {
val descriptor = when {
isInstance && isGet -> "(L${insn.owner};)${insn.desc}"
!isInstance && isGet -> "()${insn.desc}"
isInstance && !isGet -> "(L${insn.owner};${insn.desc})V"
else -> "(${insn.desc})V"
}
methodFactory.createMethod(descriptor).also { generated ->
generated.methodNode.instructions.apply {
add(loadArguments(generated.methodNode))
add(FieldInsnNode(insn.opcode, insn.owner, insn.name, insn.desc))
add(returnInstruction(generated.methodNode))
}
}
}
method.instructions.insert(
insn,
MethodInsnNode(Opcodes.INVOKESTATIC, wrapper.callOwner, wrapper.name, wrapper.descriptor, false)
)
method.instructions.remove(insn)
}
}
return super.transform(classNode, context)
}
override fun finish(context: ObfuscationContext) {
methodFactory.finish()
}
}
@@ -0,0 +1,27 @@
@file:JvmName("FieldLookup")
package site.hackery.paramorphism.strategy.indirection
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FieldNode
internal fun findField(
lookupClass: (String) -> ClassNode?,
owner: ClassNode,
name: String,
descriptor: String
): FieldNode? {
owner.fields.firstOrNull { it.name == name && it.desc == descriptor }?.let { return it }
owner.superName?.let(lookupClass)?.let { superClass ->
findField(lookupClass, superClass, name, descriptor)?.let { return it }
}
for (iface in owner.interfaces) {
lookupClass(iface)?.let { ifaceClass ->
findField(lookupClass, ifaceClass, name, descriptor)?.let { return it }
}
}
return null
}
@@ -0,0 +1,81 @@
package site.hackery.paramorphism.strategy.indirection
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodInsnNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethod
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethodFactory
import site.hackery.paramorphism.strategy.indirection.generation.buildIndirectionPackagePrefix
import site.hackery.paramorphism.strategy.indirection.generation.impl.PackedMethodGenerator
import site.hackery.paramorphism.strategy.indirection.generation.loadArguments
import site.hackery.paramorphism.strategy.indirection.generation.returnInstruction
import site.hackery.paramorphism.strategy.indirection.generation.wrapperDescriptor
import site.hackery.paramorphism.util.context.ObfuscationContext
import java.util.Random
class MethodCallIndirectionStrategy(private val random: Random) : Strategy {
override val name: String = "Method Call Indirection"
private lateinit var packagePrefix: String
private lateinit var methodFactory: GeneratedMethodFactory
private val methodWrappers = LinkedHashMap<String, GeneratedMethod>()
override fun initialize(context: ObfuscationContext) {
packagePrefix = buildIndirectionPackagePrefix(context, random, rootPackageIndex = 0)
methodFactory = PackedMethodGenerator(packagePrefix, context.nameGenerator, random)
methodFactory.initialize(context.classes, context.resources)
}
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
val lookupClass: (String) -> ClassNode? = { name ->
if (context.classes.contains(name)) context.classes.get(name) else context.libraries.get(name)
}
for (method in classNode.methods) {
for (insn in method.instructions.toArray()) {
if (insn !is MethodInsnNode) {
continue
}
if (insn.name.first() == '<' || insn.opcode == Opcodes.INVOKESPECIAL) {
continue
}
if (context.classes.get(insn.owner) != null) {
continue
}
val ownerClass = context.libraries.get(insn.owner) ?: continue
val methodAccess = findMethod(lookupClass, ownerClass, insn.name, insn.desc)?.access
if ((ownerClass.access and Opcodes.ACC_PUBLIC) == 0) {
continue
}
if (methodAccess != null && (methodAccess and Opcodes.ACC_PUBLIC) == 0) {
continue
}
val cacheKey = "${insn.owner}#${insn.name}${insn.desc}"
val wrapper = methodWrappers.getOrPut(cacheKey) {
val descriptor = wrapperDescriptor(insn.opcode, insn.owner, insn.desc)
methodFactory.createMethod(descriptor).also { generated ->
generated.methodNode.instructions.apply {
add(loadArguments(generated.methodNode))
add(MethodInsnNode(insn.opcode, insn.owner, insn.name, insn.desc, insn.itf))
add(returnInstruction(generated.methodNode))
}
}
}
method.instructions.insert(
insn,
MethodInsnNode(Opcodes.INVOKESTATIC, wrapper.callOwner, wrapper.name, wrapper.descriptor, false)
)
method.instructions.remove(insn)
}
}
return super.transform(classNode, context)
}
override fun finish(context: ObfuscationContext) {
methodFactory.finish()
}
}
@@ -0,0 +1,27 @@
@file:JvmName("MethodLookup")
package site.hackery.paramorphism.strategy.indirection
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
internal fun findMethod(
lookupClass: (String) -> ClassNode?,
owner: ClassNode,
name: String,
descriptor: String
): MethodNode? {
owner.methods.firstOrNull { it.name == name && it.desc == descriptor }?.let { return it }
owner.superName?.let(lookupClass)?.let { superClass ->
findMethod(lookupClass, superClass, name, descriptor)?.let { return it }
}
for (iface in owner.interfaces) {
lookupClass(iface)?.let { ifaceClass ->
findMethod(lookupClass, ifaceClass, name, descriptor)?.let { return it }
}
}
return null
}
@@ -0,0 +1,57 @@
package site.hackery.paramorphism.strategy.indirection
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.InsnNode
import org.objectweb.asm.tree.LdcInsnNode
import org.objectweb.asm.tree.MethodInsnNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethod
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethodFactory
import site.hackery.paramorphism.strategy.indirection.generation.buildIndirectionPackagePrefix
import site.hackery.paramorphism.strategy.indirection.generation.impl.PackedMethodGenerator
import site.hackery.paramorphism.util.context.ObfuscationContext
import java.util.Random
class StringIndirectionStrategy(private val random: Random) : Strategy {
override val name: String = "String Indirection"
private lateinit var packagePrefix: String
private lateinit var methodFactory: GeneratedMethodFactory
private val stringMethods = LinkedHashMap<String, GeneratedMethod>()
override fun initialize(context: ObfuscationContext) {
packagePrefix = buildIndirectionPackagePrefix(context, random, rootPackageIndex = 1)
methodFactory = PackedMethodGenerator(packagePrefix, context.nameGenerator, random)
methodFactory.initialize(context.classes, context.resources)
}
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
for (method in classNode.methods) {
for (insn in method.instructions.toArray()) {
if (insn is LdcInsnNode && insn.cst is String) {
val value = insn.cst as String
val wrapper = stringMethods.getOrPut(value) {
methodFactory.createMethod("()Ljava/lang/String;").also { generated ->
generated.methodNode.instructions.apply {
add(LdcInsnNode(value))
add(InsnNode(Opcodes.ARETURN))
}
}
}
method.instructions.insert(
insn,
MethodInsnNode(Opcodes.INVOKESTATIC, wrapper.callOwner, wrapper.name, wrapper.descriptor, false)
)
method.instructions.remove(insn)
}
}
}
return super.transform(classNode, context)
}
override fun finish(context: ObfuscationContext) {
methodFactory.finish()
}
}
@@ -0,0 +1,12 @@
package site.hackery.paramorphism.strategy.indirection.generation
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
class GeneratedMethod(
val callOwner: String,
val name: String,
val descriptor: String,
val methodNode: MethodNode,
val bodyOwner: ClassNode
)
@@ -0,0 +1,12 @@
package site.hackery.paramorphism.strategy.indirection.generation
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.resources.ResourceSet
interface GeneratedMethodFactory {
fun initialize(classes: ClassSet, resources: ResourceSet)
fun createMethod(descriptor: String): GeneratedMethod
fun finish()
}
@@ -0,0 +1,107 @@
@file:JvmName("MethodGenerationUtils")
package site.hackery.paramorphism.strategy.indirection.generation
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.AbstractInsnNode
import org.objectweb.asm.tree.InsnList
import org.objectweb.asm.tree.InsnNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.VarInsnNode
import site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind
import site.hackery.paramorphism.util.context.ObfuscationContext
import java.util.Random
private val loadOpcodes = mapOf(
'B' to Opcodes.ILOAD,
'C' to Opcodes.ILOAD,
'D' to Opcodes.DLOAD,
'F' to Opcodes.FLOAD,
'I' to Opcodes.ILOAD,
'J' to Opcodes.LLOAD,
';' to Opcodes.ALOAD,
'S' to Opcodes.ILOAD,
'Z' to Opcodes.ILOAD
)
private val returnOpcodes = mapOf(
'B' to Opcodes.IRETURN,
'C' to Opcodes.IRETURN,
'D' to Opcodes.DRETURN,
'F' to Opcodes.FRETURN,
'I' to Opcodes.IRETURN,
'J' to Opcodes.LRETURN,
';' to Opcodes.ARETURN,
'S' to Opcodes.IRETURN,
'V' to Opcodes.RETURN,
'Z' to Opcodes.IRETURN
)
fun wrapperDescriptor(opcode: Int, owner: String, descriptor: String): String {
if (opcode == Opcodes.INVOKESTATIC) {
return descriptor
}
return Type.getMethodDescriptor(
Type.getReturnType(descriptor),
Type.getObjectType(owner),
*Type.getArgumentTypes(descriptor)
)
}
fun loadArguments(methodNode: MethodNode): InsnList =
loadArguments(methodNode.desc, if ((methodNode.access and Opcodes.ACC_STATIC) != 0) 0 else 1)
fun loadArguments(descriptor: String, initialIndex: Int = 0): InsnList {
val insns = InsnList()
var slotOffset = 0
for (argType in Type.getArgumentTypes(descriptor)) {
val typeDesc = argType.descriptor
val opcode = if (typeDesc.first() == '[') {
Opcodes.ALOAD
} else {
loadOpcodes.getOrDefault(typeDesc.last(), Opcodes.ALOAD)
}
insns.add(VarInsnNode(opcode, slotOffset + initialIndex))
slotOffset += if (opcode == Opcodes.DLOAD || opcode == Opcodes.LLOAD) 2 else 1
}
return insns
}
fun returnInstruction(methodNode: MethodNode): AbstractInsnNode =
returnInstruction(methodNode.desc)
fun returnInstruction(descriptor: String): AbstractInsnNode {
val returnDesc = Type.getReturnType(descriptor).descriptor
val opcode = if (returnDesc.first() == '[') {
Opcodes.ARETURN
} else {
returnOpcodes.getOrDefault(descriptor.last(), Opcodes.ARETURN)
}
return InsnNode(opcode)
}
internal fun buildIndirectionPackagePrefix(
context: ObfuscationContext,
random: Random,
rootPackageIndex: Int
): String {
val nameGenerator = context.nameGenerator
val prefixBuilder = StringBuilder()
prefixBuilder.append(nameGenerator.generateName(0, rootPackageIndex, MappingElementKind.PACKAGE))
prefixBuilder.append('/')
var slashCount = 0
var classCount = 0
for (className in context.classes.names()) {
slashCount += className.count { it == '/' }
classCount++
}
val avgDepth = if (classCount > 0) slashCount / classCount else 0
for (generation in 1..avgDepth) {
prefixBuilder.append(nameGenerator.generateName(generation, random.nextInt(avgDepth * 10), MappingElementKind.PACKAGE))
prefixBuilder.append('/')
}
return prefixBuilder.toString()
}
@@ -0,0 +1,53 @@
package site.hackery.paramorphism.strategy.indirection.generation.impl
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.resources.ResourceSet
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethod
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethodFactory
import site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind
import site.hackery.paramorphism.util.naming.NameGenerator
class DirectMethodGenerator(
private val packagePrefix: String,
private val nameGenerator: NameGenerator
) : GeneratedMethodFactory {
private lateinit var classes: ClassSet
private val generatedClasses = ArrayList<ClassNode>()
private var nextClassIndex = 0
private var methodCount = 0
private fun createClass(): ClassNode = ClassNode().apply {
access = Opcodes.ACC_PUBLIC
name = packagePrefix + nameGenerator.generateName(1, nextClassIndex, MappingElementKind.CLASS)!!
version = Opcodes.V1_8
superName = "java/lang/Object"
nextClassIndex++
}
override fun initialize(classes: ClassSet, resources: ResourceSet) {
this.classes = classes
generatedClasses.add(createClass())
}
override fun createMethod(descriptor: String): GeneratedMethod {
if (methodCount >= 1024) {
methodCount = 0
generatedClasses.add(createClass())
}
methodCount++
val targetClass = generatedClasses.last()
val methodName = nameGenerator.generateName(-1, methodCount - 1, MappingElementKind.METHOD)!!
val methodNode = MethodNode(Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC, methodName, descriptor, null, null)
targetClass.methods.add(methodNode)
return GeneratedMethod(targetClass.name, methodNode.name, methodNode.desc, methodNode, targetClass)
}
override fun finish() {
for (classNode in generatedClasses) {
classes.put(classNode.name, classNode)
}
}
}
@@ -0,0 +1,237 @@
package site.hackery.paramorphism.strategy.indirection.generation.impl
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.commons.ClassRemapper
import org.objectweb.asm.commons.SimpleRemapper
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FieldInsnNode
import org.objectweb.asm.tree.FieldNode
import org.objectweb.asm.tree.InsnNode
import org.objectweb.asm.tree.LdcInsnNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
import org.objectweb.asm.tree.TypeInsnNode
import org.objectweb.asm.tree.VarInsnNode
import site.hackery.paramorphism.resources.ByteArrayResource
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.resources.LazyResource
import site.hackery.paramorphism.resources.Resource
import site.hackery.paramorphism.resources.ResourceSet
import site.hackery.paramorphism.resources.TaggedResource
import site.hackery.paramorphism.runtime.PackedFileClassLoader
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethod
import site.hackery.paramorphism.strategy.indirection.generation.GeneratedMethodFactory
import site.hackery.paramorphism.strategy.indirection.generation.loadArguments
import site.hackery.paramorphism.strategy.indirection.generation.returnInstruction
import site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind
import site.hackery.paramorphism.util.naming.NameGenerator
import java.io.ByteArrayOutputStream
import java.util.Random
import java.util.zip.GZIPOutputStream
class PackedMethodGenerator(
private val packagePrefix: String,
private val nameGenerator: NameGenerator,
private val random: Random
) : GeneratedMethodFactory {
private val generatedClasses = ArrayList<ClassNode>()
private val generatedResources = ArrayList<Pair<String, Resource>>()
private lateinit var loaderClass: ClassNode
private lateinit var wrapperClass: ClassNode
private lateinit var interfaceClass: ClassNode
private lateinit var implementationClass: ClassNode
private lateinit var delegateField: FieldNode
private lateinit var classes: ClassSet
private lateinit var resources: ResourceSet
private var nextClassIndex = 0
private var methodCount = 0
override fun initialize(classes: ClassSet, resources: ResourceSet) {
this.classes = classes
this.resources = resources
val remappedLoaderName = packagePrefix +
nameGenerator.generateName(4, 0, MappingElementKind.CLASS) +
'/' +
nameGenerator.generateName(1, 0, MappingElementKind.CLASS)
val loaderType = PackedFileClassLoader::class.java
val loaderBytes = loaderType.getResourceAsStream("${loaderType.simpleName}.class")!!.use { it.readBytes() }
val originalInternalName = loaderType.canonicalName.replace('.', '/')
val loaderNode = ClassNode()
ClassReader(loaderBytes).accept(
ClassRemapper(loaderNode, SimpleRemapper(mapOf(originalInternalName to remappedLoaderName))),
ClassReader.SKIP_DEBUG or ClassReader.EXPAND_FRAMES
)
loaderClass = loaderNode
beginGroup()
}
override fun createMethod(descriptor: String): GeneratedMethod {
if (methodCount >= 2048) {
finishGroup()
beginGroup()
}
val methodName = nameGenerator.generateName(-1, methodCount, MappingElementKind.METHOD)!!
methodCount++
val wrapperMethod = MethodNode(Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC, methodName, descriptor, null, null)
wrapperClass.methods.add(wrapperMethod)
wrapperMethod.instructions.apply {
add(FieldInsnNode(Opcodes.GETSTATIC, wrapperClass.name, delegateField.name, delegateField.desc))
add(loadArguments(wrapperMethod.desc))
add(MethodInsnNode(Opcodes.INVOKEINTERFACE, interfaceClass.name, methodName, descriptor, true))
add(returnInstruction(wrapperMethod.desc))
}
interfaceClass.methods.add(
MethodNode(Opcodes.ACC_PUBLIC or Opcodes.ACC_ABSTRACT, methodName, descriptor, null, null)
)
val implMethod = MethodNode(Opcodes.ACC_PUBLIC, methodName, descriptor, null, null)
implementationClass.methods.add(implMethod)
return GeneratedMethod(wrapperClass.name, methodName, descriptor, implMethod, implementationClass)
}
override fun finish() {
if (methodCount != 0) {
finishGroup()
}
classes.put(loaderClass.name, loaderClass)
for (classNode in generatedClasses) {
classes.put(classNode.name, classNode)
}
for ((name, resource) in generatedResources) {
resources.put(name, resource)
}
}
private fun beginGroup() {
methodCount = 0
wrapperClass = createClass()
interfaceClass = createClass().apply {
access = Opcodes.ACC_PUBLIC or Opcodes.ACC_INTERFACE or Opcodes.ACC_ABSTRACT
}
implementationClass = createClass().apply {
interfaces.add(interfaceClass.name)
}
delegateField = FieldNode(
Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC,
"\ud83e\udd14",
"L${interfaceClass.name};",
null,
null
)
wrapperClass.fields.add(delegateField)
val initMethod = MethodNode(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null).apply {
instructions.add(VarInsnNode(Opcodes.ALOAD, 0))
instructions.add(MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false))
instructions.add(InsnNode(Opcodes.RETURN))
}
implementationClass.methods.add(initMethod)
}
private fun finishGroup() {
generatedClasses.add(wrapperClass)
val interfaceWriter = ClassWriter(ClassWriter.COMPUTE_MAXS)
interfaceClass.accept(interfaceWriter)
generatedResources.add(
"${interfaceClass.name}.class" to TaggedResource(
"assembled_class",
ByteArrayResource(interfaceWriter.toByteArray())
)
)
val packedEntryBase = implementationClass.name
implementationClass.name = "?"
val (unpackedSize, packedResource) = packClass(implementationClass)
generatedResources.add("$packedEntryBase.class" to packedResource)
val clinit = MethodNode(Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC, "<clinit>", "()V", null, null).apply {
instructions.add(TypeInsnNode(Opcodes.NEW, loaderClass.name))
instructions.add(InsnNode(Opcodes.DUP))
instructions.add(LdcInsnNode(Type.getObjectType(wrapperClass.name)))
instructions.add(
MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getClassLoader", "()Ljava/lang/ClassLoader;", false)
)
instructions.add(LdcInsnNode("$packedEntryBase.class"))
instructions.add(LdcInsnNode(unpackedSize))
instructions.add(
MethodInsnNode(
Opcodes.INVOKESPECIAL,
loaderClass.name,
"<init>",
"(Ljava/lang/ClassLoader;Ljava/lang/String;I)V",
false
)
)
instructions.add(LdcInsnNode(implementationClass.name.replace('/', '.')))
instructions.add(
MethodInsnNode(
Opcodes.INVOKEVIRTUAL,
loaderClass.name,
"createClass",
"(Ljava/lang/String;)Ljava/lang/Class;",
false
)
)
instructions.add(
MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "newInstance", "()Ljava/lang/Object;", false)
)
instructions.add(FieldInsnNode(Opcodes.PUTSTATIC, wrapperClass.name, delegateField.name, delegateField.desc))
instructions.add(InsnNode(Opcodes.RETURN))
}
wrapperClass.methods.add(clinit)
}
private fun packClass(classNode: ClassNode): Pair<Int, Resource> {
val writer = ClassWriter(ClassWriter.COMPUTE_MAXS)
classNode.accept(writer)
val rawBytes = writer.toByteArray()
val resource = TaggedResource(
"assembled_class",
LazyResource({
val buffer = ByteArrayOutputStream()
GZIPOutputStream(buffer).use { it.write(rawBytes) }
val packed = buffer.toByteArray()
// Disguise the GZIP header as a Java 13 classfile header; PackedFileClassLoader restores it at runtime.
packed[0] = 0xCA.toByte()
packed[1] = 0xFE.toByte()
packed[2] = 0xBA.toByte()
packed[3] = 0xBE.toByte()
packed[4] = 0
packed[5] = 0
packed[6] = 0
packed[7] = 57
val salt = ByteArray(2)
random.nextBytes(salt)
packed[8] = salt[0]
packed[9] = salt[1]
packed
})
)
return rawBytes.size to resource
}
private fun createClass(): ClassNode = ClassNode().apply {
access = Opcodes.ACC_PUBLIC
name = packagePrefix + nameGenerator.generateName(0, nextClassIndex, MappingElementKind.CLASS)!!
version = Opcodes.V1_8
superName = "java/lang/Object"
nextClassIndex++
}
}
@@ -0,0 +1,42 @@
package site.hackery.paramorphism.strategy.kotlin
import org.objectweb.asm.Type
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.LdcInsnNode
import org.objectweb.asm.tree.MethodInsnNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.util.context.ObfuscationContext
import site.hackery.paramorphism.util.logging.LogLevel
import site.hackery.paramorphism.util.logging.Logger
class KotlinIntrinsicsConcealmentStrategy : Strategy {
override val name: String = "Kotlin Intrinsics Concealment"
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
for (method in classNode.methods) {
for ((index, insn) in method.instructions.iterator().withIndex()) {
if (insn is MethodInsnNode &&
insn.owner == "kotlin/jvm/internal/Intrinsics" &&
insn.desc.contains("Ljava/lang/String;")
) {
val argTypes = Type.getArgumentTypes(insn.desc)
val lastStringArgIndex = argTypes.indices.reversed()
.firstOrNull { argTypes[it].internalName == "java/lang/String" }
?: -1
val offsetFromEnd = argTypes.size - lastStringArgIndex
val targetIndex = index - offsetFromEnd
val targetInsn = if (targetIndex >= 0) method.instructions[targetIndex] else null
if (targetInsn is LdcInsnNode) {
targetInsn.cst = "[REDACTED]"
} else {
Logger.log(
LogLevel.WARNING,
"Kotlin Intrinsics Concealment: Estimated string constant load instruction was not 'LDC' - Is the Kotlin compiler being weird?"
)
}
}
}
}
return super.transform(classNode, context)
}
}
@@ -0,0 +1,22 @@
package site.hackery.paramorphism.strategy.kotlin
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.util.context.ObfuscationContext
class KotlinMetadataScrubbingStrategy : Strategy {
override val name: String = "Kotlin Metadata Scrubbing"
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
classNode.visibleAnnotations?.removeIf { it.desc == "Lkotlin/Metadata;" }
return super.transform(classNode, context)
}
override fun finish(context: ObfuscationContext) {
for (resourceName in context.resources.names().toList()) {
if (resourceName.endsWith(".kotlin_module")) {
context.resources.put(resourceName, null)
}
}
}
}
@@ -0,0 +1,48 @@
package site.hackery.paramorphism.strategy.renaming
import org.objectweb.asm.commons.Remapper
class CachingRemapper(private val delegate: Remapper) : Remapper() {
private val classNames = LinkedHashMap<String, String>()
private val methodNames = LinkedHashMap<String, String>()
private val fieldNames = LinkedHashMap<String, String>()
override fun map(internalName: String): String =
classNames.getOrPut(internalName) { delegate.map(internalName) }
override fun mapMethodName(owner: String, name: String, descriptor: String): String =
methodNames.getOrPut("$owner $name $descriptor") { delegate.mapMethodName(owner, name, descriptor) }
override fun mapFieldName(owner: String?, name: String?, descriptor: String?): String =
fieldNames.getOrPut("$owner $name $descriptor") { delegate.mapFieldName(owner, name, descriptor) }
override fun mapInvokeDynamicMethodName(name: String?, descriptor: String?): String =
delegate.mapInvokeDynamicMethodName(name, descriptor)
override fun mapTypes(internalNames: Array<out String>?): Array<String> =
delegate.mapTypes(internalNames)
override fun mapMethodDesc(methodDescriptor: String?): String =
delegate.mapMethodDesc(methodDescriptor)
override fun mapInnerClassName(name: String?, ownerName: String?, innerName: String?): String? =
delegate.mapInnerClassName(name, ownerName, innerName)
override fun mapSignature(signature: String?, typeSignature: Boolean): String? =
delegate.mapSignature(signature, typeSignature)
override fun mapModuleName(name: String?): String? =
delegate.mapModuleName(name)
override fun mapPackageName(name: String?): String? =
delegate.mapPackageName(name)
override fun mapValue(value: Any?): Any? =
delegate.mapValue(value)
override fun mapType(internalName: String?): String? =
delegate.mapType(internalName)
override fun mapDesc(descriptor: String?): String? =
delegate.mapDesc(descriptor)
}
@@ -0,0 +1,137 @@
package site.hackery.paramorphism.strategy.renaming
import org.objectweb.asm.commons.Remapper
import site.hackery.paramorphism.config.ElementMask
import site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind
import site.hackery.paramorphism.strategy.renaming.tree.MappingNode
import site.hackery.paramorphism.strategy.renaming.tree.MappingNodeUtils
import site.hackery.paramorphism.strategy.renaming.tree.MappingTree
import site.hackery.paramorphism.util.context.ObfuscationContext
import site.hackery.paramorphism.util.hierarchy.ClassHierarchyNode
import site.hackery.paramorphism.util.naming.NameGenerator
class MappingTreeRemapper(
val context: ObfuscationContext,
val mappingTree: MappingTree,
val nameGenerator: NameGenerator,
val globalMask: ElementMask,
val localMask: ElementMask?,
val hierarchy: Map<String, ClassHierarchyNode>,
val lambdaMappings: Map<String, MappingNode>,
val mainClass: String? = null
) : Remapper() {
private val methodSignaturesByClass: Map<String, List<String>> =
context.classes.entries().associate { (name, classNode) ->
name to classNode.methods.map { "${it.name}${it.desc}" }
}
fun shouldRename(internalName: String): Boolean =
globalMask.matches(internalName) && (localMask?.matches(internalName) ?: true)
override fun map(internalName: String): String {
val node = MappingNodeUtils.findNode(mappingTree.root, internalName)
if (node == null || !shouldRename(internalName)) {
return super.map(internalName)
}
val mappedBuilder = StringBuilder()
var current: MappingNode? = node
while (current != null) {
val parent = current.parent
val segment = StringBuilder()
if (parent != null && parent.kind == MappingElementKind.CLASS) {
segment.append('$')
}
val generatedName = current.index?.let { idx ->
nameGenerator.generateName(current.generation, idx, current.kind)
} ?: current.name
segment.append(generatedName)
if (parent != null && current.kind == MappingElementKind.PACKAGE) {
segment.append('/')
}
mappedBuilder.insert(0, segment.toString())
current = parent
}
val mapped = mappedBuilder.toString()
val inMainPackage = mainClass != null && packageName(internalName) == packageName(mainClass)
return if (inMainPackage) mapped.replace("\u0000", "") else mapped
}
override fun mapMethodName(owner: String, name: String, descriptor: String): String {
fun resolve(currentOwner: String): String? {
val hierarchyNode = hierarchy[currentOwner]
if (shouldRename(currentOwner)) {
val methodMapping = MappingNodeUtils.findNode(mappingTree.root, currentOwner)
?.children
?.get("$name $descriptor")
val index = methodMapping?.index
if (index != null) {
val generated = nameGenerator.generateName(-1, index, MappingElementKind.METHOD)
if (generated != null) {
var candidate = generated
val existingSignatures = methodSignaturesByClass[currentOwner]
if (existingSignatures != null) {
while (existingSignatures.contains("$candidate$descriptor")) {
candidate = "_$candidate"
}
}
return candidate
}
}
}
if (hierarchyNode != null) {
hierarchyNode.superClass?.let { superClass ->
resolve(superClass.name)?.let { return it }
}
for (iface in hierarchyNode.interfaces) {
resolve(iface.name)?.let { return it }
}
}
return null
}
return resolve(owner) ?: super.mapMethodName(owner, name, descriptor)
}
override fun mapFieldName(owner: String, name: String, descriptor: String): String {
fun resolve(currentOwner: String): String? {
val hierarchyNode = hierarchy[currentOwner]
if (shouldRename(currentOwner)) {
val fieldMapping = MappingNodeUtils.findNode(mappingTree.root, currentOwner)
?.children
?.get("$name $descriptor")
val index = fieldMapping?.index
if (index != null) {
val generated = nameGenerator.generateName(-1, index, MappingElementKind.FIELD)
if (generated != null) {
return generated
}
}
}
if (hierarchyNode != null) {
hierarchyNode.superClass?.let { superClass ->
resolve(superClass.name)?.let { return it }
}
for (iface in hierarchyNode.interfaces) {
resolve(iface.name)?.let { return it }
}
}
return null
}
return resolve(owner) ?: super.mapFieldName(owner, name, descriptor)
}
override fun mapInvokeDynamicMethodName(name: String, descriptor: String): String {
val mappedNode = lambdaMappings["$name $descriptor"] ?: return name
val ownerPath = mappedNode.parent!!.getPath()
val (samName, samDesc) = mappedNode.name.split(" ")
return mapMethodName(ownerPath, samName, samDesc)
}
private fun packageName(internalName: String): String {
val lastSlash = internalName.lastIndexOf('/')
return if (lastSlash == -1) "" else internalName.substring(0, lastSlash)
}
}
@@ -0,0 +1,74 @@
package site.hackery.paramorphism.strategy.renaming
import org.objectweb.asm.commons.ClassRemapper
import org.objectweb.asm.commons.Remapper
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.strategy.Strategy
import site.hackery.paramorphism.strategy.renaming.assignment.MappingIndexAssignment
import site.hackery.paramorphism.strategy.renaming.lambda.LambdaMappingUtils
import site.hackery.paramorphism.strategy.renaming.tree.MappingTree
import site.hackery.paramorphism.strategy.renaming.tree.MappingTreeBuilder
import site.hackery.paramorphism.util.context.ObfuscationContext
import site.hackery.paramorphism.util.hierarchy.ClassHierarchyBuilder
import site.hackery.paramorphism.util.logging.PerformanceProfiler
import java.util.jar.Attributes
class RenamingStrategy : Strategy {
override val name: String = "Remapper"
private lateinit var mappingTree: MappingTree
private lateinit var remapper: Remapper
override fun runsOnExcludedClasses(): Boolean = true
override fun initialize(context: ObfuscationContext) {
mappingTree = PerformanceProfiler.measurePhase("Mapping Tree Generation") {
MappingTreeBuilder.buildTree(context.classes, context)
}
val hierarchy = PerformanceProfiler.measurePhase("Build Hierarchy Map") {
ClassHierarchyBuilder.buildHierarchy(context.classes, context.libraries)
}
PerformanceProfiler.measurePhase("Mapping Application") {
MappingIndexAssignment.assignIndices(mappingTree, hierarchy, context)
}
val lambdaMappings = PerformanceProfiler.measurePhase("Invoke Dynamic") {
LambdaMappingUtils.collectLambdaMappings(mappingTree, context.classes, hierarchy)
}
val redirectMain = context.config.getValue("remapper.redirect_main", Boolean::class.javaObjectType) ?: true
val mainClassInternal = if (redirectMain) {
(context.manifest.mainAttributes[Attributes.Name.MAIN_CLASS] as? String)?.replace('.', '/')
} else {
null
}
remapper = CachingRemapper(
MappingTreeRemapper(
context = context,
mappingTree = mappingTree,
nameGenerator = context.nameGenerator,
globalMask = context.globalMask,
localMask = context.localMask,
hierarchy = hierarchy,
lambdaMappings = lambdaMappings,
mainClass = mainClassInternal
)
)
}
override fun transform(classNode: ClassNode, context: ObfuscationContext): ClassNode {
val remappedNode = ClassNode()
classNode.accept(ClassRemapper(remappedNode, remapper))
val redirectMain = context.config.getValue("remapper.redirect_main", Boolean::class.javaObjectType) ?: true
if (redirectMain) {
val mainAttributes = context.manifest.mainAttributes
val configuredMain = mainAttributes[Attributes.Name.MAIN_CLASS]
if (configuredMain == classNode.name.replace('/', '.')) {
mainAttributes[Attributes.Name.MAIN_CLASS] = remappedNode.name.replace('/', '.')
}
}
return remappedNode
}
}
@@ -0,0 +1,31 @@
package site.hackery.paramorphism.strategy.renaming.assignment
import org.objectweb.asm.Opcodes
import site.hackery.paramorphism.config.ConfigFlags
import site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind
import site.hackery.paramorphism.strategy.renaming.tree.MappingNode
import site.hackery.paramorphism.strategy.renaming.tree.MappingNodeUtils
import site.hackery.paramorphism.util.context.ObfuscationContext
object ClassIndexAssignment {
fun assignClassIndices(node: MappingNode, context: ObfuscationContext) {
val flags = context.getService(ConfigFlags::class.java)
val retainEnumNames = flags["retain_enum_simple_name"] ?: false
var nextIndex = 0
for (child in node.children.values) {
if (child.kind != MappingElementKind.PACKAGE && child.kind != MappingElementKind.CLASS) {
continue
}
if (retainEnumNames && child.kind == MappingElementKind.CLASS) {
val classNode = context.classes.get(MappingNodeUtils.internalName(child))
if (classNode != null && (classNode.access and Opcodes.ACC_ENUM) != 0) {
child.index = -1
continue
}
}
child.index = nextIndex++
assignClassIndices(child, context)
}
}
}
@@ -0,0 +1,27 @@
package site.hackery.paramorphism.strategy.renaming.assignment
import org.objectweb.asm.Opcodes
import site.hackery.paramorphism.config.ConfigFlags
import site.hackery.paramorphism.strategy.renaming.tree.MappingNodeUtils
import site.hackery.paramorphism.strategy.renaming.tree.MappingTree
import site.hackery.paramorphism.util.ReservedMembers
import site.hackery.paramorphism.util.context.ObfuscationContext
object FieldIndexAssignment {
fun assignFieldIndices(mappingTree: MappingTree, context: ObfuscationContext) {
val allocator = ScopedIndexAllocator()
val flags = context.getService(ConfigFlags::class.java)
val retainEnumFieldNames = flags["retain_enum_field_names"] ?: false
for (fieldMapping in mappingTree.fields) {
val ownerName = MappingNodeUtils.internalName(fieldMapping.parent!!)
val ownerClass = context.classes.get(ownerName)!!
val (fieldName, fieldDesc) = fieldMapping.name.split(" ")
val keepOriginal = (retainEnumFieldNames && (ownerClass.access and Opcodes.ACC_ENUM) != 0) ||
ReservedMembers.isReservedField(ownerClass, fieldName, fieldDesc)
fieldMapping.index = if (keepOriginal) -1 else allocator.allocate("")
}
}
}
@@ -0,0 +1,17 @@
package site.hackery.paramorphism.strategy.renaming.assignment
import site.hackery.paramorphism.strategy.renaming.tree.MappingTree
import site.hackery.paramorphism.util.context.ObfuscationContext
import site.hackery.paramorphism.util.hierarchy.ClassHierarchyNode
object MappingIndexAssignment {
fun assignIndices(
mappingTree: MappingTree,
hierarchy: Map<String, ClassHierarchyNode>,
context: ObfuscationContext
) {
ClassIndexAssignment.assignClassIndices(mappingTree.root, context)
MethodIndexAssignment.assignMethodIndices(mappingTree, hierarchy, context)
FieldIndexAssignment.assignFieldIndices(mappingTree, context)
}
}
@@ -0,0 +1,72 @@
package site.hackery.paramorphism.strategy.renaming.assignment
import site.hackery.paramorphism.strategy.renaming.tree.MappingNode
import site.hackery.paramorphism.strategy.renaming.tree.MappingNodeUtils
import site.hackery.paramorphism.strategy.renaming.tree.MappingTree
import site.hackery.paramorphism.util.ReservedMembers
import site.hackery.paramorphism.util.context.ObfuscationContext
import site.hackery.paramorphism.util.hierarchy.ClassHierarchyNode
object MethodIndexAssignment {
fun assignMethodIndices(
mappingTree: MappingTree,
hierarchy: Map<String, ClassHierarchyNode>,
context: ObfuscationContext
) {
val signatureIndices = LinkedHashMap<String, Int>()
val allocator = ScopedIndexAllocator()
for (methodMapping in mappingTree.methods) {
val ownerName = MappingNodeUtils.internalName(methodMapping.parent!!)
val ownerClass = context.classes.get(ownerName)!!
val (methodName, methodDesc) = methodMapping.name.split(" ")
if (ReservedMembers.isReservedMethod(ownerClass, methodName, methodDesc)) {
continue
}
val ancestors = declaringAncestors(methodMapping, hierarchy)
val allAncestorsRemappable = ancestors.all { MappingNodeUtils.findNode(mappingTree.root, it.name) != null }
if (!allAncestorsRemappable) {
methodMapping.index = -1
} else if (!signatureIndices.containsKey(methodMapping.name)) {
val closeParen = methodDesc.lastIndexOf(')')
val parameterScope = if (closeParen >= 0) methodDesc.substring(0, closeParen + 1) else ""
signatureIndices[methodMapping.name] = allocator.allocate(parameterScope)
}
}
for (methodMapping in mappingTree.methods) {
if (methodMapping.index == null) {
methodMapping.index = signatureIndices[methodMapping.name] ?: -1
}
}
}
private fun declaringAncestors(
methodMapping: MappingNode,
hierarchy: Map<String, ClassHierarchyNode>
): List<ClassHierarchyNode> {
val ownerName = MappingNodeUtils.internalName(methodMapping.parent!!)
val ownerNode = hierarchy.getValue(ownerName)
val ancestors = ArrayList<ClassHierarchyNode>()
fun visit(node: ClassHierarchyNode) {
for (iface in node.interfaces) {
if (iface.methodSignatures.contains(methodMapping.name)) {
ancestors.add(iface)
}
visit(iface)
}
node.superClass?.let { superNode ->
if (superNode.methodSignatures.contains(methodMapping.name)) {
ancestors.add(superNode)
}
visit(superNode)
}
}
visit(ownerNode)
return ancestors
}
}
@@ -0,0 +1,35 @@
package site.hackery.paramorphism.strategy.renaming.assignment
import java.util.Stack
class ScopedIndexAllocator {
private val nextIndices = LinkedHashMap<String, Int>()
private val reusableIndices = LinkedHashMap<String, Stack<Int>>()
private val reservedIndices = LinkedHashMap<String, MutableSet<Int>>()
fun allocate(scope: String): Int {
var next = nextIndices.getOrPut(scope) { 0 }
val reusable = reusableIndices.getOrPut(scope) { Stack() }
val reserved = reservedIndices.getOrPut(scope) { LinkedHashSet() }
var candidate: Int
do {
candidate = if (reusable.isNotEmpty() && reusable.peek() <= next) {
reusable.pop()
} else {
next++
}
nextIndices[scope] = next
} while (reserved.contains(candidate))
return candidate
}
fun release(scope: String, index: Int) {
reusableIndices.getOrPut(scope) { Stack() }.push(index)
}
fun reserve(scope: String, index: Int) {
reservedIndices.getOrPut(scope) { LinkedHashSet() }.add(index)
}
}
@@ -0,0 +1,38 @@
package site.hackery.paramorphism.strategy.renaming.lambda
import org.objectweb.asm.Type
import org.objectweb.asm.tree.InvokeDynamicInsnNode
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.strategy.renaming.tree.MappingNode
import site.hackery.paramorphism.strategy.renaming.tree.MappingNodeUtils
import site.hackery.paramorphism.strategy.renaming.tree.MappingTree
import site.hackery.paramorphism.util.hierarchy.ClassHierarchyNode
object LambdaMappingUtils {
fun collectLambdaMappings(
mappingTree: MappingTree,
classes: ClassSet,
hierarchy: Map<String, ClassHierarchyNode>
): Map<String, MappingNode> {
val mappings = LinkedHashMap<String, MappingNode>()
for (indy in invokeDynamicInstructions(classes)) {
if (indy.bsm.owner == "java/lang/invoke/LambdaMetafactory" && indy.bsm.name == "metafactory") {
val samMethodName = indy.name
val samMethodDesc = indy.bsmArgs[0].toString()
val functionalInterface = Type.getReturnType(indy.desc).internalName
val hierarchyNode = hierarchy[functionalInterface] ?: continue
val classMapping = MappingNodeUtils.findNode(mappingTree.root, hierarchyNode.name) ?: continue
val methodMapping = classMapping.children["$samMethodName $samMethodDesc"] ?: continue
mappings["${indy.name} ${indy.desc}"] = methodMapping
}
}
return mappings
}
private fun invokeDynamicInstructions(classes: ClassSet): Sequence<InvokeDynamicInsnNode> =
classes.entries()
.map { (_, classNode) -> classNode }
.flatMap { it.methods.asSequence() }
.flatMap { it.instructions.iterator().asSequence() }
.filterIsInstance<InvokeDynamicInsnNode>()
}
@@ -0,0 +1,39 @@
package site.hackery.paramorphism.strategy.renaming.tree
class MappingNode(
val name: String,
val kind: MappingElementKind,
val parent: MappingNode?
) {
var index: Int? = null
val children: MutableMap<String, MappingNode> = LinkedHashMap()
val generation: Int by lazy {
var depth = 0
var current: MappingNode? = this
while (current != null) {
depth++
current = current.parent
}
depth
}
fun addChild(name: String, kind: MappingElementKind): MappingNode {
val child = MappingNode(name, kind, this)
children[name] = child
return child
}
fun getPath(): String {
val builder = StringBuilder()
var current: MappingNode? = this
while (current != null) {
builder.insert(0, current.name)
if (current.parent?.parent != null) {
builder.insert(0, '/')
}
current = current.parent
}
return builder.toString()
}
}
@@ -0,0 +1,30 @@
package site.hackery.paramorphism.strategy.renaming.tree
object MappingNodeUtils {
fun findNode(root: MappingNode, internalName: String): MappingNode? {
var current: MappingNode? = root
for (segment in internalName.split('/', '$')) {
current = current?.children?.get(segment) ?: return null
}
return current
}
fun internalName(node: MappingNode): String {
val builder = StringBuilder()
var current: MappingNode? = node
while (current != null) {
val parent = current.parent
val part = StringBuilder()
if (parent != null && parent.kind == MappingElementKind.CLASS) {
part.append('$')
}
part.append(current.name)
if (parent != null && current.kind == MappingElementKind.PACKAGE) {
part.append('/')
}
builder.insert(0, part.toString())
current = parent
}
return builder.toString()
}
}
@@ -0,0 +1,8 @@
package site.hackery.paramorphism.strategy.renaming.tree
class MappingTree(
val root: MappingNode,
val classes: List<MappingNode>,
val methods: List<MappingNode>,
val fields: List<MappingNode>
)
@@ -0,0 +1,53 @@
package site.hackery.paramorphism.strategy.renaming.tree
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.util.context.ObfuscationContext
object MappingTreeBuilder {
fun buildTree(classes: ClassSet, context: ObfuscationContext): MappingTree {
val root = MappingNode("", MappingElementKind.PACKAGE, null)
val classNodes = ArrayList<MappingNode>()
val methodNodes = ArrayList<MappingNode>()
val fieldNodes = ArrayList<MappingNode>()
for ((name, classNode) in classes.entries()) {
val matchesMasks = context.globalMask.matches(name) &&
(context.localMask?.matches(name) ?: true)
if (!matchesMasks) {
continue
}
val classMapping = addClassPath(root, classNode.name)
classNodes.add(classMapping)
for (method in classNode.methods) {
methodNodes.add(classMapping.addChild("${method.name} ${method.desc}", MappingElementKind.METHOD))
}
for (field in classNode.fields) {
fieldNodes.add(classMapping.addChild("${field.name} ${field.desc}", MappingElementKind.FIELD))
}
}
return MappingTree(root, classNodes, methodNodes, fieldNodes)
}
private fun addClassPath(root: MappingNode, internalName: String): MappingNode {
val segments = internalName.split('/')
var current = root
for ((index, segment) in segments.withIndex()) {
val innerParts = segment.split('$')
if (innerParts.size > 1) {
for (innerPart in innerParts) {
current = getOrCreateChild(current, innerPart, MappingElementKind.CLASS)
}
} else {
val kind = if (index == segments.lastIndex) MappingElementKind.CLASS else MappingElementKind.PACKAGE
current = getOrCreateChild(current, segment, kind)
}
}
return current
}
private fun getOrCreateChild(parent: MappingNode, name: String, kind: MappingElementKind): MappingNode =
parent.children[name] ?: parent.addChild(name, kind)
}
@@ -0,0 +1,9 @@
package site.hackery.paramorphism.update
class UpdateCheckThread : Thread("Paramorphism Update Thread") {
var updateInformation: Array<String>? = null
override fun run() {
// no
}
}
@@ -0,0 +1,5 @@
package site.hackery.paramorphism.update
object UpdateEndpoint {
const val UPDATE_URL: String = "https://musee.paramorphism.serenity.enterprises"
}
@@ -0,0 +1,9 @@
package site.hackery.paramorphism.util
import java.util.Random
class RandomContext(seed: Long) {
private val random = Random(seed)
fun getRandom(): Random = Random(random.nextLong())
}
@@ -0,0 +1,35 @@
package site.hackery.paramorphism.util
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
object ReservedMembers {
fun isReservedMethod(classNode: ClassNode, name: String, descriptor: String): Boolean {
if ((classNode.access and Opcodes.ACC_ANNOTATION) != 0) {
return true
}
if (name == "<init>" || name == "<clinit>") {
return true
}
if (name == "main" && descriptor == "([Ljava/lang/String;)V") {
return true
}
if (name == "premain" || name == "agentmain") {
return true
}
if ((classNode.access and Opcodes.ACC_ENUM) != 0) {
if (name == "values" && descriptor == "()[L${classNode.name};") {
return true
}
if (name == "valueOf" && descriptor == "(Ljava/lang/String;)L${classNode.name};") {
return true
}
}
return false
}
fun isReservedField(classNode: ClassNode, name: String, descriptor: String): Boolean =
(classNode.access and Opcodes.ACC_ENUM) != 0 &&
name == "\$VALUES" &&
descriptor == "[L${classNode.name};"
}
@@ -0,0 +1,25 @@
package site.hackery.paramorphism.util.context
class ContextStore {
private val namedValues = LinkedHashMap<String, Any?>()
private val typedValues = LinkedHashMap<Class<*>, Any>()
fun putNamed(key: String, value: Any?) {
if (value == null) {
namedValues.remove(key)
} else {
namedValues[key] = value
}
}
fun namedProperty(key: String): NamedContextProperty = NamedContextProperty(key, namedValues)
fun <T : Any> putTyped(value: T, type: Class<T>) {
typedValues[type] = value
}
@Suppress("UNCHECKED_CAST")
fun <T> getTyped(type: Class<T>): T = typedValues[type] as T
fun <T> typedProperty(type: Class<T>): TypedContextProperty = TypedContextProperty(type, typedValues)
}
@@ -0,0 +1,26 @@
package site.hackery.paramorphism.util.context
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.ResourceSet
import site.hackery.paramorphism.util.naming.NameGenerator
import java.util.jar.Manifest
class MutableObfuscationContext(private val store: ContextStore) {
var config: ParamorphismConfig by store.typedProperty(ParamorphismConfig::class.java)
var classes: ClassSet by store.typedProperty(ClassSet::class.java)
var resources: ResourceSet by store.typedProperty(ResourceSet::class.java)
var libraries: ClassSetGroup by store.namedProperty("libraries")
var globalMask: ElementMask by store.namedProperty("globalMask")
var localMask: ElementMask? by store.namedProperty("localMask")
var nameGenerator: NameGenerator by store.typedProperty(NameGenerator::class.java)
var manifest: Manifest by store.typedProperty(Manifest::class.java)
fun <T> getService(type: Class<T>): T = store.getTyped(type)
fun <T : Any> putService(type: Class<T>, value: T) {
store.putTyped(value, type)
}
}
@@ -0,0 +1,15 @@
package site.hackery.paramorphism.util.context
import kotlin.reflect.KProperty
class NamedContextProperty(
val key: String,
val values: MutableMap<String, Any?>
) {
inline operator fun <reified T> getValue(thisRef: Any?, property: KProperty<*>): T =
values[key] as T
operator fun <T> setValue(thisRef: Any?, property: KProperty<*>, value: T) {
values[key] = value
}
}
@@ -0,0 +1,22 @@
package site.hackery.paramorphism.util.context
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.ResourceSet
import site.hackery.paramorphism.util.naming.NameGenerator
import java.util.jar.Manifest
class ObfuscationContext(private val store: ContextStore) {
val config: ParamorphismConfig by store.typedProperty(ParamorphismConfig::class.java)
val classes: ClassSet by store.typedProperty(ClassSet::class.java)
val resources: ResourceSet by store.typedProperty(ResourceSet::class.java)
val libraries: ClassSetGroup by store.namedProperty("libraries")
val globalMask: ElementMask by store.namedProperty("globalMask")
val localMask: ElementMask? by store.namedProperty("localMask")
val nameGenerator: NameGenerator by store.typedProperty(NameGenerator::class.java)
val manifest: Manifest by store.typedProperty(Manifest::class.java)
fun <T> getService(type: Class<T>): T = store.getTyped(type)
}
@@ -0,0 +1,15 @@
package site.hackery.paramorphism.util.context
import kotlin.reflect.KProperty
class TypedContextProperty(
val keyType: Class<*>,
val values: MutableMap<Class<*>, Any>
) {
inline operator fun <reified T> getValue(thisRef: Any?, property: KProperty<*>): T =
values[keyType] as T
operator fun <T : Any> setValue(thisRef: Any?, property: KProperty<*>, value: T) {
values[keyType] = value
}
}
@@ -0,0 +1,70 @@
package site.hackery.paramorphism.util.hierarchy
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
import site.hackery.paramorphism.resources.ClassSet
import site.hackery.paramorphism.resources.ClassSetGroup
import site.hackery.paramorphism.util.logging.LogLevel
import site.hackery.paramorphism.util.logging.Logger
object ClassHierarchyBuilder {
private val missingDependencies = LinkedHashSet<String>()
fun buildHierarchy(classes: ClassSet, libraries: ClassSetGroup): Map<String, ClassHierarchyNode> {
val hierarchy = LinkedHashMap<String, ClassHierarchyNode>()
for (className in classes.names()) {
buildNode(className, classes, libraries, hierarchy)
}
return hierarchy
}
private fun findClass(internalName: String, classes: ClassSet, libraries: ClassSetGroup): ClassNode? =
if (classes.contains(internalName)) classes.get(internalName) else libraries.get(internalName)
private fun buildNode(
internalName: String,
classes: ClassSet,
libraries: ClassSetGroup,
hierarchy: MutableMap<String, ClassHierarchyNode>
): ClassHierarchyNode? {
hierarchy[internalName]?.let { return it }
val classNode = findClass(internalName, classes, libraries)
if (classNode == null) {
if (missingDependencies.add(internalName)) {
Logger.log(
LogLevel.WARNING,
"Could not find dependency class '$internalName' - Is there an unspecified library?"
)
}
return null
}
val overridableFlagMask = Opcodes.ACC_PRIVATE or Opcodes.ACC_FINAL
val methodSignatures = classNode.methods
.filter { !it.name.startsWith("<") && (it.access and overridableFlagMask) == 0 }
.map { "${it.name} ${it.desc}" }
.toTypedArray()
val fieldSignatures = classNode.fields
.filter { (it.access and overridableFlagMask) == 0 }
.map { "${it.name} ${it.desc}" }
.toTypedArray()
val superNode = classNode.superName?.let { buildNode(it, classes, libraries, hierarchy) }
val interfaceNodes = classNode.interfaces
?.mapNotNull { buildNode(it, classes, libraries, hierarchy) }
?.toTypedArray()
?: emptyArray()
val node = ClassHierarchyNode(
classNode.name,
methodSignatures,
fieldSignatures,
superNode,
interfaceNodes
)
hierarchy[internalName] = node
return node
}
}
@@ -0,0 +1,9 @@
package site.hackery.paramorphism.util.hierarchy
class ClassHierarchyNode(
val name: String,
val methodSignatures: Array<String>,
val fieldSignatures: Array<String>,
val superClass: ClassHierarchyNode?,
val interfaces: Array<ClassHierarchyNode>
)
@@ -0,0 +1,9 @@
package site.hackery.paramorphism.util.logging
enum class LogLevel(val label: String) {
ERROR("ERROR"),
WARNING("WARN"),
INFO("INFO"),
DEBUG("DEBUG"),
PERFORMANCE("PERF")
}
@@ -0,0 +1,36 @@
package site.hackery.paramorphism.util.logging
import java.io.BufferedWriter
import java.io.FileDescriptor
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.io.PrintWriter
import kotlin.concurrent.thread
object Logger {
val writer: PrintWriter = PrintWriter(
BufferedWriter(OutputStreamWriter(FileOutputStream(FileDescriptor.out), Charsets.UTF_8), 256)
).also { printWriter ->
Runtime.getRuntime().addShutdownHook(thread(start = false) {
printWriter.flush()
})
}
var verbosity: Int = LogLevel.DEBUG.ordinal
fun log(level: LogLevel, message: String, newLine: Boolean = true) {
if (level.ordinal <= verbosity) {
val formatted = "[${level.label}] $message"
if (newLine) {
writer.println(formatted)
} else {
writer.print(formatted)
}
writer.flush()
}
}
fun log(message: String, newLine: Boolean = true) {
log(LogLevel.INFO, message, newLine)
}
}
@@ -0,0 +1,78 @@
package site.hackery.paramorphism.util.logging
import java.util.Stack
object PerformanceProfiler {
val phaseStartTimes = Stack<Long>()
val phaseNames = Stack<String>()
val sectionTimings = Stack<MutableMap<String, Long>>()
val activeSections = Stack<String?>()
val sectionStartTimes = Stack<Long>()
fun beginPhase(phaseName: String) {
phaseStartTimes.push(System.nanoTime())
phaseNames.push(phaseName)
if (Logger.verbosity >= LogLevel.PERFORMANCE.ordinal) {
Logger.log(LogLevel.PERFORMANCE, "${" ".repeat(phaseNames.size)}$phaseName...")
} else {
val depth = phaseNames.size
if (depth < 3) {
Logger.log(LogLevel.INFO, "${"=".repeat(depth)}> $phaseName")
}
}
}
fun endPhase(): Double {
val elapsedMillis = (System.nanoTime() - phaseStartTimes.pop()) * 1.0E-6
Logger.log(
LogLevel.PERFORMANCE,
"${" ".repeat(phaseNames.size)}Took ${"%.1f".format(elapsedMillis)}ms"
)
phaseNames.pop()
return elapsedMillis
}
inline fun <R> measurePhase(phaseName: String, block: () -> R): R {
beginPhase(phaseName)
val result = block()
endPhase()
return result
}
inline fun <R> measureSections(block: () -> R): R {
sectionTimings.push(LinkedHashMap())
activeSections.push(null)
val result = block()
val timings = sectionTimings.pop()
val lastSection = activeSections.pop()
if (lastSection != null) {
val sectionStart = sectionStartTimes.pop()
timings.compute(lastSection) { _, existing ->
(existing ?: 0L) + System.nanoTime() - sectionStart
}
}
Logger.log(LogLevel.PERFORMANCE, "${" ".repeat(phaseNames.size + 1)}Summary:")
for ((section, durationNanos) in timings) {
val durationMillis = durationNanos * 1.0E-6
Logger.log(
LogLevel.PERFORMANCE,
"${" ".repeat(phaseNames.size + 2)}$section took ${"%.3f".format(durationMillis)}ms"
)
}
return result
}
fun switchSection(sectionName: String) {
val previous = activeSections.pop()
activeSections.push(sectionName)
if (previous != sectionName) {
if (previous != null) {
val sectionStart = sectionStartTimes.pop()
sectionTimings.peek().compute(previous) { _, existing ->
(existing ?: 0L) + System.nanoTime() - sectionStart
}
}
sectionStartTimes.push(System.nanoTime())
}
}
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more