commit 09aab327eacbdacb3f732323343caaf6b5d0c829 Author: nitrogenoliquido <203537016+nitrogenoliquido@users.noreply.github.com> Date: Fri Nov 27 10:00:18 2026 -0500 added files. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bede429 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.gradle/ +.kotlin/ +build/ +out/ +.idea/ +*.iml +.classpath +.project +.settings/ +*.log +*.BACKUP +*.obf.jar +out.jar +*-out.jar diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf0b4cd --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +

+ Skid Solutions Banner +

+ + Discord + + Version 1.3-beta-hotfix + Java 17 + Gradle 8.14.3 +

+ +

+ https://discord.gg/skidsolutions +

+ +

+ +

+ +

+ jak + hack + deobf2 + deobf +

+ +

+ This is not a reconstruction nor a remake. +

+ +

+ +

+ +## How to build + +### Prerequisites +- **Java Development Kit**: JDK 17 (the Gradle wrapper 8.14.3 does not run on newer JDKs) + +### Building OpenParamorphism + +Run from this folder: + +```powershell +$env:JAVA_HOME = "C:\Program Files\Java\jdk-17" + +.\gradlew.bat clean build +``` + +Generated `build/libs/`: +- `OpenParamorphism-1.3-beta-hotfix.jar` +- `OpenParamorphism-1.3-beta-hotfix-sources.jar` + +### Running + +```powershell +java -jar build\libs\OpenParamorphism-1.3-beta-hotfix.jar +``` diff --git a/assets/deobf.jpg b/assets/deobf.jpg new file mode 100644 index 0000000..fa8dbde Binary files /dev/null and b/assets/deobf.jpg differ diff --git a/assets/deobf2.png b/assets/deobf2.png new file mode 100644 index 0000000..1d4014d Binary files /dev/null and b/assets/deobf2.png differ diff --git a/assets/divider.svg b/assets/divider.svg new file mode 100644 index 0000000..f473231 --- /dev/null +++ b/assets/divider.svg @@ -0,0 +1,26 @@ + diff --git a/assets/hack.jpg b/assets/hack.jpg new file mode 100644 index 0000000..c4252ef Binary files /dev/null and b/assets/hack.jpg differ diff --git a/assets/jak.jpg b/assets/jak.jpg new file mode 100644 index 0000000..162bfe5 Binary files /dev/null and b/assets/jak.jpg differ diff --git a/assets/ss.png b/assets/ss.png new file mode 100644 index 0000000..041b33a Binary files /dev/null and b/assets/ss.png differ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..0153844 --- /dev/null +++ b/build.gradle @@ -0,0 +1,101 @@ +plugins { + id 'org.jetbrains.kotlin.jvm' version '2.4.21' + id 'java' + id 'application' + id 'idea' + id 'eclipse' +} + +group = 'site.hackery.paramorphism' +version = '1.3-beta-hotfix' + +def javaVersion = 17 + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.jetbrains.kotlin:kotlin-stdlib' + implementation 'org.ow2.asm:asm:9.8' + implementation 'org.ow2.asm:asm-tree:9.8' + implementation 'org.ow2.asm:asm-commons:9.8' + implementation 'org.ow2.asm:asm-analysis:9.8' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2' + implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.17.2' + implementation 'org.apache.maven:maven-aether-provider:3.3.9' + implementation 'org.eclipse.aether:aether-connector-basic:1.0.2.v20150114' + implementation 'org.eclipse.aether:aether-transport-file:1.0.2.v20150114' + + testImplementation 'org.junit.jupiter:junit-jupiter:5.11.4' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(javaVersion) + } + withSourcesJar() +} + +kotlin { + jvmToolchain(javaVersion) +} + +application { + applicationName = 'OpenParamorphism' + mainClass = 'site.hackery.paramorphism.ParamorphismMain' +} + +tasks.withType(JavaCompile).configureEach { + options.release = javaVersion + options.encoding = 'UTF-8' + options.compilerArgs += ['-parameters', '-Xlint:none', '-Xmaxerrs', '4096'] +} + +tasks.withType(JavaExec).configureEach { + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(javaVersion) + } +} + +tasks.withType(AbstractArchiveTask).configureEach { + preserveFileTimestamps = false + reproducibleFileOrder = true +} + +tasks.named('test', Test) { + useJUnitPlatform() +} + +tasks.named('jar', Jar) { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + manifest { + attributes( + 'Main-Class': 'site.hackery.paramorphism.ParamorphismMain', + 'Implementation-Title': 'OpenParamorphism', + 'Implementation-Version': project.version) + } + exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA' + from { + configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } + } +} + +tasks.named('sourcesJar', Jar) { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE +} + +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e05d1fe --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true +kotlin.code.style=official +kotlin.suppressGradlePluginWarnings=DeprecatedGradleVersionWarning diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9251069 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531 diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d8ce4de --- /dev/null +++ b/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} +rootProject.name = 'OpenParamorphism' diff --git a/src/main/java/site/hackery/paramorphism/runtime/PackedFileClassLoader.java b/src/main/java/site/hackery/paramorphism/runtime/PackedFileClassLoader.java new file mode 100644 index 0000000..85fd386 --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/runtime/PackedFileClassLoader.java @@ -0,0 +1,42 @@ +package site.hackery.paramorphism.runtime; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.InputStream; +import java.util.zip.GZIPInputStream; + +public class PackedFileClassLoader extends ClassLoader { + private static final long GZIP_HEADER_MAGIC = 0x1F8B080000000000L; + private byte[] packedBytes; + + public PackedFileClassLoader(ClassLoader parent, String resourceName, int unpackedSize) { + super(parent); + try { + InputStream stream = parent.getResourceAsStream(resourceName); + DataInputStream dataInputStream = new DataInputStream(stream); + this.packedBytes = new byte[unpackedSize]; + dataInputStream.readFully(this.packedBytes, 0, stream.available()); + + for (int i = 7; i >= 0; i--) { + this.packedBytes[7 - i] = (byte) ((GZIP_HEADER_MAGIC >> (8 * i)) & 0xFFL); + } + + stream.close(); + GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(this.packedBytes.clone())); + dataInputStream = new DataInputStream(gzipInputStream); + dataInputStream.readFully(this.packedBytes); + gzipInputStream.close(); + } catch (Exception ignored) { + while (true) { + } + } + } + + public Class createClass(String name) throws ClassNotFoundException { + try { + return super.defineClass(name, this.packedBytes, 0, this.packedBytes.length); + } catch (Exception ignored) { + return super.findClass(name); + } + } +} diff --git a/src/main/java/site/hackery/paramorphism/strategy/controlflow/graph/IntPair.java b/src/main/java/site/hackery/paramorphism/strategy/controlflow/graph/IntPair.java new file mode 100644 index 0000000..e410026 --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/strategy/controlflow/graph/IntPair.java @@ -0,0 +1,19 @@ +package site.hackery.paramorphism.strategy.controlflow.graph; + +public final class IntPair { + private final int first; + private final int second; + + public IntPair(int first, int second) { + this.first = first; + this.second = second; + } + + public int getFirst() { + return this.first; + } + + public int getSecond() { + return this.second; + } +} diff --git a/src/main/java/site/hackery/paramorphism/strategy/renaming/tree/MappingElementKind.java b/src/main/java/site/hackery/paramorphism/strategy/renaming/tree/MappingElementKind.java new file mode 100644 index 0000000..2f1dd66 --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/strategy/renaming/tree/MappingElementKind.java @@ -0,0 +1,8 @@ +package site.hackery.paramorphism.strategy.renaming.tree; + +public enum MappingElementKind { + PACKAGE, + CLASS, + FIELD, + METHOD +} diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipCoder.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipCoder.java new file mode 100644 index 0000000..f907a5d --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipCoder.java @@ -0,0 +1,59 @@ +package site.hackery.paramorphism.util.zip; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public class ZipCoder { + private final Charset charset; + private final boolean utf8; + private CharsetEncoder encoder; + + private ZipCoder(Charset charset) { + this.charset = charset; + this.utf8 = charset.name().equals(StandardCharsets.UTF_8.name()); + } + + static ZipCoder forCharset(Charset charset) { + return new ZipCoder(charset); + } + + byte[] encode(String text) { + CharsetEncoder charsetEncoder = getEncoder().reset(); + char[] chars = text.toCharArray(); + int maxBytes = (int) ((float) chars.length * charsetEncoder.maxBytesPerChar()); + byte[] output = new byte[maxBytes]; + if (maxBytes == 0) { + return output; + } + ByteBuffer byteBuffer = ByteBuffer.wrap(output); + CharBuffer charBuffer = CharBuffer.wrap(chars); + CoderResult result = charsetEncoder.encode(charBuffer, byteBuffer, true); + if (!result.isUnderflow()) { + throw new IllegalArgumentException(result.toString()); + } + result = charsetEncoder.flush(byteBuffer); + if (!result.isUnderflow()) { + throw new IllegalArgumentException(result.toString()); + } + return byteBuffer.position() == output.length ? output : Arrays.copyOf(output, byteBuffer.position()); + } + + boolean isUtf8() { + return this.utf8; + } + + private CharsetEncoder getEncoder() { + if (this.encoder == null) { + this.encoder = this.charset.newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); + } + return this.encoder; + } +} diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants.java new file mode 100644 index 0000000..d162907 --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants.java @@ -0,0 +1,8 @@ +package site.hackery.paramorphism.util.zip; + +public interface ZipConstants { + long LOCAL_HEADER_SIGNATURE = 0x04034B50L; + long DATA_DESCRIPTOR_SIGNATURE = 0x08074B50L; + long CENTRAL_DIRECTORY_SIGNATURE = 0x02014B50L; + long END_RECORD_SIGNATURE = 0x06054B50L; +} diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants64.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants64.java new file mode 100644 index 0000000..42a4c2a --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipConstants64.java @@ -0,0 +1,17 @@ +package site.hackery.paramorphism.util.zip; + +public interface ZipConstants64 { + long ZIP64_END_SIGNATURE = 0x06064B50L; + long ZIP64_LOCATOR_SIGNATURE = 0x07064B50L; + int ZIP64_END_HEADER_SIZE = 56; + int ZIP64_EXTRA_ID = 1; + int ZIP64_ENTRY_COUNT_SENTINEL = 0xFFFF; + long ZIP64_SIZE_SENTINEL = 0xFFFFFFFFL; + int UTF8_FLAG = 2048; + int ZIP64_TAG = 1; + int NTFS_EXTRA_ID = 10; + int EXTENDED_TIMESTAMP_EXTRA_ID = 21589; + int MODIFIED_TIME_FLAG = 1; + int ACCESS_TIME_FLAG = 2; + int CREATION_TIME_FLAG = 4; +} diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipEntry.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipEntry.java new file mode 100644 index 0000000..c1cd1bd --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipEntry.java @@ -0,0 +1,241 @@ +package site.hackery.paramorphism.util.zip; + +import java.nio.file.attribute.FileTime; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +public class ZipEntry implements ZipConstants, Cloneable { + public static final int STORED = 0; + public static final int DEFLATED = 8; + static final long DOS_TIME_BEFORE_1980 = (1L << 21) | (1L << 16); + private static final long UPPER_DOS_TIME_BOUND = 4036608000000L; + + String name; + long extendedDosTime = -1L; + FileTime modifiedTime; + FileTime accessTime; + FileTime creationTime; + long crc = -1L; + long size = -1L; + long compressedSize = -1L; + int method = -1; + int flags = 0; + byte[] extra; + String comment; + + public ZipEntry(String name) { + Objects.requireNonNull(name, "name"); + if (name.length() > 0xFFFF) { + throw new IllegalArgumentException("entry name too long"); + } + this.name = name; + } + + public ZipEntry(ZipEntry entry) { + Objects.requireNonNull(entry, "entry"); + this.name = entry.name; + this.extendedDosTime = entry.extendedDosTime; + this.modifiedTime = entry.modifiedTime; + this.accessTime = entry.accessTime; + this.creationTime = entry.creationTime; + this.crc = entry.crc; + this.size = entry.size; + this.compressedSize = entry.compressedSize; + this.method = entry.method; + this.flags = entry.flags; + this.extra = entry.extra; + this.comment = entry.comment; + } + + ZipEntry() { + } + + public String getName() { + return this.name; + } + + public void setTime(long time) { + this.extendedDosTime = ZipUtils.javaToExtendedDosTime(time); + if (this.extendedDosTime != DOS_TIME_BEFORE_1980 && time <= UPPER_DOS_TIME_BOUND) { + this.modifiedTime = null; + } else { + this.modifiedTime = FileTime.from(time, TimeUnit.MILLISECONDS); + } + } + + public long getTime() { + if (this.modifiedTime != null) { + return this.modifiedTime.toMillis(); + } + return this.extendedDosTime != -1L ? ZipUtils.extendedDosToJavaTime(this.extendedDosTime) : -1L; + } + + public ZipEntry setLastModifiedTime(FileTime fileTime) { + this.modifiedTime = Objects.requireNonNull(fileTime, "lastModifiedTime"); + this.extendedDosTime = ZipUtils.javaToExtendedDosTime(fileTime.to(TimeUnit.MILLISECONDS)); + return this; + } + + public FileTime getLastModifiedTime() { + if (this.modifiedTime != null) { + return this.modifiedTime; + } + return this.extendedDosTime == -1L ? null : FileTime.from(this.getTime(), TimeUnit.MILLISECONDS); + } + + public ZipEntry setLastAccessTime(FileTime fileTime) { + this.accessTime = Objects.requireNonNull(fileTime, "lastAccessTime"); + return this; + } + + public FileTime getLastAccessTime() { + return this.accessTime; + } + + public ZipEntry setCreationTime(FileTime fileTime) { + this.creationTime = Objects.requireNonNull(fileTime, "creationTime"); + return this; + } + + public FileTime getCreationTime() { + return this.creationTime; + } + + public void setSize(long size) { + if (size < 0L) { + throw new IllegalArgumentException("invalid entry size"); + } + this.size = size; + } + + public long getSize() { + return this.size; + } + + public long getCompressedSize() { + return this.compressedSize; + } + + public void setCompressedSize(long compressedSize) { + this.compressedSize = compressedSize; + } + + public void setCrc(long crc) { + if (crc < 0L || crc > 0xFFFFFFFFL) { + throw new IllegalArgumentException("invalid entry crc-32"); + } + this.crc = crc; + } + + public long getCrc() { + return this.crc; + } + + public void setMethod(int method) { + if (method != STORED && method != DEFLATED) { + throw new IllegalArgumentException("invalid compression method"); + } + this.method = method; + } + + public int getMethod() { + return this.method; + } + + public void setExtra(byte[] extra) { + this.setExtraFields(extra, false); + } + + void setExtraFields(byte[] extra, boolean applyZip64Sizes) { + if (extra != null) { + if (extra.length > 0xFFFF) { + throw new IllegalArgumentException("invalid extra field length"); + } + int offset = 0; + int length = extra.length; + while (offset + 4 < length) { + int tag = ZipUtils.readUnsignedShort(extra, offset); + int fieldSize = ZipUtils.readUnsignedShort(extra, offset + 2); + offset += 4; + if (offset + fieldSize > length) { + break; + } + switch (tag) { + case ZipConstants64.ZIP64_EXTRA_ID: + if (applyZip64Sizes && fieldSize >= 16) { + this.size = ZipUtils.readLong(extra, offset); + this.compressedSize = ZipUtils.readLong(extra, offset + 8); + } + break; + case ZipConstants64.NTFS_EXTRA_ID: + if (fieldSize >= 32) { + int ntfsOffset = offset + 4; + if (ZipUtils.readUnsignedShort(extra, ntfsOffset) == ZipConstants64.ZIP64_TAG + && ZipUtils.readUnsignedShort(extra, ntfsOffset + 2) == 24) { + this.modifiedTime = ZipUtils.windowsTimeToFileTime(ZipUtils.readLong(extra, ntfsOffset + 4)); + this.accessTime = ZipUtils.windowsTimeToFileTime(ZipUtils.readLong(extra, ntfsOffset + 12)); + this.creationTime = ZipUtils.windowsTimeToFileTime(ZipUtils.readLong(extra, ntfsOffset + 20)); + } + } + break; + case ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID: + int flags = Byte.toUnsignedInt(extra[offset]); + int pos = 1; + if ((flags & ZipConstants64.MODIFIED_TIME_FLAG) != 0 && 5 <= fieldSize) { + this.modifiedTime = ZipUtils.unixTimeToFileTime(ZipUtils.readUnsignedInt(extra, offset + 1)); + pos += 4; + } + if ((flags & ZipConstants64.ACCESS_TIME_FLAG) != 0 && pos + 4 <= fieldSize) { + this.accessTime = ZipUtils.unixTimeToFileTime(ZipUtils.readUnsignedInt(extra, offset + pos)); + pos += 4; + } + if ((flags & ZipConstants64.CREATION_TIME_FLAG) != 0 && pos + 4 <= fieldSize) { + this.creationTime = ZipUtils.unixTimeToFileTime(ZipUtils.readUnsignedInt(extra, offset + pos)); + } + break; + default: + break; + } + offset += fieldSize; + } + } + this.extra = extra; + } + + public byte[] getExtra() { + return this.extra; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getComment() { + return this.comment; + } + + public boolean isDirectory() { + return this.name.endsWith("/"); + } + + @Override + public String toString() { + return this.getName(); + } + + @Override + public int hashCode() { + return this.name.hashCode(); + } + + @Override + public Object clone() { + try { + ZipEntry copy = (ZipEntry) super.clone(); + copy.extra = this.extra == null ? null : this.extra.clone(); + return copy; + } catch (CloneNotSupportedException ex) { + throw new InternalError(ex); + } + } +} diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipOutputStream.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipOutputStream.java new file mode 100644 index 0000000..f9607f9 --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipOutputStream.java @@ -0,0 +1,615 @@ +package site.hackery.paramorphism.util.zip; + +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Vector; +import java.util.zip.CRC32; +import java.util.zip.Deflater; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.ZipException; + +public class ZipOutputStream extends DeflaterOutputStream implements ZipConstants { + public static final int STORED = 0; + public static final int DEFLATED = 8; + + private static final boolean inhibitZip64 = + Boolean.parseBoolean(System.getProperty("jdk.util.zip.inhibitZip64", "false")); + + private EntryRecord currentEntry; + private final Vector entries = new Vector<>(); + private final HashSet entryNames = new HashSet<>(); + private final CRC32 crc = new CRC32(); + private long writtenBytes = 0L; + private long entryDataOffset = 0L; + private byte[] comment; + private int defaultMethod = DEFLATED; + private boolean finished; + private boolean closed = false; + private final ZipCoder coder; + private ZipDataDescriptorTransformers dataDescriptorTransformers; + + public ZipOutputStream(OutputStream outputStream) { + this(outputStream, StandardCharsets.UTF_8); + } + + public ZipOutputStream(OutputStream outputStream, Charset charset) { + super(outputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true)); + if (charset == null) { + throw new NullPointerException("charset is null"); + } + this.coder = ZipCoder.forCharset(charset); + } + + private static int versionNeeded(ZipEntry entry) throws ZipException { + switch (entry.method) { + case STORED: + return 10; + case DEFLATED: + return 20; + default: + throw new ZipException("unsupported compression method"); + } + } + + private void ensureOpen() throws IOException { + if (this.closed) { + throw new IOException("Stream closed"); + } + } + + public void setComment(String comment) { + if (comment != null) { + this.comment = this.coder.encode(comment); + if (this.comment.length > 0xFFFF) { + throw new IllegalArgumentException("ZIP file comment too long."); + } + } + } + + public void setMethod(int defaultMethod) { + if (defaultMethod != DEFLATED && defaultMethod != STORED) { + throw new IllegalArgumentException("invalid compression method"); + } + this.defaultMethod = defaultMethod; + } + + public void setLevel(int level) { + this.def.setLevel(level); + } + + public void putNextEntry(ZipEntry entry) throws IOException { + this.ensureOpen(); + if (this.currentEntry != null) { + this.closeEntry(); + } + if (entry.extendedDosTime == -1L) { + entry.setTime(System.currentTimeMillis()); + } + if (entry.method == -1) { + entry.method = this.defaultMethod; + } + entry.flags = 0; + switch (entry.method) { + case STORED: + if (entry.size == -1L) { + entry.size = entry.compressedSize; + } else if (entry.compressedSize == -1L) { + entry.compressedSize = entry.size; + } else if (entry.size != entry.compressedSize) { + throw new ZipException("STORED entry where compressed != uncompressed size"); + } + if (entry.size == -1L || entry.crc == -1L) { + throw new ZipException("STORED entry missing size, compressed size, or crc-32"); + } + break; + case DEFLATED: + if (entry.size == -1L || entry.compressedSize == -1L || entry.crc == -1L) { + entry.flags = 8; + } + break; + default: + throw new ZipException("unsupported compression method"); + } + if (!this.entryNames.add(entry.name)) { + throw new ZipException("duplicate entry: " + entry.name); + } + if (this.coder.isUtf8()) { + entry.flags |= ZipConstants64.UTF8_FLAG; + } + this.currentEntry = new EntryRecord(entry, this.writtenBytes); + this.entries.add(this.currentEntry); + this.writeLocalHeader(this.currentEntry); + } + + public void closeEntry() throws IOException { + this.ensureOpen(); + if (this.currentEntry == null) { + return; + } + ZipEntry entry = this.currentEntry.entry; + switch (entry.method) { + case STORED: + if (entry.size != this.writtenBytes - this.entryDataOffset) { + throw new ZipException("invalid entry size (expected " + entry.size + " but got " + + (this.writtenBytes - this.entryDataOffset) + " bytes)"); + } + if (entry.crc != this.crc.getValue()) { + throw new ZipException("invalid entry crc-32 (expected 0x" + Long.toHexString(entry.crc) + + " but got 0x" + Long.toHexString(this.crc.getValue()) + ")"); + } + break; + case DEFLATED: + this.def.finish(); + while (!this.def.finished()) { + this.deflate(); + } + if ((entry.flags & 8) == 0) { + if (entry.size != this.def.getBytesRead()) { + throw new ZipException("invalid entry size (expected " + entry.size + + " but got " + this.def.getBytesRead() + " bytes)"); + } + if (entry.compressedSize != this.def.getBytesWritten()) { + throw new ZipException("invalid entry compressed size (expected " + entry.compressedSize + + " but got " + this.def.getBytesWritten() + " bytes)"); + } + if (entry.crc != this.crc.getValue()) { + throw new ZipException("invalid entry CRC-32 (expected 0x" + Long.toHexString(entry.crc) + + " but got 0x" + Long.toHexString(this.crc.getValue()) + ")"); + } + } else { + entry.size = this.def.getBytesRead(); + entry.compressedSize = this.def.getBytesWritten(); + entry.crc = this.crc.getValue(); + this.writeDataDescriptor(entry); + } + this.def.reset(); + this.writtenBytes += entry.compressedSize; + break; + default: + throw new ZipException("invalid compression method"); + } + this.crc.reset(); + this.currentEntry = null; + } + + @Override + public synchronized void write(byte[] bytes, int off, int len) throws IOException { + this.ensureOpen(); + if (off < 0 || len < 0 || off > bytes.length - len) { + throw new IndexOutOfBoundsException(); + } + if (len == 0) { + return; + } + if (this.currentEntry == null) { + throw new ZipException("no current ZIP entry"); + } + ZipEntry entry = this.currentEntry.entry; + switch (entry.method) { + case STORED: + this.writtenBytes += len; + if (this.writtenBytes - this.entryDataOffset > entry.size) { + throw new ZipException("attempt to write past end of STORED entry"); + } + this.out.write(bytes, off, len); + break; + case DEFLATED: + super.write(bytes, off, len); + break; + default: + throw new ZipException("invalid compression method"); + } + this.crc.update(bytes, off, len); + } + + @Override + public void finish() throws IOException { + this.ensureOpen(); + if (this.finished) { + return; + } + if (this.currentEntry != null) { + this.closeEntry(); + } + long centralDirectoryOffset = this.writtenBytes; + for (EntryRecord record : this.entries) { + this.writeCentralHeader(record); + } + this.writeEndRecord(centralDirectoryOffset, this.writtenBytes - centralDirectoryOffset); + this.finished = true; + } + + @Override + public void close() throws IOException { + if (!this.closed) { + try { + super.close(); + } finally { + this.def.end(); + this.closed = true; + } + } + } + + private void writeLocalHeader(EntryRecord record) throws IOException { + ZipEntry entry = record.entry; + int flags = entry.flags; + boolean zip64 = false; + int extraLength = this.getExtraLength(entry.extra); + + this.writeInt(LOCAL_HEADER_SIGNATURE); + if ((flags & 8) == 8) { + this.writeShort(versionNeeded(entry)); + this.writeShort(flags); + this.writeShort(entry.method); + this.writeInt(entry.extendedDosTime); + this.writeInt(0L); + this.writeInt(0L); + this.writeInt(0L); + } else { + if (entry.compressedSize < ZipConstants64.ZIP64_SIZE_SENTINEL + && entry.size < ZipConstants64.ZIP64_SIZE_SENTINEL) { + this.writeShort(versionNeeded(entry)); + } else { + zip64 = true; + this.writeShort(45); + } + this.writeShort(flags); + this.writeShort(entry.method); + this.writeInt(entry.extendedDosTime); + this.writeInt(entry.crc); + if (zip64) { + this.writeInt(ZipConstants64.ZIP64_SIZE_SENTINEL); + this.writeInt(ZipConstants64.ZIP64_SIZE_SENTINEL); + extraLength += 20; + } else { + this.writeInt(entry.compressedSize); + this.writeInt(entry.size); + } + } + + byte[] encodedName = this.coder.encode(entry.name); + this.writeShort(encodedName.length); + + int timestampBytes = 0; + int timestampFlags = 0; + if (entry.modifiedTime != null) { + timestampBytes += 4; + timestampFlags |= ZipConstants64.MODIFIED_TIME_FLAG; + } + if (entry.accessTime != null) { + timestampBytes += 4; + timestampFlags |= ZipConstants64.ACCESS_TIME_FLAG; + } + if (entry.creationTime != null) { + timestampBytes += 4; + timestampFlags |= ZipConstants64.CREATION_TIME_FLAG; + } + if (timestampFlags != 0) { + extraLength += timestampBytes + 5; + } + + this.writeShort(extraLength); + this.writeBytes(encodedName, 0, encodedName.length); + + if (zip64) { + this.writeShort(ZipConstants64.ZIP64_EXTRA_ID); + this.writeShort(16); + this.writeLong(entry.size); + this.writeLong(entry.compressedSize); + } + + if (timestampFlags != 0) { + this.writeShort(ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID); + this.writeShort(timestampBytes + 1); + this.writeByte(timestampFlags); + if (entry.modifiedTime != null) { + this.writeInt(ZipUtils.fileTimeToUnixTime(entry.modifiedTime)); + } + if (entry.accessTime != null) { + this.writeInt(ZipUtils.fileTimeToUnixTime(entry.accessTime)); + } + if (entry.creationTime != null) { + this.writeInt(ZipUtils.fileTimeToUnixTime(entry.creationTime)); + } + } + + this.writeExtra(entry.extra); + this.entryDataOffset = this.writtenBytes; + } + + public void setDataDescriptorTransformers(@Nullable ZipDataDescriptorTransformers dataDescriptorTransformers) { + this.dataDescriptorTransformers = dataDescriptorTransformers; + } + + public ZipDataDescriptorTransformers getDataDescriptorTransformers() { + return this.dataDescriptorTransformers; + } + + private void writeDataDescriptor(ZipEntry entry) throws IOException { + if (this.dataDescriptorTransformers != null) { + if (this.dataDescriptorTransformers.getCrcTransformer() != null) { + entry.crc = this.dataDescriptorTransformers.getCrcTransformer().invoke(entry.crc); + } + if (this.dataDescriptorTransformers.getCompressedSizeTransformer() != null) { + entry.compressedSize = this.dataDescriptorTransformers.getCompressedSizeTransformer().invoke(entry.compressedSize); + } + if (this.dataDescriptorTransformers.getSizeTransformer() != null) { + entry.size = this.dataDescriptorTransformers.getSizeTransformer().invoke(entry.size); + } + } + + this.writeInt(DATA_DESCRIPTOR_SIGNATURE); + this.writeInt(entry.crc); + if (entry.compressedSize < ZipConstants64.ZIP64_SIZE_SENTINEL + && entry.size < ZipConstants64.ZIP64_SIZE_SENTINEL) { + this.writeInt(entry.compressedSize); + this.writeInt(entry.size); + } else { + this.writeLong(entry.compressedSize); + this.writeLong(entry.size); + } + } + + private void writeCentralHeader(EntryRecord record) throws IOException { + ZipEntry entry = record.entry; + int flags = entry.flags; + int versionNeeded = versionNeeded(entry); + long compressedSize = entry.compressedSize; + long size = entry.size; + long offset = record.offset; + int zip64ExtraSize = 0; + boolean zip64 = false; + + if (entry.compressedSize >= ZipConstants64.ZIP64_SIZE_SENTINEL) { + compressedSize = ZipConstants64.ZIP64_SIZE_SENTINEL; + zip64ExtraSize += 8; + zip64 = true; + } + if (entry.size >= ZipConstants64.ZIP64_SIZE_SENTINEL) { + size = ZipConstants64.ZIP64_SIZE_SENTINEL; + zip64ExtraSize += 8; + zip64 = true; + } + if (record.offset >= ZipConstants64.ZIP64_SIZE_SENTINEL || record.offset < 0L) { + offset = ZipConstants64.ZIP64_SIZE_SENTINEL; + zip64ExtraSize += 8; + zip64 = true; + } + + this.writeInt(CENTRAL_DIRECTORY_SIGNATURE); + if (zip64) { + this.writeShort(45); + this.writeShort(45); + } else { + this.writeShort(versionNeeded); + this.writeShort(versionNeeded); + } + + this.writeShort(flags); + this.writeShort(entry.method); + this.writeInt(entry.extendedDosTime); + this.writeInt(entry.crc); + this.writeInt(compressedSize); + this.writeInt(size); + + byte[] encodedName = this.coder.encode(entry.name); + this.writeShort(encodedName.length); + + int extraLength = this.getExtraLength(entry.extra); + if (zip64) { + extraLength += zip64ExtraSize + 4; + } + + int timestampFlags = 0; + if (entry.modifiedTime != null) { + extraLength += 4; + timestampFlags = ZipConstants64.MODIFIED_TIME_FLAG; + } + if (entry.accessTime != null) { + timestampFlags |= ZipConstants64.ACCESS_TIME_FLAG; + } + if (entry.creationTime != null) { + timestampFlags |= ZipConstants64.CREATION_TIME_FLAG; + } + if (timestampFlags != 0) { + extraLength += 5; + } + + this.writeShort(extraLength); + byte[] encodedComment; + if (entry.comment != null) { + encodedComment = this.coder.encode(entry.comment); + this.writeShort(Math.min(encodedComment.length, 0xFFFF)); + } else { + encodedComment = null; + this.writeShort(0); + } + + this.writeShort(0); + this.writeShort(0); + this.writeInt(0L); + this.writeInt(offset); + this.writeBytes(encodedName, 0, encodedName.length); + + if (zip64) { + this.writeShort(ZipConstants64.ZIP64_EXTRA_ID); + this.writeShort(zip64ExtraSize); + if (size == ZipConstants64.ZIP64_SIZE_SENTINEL) { + this.writeLong(entry.size); + } + if (compressedSize == ZipConstants64.ZIP64_SIZE_SENTINEL) { + this.writeLong(entry.compressedSize); + } + if (offset == ZipConstants64.ZIP64_SIZE_SENTINEL) { + this.writeLong(record.offset); + } + } + + if (timestampFlags != 0) { + this.writeShort(ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID); + if (entry.modifiedTime != null) { + this.writeShort(5); + this.writeByte(timestampFlags); + this.writeInt(ZipUtils.fileTimeToUnixTime(entry.modifiedTime)); + } else { + this.writeShort(1); + this.writeByte(timestampFlags); + } + } + + this.writeExtra(entry.extra); + if (encodedComment != null) { + this.writeBytes(encodedComment, 0, Math.min(encodedComment.length, 0xFFFF)); + } + } + + private void writeEndRecord(long centralOffset, long centralSize) throws IOException { + boolean zip64 = false; + long recordedSize = centralSize; + long recordedOffset = centralOffset; + if (centralSize >= ZipConstants64.ZIP64_SIZE_SENTINEL) { + recordedSize = ZipConstants64.ZIP64_SIZE_SENTINEL; + zip64 = true; + } + if (centralOffset >= ZipConstants64.ZIP64_SIZE_SENTINEL) { + recordedOffset = ZipConstants64.ZIP64_SIZE_SENTINEL; + zip64 = true; + } + + int entryCount = this.entries.size(); + if (entryCount >= ZipConstants64.ZIP64_ENTRY_COUNT_SENTINEL) { + zip64 |= !inhibitZip64; + if (zip64) { + entryCount = ZipConstants64.ZIP64_ENTRY_COUNT_SENTINEL; + } + } + + if (zip64) { + long zip64EndOffset = this.writtenBytes; + this.writeInt(ZipConstants64.ZIP64_END_SIGNATURE); + this.writeLong(44L); + this.writeShort(45); + this.writeShort(45); + this.writeInt(0L); + this.writeInt(0L); + this.writeLong(this.entries.size()); + this.writeLong(this.entries.size()); + this.writeLong(centralSize); + this.writeLong(centralOffset); + this.writeInt(ZipConstants64.ZIP64_LOCATOR_SIGNATURE); + this.writeInt(0L); + this.writeLong(zip64EndOffset); + this.writeInt(1L); + } + + this.writeInt(END_RECORD_SIGNATURE); + this.writeShort(0); + this.writeShort(0); + this.writeShort(entryCount); + this.writeShort(entryCount); + this.writeInt(recordedSize); + this.writeInt(recordedOffset); + if (this.comment != null) { + this.writeShort(this.comment.length); + this.writeBytes(this.comment, 0, this.comment.length); + } else { + this.writeShort(0); + } + } + + private int getExtraLength(byte[] extra) { + if (extra == null) { + return 0; + } + int skipped = 0; + int totalLength = extra.length; + int offset = 0; + while (offset + 4 <= totalLength) { + int tag = ZipUtils.readUnsignedShort(extra, offset); + int fieldSize = ZipUtils.readUnsignedShort(extra, offset + 2); + if (fieldSize < 0 || offset + 4 + fieldSize > totalLength) { + break; + } + if (tag == ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID || tag == ZipConstants64.ZIP64_EXTRA_ID) { + skipped += fieldSize + 4; + } + offset += fieldSize + 4; + } + return totalLength - skipped; + } + + private void writeExtra(byte[] extra) throws IOException { + if (extra == null) { + return; + } + int totalLength = extra.length; + int offset = 0; + while (offset + 4 <= totalLength) { + int tag = ZipUtils.readUnsignedShort(extra, offset); + int fieldSize = ZipUtils.readUnsignedShort(extra, offset + 2); + if (fieldSize < 0 || offset + 4 + fieldSize > totalLength) { + this.writeBytes(extra, offset, totalLength - offset); + return; + } + if (tag != ZipConstants64.EXTENDED_TIMESTAMP_EXTRA_ID && tag != ZipConstants64.ZIP64_EXTRA_ID) { + this.writeBytes(extra, offset, fieldSize + 4); + } + offset += fieldSize + 4; + } + if (offset < totalLength) { + this.writeBytes(extra, offset, totalLength - offset); + } + } + + private void writeByte(int value) throws IOException { + this.out.write(value & 0xFF); + this.writtenBytes++; + } + + private void writeShort(int value) throws IOException { + this.out.write(value & 0xFF); + this.out.write((value >>> 8) & 0xFF); + this.writtenBytes += 2L; + } + + private void writeInt(long value) throws IOException { + this.out.write((int) (value & 0xFFL)); + this.out.write((int) ((value >>> 8) & 0xFFL)); + this.out.write((int) ((value >>> 16) & 0xFFL)); + this.out.write((int) ((value >>> 24) & 0xFFL)); + this.writtenBytes += 4L; + } + + private void writeLong(long value) throws IOException { + this.out.write((int) (value & 0xFFL)); + this.out.write((int) ((value >>> 8) & 0xFFL)); + this.out.write((int) ((value >>> 16) & 0xFFL)); + this.out.write((int) ((value >>> 24) & 0xFFL)); + this.out.write((int) ((value >>> 32) & 0xFFL)); + this.out.write((int) ((value >>> 40) & 0xFFL)); + this.out.write((int) ((value >>> 48) & 0xFFL)); + this.out.write((int) ((value >>> 56) & 0xFFL)); + this.writtenBytes += 8L; + } + + private void writeBytes(byte[] bytes, int off, int len) throws IOException { + super.out.write(bytes, off, len); + this.writtenBytes += len; + } + + private static class EntryRecord { + final ZipEntry entry; + final long offset; + + EntryRecord(ZipEntry entry, long offset) { + this.entry = entry; + this.offset = offset; + } + } +} diff --git a/src/main/java/site/hackery/paramorphism/util/zip/ZipUtils.java b/src/main/java/site/hackery/paramorphism/util/zip/ZipUtils.java new file mode 100644 index 0000000..4206802 --- /dev/null +++ b/src/main/java/site/hackery/paramorphism/util/zip/ZipUtils.java @@ -0,0 +1,79 @@ +package site.hackery.paramorphism.util.zip; + +import java.nio.file.attribute.FileTime; +import java.util.Date; +import java.util.concurrent.TimeUnit; + +public class ZipUtils { + private static final long DOS_TIME_BEFORE_1980 = (1L << 21) | (1L << 16); + private static final long WINDOWS_EPOCH_MICROSECONDS = -11644473600000000L; + + public static FileTime windowsTimeToFileTime(long windowsTime) { + return FileTime.from(windowsTime / 10L + WINDOWS_EPOCH_MICROSECONDS, TimeUnit.MICROSECONDS); + } + + public static long fileTimeToWindowsTime(FileTime fileTime) { + return (fileTime.to(TimeUnit.MICROSECONDS) - WINDOWS_EPOCH_MICROSECONDS) * 10L; + } + + public static FileTime unixTimeToFileTime(long unixSeconds) { + return FileTime.from(unixSeconds, TimeUnit.SECONDS); + } + + public static long fileTimeToUnixTime(FileTime fileTime) { + return fileTime.to(TimeUnit.SECONDS); + } + + @SuppressWarnings("deprecation") + private static long dosToJavaTime(long dosTime) { + Date date = new Date( + (int) (((dosTime >> 25) & 0x7FL) + 80L), + (int) (((dosTime >> 21) & 0x0FL) - 1L), + (int) ((dosTime >> 16) & 0x1FL), + (int) ((dosTime >> 11) & 0x1FL), + (int) ((dosTime >> 5) & 0x3FL), + (int) ((dosTime << 1) & 0x3EL) + ); + return date.getTime(); + } + + public static long extendedDosToJavaTime(long extendedDosTime) { + long time = dosToJavaTime(extendedDosTime); + return time + (extendedDosTime >> 32); + } + + @SuppressWarnings("deprecation") + private static long javaToDosTime(long time) { + Date date = new Date(time); + int year = date.getYear() + 1900; + if (year < 1980) { + return DOS_TIME_BEFORE_1980; + } + return (long) ((year - 1980) << 25 + | (date.getMonth() + 1) << 21 + | date.getDate() << 16 + | date.getHours() << 11 + | date.getMinutes() << 5 + | (date.getSeconds() >> 1)); + } + + public static long javaToExtendedDosTime(long time) { + if (time < 0L) { + return DOS_TIME_BEFORE_1980; + } + long dosTime = javaToDosTime(time); + return dosTime != DOS_TIME_BEFORE_1980 ? dosTime + ((time % 2000L) << 32) : DOS_TIME_BEFORE_1980; + } + + public static int readUnsignedShort(byte[] bytes, int offset) { + return Byte.toUnsignedInt(bytes[offset]) | (Byte.toUnsignedInt(bytes[offset + 1]) << 8); + } + + public static long readUnsignedInt(byte[] bytes, int offset) { + return ((long) readUnsignedShort(bytes, offset) | ((long) readUnsignedShort(bytes, offset + 2) << 16)) & 0xFFFFFFFFL; + } + + public static long readLong(byte[] bytes, int offset) { + return readUnsignedInt(bytes, offset) | (readUnsignedInt(bytes, offset + 4) << 32); + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/ConfigurationGenerator.kt b/src/main/kotlin/site/hackery/paramorphism/ConfigurationGenerator.kt new file mode 100644 index 0000000..8c9e519 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/ConfigurationGenerator.kt @@ -0,0 +1,39 @@ +package site.hackery.paramorphism + +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory +import com.fasterxml.jackson.dataformat.yaml.YAMLMapper +import site.hackery.paramorphism.config.ElementMask +import site.hackery.paramorphism.resources.io.ZipResourceSet +import site.hackery.paramorphism.resources.masking.MaskedClassSet +import site.hackery.paramorphism.resources.views.ResourceBackedClassSet +import site.hackery.paramorphism.util.logging.LogLevel +import site.hackery.paramorphism.util.logging.Logger +import java.io.File + +object ConfigurationGenerator { + fun generateConfiguration(jarFile: File, mask: ElementMask) { + val zipResources = ZipResourceSet(jarFile) + val classes = MaskedClassSet(mask, ResourceBackedClassSet(zipResources)) + val yamlMapper = YAMLMapper(YAMLFactory()) + + val configMap = LinkedHashMap() + configMap["input"] = jarFile.path + val flags = LinkedHashMap() + configMap["flags"] = flags + + for ((_, classNode) in classes.entries()) { + val hasKotlinMetadata = classNode.visibleAnnotations?.any { it.desc == "Lkotlin/Metadata;" } == true + if (hasKotlinMetadata && flags["kotlin"] != true) { + Logger.log(LogLevel.INFO, "Kotlin class detected: ${classNode.name}") + Logger.log(LogLevel.INFO, "Suggesting the 'kotlin' flag be set to true") + flags["kotlin"] = true + } + } + + if (flags.isEmpty()) { + configMap.remove("flags") + } + + println("Config:\n${yamlMapper.writeValueAsString(configMap)}") + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/ObfuscationPipeline.kt b/src/main/kotlin/site/hackery/paramorphism/ObfuscationPipeline.kt new file mode 100644 index 0000000..4570440 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/ObfuscationPipeline.kt @@ -0,0 +1,281 @@ +package site.hackery.paramorphism + +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassWriter +import site.hackery.paramorphism.config.ElementMask +import site.hackery.paramorphism.config.ParamorphismConfig +import site.hackery.paramorphism.resources.ClassSet +import site.hackery.paramorphism.resources.ClassSetGroup +import site.hackery.paramorphism.resources.LazyResource +import site.hackery.paramorphism.resources.ManifestResource +import site.hackery.paramorphism.resources.ResourceSet +import site.hackery.paramorphism.resources.TaggedResource +import site.hackery.paramorphism.resources.io.ZipResourceSet +import site.hackery.paramorphism.resources.masking.IncludedClassSet +import site.hackery.paramorphism.resources.masking.MaskedClassSet +import site.hackery.paramorphism.resources.overlay.OverlayClassSet +import site.hackery.paramorphism.resources.overlay.OverlayResourceSet +import site.hackery.paramorphism.resources.views.NonClassResourceSet +import site.hackery.paramorphism.resources.views.ResourceBackedClassSet +import site.hackery.paramorphism.strategy.StrategyPipeline +import site.hackery.paramorphism.util.RandomContext +import site.hackery.paramorphism.util.context.ContextStore +import site.hackery.paramorphism.util.context.MutableObfuscationContext +import site.hackery.paramorphism.util.context.ObfuscationContext +import site.hackery.paramorphism.util.logging.LogLevel +import site.hackery.paramorphism.util.logging.Logger +import site.hackery.paramorphism.util.logging.PerformanceProfiler +import site.hackery.paramorphism.util.manifest.ManifestAttributes +import site.hackery.paramorphism.util.runtime.JavaRuntimeClassSet +import site.hackery.paramorphism.util.zip.ZipDataDescriptorTransformers +import site.hackery.paramorphism.util.zip.ZipEntry +import site.hackery.paramorphism.util.zip.ZipOutputStream +import java.io.ByteArrayInputStream +import java.io.Closeable +import java.io.File +import java.io.FileFilter +import java.io.FileOutputStream +import java.math.BigInteger +import java.security.MessageDigest +import java.util.jar.Attributes +import java.util.jar.Manifest + +object ObfuscationPipeline { + fun run(config: ParamorphismConfig) { + var inputArchive: ZipResourceSet? = null + var classSet: ClassSet? = null + var resourceSet: ResourceSet? = null + var libraries: ClassSetGroup? = null + try { + PerformanceProfiler.beginPhase("Initialize") + val store = ContextStore() + val context = ObfuscationContext(store) + val mutableContext = MutableObfuscationContext(store) + mutableContext.config = config + + val (resolvedInput, outputFile) = resolveInputOutput(config) + inputArchive = ZipResourceSet(resolvedInput) + val randomContext = createRandomContext(config, inputArchive) + mutableContext.putService(RandomContext::class.java, randomContext) + + val shadedMask = config.shadedLibraries.get() + classSet = createClassSet(inputArchive, shadedMask) + resourceSet = createResourceSet(inputArchive) + libraries = loadLibraries(inputArchive, config, shadedMask) + mutableContext.classes = classSet + mutableContext.resources = resourceSet + mutableContext.libraries = libraries + mutableContext.globalMask = config.mask.getOrDefault(ElementMask(emptyArray(), emptyArray())) + mutableContext.nameGenerator = config.nameGeneration.get()!! + context.nameGenerator.random = randomContext.getRandom() + + val flags = config.flags.get()!! + mutableContext.putService(site.hackery.paramorphism.config.ConfigFlags::class.java, flags) + + flags["anti_decompression"]?.let { context.nameGenerator.prefixClassNamesWithNul = it } + + try { + val manifestResource = context.resources.get("META-INF/MANIFEST.MF") + if (manifestResource != null) { + mutableContext.manifest = Manifest(ByteArrayInputStream(manifestResource.getBytes())) + } else { + mutableContext.manifest = Manifest() + context.manifest.mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0" + } + } catch (_: Exception) { + Logger.log(LogLevel.WARNING, "Error parsing MANIFEST.MF - It will be overwritten") + mutableContext.manifest = Manifest() + context.manifest.mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0" + } + + context.resources.put("META-INF/MANIFEST.MF", ManifestResource(context.manifest, -999)) + if (config.branding.getOrDefault(true)) { + context.manifest.mainAttributes[ManifestAttributes.OBFUSCATED_BY] = "Paramorphism" + } + + val pipeline = StrategyPipeline(context) + val initMillis = PerformanceProfiler.endPhase() + + PerformanceProfiler.beginPhase("Obfuscate") + pipeline.run(context, mutableContext) + val obfuscateMillis = PerformanceProfiler.endPhase() + + PerformanceProfiler.beginPhase("Write") + val classes = context.classes + val resources = context.resources + + PerformanceProfiler.measurePhase("Assemble Classes") { + for ((_, classNode) in classes.entries()) { + resources.put( + "${classNode.name}.class", + TaggedResource( + "assembled_class", + LazyResource({ + val writer = ClassWriter(ClassWriter.COMPUTE_MAXS) + classNode.accept(writer) + writer.toByteArray() + }, 0) + ) + ) + } + } + + shadedMask?.let { mask -> + PerformanceProfiler.measurePhase("Shade Library Resources") { + inputArchive.names() + .filter { mask.matches(it) } + .map { it to inputArchive.get(it)!! } + .forEach { (name, resource) -> resources.put(name, resource) } + } + } + + PerformanceProfiler.measurePhase("Write Resources") { + if (outputFile.exists()) { + outputFile.delete() + } + + ZipOutputStream(FileOutputStream(outputFile)).use { zipOut -> + val corruptArchive = flags["corruption"] ?: false + if (corruptArchive) { + zipOut.dataDescriptorTransformers = ZipDataDescriptorTransformers( + crcTransformer = { -1L }, + compressedSizeTransformer = null, + sizeTransformer = { -1L } + ) + zipOut.putNextEntry(ZipEntry("//\u0000//.class")) + zipOut.write('i'.code) + zipOut.closeEntry() + zipOut.dataDescriptorTransformers = null + } + + val writeRandom = randomContext.getRandom() + val groupedByPriority = resources.entries() + .filter { (name, _) -> !name.endsWith(".SF") && !name.endsWith(".RSA") } + .distinctBy { (name, _) -> name } + .groupBy { (_, resource) -> resource.writePriority } + .toSortedMap() + + for (group in groupedByPriority.values) { + for ((name, resource) in group.shuffled(writeRandom)) { + val isClassEntry = name.endsWith(".class") + val corruptEntry = corruptArchive && + isClassEntry && + resource is TaggedResource && + resource.tag == "assembled_class" + val entryName = if (corruptEntry) "$name/" else name + + zipOut.putNextEntry(ZipEntry(entryName)) + zipOut.write(resource.getBytes()) + zipOut.closeEntry() + + if (corruptEntry) { + zipOut.dataDescriptorTransformers = ZipDataDescriptorTransformers( + crcTransformer = { writeRandom.nextLong() }, + compressedSizeTransformer = null, + sizeTransformer = { resource.getBytes().size.toLong() } + ) + zipOut.putNextEntry(ZipEntry("$name/encrypted_data")) + zipOut.write('i'.code) + zipOut.closeEntry() + zipOut.dataDescriptorTransformers = null + + zipOut.putNextEntry(ZipEntry("$name/name")) + zipOut.write(name.dropLast(".class".length).toByteArray(Charsets.UTF_8)) + zipOut.closeEntry() + } + } + } + } + } + val writeMillis = PerformanceProfiler.endPhase() + + val totalMillis = initMillis + obfuscateMillis + writeMillis + val formatMs: (Double) -> String = { "%.2fms".format(it) } + Logger.log( + "Finished in ${formatMs(totalMillis)} (init: ${formatMs(initMillis)}, obfuscate: ${formatMs(obfuscateMillis)}, write: ${formatMs(writeMillis)})" + ) + + try { + val relativeOut = outputFile.absoluteFile.toRelativeString(config.file.absoluteFile.parentFile) + Logger.log("Saved output to: $relativeOut") + } catch (_: Exception) { + Logger.log("Saved output to: ${outputFile.absolutePath}") + } + } catch (ex: Exception) { + Logger.log(LogLevel.ERROR, "An error occurred during obfuscation: ${ex.message ?: ex}") + Logger.writer.flush() + ex.printStackTrace() + } finally { + closeQuietly(libraries) + closeQuietly(classSet) + closeQuietly(resourceSet) + closeQuietly(inputArchive) + } + } + + private fun closeQuietly(closeable: Closeable?) { + if (closeable != null) { + runCatching { closeable.close() } + } + } + + private fun resolveInputOutput(config: ParamorphismConfig): Pair { + val input = config.input.get() ?: error("Input JAR file was not defined") + val output = config.output.get() ?: File("${input.absolutePath.substringBeforeLast('.')}.obf.jar") + if (!input.exists()) { + error("Input JAR file does not exist") + } + return input to output + } + + private fun createRandomContext(config: ParamorphismConfig, resources: ResourceSet): RandomContext { + val digest = MessageDigest.getInstance("SHA-256") + for ((_, resource) in resources.entries()) { + digest.update(resource.getBytes()) + } + val hashSeed = BigInteger(digest.digest()).toLong() + return RandomContext(hashSeed + config.randomOffset.getOrDefault(0).toLong()) + } + + private fun createClassSet(resources: ResourceSet, shadedLibraries: ElementMask?): ClassSet { + val classSet: ClassSet = ResourceBackedClassSet(resources) + val filtered: ClassSet = if (shadedLibraries != null) MaskedClassSet(shadedLibraries, classSet) else classSet + return OverlayClassSet(filtered) + } + + private fun createResourceSet(resources: ResourceSet): ResourceSet = + OverlayResourceSet(NonClassResourceSet(resources)) + + private fun loadLibraries( + resources: ResourceSet, + config: ParamorphismConfig, + shadedLibraries: ElementMask? + ): ClassSetGroup { + val configuredFiles = config.libraries.getOrDefault(emptyArray()).flatMap { file -> + if (file.isDirectory) { + file.listFiles(FileFilter { it.extension.equals("jar", ignoreCase = true) })?.toList() ?: emptyList() + } else { + listOf(file) + } + } + + val classSets = configuredFiles + .map { ResourceBackedClassSet(ZipResourceSet(it), ClassReader.SKIP_CODE) as ClassSet } + .toMutableList() + + if (shadedLibraries != null) { + classSets.add(0, IncludedClassSet(shadedLibraries, ResourceBackedClassSet(resources, ClassReader.SKIP_CODE))) + } + if (config.addJavaRuntime.getOrDefault(true)) { + classSets.add(0, JavaRuntimeClassSet.locateRuntimeClasses()) + } + classSets.addAll(loadMavenLibraries(config)) + + return ClassSetGroup(classSets.toTypedArray()) + } + + private fun loadMavenLibraries(config: ParamorphismConfig): List = + config.mavenLibraries.getOrDefault(emptyArray()).map { file -> + ResourceBackedClassSet(ZipResourceSet(file), ClassReader.SKIP_CODE) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/ParamorphismMain.kt b/src/main/kotlin/site/hackery/paramorphism/ParamorphismMain.kt new file mode 100644 index 0000000..a767231 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/ParamorphismMain.kt @@ -0,0 +1,54 @@ +@file:JvmName("ParamorphismMain") + +package site.hackery.paramorphism + +import com.fasterxml.jackson.core.JsonParseException +import site.hackery.paramorphism.config.ParamorphismConfig +import site.hackery.paramorphism.update.UpdateCheckThread +import site.hackery.paramorphism.util.logging.LogLevel +import site.hackery.paramorphism.util.logging.Logger +import java.io.File +import java.io.InputStreamReader + +const val VERSION: String = "1.3-beta-hotfix" + +fun main(args: Array) { + val updateThread = UpdateCheckThread() + updateThread.start() + runCommandLine(args) + updateThread.join() + + val updateInfo = updateThread.updateInformation ?: return + val latestVersion = updateInfo.last() + val currentIndex = updateInfo.indexOf(VERSION) + if (currentIndex != -1 && currentIndex < updateInfo.lastIndex) { + println() + Logger.log(LogLevel.WARNING, "Your current version is outdated!") + Logger.log(LogLevel.WARNING, "Your version: $VERSION, new version: $latestVersion") + Logger.log(LogLevel.WARNING, "Download the new version at: https://paramorphism.serenity.enterprises/") + if (System.getProperty("os.name").contains("Windows")) { + print("\nPress return to exit...") + InputStreamReader(System.`in`, Charsets.UTF_8).read() + } + } +} + +private fun runCommandLine(args: Array) { + if (args.isEmpty()) { + println("Usage:") + println("\tparamorphism.jar [config]") + return + } + val configFile = File(args.joinToString(" ")) + if (!configFile.exists()) { + println("Config file was not found: ${configFile.absolutePath}") + return + } + try { + val config = ParamorphismConfig(configFile) + ObfuscationPipeline.run(config) + } catch (ex: JsonParseException) { + System.err.println("There was an error parsing the configuration file:") + System.err.println(ex.message) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigAccess.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigAccess.kt new file mode 100644 index 0000000..3a918f8 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigAccess.kt @@ -0,0 +1,12 @@ +@file:JvmName("ConfigAccess") + +package site.hackery.paramorphism.config + +inline fun ConfigDocument.getTyped(key: String): T? = + getValue(key, T::class.java) + +inline fun ConfigDocument.getOrDefault(key: String, defaultValue: T): T = + getValue(key, T::class.java) ?: defaultValue + +inline fun ConfigDocument.getArray(key: String): Array? = + getValue(key, Array::class.java) diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigDecoder.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigDecoder.kt new file mode 100644 index 0000000..a368e49 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigDecoder.kt @@ -0,0 +1,103 @@ +package site.hackery.paramorphism.config + +import com.fasterxml.jackson.core.type.TypeReference +import site.hackery.paramorphism.util.maven.MavenLibraryResolver +import site.hackery.paramorphism.util.naming.NameDictionaries +import site.hackery.paramorphism.util.naming.NameDictionary +import site.hackery.paramorphism.util.naming.NameGenerator +import java.io.File + +interface ConfigDecoder { + fun decode(document: ConfigDocument, key: String): T? + + companion object { + val stringDecoder: ScalarConfigDecoder = ScalarConfigDecoder(String::class) + val stringArrayDecoder: ScalarConfigDecoder> = ScalarConfigDecoder(Array::class) + val integerDecoder: ScalarConfigDecoder = ScalarConfigDecoder(Int::class) + val booleanDecoder: ScalarConfigDecoder = ScalarConfigDecoder(Boolean::class) + + val fileDecoder: ConfigDecoder = object : ConfigDecoder { + override fun decode(document: ConfigDocument, key: String): File? = + document.getValue(key, String::class.java)?.let { document.resolvePath(it) } + } + + val fileArrayDecoder: ConfigDecoder> = object : ConfigDecoder> { + override fun decode(document: ConfigDocument, key: String): Array? { + val paths = document.getValue(key, Array::class.java) ?: return null + return paths.map { document.resolvePath(it) }.toTypedArray() + } + } + + val elementMaskDecoder: ConfigDecoder = object : ConfigDecoder { + override fun decode(document: ConfigDocument, key: String): ElementMask? { + val includes = stringArrayDecoder.decode(document, "$key.include") ?: emptyArray() + val excludes = stringArrayDecoder.decode(document, "$key.exclude") ?: emptyArray() + return if (includes.isEmpty() && excludes.isEmpty()) null else ElementMask(includes, excludes) + } + } + + val nameAffixDecoder: ConfigDecoder> = object : ConfigDecoder> { + override fun decode(document: ConfigDocument, key: String): Array? { + val map = document.getValue(key, object : TypeReference>() {}) ?: 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> = object : ConfigDecoder> { + override fun decode(document: ConfigDocument, key: String): Array { + val result = Array(4) { NameDictionaries.ALPHABET } + val map = document.getValue(key, object : TypeReference>() {}) ?: 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 = object : ConfigDecoder { + 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 = object : ConfigDecoder { + override fun decode(document: ConfigDocument, key: String): ConfigFlags { + val map = document.getValue(key, object : TypeReference>() {}) ?: emptyMap() + return ConfigFlags(map) + } + } + + val mavenLibrariesDecoder: ConfigDecoder> = object : ConfigDecoder> { + override fun decode(document: ConfigDocument, key: String): Array? { + val repos = document.getValue(key, object : TypeReference>>() {}) ?: return null + val resolvedFiles = ArrayList() + 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() + } + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigDocument.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigDocument.kt new file mode 100644 index 0000000..dabe709 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigDocument.kt @@ -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 convertValue(node: JsonNode, type: Class): T? { + if (node.isMissingNode || node.isNull) { + return null + } + return try { + mapper.treeToValue(node, type) + } catch (_: Exception) { + null + } + } + + private fun convertValue(node: JsonNode, typeReference: TypeReference): 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 getValue(key: String, type: Class): T? = convertValue(findNode(key), type) + + fun getValue(key: String, typeReference: TypeReference): T? = convertValue(findNode(key), typeReference) + + fun resolvePath(path: String): File { + val candidate = File(path) + return if (candidate.isAbsolute) candidate else File(file.parentFile, path) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigFlags.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigFlags.kt new file mode 100644 index 0000000..a8e8d91 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigFlags.kt @@ -0,0 +1,5 @@ +package site.hackery.paramorphism.config + +class ConfigFlags(private val flags: Map) { + operator fun get(flag: String): Boolean? = flags[flag] +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ConfigValue.kt b/src/main/kotlin/site/hackery/paramorphism/config/ConfigValue.kt new file mode 100644 index 0000000..5b4c05b --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ConfigValue.kt @@ -0,0 +1,12 @@ +package site.hackery.paramorphism.config + +class ConfigValue( + private val document: ConfigDocument, + private val key: String, + private val decoder: ConfigDecoder, + private val defaultValue: T? = null +) { + fun get(): T? = decoder.decode(document, key) ?: defaultValue + + fun getOrDefault(fallback: T): T = decoder.decode(document, key) ?: fallback +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ElementMask.kt b/src/main/kotlin/site/hackery/paramorphism/config/ElementMask.kt new file mode 100644 index 0000000..32a7628 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ElementMask.kt @@ -0,0 +1,24 @@ +package site.hackery.paramorphism.config + +class ElementMask( + private val includes: Array, + private val excludes: Array +) { + 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 + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ParamorphismConfig.kt b/src/main/kotlin/site/hackery/paramorphism/config/ParamorphismConfig.kt new file mode 100644 index 0000000..c8f1ee1 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ParamorphismConfig.kt @@ -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 = ConfigValue(this, "input", ConfigDecoder.fileDecoder) + val output: ConfigValue = ConfigValue(this, "output", ConfigDecoder.fileDecoder) + val libraries: ConfigValue> = ConfigValue(this, "libraries", ConfigDecoder.fileArrayDecoder) + val mavenLibraries: ConfigValue> = ConfigValue(this, "maven_libraries", ConfigDecoder.mavenLibrariesDecoder) + val addJavaRuntime: ConfigValue = ConfigValue(this, "add_java_runtime", ConfigDecoder.booleanDecoder) + val shadedLibraries: ConfigValue = ConfigValue(this, "shaded_libraries", ConfigDecoder.elementMaskDecoder) + val mask: ConfigValue = ConfigValue(this, "mask", ConfigDecoder.elementMaskDecoder) + val flags: ConfigValue = ConfigValue(this, "flags", ConfigDecoder.flagsDecoder) + val nameGeneration: ConfigValue = ConfigValue(this, "name_generation", ConfigDecoder.nameGeneratorDecoder) + val randomOffset: ConfigValue = ConfigValue(this, "random_offset", ConfigDecoder.integerDecoder) + val branding: ConfigValue = ConfigValue(this, "branding", ConfigDecoder.booleanDecoder) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/config/ScalarConfigDecoder.kt b/src/main/kotlin/site/hackery/paramorphism/config/ScalarConfigDecoder.kt new file mode 100644 index 0000000..128665e --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/config/ScalarConfigDecoder.kt @@ -0,0 +1,8 @@ +package site.hackery.paramorphism.config + +import kotlin.reflect.KClass + +class ScalarConfigDecoder(private val type: KClass) : ConfigDecoder { + override fun decode(document: ConfigDocument, key: String): T? = + document.getValue(key, type.java) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/ByteArrayResource.kt b/src/main/kotlin/site/hackery/paramorphism/resources/ByteArrayResource.kt new file mode 100644 index 0000000..3d61f02 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/ByteArrayResource.kt @@ -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 +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/ClassSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/ClassSet.kt new file mode 100644 index 0000000..209a6e2 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/ClassSet.kt @@ -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> + + fun names(): Sequence +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/ClassSetGroup.kt b/src/main/kotlin/site/hackery/paramorphism/resources/ClassSetGroup.kt new file mode 100644 index 0000000..2a52b9d --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/ClassSetGroup.kt @@ -0,0 +1,37 @@ +package site.hackery.paramorphism.resources + +import org.objectweb.asm.tree.ClassNode +import java.io.Closeable + +class ClassSetGroup(val classSets: Array) : Closeable { + private val classSetIndices = LinkedHashMap() + + 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> = + classSets.asSequence().flatMap { it.entries() } + + override fun close() { + for (classSet in classSets) { + runCatching { classSet.close() } + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/LazyResource.kt b/src/main/kotlin/site/hackery/paramorphism/resources/LazyResource.kt new file mode 100644 index 0000000..f74a695 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/LazyResource.kt @@ -0,0 +1,8 @@ +package site.hackery.paramorphism.resources + +class LazyResource( + val supplier: () -> ByteArray, + writePriority: Int = 1 +) : Resource(writePriority) { + override fun getBytes(): ByteArray = supplier() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/ManifestResource.kt b/src/main/kotlin/site/hackery/paramorphism/resources/ManifestResource.kt new file mode 100644 index 0000000..89e5270 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/ManifestResource.kt @@ -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() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/Resource.kt b/src/main/kotlin/site/hackery/paramorphism/resources/Resource.kt new file mode 100644 index 0000000..2a1e183 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/Resource.kt @@ -0,0 +1,5 @@ +package site.hackery.paramorphism.resources + +sealed class Resource(val writePriority: Int) { + abstract fun getBytes(): ByteArray +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/ResourceSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/ResourceSet.kt new file mode 100644 index 0000000..e4cd498 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/ResourceSet.kt @@ -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> + + fun names(): Sequence +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/TaggedResource.kt b/src/main/kotlin/site/hackery/paramorphism/resources/TaggedResource.kt new file mode 100644 index 0000000..0e127e5 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/TaggedResource.kt @@ -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() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/io/FileSystemResourceSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/io/FileSystemResourceSet.kt new file mode 100644 index 0000000..3e90713 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/io/FileSystemResourceSet.kt @@ -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 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> = + Files.walk(walkRoot()) + .asSequence() + .filter { Files.isRegularFile(it) } + .map { path -> normalizeEntryName(path) to LazyResource({ Files.readAllBytes(path) }) } + + override fun names(): Sequence = + 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. + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/io/ZipResourceSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/io/ZipResourceSet.kt new file mode 100644 index 0000000..51966e1 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/io/ZipResourceSet.kt @@ -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> = + 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 = + zipFile.stream().asSequence().map { it.name } + + override fun close() { + zipFile.close() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/masking/IncludedClassSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/masking/IncludedClassSet.kt new file mode 100644 index 0000000..1889fd0 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/masking/IncludedClassSet.kt @@ -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> = + delegate.entries().filter { (name, _) -> mask.matches(name) } + + override fun names(): Sequence = + delegate.names().filter { mask.matches(it) } + + override fun close() { + delegate.close() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/masking/MaskedClassSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/masking/MaskedClassSet.kt new file mode 100644 index 0000000..35a3862 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/masking/MaskedClassSet.kt @@ -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> = + delegate.entries().filter { (name, _) -> !mask.matches(name) } + + override fun names(): Sequence = + delegate.names().filter { !mask.matches(it) } + + override fun close() { + delegate.close() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/overlay/OverlayClassSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/overlay/OverlayClassSet.kt new file mode 100644 index 0000000..6579992 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/overlay/OverlayClassSet.kt @@ -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 = 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> { + 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 { + val localNames = overrides.keys.asSequence() + val parentNames = parent?.names()?.filter { !overrides.containsKey(it) } ?: emptySequence() + return localNames + parentNames + } + + override fun close() { + parent?.close() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/overlay/OverlayResourceSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/overlay/OverlayResourceSet.kt new file mode 100644 index 0000000..3455b29 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/overlay/OverlayResourceSet.kt @@ -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 = 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> { + 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 { + val localNames = overrides.keys.asSequence() + val parentNames = parent?.names()?.filter { !overrides.containsKey(it) } ?: emptySequence() + return localNames + parentNames + } + + override fun close() { + parent?.close() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/views/NonClassResourceSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/views/NonClassResourceSet.kt new file mode 100644 index 0000000..a31c617 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/views/NonClassResourceSet.kt @@ -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> = + delegate.entries().filter { (name, _) -> !name.endsWith(".class") } + + override fun names(): Sequence = + delegate.names().filter { !it.endsWith(".class") } + + override fun close() { + delegate.close() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/resources/views/ResourceBackedClassSet.kt b/src/main/kotlin/site/hackery/paramorphism/resources/views/ResourceBackedClassSet.kt new file mode 100644 index 0000000..db24365 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/resources/views/ResourceBackedClassSet.kt @@ -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> = + resources.entries() + .filter { (name, _) -> name.endsWith(".class") } + .map { (name, resource) -> name.dropLast(".class".length) to readClass(resource.getBytes()) } + + override fun names(): Sequence = + 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) } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/Strategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/Strategy.kt new file mode 100644 index 0000000..05bc794 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/Strategy.kt @@ -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) { + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyPass.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyPass.kt new file mode 100644 index 0000000..844d0a4 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyPass.kt @@ -0,0 +1,6 @@ +package site.hackery.paramorphism.strategy + +class StrategyPass( + val name: String, + private val strategies: MutableList +) : MutableList by strategies diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyPipeline.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyPipeline.kt new file mode 100644 index 0000000..ae62434 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyPipeline.kt @@ -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() + private val passes: List + + init { + val flags = config.flags.get()!! + val builtPasses = ArrayList() + + 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() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyUtils.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyUtils.kt new file mode 100644 index 0000000..f5c2d42 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/StrategyUtils.kt @@ -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()) + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/ControlFlowManglingStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/ControlFlowManglingStrategy.kt new file mode 100644 index 0000000..0788ad4 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/ControlFlowManglingStrategy.kt @@ -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") + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/BasicBlock.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/BasicBlock.kt new file mode 100644 index 0000000..bb528d7 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/BasicBlock.kt @@ -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 = ArrayList() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/BasicBlockBuilder.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/BasicBlockBuilder.kt new file mode 100644 index 0000000..990b94b --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/BasicBlockBuilder.kt @@ -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 = ArrayList() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/ControlFlowAnalyzer.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/ControlFlowAnalyzer.kt new file mode 100644 index 0000000..c8b7e38 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/ControlFlowAnalyzer.kt @@ -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(interpreter: Interpreter) : Analyzer(interpreter) { + val successors: MutableMap> = 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) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/ControlFlowGraphUtils.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/ControlFlowGraphUtils.kt new file mode 100644 index 0000000..a8ce9d6 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/controlflow/graph/ControlFlowGraphUtils.kt @@ -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>): Map> { + val reversed = LinkedHashMap>() + for ((source, targets) in edges) { + for (target in targets) { + reversed.getOrPut(target) { LinkedHashSet() }.add(source) + } + } + return reversed +} + +fun buildBlocks(classNode: ClassNode, methodNode: MethodNode): Set { + 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() + 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() + + 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() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/debug/DebugInfoScrubbingStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/debug/DebugInfoScrubbingStrategy.kt new file mode 100644 index 0000000..d423b32 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/debug/DebugInfoScrubbingStrategy.kt @@ -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) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/FieldAccessIndirectionStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/FieldAccessIndirectionStrategy.kt new file mode 100644 index 0000000..20b6636 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/FieldAccessIndirectionStrategy.kt @@ -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() + + 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() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/FieldLookup.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/FieldLookup.kt new file mode 100644 index 0000000..a837fda --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/FieldLookup.kt @@ -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 +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/MethodCallIndirectionStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/MethodCallIndirectionStrategy.kt new file mode 100644 index 0000000..befd64c --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/MethodCallIndirectionStrategy.kt @@ -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() + + 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() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/MethodLookup.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/MethodLookup.kt new file mode 100644 index 0000000..e33b995 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/MethodLookup.kt @@ -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 +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/StringIndirectionStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/StringIndirectionStrategy.kt new file mode 100644 index 0000000..3219247 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/StringIndirectionStrategy.kt @@ -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() + + 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() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/GeneratedMethod.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/GeneratedMethod.kt new file mode 100644 index 0000000..b0c8899 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/GeneratedMethod.kt @@ -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 +) diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/GeneratedMethodFactory.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/GeneratedMethodFactory.kt new file mode 100644 index 0000000..9323c95 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/GeneratedMethodFactory.kt @@ -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() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/MethodGenerationUtils.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/MethodGenerationUtils.kt new file mode 100644 index 0000000..6614249 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/MethodGenerationUtils.kt @@ -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() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/impl/DirectMethodGenerator.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/impl/DirectMethodGenerator.kt new file mode 100644 index 0000000..ebf7594 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/impl/DirectMethodGenerator.kt @@ -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() + 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) + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/impl/PackedMethodGenerator.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/impl/PackedMethodGenerator.kt new file mode 100644 index 0000000..58d0fb5 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/indirection/generation/impl/PackedMethodGenerator.kt @@ -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() + private val generatedResources = ArrayList>() + + 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, "", "()V", null, null).apply { + instructions.add(VarInsnNode(Opcodes.ALOAD, 0)) + instructions.add(MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()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, "", "()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, + "", + "(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 { + 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++ + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/kotlin/KotlinIntrinsicsConcealmentStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/kotlin/KotlinIntrinsicsConcealmentStrategy.kt new file mode 100644 index 0000000..59adafa --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/kotlin/KotlinIntrinsicsConcealmentStrategy.kt @@ -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) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/kotlin/KotlinMetadataScrubbingStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/kotlin/KotlinMetadataScrubbingStrategy.kt new file mode 100644 index 0000000..9b5eb88 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/kotlin/KotlinMetadataScrubbingStrategy.kt @@ -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) + } + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/CachingRemapper.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/CachingRemapper.kt new file mode 100644 index 0000000..3267358 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/CachingRemapper.kt @@ -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() + private val methodNames = LinkedHashMap() + private val fieldNames = LinkedHashMap() + + 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?): Array = + 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) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/MappingTreeRemapper.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/MappingTreeRemapper.kt new file mode 100644 index 0000000..b3d993e --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/MappingTreeRemapper.kt @@ -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, + val lambdaMappings: Map, + val mainClass: String? = null +) : Remapper() { + private val methodSignaturesByClass: Map> = + 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) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/RenamingStrategy.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/RenamingStrategy.kt new file mode 100644 index 0000000..54bcb0c --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/RenamingStrategy.kt @@ -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 + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/ClassIndexAssignment.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/ClassIndexAssignment.kt new file mode 100644 index 0000000..9f3b0ef --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/ClassIndexAssignment.kt @@ -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) + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/FieldIndexAssignment.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/FieldIndexAssignment.kt new file mode 100644 index 0000000..68f7f3c --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/FieldIndexAssignment.kt @@ -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("") + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/MappingIndexAssignment.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/MappingIndexAssignment.kt new file mode 100644 index 0000000..3bf5a4b --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/MappingIndexAssignment.kt @@ -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, + context: ObfuscationContext + ) { + ClassIndexAssignment.assignClassIndices(mappingTree.root, context) + MethodIndexAssignment.assignMethodIndices(mappingTree, hierarchy, context) + FieldIndexAssignment.assignFieldIndices(mappingTree, context) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/MethodIndexAssignment.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/MethodIndexAssignment.kt new file mode 100644 index 0000000..a00d100 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/MethodIndexAssignment.kt @@ -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, + context: ObfuscationContext + ) { + val signatureIndices = LinkedHashMap() + 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 + ): List { + val ownerName = MappingNodeUtils.internalName(methodMapping.parent!!) + val ownerNode = hierarchy.getValue(ownerName) + val ancestors = ArrayList() + + 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 + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/ScopedIndexAllocator.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/ScopedIndexAllocator.kt new file mode 100644 index 0000000..97b5cc0 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/assignment/ScopedIndexAllocator.kt @@ -0,0 +1,35 @@ +package site.hackery.paramorphism.strategy.renaming.assignment + +import java.util.Stack + +class ScopedIndexAllocator { + private val nextIndices = LinkedHashMap() + private val reusableIndices = LinkedHashMap>() + private val reservedIndices = LinkedHashMap>() + + 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) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/lambda/LambdaMappingUtils.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/lambda/LambdaMappingUtils.kt new file mode 100644 index 0000000..646d08d --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/lambda/LambdaMappingUtils.kt @@ -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 + ): Map { + val mappings = LinkedHashMap() + 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 = + classes.entries() + .map { (_, classNode) -> classNode } + .flatMap { it.methods.asSequence() } + .flatMap { it.instructions.iterator().asSequence() } + .filterIsInstance() +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingNode.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingNode.kt new file mode 100644 index 0000000..2e8bd65 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingNode.kt @@ -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 = 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() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingNodeUtils.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingNodeUtils.kt new file mode 100644 index 0000000..4be48cc --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingNodeUtils.kt @@ -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() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingTree.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingTree.kt new file mode 100644 index 0000000..639986e --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingTree.kt @@ -0,0 +1,8 @@ +package site.hackery.paramorphism.strategy.renaming.tree + +class MappingTree( + val root: MappingNode, + val classes: List, + val methods: List, + val fields: List +) diff --git a/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingTreeBuilder.kt b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingTreeBuilder.kt new file mode 100644 index 0000000..e57695f --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/strategy/renaming/tree/MappingTreeBuilder.kt @@ -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() + val methodNodes = ArrayList() + val fieldNodes = ArrayList() + + 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) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/update/UpdateCheckThread.kt b/src/main/kotlin/site/hackery/paramorphism/update/UpdateCheckThread.kt new file mode 100644 index 0000000..a7c3161 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/update/UpdateCheckThread.kt @@ -0,0 +1,9 @@ +package site.hackery.paramorphism.update + +class UpdateCheckThread : Thread("Paramorphism Update Thread") { + var updateInformation: Array? = null + + override fun run() { + // no + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/update/UpdateEndpoint.kt b/src/main/kotlin/site/hackery/paramorphism/update/UpdateEndpoint.kt new file mode 100644 index 0000000..fd4428a --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/update/UpdateEndpoint.kt @@ -0,0 +1,5 @@ +package site.hackery.paramorphism.update + +object UpdateEndpoint { + const val UPDATE_URL: String = "https://musee.paramorphism.serenity.enterprises" +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/RandomContext.kt b/src/main/kotlin/site/hackery/paramorphism/util/RandomContext.kt new file mode 100644 index 0000000..07f510f --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/RandomContext.kt @@ -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()) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/ReservedMembers.kt b/src/main/kotlin/site/hackery/paramorphism/util/ReservedMembers.kt new file mode 100644 index 0000000..9b4b564 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/ReservedMembers.kt @@ -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 == "" || name == "") { + 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};" +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/context/ContextStore.kt b/src/main/kotlin/site/hackery/paramorphism/util/context/ContextStore.kt new file mode 100644 index 0000000..ff97ae8 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/context/ContextStore.kt @@ -0,0 +1,25 @@ +package site.hackery.paramorphism.util.context + +class ContextStore { + private val namedValues = LinkedHashMap() + private val typedValues = LinkedHashMap, 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 putTyped(value: T, type: Class) { + typedValues[type] = value + } + + @Suppress("UNCHECKED_CAST") + fun getTyped(type: Class): T = typedValues[type] as T + + fun typedProperty(type: Class): TypedContextProperty = TypedContextProperty(type, typedValues) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/context/MutableObfuscationContext.kt b/src/main/kotlin/site/hackery/paramorphism/util/context/MutableObfuscationContext.kt new file mode 100644 index 0000000..94a38aa --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/context/MutableObfuscationContext.kt @@ -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 getService(type: Class): T = store.getTyped(type) + + fun putService(type: Class, value: T) { + store.putTyped(value, type) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/context/NamedContextProperty.kt b/src/main/kotlin/site/hackery/paramorphism/util/context/NamedContextProperty.kt new file mode 100644 index 0000000..2b7256d --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/context/NamedContextProperty.kt @@ -0,0 +1,15 @@ +package site.hackery.paramorphism.util.context + +import kotlin.reflect.KProperty + +class NamedContextProperty( + val key: String, + val values: MutableMap +) { + inline operator fun getValue(thisRef: Any?, property: KProperty<*>): T = + values[key] as T + + operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { + values[key] = value + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/context/ObfuscationContext.kt b/src/main/kotlin/site/hackery/paramorphism/util/context/ObfuscationContext.kt new file mode 100644 index 0000000..e3f4bd6 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/context/ObfuscationContext.kt @@ -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 getService(type: Class): T = store.getTyped(type) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/context/TypedContextProperty.kt b/src/main/kotlin/site/hackery/paramorphism/util/context/TypedContextProperty.kt new file mode 100644 index 0000000..cf958c3 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/context/TypedContextProperty.kt @@ -0,0 +1,15 @@ +package site.hackery.paramorphism.util.context + +import kotlin.reflect.KProperty + +class TypedContextProperty( + val keyType: Class<*>, + val values: MutableMap, Any> +) { + inline operator fun getValue(thisRef: Any?, property: KProperty<*>): T = + values[keyType] as T + + operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { + values[keyType] = value + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/hierarchy/ClassHierarchyBuilder.kt b/src/main/kotlin/site/hackery/paramorphism/util/hierarchy/ClassHierarchyBuilder.kt new file mode 100644 index 0000000..0a1113e --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/hierarchy/ClassHierarchyBuilder.kt @@ -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() + + fun buildHierarchy(classes: ClassSet, libraries: ClassSetGroup): Map { + val hierarchy = LinkedHashMap() + 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 + ): 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 + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/hierarchy/ClassHierarchyNode.kt b/src/main/kotlin/site/hackery/paramorphism/util/hierarchy/ClassHierarchyNode.kt new file mode 100644 index 0000000..b537021 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/hierarchy/ClassHierarchyNode.kt @@ -0,0 +1,9 @@ +package site.hackery.paramorphism.util.hierarchy + +class ClassHierarchyNode( + val name: String, + val methodSignatures: Array, + val fieldSignatures: Array, + val superClass: ClassHierarchyNode?, + val interfaces: Array +) diff --git a/src/main/kotlin/site/hackery/paramorphism/util/logging/LogLevel.kt b/src/main/kotlin/site/hackery/paramorphism/util/logging/LogLevel.kt new file mode 100644 index 0000000..51058fa --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/logging/LogLevel.kt @@ -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") +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/logging/Logger.kt b/src/main/kotlin/site/hackery/paramorphism/util/logging/Logger.kt new file mode 100644 index 0000000..c6f989e --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/logging/Logger.kt @@ -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) + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/logging/PerformanceProfiler.kt b/src/main/kotlin/site/hackery/paramorphism/util/logging/PerformanceProfiler.kt new file mode 100644 index 0000000..6e54be2 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/logging/PerformanceProfiler.kt @@ -0,0 +1,78 @@ +package site.hackery.paramorphism.util.logging + +import java.util.Stack + +object PerformanceProfiler { + val phaseStartTimes = Stack() + val phaseNames = Stack() + val sectionTimings = Stack>() + val activeSections = Stack() + val sectionStartTimes = Stack() + + 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 measurePhase(phaseName: String, block: () -> R): R { + beginPhase(phaseName) + val result = block() + endPhase() + return result + } + + inline fun 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()) + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/manifest/ManifestAttributes.kt b/src/main/kotlin/site/hackery/paramorphism/util/manifest/ManifestAttributes.kt new file mode 100644 index 0000000..c40bebb --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/manifest/ManifestAttributes.kt @@ -0,0 +1,7 @@ +package site.hackery.paramorphism.util.manifest + +import java.util.jar.Attributes + +object ManifestAttributes { + val OBFUSCATED_BY: Attributes.Name = Attributes.Name("Obfuscated-By") +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/maven/MavenLibraryResolver.kt b/src/main/kotlin/site/hackery/paramorphism/util/maven/MavenLibraryResolver.kt new file mode 100644 index 0000000..fa68f95 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/maven/MavenLibraryResolver.kt @@ -0,0 +1,49 @@ +package site.hackery.paramorphism.util.maven + +import org.apache.maven.repository.internal.MavenRepositorySystemUtils +import org.eclipse.aether.DefaultRepositorySystemSession +import org.eclipse.aether.RepositorySystem +import org.eclipse.aether.artifact.DefaultArtifact +import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory +import org.eclipse.aether.impl.DefaultServiceLocator +import org.eclipse.aether.repository.LocalRepository +import org.eclipse.aether.resolution.ArtifactRequest +import org.eclipse.aether.spi.connector.RepositoryConnectorFactory +import org.eclipse.aether.spi.connector.transport.TransporterFactory +import org.eclipse.aether.transport.file.FileTransporterFactory +import site.hackery.paramorphism.util.logging.LogLevel +import site.hackery.paramorphism.util.logging.Logger +import java.io.File + +class MavenLibraryResolver(repositoryDir: File) { + private val localRepository = LocalRepository(repositoryDir) + private val repositorySystem: RepositorySystem + private val session: DefaultRepositorySystemSession = MavenRepositorySystemUtils.newSession() + + init { + @Suppress("DEPRECATION") + val locator: DefaultServiceLocator = MavenRepositorySystemUtils.newServiceLocator() + locator.addService(RepositoryConnectorFactory::class.java, BasicRepositoryConnectorFactory::class.java) + locator.addService(TransporterFactory::class.java, FileTransporterFactory::class.java) + locator.setErrorHandler(object : DefaultServiceLocator.ErrorHandler() { + override fun serviceCreationFailed(type: Class<*>?, impl: Class<*>?, exception: Throwable?) { + val message = exception?.message ?: "An exception occurred while locating a maven library." + Logger.log(LogLevel.ERROR, message) + } + }) + this.repositorySystem = locator.getService(RepositorySystem::class.java) + this.session.localRepositoryManager = repositorySystem.newLocalRepositoryManager(session, localRepository) + } + + fun resolveArtifact(coordinates: String): File? { + val request = ArtifactRequest().apply { + artifact = DefaultArtifact(coordinates) + } + return try { + repositorySystem.resolveArtifact(session, request).artifact.file + } catch (ex: Exception) { + Logger.log(LogLevel.ERROR, "An error occurred while locating a maven library: ${ex.message}") + null + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/naming/DictionaryIndexEncoding.kt b/src/main/kotlin/site/hackery/paramorphism/util/naming/DictionaryIndexEncoding.kt new file mode 100644 index 0000000..86c6a94 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/naming/DictionaryIndexEncoding.kt @@ -0,0 +1,21 @@ +package site.hackery.paramorphism.util.naming + +import java.util.Random + +object DictionaryIndexEncoding { + fun identityIndices(size: Int): IntArray = IntArray(size) { it } + + fun shuffleIndices(size: Int, random: Random): IntArray { + val indices = identityIndices(size) + for (i in indices.indices) { + val swapIndex = random.nextInt(size) + val tmp = indices[i] + indices[i] = indices[swapIndex] + indices[swapIndex] = tmp + } + return indices + } + + fun tokenAt(dictionary: NameDictionary, index: Int, permutation: IntArray): String = + dictionary.tokens[permutation[index]] +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/naming/NameDictionaries.kt b/src/main/kotlin/site/hackery/paramorphism/util/naming/NameDictionaries.kt new file mode 100644 index 0000000..17abd20 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/naming/NameDictionaries.kt @@ -0,0 +1,57 @@ +package site.hackery.paramorphism.util.naming + +object NameDictionaries { + val ALPHABET: NameDictionary = fromCharacters("abcdefghijklmnopqrstuvwxyz") + val ALPHABET_UPPER: NameDictionary = fromCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + + val JAVA_KEYWORDS: NameDictionary = NameDictionary( + tokens = arrayOf( + "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", + "class", "const", "continue", "default", "do", "double", "else", "enum", + "extends", "false", "final", "finally", "float", "for", "goto", "if", + "implements", "import", "instanceof", "int", "interface", "long", "native", "new", + "null", "package", "private", "protected", "public", "return", "short", "static", + "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", + "true", "try", "void", "volatile", "while" + ), + separator = "\u00a0" + ) + + val ENTERPRISE: NameDictionary = NameDictionary( + tokens = arrayOf( + "Abstract", "Adapter", "Advisable", "Advisor", "Annotation", "Aspect", "Attribute", + "Authentication", "Aware", "Based", "Batch", "Bean", "Bridge", "Broadcaster", + "Business", "Callback", "Candidate", "Client", "Clone", "Collection", "Common", + "Comparator", "Composer", "Composite", "Concrete", "Configuration", "Connection", + "Consumer", "Container", "Context", "Data", "Database", "Decorator", "Definition", + "Descriptor", "Dispatcher", "Distributed", "Driven", "Error", "Event", "Exception", + "Exporter", "Expression", "Facade", "Factory", "Failure", "Field", "Filter", + "Focus", "Generic", "Getter", "Global", "Helper", "HTTP", "Identifiable", + "Identifier", "Importer", "Info", "Initializer", "Instance", "Interceptor", + "Interface", "Interpreter", "Interruptible", "Invalid", "Invocation", "Iterable", + "Iterator", "JDBC", "JMS", "List", "Listener", "Literal", "Management", + "Manager", "Map", "Mapper", "Mapping", "Message", "Meta", "Method", "Mock", + "Model", "Multipart", "Notification", "Object", "Observable", "Observer", "Order", + "Parameter", "Parser", "Policy", "Pool", "Predicate", "Prepared", "Principal", + "Printer", "Proccesor", "Producer", "Property", "Prototype", "Proxy", "Publisher", + "Queue", "Readable", "Reflective", "Registry", "Remote", "Response", "Repository", + "Request", "Resolver", "Rules", "Schema", "Scope", "Serializer", "Server", + "Service", "Servlet", "Session", "Setter", "Simple", "Singleton", "State", + "Stateless", "Statement", "Strategy", "String", "Stub", "Supported", "Tag", + "Task", "Template", "Test", "Tests", "Thread", "Token", "Tokenizer", + "Transaction", "Transactional", "Transformer", "Traversal", "Type", "Util", + "Utilities", "Utils", "Value", "Visitor", "Watcher", "Worker", "Wrapper", "XML" + ), + defaultInflation = 3 + ) + + val dictionaries: Map = mapOf( + "alphabet" to ALPHABET, + "alphabet_upper" to ALPHABET_UPPER, + "java_keywords" to JAVA_KEYWORDS, + "enterprise" to ENTERPRISE + ) + + private fun fromCharacters(characters: String): NameDictionary = + NameDictionary(characters.toCharArray().map { it.toString() }.toTypedArray()) +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/naming/NameDictionary.kt b/src/main/kotlin/site/hackery/paramorphism/util/naming/NameDictionary.kt new file mode 100644 index 0000000..e76a767 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/naming/NameDictionary.kt @@ -0,0 +1,7 @@ +package site.hackery.paramorphism.util.naming + +class NameDictionary( + val tokens: Array, + val separator: String = "", + val defaultInflation: Int = 0 +) diff --git a/src/main/kotlin/site/hackery/paramorphism/util/naming/NameGenerator.kt b/src/main/kotlin/site/hackery/paramorphism/util/naming/NameGenerator.kt new file mode 100644 index 0000000..b623e9c --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/naming/NameGenerator.kt @@ -0,0 +1,77 @@ +package site.hackery.paramorphism.util.naming + +import site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind +import java.util.Random + +class NameGenerator( + private val dictionaries: Array, + private val inflation: Int? = null, + private val prefixes: Array = arrayOfNulls(4), + private val suffixes: Array = arrayOfNulls(4), + private val shuffle: Boolean = false +) { + lateinit var random: Random + var prefixClassNamesWithNul: Boolean = false + + private val inflationRandom = Random(0L) + private val indexPermutations = LinkedHashMap, IntArray>() + + private fun dictionaryFor(kind: MappingElementKind): NameDictionary = + dictionaries[minOf(kind.ordinal, dictionaries.lastIndex)] + + private fun permutationFor(dictionary: NameDictionary, generation: Int): IntArray { + val cacheKey = dictionary to generation + return indexPermutations.getOrPut(cacheKey) { + if (shuffle) { + DictionaryIndexEncoding.shuffleIndices(dictionary.tokens.size, random) + } else { + DictionaryIndexEncoding.identityIndices(dictionary.tokens.size) + } + } + } + + fun generateName(generation: Int, index: Int, kind: MappingElementKind): String? { + if (index < 0) { + return null + } + val dictionary = dictionaryFor(kind) + val inflationCount = inflation ?: dictionary.defaultInflation + val permutation = permutationFor(dictionary, generation) + val builder = StringBuilder() + + if (inflationCount != 0) { + inflationRandom.setSeed(index.toLong()) + repeat(inflationCount) { + val randomToken = DictionaryIndexEncoding.tokenAt( + dictionary, + inflationRandom.nextInt(dictionary.tokens.size), + permutation + ) + builder.insert(0, randomToken) + builder.insert(0, dictionary.separator) + } + } + + var remaining = index + if (remaining == 0) { + builder.insert(0, DictionaryIndexEncoding.tokenAt(dictionary, 0, permutation)) + } + while (remaining > 0) { + val digit = remaining % dictionary.tokens.size + remaining /= dictionary.tokens.size + builder.insert(0, DictionaryIndexEncoding.tokenAt(dictionary, digit, permutation)) + if (remaining != 0) { + builder.insert(0, dictionary.separator) + } + } + + suffixes[kind.ordinal]?.let { builder.append(it) } + prefixes[kind.ordinal]?.let { builder.insert(0, it) } + + if (prefixClassNamesWithNul && (kind == MappingElementKind.CLASS || kind == MappingElementKind.PACKAGE)) { + builder.insert(0, '\u0000') + } + + return builder.toString() + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/runtime/JavaRuntimeClassSet.kt b/src/main/kotlin/site/hackery/paramorphism/util/runtime/JavaRuntimeClassSet.kt new file mode 100644 index 0000000..141d93a --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/runtime/JavaRuntimeClassSet.kt @@ -0,0 +1,34 @@ +package site.hackery.paramorphism.util.runtime + +import org.objectweb.asm.ClassReader +import site.hackery.paramorphism.resources.ClassSet +import site.hackery.paramorphism.resources.io.FileSystemResourceSet +import site.hackery.paramorphism.resources.io.ZipResourceSet +import site.hackery.paramorphism.resources.views.ResourceBackedClassSet +import java.io.File +import java.net.URI +import java.net.URLDecoder +import java.nio.charset.StandardCharsets +import java.nio.file.FileSystems + +object JavaRuntimeClassSet { + fun locateRuntimeClasses(): ClassSet { + val objectResource = Any::class.java.getResource("Object.class") + ?: error("Error obtaining resource for runtime class 'java/lang/Object'") + + return when (objectResource.protocol) { + "jar" -> { + val filePart = objectResource.file + val start = filePart.indexOf(':') + 1 + val end = filePart.indexOf('!') + val jarPath = URLDecoder.decode(filePart.substring(start, end), StandardCharsets.UTF_8.name()) + ResourceBackedClassSet(ZipResourceSet(File(jarPath)), ClassReader.SKIP_CODE) + } + "jrt" -> { + val jrtFileSystem = FileSystems.getFileSystem(URI.create("jrt:/")) + ResourceBackedClassSet(FileSystemResourceSet(jrtFileSystem), ClassReader.SKIP_CODE) + } + else -> error("Could not locate the runtime classes.") + } + } +} diff --git a/src/main/kotlin/site/hackery/paramorphism/util/zip/ZipDataDescriptorTransformers.kt b/src/main/kotlin/site/hackery/paramorphism/util/zip/ZipDataDescriptorTransformers.kt new file mode 100644 index 0000000..84aeed2 --- /dev/null +++ b/src/main/kotlin/site/hackery/paramorphism/util/zip/ZipDataDescriptorTransformers.kt @@ -0,0 +1,7 @@ +package site.hackery.paramorphism.util.zip + +class ZipDataDescriptorTransformers( + val crcTransformer: ((Long) -> Long)? = null, + val compressedSizeTransformer: ((Long) -> Long)? = null, + val sizeTransformer: ((Long) -> Long)? = null +) diff --git a/src/test/kotlin/site/hackery/paramorphism/ObfuscationPipelineTest.kt b/src/test/kotlin/site/hackery/paramorphism/ObfuscationPipelineTest.kt new file mode 100644 index 0000000..12e7257 --- /dev/null +++ b/src/test/kotlin/site/hackery/paramorphism/ObfuscationPipelineTest.kt @@ -0,0 +1,254 @@ +package site.hackery.paramorphism + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassWriter +import org.objectweb.asm.Handle +import org.objectweb.asm.Opcodes +import org.objectweb.asm.Type +import org.objectweb.asm.tree.ClassNode +import site.hackery.paramorphism.config.ElementMask +import site.hackery.paramorphism.config.ParamorphismConfig +import site.hackery.paramorphism.strategy.controlflow.graph.buildBlocks +import site.hackery.paramorphism.util.naming.NameDictionaries +import site.hackery.paramorphism.util.naming.NameGenerator +import java.io.File +import java.nio.file.Path +import java.util.Random +import java.util.jar.Attributes +import java.util.jar.JarEntry +import java.util.jar.JarFile +import java.util.jar.JarOutputStream +import java.util.jar.Manifest + +class ObfuscationPipelineTest { + + @Test + fun `obfuscates and executes sample jar end to end`(@TempDir tempDir: Path) { + val inputJar = tempDir.resolve("sample-in.jar").toFile() + val outputJar = tempDir.resolve("sample-out.jar").toFile() + val configFile = tempDir.resolve("config.yml").toFile() + + createSampleJar(inputJar) + + configFile.writeText( + """ + input: ${inputJar.absolutePath.replace("\\", "/")} + output: ${outputJar.absolutePath.replace("\\", "/")} + flags: + corruption: false + kotlin: false + """.trimIndent() + ) + + ObfuscationPipeline.run(ParamorphismConfig(configFile)) + assertTrue(outputJar.exists(), "Expected obfuscated jar to be created") + + JarFile(outputJar).use { jar -> + val manifest = jar.manifest + assertEquals("Paramorphism", manifest.mainAttributes.getValue("Obfuscated-By")) + val mainClass = manifest.mainAttributes.getValue(Attributes.Name.MAIN_CLASS) + assertNotEquals("sample.app.SampleApp", mainClass, "Main-Class should be redirected") + + val classEntries = jar.entries().toList().filter { it.name.endsWith(".class") && !it.name.endsWith("/") } + assertTrue(classEntries.size > 3, "Expected packed indirection classes in output jar") + assertFalse(classEntries.any { it.name == "sample/app/SampleApp.class" }, "Original class name should be remapped") + } + + val javaExe = Path.of(System.getProperty("java.home"), "bin", "java").toString() + val process = ProcessBuilder(javaExe, "-jar", outputJar.absolutePath) + .redirectErrorStream(true) + .start() + val stdout = process.inputStream.bufferedReader().readText().trim() + val exitCode = process.waitFor() + assertEquals(0, exitCode, "Obfuscated jar failed with output:\n$stdout") + assertEquals("PARAMORPHISM_OK:42:ALPHA", stdout) + } + + @Test + fun `element mask and name generator handle includes excludes and dictionaries`() { + val mask = ElementMask( + includes = arrayOf("com/example/*"), + excludes = arrayOf("com/example/keep/") + ) + assertTrue(mask.matches("com/example/Service")) + assertFalse(mask.matches("com/example/keep/Config")) + assertFalse(mask.matches("org/other/Util")) + + val generator = NameGenerator( + dictionaries = arrayOf(NameDictionaries.ENTERPRISE), + shuffle = true + ).apply { + random = Random(1234L) + } + val first = generator.generateName(0, 0, site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind.CLASS) + val second = generator.generateName(0, 1, site.hackery.paramorphism.strategy.renaming.tree.MappingElementKind.CLASS) + assertTrue(!first.isNullOrBlank() && !second.isNullOrBlank() && first != second) + } + + @Test + fun `control flow graph builder extracts basic blocks`() { + val classBytes = buildSampleMainClass() + val classNode = ClassNode() + ClassReader(classBytes).accept(classNode, 0) + val mainMethod = classNode.methods.first { it.name == "main" } + val blocks = buildBlocks(classNode, mainMethod) + assertTrue(blocks.isNotEmpty()) + } + + private fun createSampleJar(target: File) { + val manifest = Manifest().apply { + mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0" + mainAttributes[Attributes.Name.MAIN_CLASS] = "sample.app.SampleApp" + } + + JarOutputStream(target.outputStream(), manifest).use { jos -> + jos.putNextEntry(JarEntry("sample/app/Mode.class")) + jos.write(buildSampleEnumClass()) + jos.closeEntry() + + jos.putNextEntry(JarEntry("sample/app/Formatter.class")) + jos.write(buildFormatterInterface()) + jos.closeEntry() + + jos.putNextEntry(JarEntry("sample/app/SampleApp.class")) + jos.write(buildSampleMainClass()) + jos.closeEntry() + } + } + + private fun buildSampleEnumClass(): ByteArray { + val cw = ClassWriter(ClassWriter.COMPUTE_MAXS or ClassWriter.COMPUTE_FRAMES) + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC or Opcodes.ACC_FINAL or Opcodes.ACC_SUPER or Opcodes.ACC_ENUM, + "sample/app/Mode", "Ljava/lang/Enum;", "java/lang/Enum", null) + + cw.visitField(Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_ENUM, + "ALPHA", "Lsample/app/Mode;", null, null).visitEnd() + cw.visitField(Opcodes.ACC_PRIVATE or Opcodes.ACC_STATIC or Opcodes.ACC_FINAL or Opcodes.ACC_SYNTHETIC, + "\$VALUES", "[Lsample/app/Mode;", null, null).visitEnd() + + cw.visitMethod(Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC, "values", "()[Lsample/app/Mode;", null, null).apply { + visitCode() + visitFieldInsn(Opcodes.GETSTATIC, "sample/app/Mode", "\$VALUES", "[Lsample/app/Mode;") + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "[Lsample/app/Mode;", "clone", "()Ljava/lang/Object;", false) + visitTypeInsn(Opcodes.CHECKCAST, "[Lsample/app/Mode;") + visitInsn(Opcodes.ARETURN) + visitMaxs(1, 0) + visitEnd() + } + + cw.visitMethod(Opcodes.ACC_PRIVATE, "", "(Ljava/lang/String;I)V", null, null).apply { + visitCode() + visitVarInsn(Opcodes.ALOAD, 0) + visitVarInsn(Opcodes.ALOAD, 1) + visitVarInsn(Opcodes.ILOAD, 2) + visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Enum", "", "(Ljava/lang/String;I)V", false) + visitInsn(Opcodes.RETURN) + visitMaxs(3, 3) + visitEnd() + } + + cw.visitMethod(Opcodes.ACC_STATIC, "", "()V", null, null).apply { + visitCode() + visitTypeInsn(Opcodes.NEW, "sample/app/Mode") + visitInsn(Opcodes.DUP) + visitLdcInsn("ALPHA") + visitInsn(Opcodes.ICONST_0) + visitMethodInsn(Opcodes.INVOKESPECIAL, "sample/app/Mode", "", "(Ljava/lang/String;I)V", false) + visitFieldInsn(Opcodes.PUTSTATIC, "sample/app/Mode", "ALPHA", "Lsample/app/Mode;") + visitInsn(Opcodes.ICONST_1) + visitTypeInsn(Opcodes.ANEWARRAY, "sample/app/Mode") + visitInsn(Opcodes.DUP) + visitInsn(Opcodes.ICONST_0) + visitFieldInsn(Opcodes.GETSTATIC, "sample/app/Mode", "ALPHA", "Lsample/app/Mode;") + visitInsn(Opcodes.AASTORE) + visitFieldInsn(Opcodes.PUTSTATIC, "sample/app/Mode", "\$VALUES", "[Lsample/app/Mode;") + visitInsn(Opcodes.RETURN) + visitMaxs(4, 0) + visitEnd() + } + + cw.visitEnd() + return cw.toByteArray() + } + + private fun buildFormatterInterface(): ByteArray { + val cw = ClassWriter(0) + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC or Opcodes.ACC_INTERFACE or Opcodes.ACC_ABSTRACT, + "sample/app/Formatter", null, "java/lang/Object", null) + cw.visitMethod(Opcodes.ACC_PUBLIC or Opcodes.ACC_ABSTRACT, "format", "(ILsample/app/Mode;)Ljava/lang/String;", null, null) + .visitEnd() + cw.visitEnd() + return cw.toByteArray() + } + + private fun buildSampleMainClass(): ByteArray { + val cw = ClassWriter(ClassWriter.COMPUTE_MAXS or ClassWriter.COMPUTE_FRAMES) + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC or Opcodes.ACC_SUPER, + "sample/app/SampleApp", null, "java/lang/Object", null) + + cw.visitMethod(Opcodes.ACC_PRIVATE or Opcodes.ACC_STATIC, "formatImpl", "(ILsample/app/Mode;)Ljava/lang/String;", null, null).apply { + visitCode() + visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder") + visitInsn(Opcodes.DUP) + visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/StringBuilder", "", "()V", false) + visitLdcInsn("PARAMORPHISM_OK:") + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) + visitVarInsn(Opcodes.ILOAD, 0) + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false) + visitLdcInsn(":") + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) + visitVarInsn(Opcodes.ALOAD, 1) + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "sample/app/Mode", "name", "()Ljava/lang/String;", false) + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false) + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false) + visitInsn(Opcodes.ARETURN) + visitMaxs(2, 2) + visitEnd() + } + + cw.visitMethod(Opcodes.ACC_PUBLIC or Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null).apply { + visitCode() + val metafactory = Handle( + Opcodes.H_INVOKESTATIC, + "java/lang/invoke/LambdaMetafactory", + "metafactory", + "(Ljava/lang/invoke/MethodHandles\$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", + false + ) + val implHandle = Handle( + Opcodes.H_INVOKESTATIC, + "sample/app/SampleApp", + "formatImpl", + "(ILsample/app/Mode;)Ljava/lang/String;", + false + ) + visitInvokeDynamicInsn( + "format", + "()Lsample/app/Formatter;", + metafactory, + Type.getMethodType("(ILsample/app/Mode;)Ljava/lang/String;"), + implHandle, + Type.getMethodType("(ILsample/app/Mode;)Ljava/lang/String;") + ) + visitVarInsn(Opcodes.ASTORE, 1) + visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;") + visitVarInsn(Opcodes.ALOAD, 1) + visitIntInsn(Opcodes.BIPUSH, 42) + visitFieldInsn(Opcodes.GETSTATIC, "sample/app/Mode", "ALPHA", "Lsample/app/Mode;") + visitMethodInsn(Opcodes.INVOKEINTERFACE, "sample/app/Formatter", "format", "(ILsample/app/Mode;)Ljava/lang/String;", true) + visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false) + visitInsn(Opcodes.RETURN) + visitMaxs(4, 2) + visitEnd() + } + + cw.visitEnd() + return cw.toByteArray() + } +}