commit 4168f752a4740cde77dacabc262ea87fccf6d9d2 Author: TudbuT Date: Fri Jun 28 22:40:55 2024 +0200 Initial commit (Tested from J_8 to J_21) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f35ca9e --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..42426ba --- /dev/null +++ b/build.gradle @@ -0,0 +1,15 @@ +plugins { + id 'java' + id 'maven-publish' +} + +group = 'de.tudbut' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { +} + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 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..a3394fc --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jun 28 19:18:18 CEST 2024 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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. +# + +############################################################################## +# +# 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/master/subprojects/plugins/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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..ac1b06f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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 + +@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=. +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%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..b5406b9 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'darkreflection' + diff --git a/src/main/java/de/tudbut/darkreflection/DarkAccessibleObject.java b/src/main/java/de/tudbut/darkreflection/DarkAccessibleObject.java new file mode 100644 index 0000000..cf28d94 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/DarkAccessibleObject.java @@ -0,0 +1,32 @@ +package de.tudbut.darkreflection; + +import java.lang.reflect.AccessibleObject; + +import static de.tudbut.darkreflection.UnsafeProvider.unsafe; + +public class DarkAccessibleObject { + public static void makeAccessible(AccessibleObject object) { + if(object.isAccessible()) + return; + try { + unsafe.putBoolean(object, unsafe.objectFieldOffset(AccessibleObject.class.getDeclaredField("override")), true); + if(!object.isAccessible()) + throw new IllegalAccessException(); + } catch (Throwable basicOverrideError) { + try { + unsafe.putBoolean(object, unsafe.objectFieldOffset(FakeAccessibleObject.class.getDeclaredFields()[0]), true); + if(!object.isAccessible()) + throw new IllegalAccessException(); + } catch (Throwable adaptedOverrideError) { + basicOverrideError.printStackTrace(); + adaptedOverrideError.printStackTrace(); + throw new AssertionError("This JVM does not support changing the override"); + } + } + } + + @SuppressWarnings("unused") + private static class FakeAccessibleObject { + boolean override; + } +} diff --git a/src/main/java/de/tudbut/darkreflection/DarkClass.java b/src/main/java/de/tudbut/darkreflection/DarkClass.java new file mode 100644 index 0000000..d6a0856 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/DarkClass.java @@ -0,0 +1,11 @@ +package de.tudbut.darkreflection; + +import de.tudbut.darkreflection.classes.IClassAccess; + +// i have made it my life mission to make reflection unrestricted. i will not let jdk.internal.reflect.Reflection stop me. +public class DarkClass { + + public static IClassAccess obtainAccess(Class clazz) { + return Strategy.classStrategy.instance(clazz); + } +} diff --git a/src/main/java/de/tudbut/darkreflection/DarkField.java b/src/main/java/de/tudbut/darkreflection/DarkField.java new file mode 100644 index 0000000..603fdb9 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/DarkField.java @@ -0,0 +1,28 @@ +package de.tudbut.darkreflection; + +import de.tudbut.darkreflection.fields.IFieldAccess; + +import java.lang.reflect.Field; +import java.util.Arrays; + +public class DarkField { + + public static IFieldAccess obtainByField(Field f) { + return Strategy.reflectedFieldStrategy.instance(f); + } + + public static IFieldAccess obtainByName(Class owner, String name, boolean isStatic, Class type) { + return Strategy.fieldByNameStrategy.instance(owner, name, isStatic, type); + } + + public static Field nameToField(Class owner, String name) { + try { + // try the basic strategy first - it works often enough for this to be a speed advantage. + // this also prevents a StackOverflowError if we're using a ReflectionDataClass with a + // BasicOffsetGetter (like on some non-openjdk jvms) + return owner.getDeclaredField(name); + } catch (NoSuchFieldException e) { + return Arrays.stream(Strategy.classStrategy.instance(owner).getDeclaredFields()).filter(x -> x.getName().equals(name)).findAny().orElse(null); + } + } +} diff --git a/src/main/java/de/tudbut/darkreflection/DarkMethod.java b/src/main/java/de/tudbut/darkreflection/DarkMethod.java new file mode 100644 index 0000000..2bb917b --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/DarkMethod.java @@ -0,0 +1,25 @@ +package de.tudbut.darkreflection; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; + +public class DarkMethod { + + public static Method instance(Class owner, String name, Class... args) { + try { + return owner.getDeclaredMethod(name, args); + } catch (NoSuchMethodException e) { + return Arrays.stream(DarkClass.obtainAccess(owner).getDeclaredMethods()).filter(x -> x.getName().equals(name) && Arrays.equals(x.getParameterTypes(), args)).findAny().orElse(null); + } + } + + public static T invoke(Method m, Object owner, Object... args) throws InvocationTargetException { + DarkAccessibleObject.makeAccessible(m); + try { + return (T) m.invoke(owner, args); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/de/tudbut/darkreflection/InvalidStrategyException.java b/src/main/java/de/tudbut/darkreflection/InvalidStrategyException.java new file mode 100644 index 0000000..bd31ea9 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/InvalidStrategyException.java @@ -0,0 +1,8 @@ +package de.tudbut.darkreflection; + +public class InvalidStrategyException extends RuntimeException { + public InvalidStrategyException() {} + public InvalidStrategyException(Throwable e) { + super(e); + } +} diff --git a/src/main/java/de/tudbut/darkreflection/Strategy.java b/src/main/java/de/tudbut/darkreflection/Strategy.java new file mode 100644 index 0000000..b038d33 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/Strategy.java @@ -0,0 +1,149 @@ +package de.tudbut.darkreflection; + +import de.tudbut.darkreflection.classes.*; +import de.tudbut.darkreflection.fields.AdaptedReflectionField; +import de.tudbut.darkreflection.fields.BasicReflectionField; +import de.tudbut.darkreflection.fields.IFieldAccess; +import de.tudbut.darkreflection.fields.UnsafeField; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Field; +import java.util.Arrays; + +import static de.tudbut.darkreflection.UnsafeProvider.offsetGetter; + + +// which strategy depends on which? +// FReflectionDataClass -> reflectionFieldStrategy +// FieldByName -> reflectedFieldStrategy +// FieldByName -> classStrategy + +public class Strategy { + public static ClassStrategy classStrategy = ClassStrategy.Basic; + public static ReflectedFieldStrategy reflectedFieldStrategy = ReflectedFieldStrategy.Basic; + public static FieldByNameStrategy fieldByNameStrategy = FieldByNameStrategy.GetDeclaredField; + + public static void detect(boolean log) { + for (ReflectedFieldStrategy value : ReflectedFieldStrategy.values()) { + try { + String s = "hi"; + IFieldAccess field = value.instance(String.class.getDeclaredField("value")); + field.set(s, field.get("hi!")); + //noinspection ConstantValue + if(s.equals("hi!")) { + if(log) + System.out.println("Found working strategy for reflected fields: " + value.name()); + reflectedFieldStrategy = value; + break; + } + } catch (NoSuchFieldException e) { + throw new Error("Please update DarkReflection or open an issue on it.", e); + } catch (InvalidStrategyException ignore) {} + } + + for (ClassStrategy value : ClassStrategy.values()) { + try { + if(value.instance(AccessibleObject.class).getDeclaredFields().length >= 1) { + if(log) + System.out.println("Found working strategy for classes: " + value.name()); + classStrategy = value; + break; + } + } catch (InvalidStrategyException e) { + e.printStackTrace(); + } + } + + for (FieldByNameStrategy value : FieldByNameStrategy.values()) { + try { + if(value.instance(AccessibleObject.class, "override", false, boolean.class) != null) { + if(log) + System.out.println("Found working strategy for fields by name: " + value.name()); + fieldByNameStrategy = value; + break; + } + } catch (InvalidStrategyException ignore) {} + } + } + + @SuppressWarnings("rawtypes") + public enum ClassStrategy { + Basic(BasicClass.class), + NativeGet(NativeGetClass.class), + + ; + private final Class backend; + + ClassStrategy(Class backend) { + this.backend = backend; + } + + public IClassAccess instance(Class clazz) { + try { + return (IClassAccess) backend.getConstructor(Class.class).newInstance(clazz); + } catch (Exception e) { + throw new InvalidStrategyException(e); + } + } + } + @SuppressWarnings("rawtypes") + public enum ReflectedFieldStrategy { + Basic(BasicReflectionField.class), + Adapted(AdaptedReflectionField.class), + Unsafe(UnsafeField.class), + + ; + private final Class backend; + + ReflectedFieldStrategy(Class backend) { + this.backend = backend; + } + + public IFieldAccess instance(Field f) { + try { + return (IFieldAccess) backend.getConstructor(Field.class).newInstance(f); + } catch (Exception e) { + throw new InvalidStrategyException(e); + } + } + } + @SuppressWarnings("rawtypes") + public enum FieldByNameStrategy { + GetDeclaredField((owner, field, isStatic, type) -> { + try { + return reflectedFieldStrategy.instance(owner.getDeclaredField(field)); + } catch (NoSuchFieldException e) { + return null; + } + }), + DarkReflection((owner, field, isStatic, type) -> { + try { + return reflectedFieldStrategy.instance(Arrays.stream(classStrategy.instance(owner).getDeclaredFields()).filter(x -> x.getName().equals(field)).findAny().orElseThrow(() -> new NoSuchFieldException(field))); + } catch (NoSuchFieldException e) { + return null; + } + }), + Unsafe((owner, field, isStatic, type) -> new UnsafeField<>( + isStatic ? offsetGetter.staticFieldBase(owner, field) : null, + isStatic ? offsetGetter.staticFieldOffset(owner, field) : offsetGetter.objectFieldOffset(owner, field), type)), + + ; + private final FieldByNameStrategyProvider backend; + + FieldByNameStrategy(FieldByNameStrategyProvider backend) { + this.backend = backend; + } + + public IFieldAccess instance(Class owner, String field, boolean isStatic, Class type) { + try { + return (IFieldAccess) backend.get(owner, field, isStatic, type); + } catch (Exception e) { + throw new InvalidStrategyException(e); + } + } + + private interface FieldByNameStrategyProvider { + IFieldAccess get(Class owner, String field, boolean isStatic, Class type); + } + } +} diff --git a/src/main/java/de/tudbut/darkreflection/UnsafeProvider.java b/src/main/java/de/tudbut/darkreflection/UnsafeProvider.java new file mode 100644 index 0000000..8690390 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/UnsafeProvider.java @@ -0,0 +1,34 @@ +package de.tudbut.darkreflection; + +import de.tudbut.darkreflection.unsafe.BasicOffsetGetter; +import de.tudbut.darkreflection.unsafe.IOffsetGetter; +import de.tudbut.darkreflection.unsafe.InternalUnsafeOffsetGetter; +import sun.misc.Unsafe; + +import java.lang.reflect.Field; + +public class UnsafeProvider { + + public static final Unsafe unsafe; + static { + try { + Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + unsafe = (Unsafe) f.get(null); + } catch (Throwable e) { + throw new Error(e); // Don't recover. + } + } + + public static IOffsetGetter offsetGetter; + static { + try { + Class c = Class.forName("jdk.internal.misc.Unsafe"); + c.getMethod("objectFieldOffset", Class.class, String.class); + Object o = DarkMethod.invoke(c.getMethod("getUnsafe"), null); + offsetGetter = new InternalUnsafeOffsetGetter(c, o); + } catch (Throwable e) { + offsetGetter = new BasicOffsetGetter(); + } + } +} diff --git a/src/main/java/de/tudbut/darkreflection/classes/BasicClass.java b/src/main/java/de/tudbut/darkreflection/classes/BasicClass.java new file mode 100644 index 0000000..2653a9e --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/classes/BasicClass.java @@ -0,0 +1,32 @@ +package de.tudbut.darkreflection.classes; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +public class BasicClass implements IClassAccess { + private final Class clazz; + public BasicClass(Class clazz) { + this.clazz = clazz; + } + + @Override + public Field[] getDeclaredFields() { + return clazz.getDeclaredFields(); + } + + @Override + public Method[] getDeclaredMethods() { + return clazz.getDeclaredMethods(); + } + + @Override + public Constructor[] getDeclaredConstructors() { + return (Constructor[]) clazz.getDeclaredConstructors(); + } + + @Override + public Class getAccessedClass() { + return clazz; + } +} diff --git a/src/main/java/de/tudbut/darkreflection/classes/IClassAccess.java b/src/main/java/de/tudbut/darkreflection/classes/IClassAccess.java new file mode 100644 index 0000000..e9ed0b3 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/classes/IClassAccess.java @@ -0,0 +1,12 @@ +package de.tudbut.darkreflection.classes; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +public interface IClassAccess { + Field[] getDeclaredFields(); + Method[] getDeclaredMethods(); + Constructor[] getDeclaredConstructors(); + Class getAccessedClass(); +} diff --git a/src/main/java/de/tudbut/darkreflection/classes/NativeGetClass.java b/src/main/java/de/tudbut/darkreflection/classes/NativeGetClass.java new file mode 100644 index 0000000..f8d5904 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/classes/NativeGetClass.java @@ -0,0 +1,56 @@ +package de.tudbut.darkreflection.classes; + +import de.tudbut.darkreflection.DarkMethod; +import de.tudbut.darkreflection.InvalidStrategyException; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class NativeGetClass implements IClassAccess { + private final Class clazz; + private final Method getDeclaredFields0, getDeclaredMethods0, getDeclaredConstructors0; + public NativeGetClass(Class clazz) { + this.clazz = clazz; + try { + getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); + getDeclaredMethods0 = Class.class.getDeclaredMethod("getDeclaredMethods0", boolean.class); + getDeclaredConstructors0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class); + } catch (NoSuchMethodException e) { + throw new InvalidStrategyException(e); + } + } + + @Override + public Field[] getDeclaredFields() { + try { + return DarkMethod.invoke(getDeclaredFields0, clazz, false); + } catch (InvocationTargetException e) { + throw new InvalidStrategyException(e); + } + } + + @Override + public Method[] getDeclaredMethods() { + try { + return DarkMethod.invoke(getDeclaredMethods0, clazz, false); + } catch (InvocationTargetException e) { + throw new InvalidStrategyException(e); + } + } + + @Override + public Constructor[] getDeclaredConstructors() { + try { + return DarkMethod.invoke(getDeclaredConstructors0, clazz, false); + } catch (InvocationTargetException e) { + throw new InvalidStrategyException(e); + } + } + + @Override + public Class getAccessedClass() { + return clazz; + } +} diff --git a/src/main/java/de/tudbut/darkreflection/fields/AdaptedReflectionField.java b/src/main/java/de/tudbut/darkreflection/fields/AdaptedReflectionField.java new file mode 100644 index 0000000..fc53eef --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/fields/AdaptedReflectionField.java @@ -0,0 +1,17 @@ +package de.tudbut.darkreflection.fields; + +import de.tudbut.darkreflection.DarkAccessibleObject; + +import java.lang.reflect.Field; + +public class AdaptedReflectionField extends ReflectionField { + public AdaptedReflectionField(Field backend) { + super(backend); + } + + @Override + protected void makeAccessible() { + DarkAccessibleObject.makeAccessible(backend); + } + +} diff --git a/src/main/java/de/tudbut/darkreflection/fields/BasicReflectionField.java b/src/main/java/de/tudbut/darkreflection/fields/BasicReflectionField.java new file mode 100644 index 0000000..72bfda1 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/fields/BasicReflectionField.java @@ -0,0 +1,22 @@ +package de.tudbut.darkreflection.fields; + +import de.tudbut.darkreflection.InvalidStrategyException; + +import java.lang.reflect.Field; + +public class BasicReflectionField extends ReflectionField { + public BasicReflectionField(Field backend) { + super(backend); + } + + @Override + protected void makeAccessible() { + try { + backend.setAccessible(true); + if(!backend.isAccessible()) + throw new IllegalAccessException(); + } catch (Exception e) { + throw new InvalidStrategyException(); + } + } +} diff --git a/src/main/java/de/tudbut/darkreflection/fields/IFieldAccess.java b/src/main/java/de/tudbut/darkreflection/fields/IFieldAccess.java new file mode 100644 index 0000000..2c2f5df --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/fields/IFieldAccess.java @@ -0,0 +1,6 @@ +package de.tudbut.darkreflection.fields; + +public interface IFieldAccess { + T get(Object owner); + void set(Object owner, T item); +} diff --git a/src/main/java/de/tudbut/darkreflection/fields/ReflectionField.java b/src/main/java/de/tudbut/darkreflection/fields/ReflectionField.java new file mode 100644 index 0000000..4301173 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/fields/ReflectionField.java @@ -0,0 +1,32 @@ +package de.tudbut.darkreflection.fields; + +import java.lang.reflect.Field; + +public abstract class ReflectionField implements IFieldAccess { + protected final Field backend; + + public ReflectionField(Field backend) { + this.backend = backend; + makeAccessible(); + } + + protected abstract void makeAccessible(); + + @Override + public T get(Object owner) { + try { + return (T) backend.get(owner); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + @Override + public void set(Object owner, T item) { + try { + backend.set(owner, item); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/de/tudbut/darkreflection/fields/UnsafeField.java b/src/main/java/de/tudbut/darkreflection/fields/UnsafeField.java new file mode 100644 index 0000000..63c6b64 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/fields/UnsafeField.java @@ -0,0 +1,76 @@ +package de.tudbut.darkreflection.fields; + +import java.lang.reflect.Field; + +import static de.tudbut.darkreflection.UnsafeProvider.unsafe; + +public class UnsafeField implements IFieldAccess { + protected final Class type; + protected Field backend; + protected Object o; + protected long offset = -1; + + public UnsafeField(Field field) { + this.backend = field; + this.type = field.getType(); + } + public UnsafeField(Object o, long offset, Class type) { + this.o = o; + this.offset = offset; + this.type = type; + } + + @Override + public T get(Object owner) { + Object o = this.o == null ? (owner == null ? unsafe.staticFieldBase(backend) : owner) : this.o; + long offset = this.offset == -1 ? (owner == null ? unsafe.staticFieldOffset(backend) : unsafe.objectFieldOffset(backend)) : this.offset; + this.offset = offset; + + if(type.isPrimitive()) { + if(type == int.class) + return (T) (Object) unsafe.getInt(o, offset); + if(type == boolean.class) + return (T) (Object) unsafe.getBoolean(o, offset); + if(type == byte.class) + return (T) (Object) unsafe.getByte(o, offset); + if(type == short.class) + return (T) (Object) unsafe.getShort(o, offset); + if(type == char.class) + return (T) (Object) unsafe.getChar(o, offset); + if(type == long.class) + return (T) (Object) unsafe.getLong(o, offset); + if(type == float.class) + return (T) (Object) unsafe.getFloat(o, offset); + if(type == double.class) + return (T) (Object) unsafe.getDouble(o, offset); + } + return (T) unsafe.getObject(o, offset); + } + + @Override + public void set(Object owner, T item) { + Object o = this.o == null ? (owner == null ? unsafe.staticFieldBase(backend) : owner) : this.o; + long offset = this.offset == -1 ? (owner == null ? unsafe.staticFieldOffset(backend) : unsafe.objectFieldOffset(backend)) : this.offset; + this.offset = offset; + + if(type.isPrimitive()) { + if(type == int.class) + unsafe.putInt(o, offset, (Integer) item); + else if(type == boolean.class) + unsafe.putBoolean(o, offset, (Boolean) item); + else if(type == byte.class) + unsafe.putByte(o, offset, (Byte) item); + else if(type == short.class) + unsafe.putShort(o, offset, (Short) item); + else if(type == char.class) + unsafe.putChar(o, offset, (Character) item); + else if(type == long.class) + unsafe.putLong(o, offset, (Long) item); + else if(type == float.class) + unsafe.putFloat(o, offset, (Float) item); + else if(type == double.class) + unsafe.putDouble(o, offset, (Double) item); + } + unsafe.putObject(o, offset, item); + } +} diff --git a/src/main/java/de/tudbut/darkreflection/unsafe/BasicOffsetGetter.java b/src/main/java/de/tudbut/darkreflection/unsafe/BasicOffsetGetter.java new file mode 100644 index 0000000..2b22d5e --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/unsafe/BasicOffsetGetter.java @@ -0,0 +1,39 @@ +package de.tudbut.darkreflection.unsafe; + +import de.tudbut.darkreflection.DarkField; + +import java.lang.reflect.Field; + +import static de.tudbut.darkreflection.UnsafeProvider.unsafe; + +public class BasicOffsetGetter implements IOffsetGetter { + @Override + public long objectFieldOffset(Field f) { + return unsafe.objectFieldOffset(f); + } + + @Override + public long objectFieldOffset(Class clazz, String name) { + return unsafe.objectFieldOffset(DarkField.nameToField(clazz, name)); + } + + @Override + public long staticFieldOffset(Field f) { + return unsafe.staticFieldOffset(f); + } + + @Override + public long staticFieldOffset(Class clazz, String name) { + return unsafe.staticFieldOffset(DarkField.nameToField(clazz, name)); + } + + @Override + public Object staticFieldBase(Field f) { + return unsafe.staticFieldBase(f); + } + + @Override + public Object staticFieldBase(Class clazz, String name) { + return unsafe.staticFieldBase(DarkField.nameToField(clazz, name)); + } +} diff --git a/src/main/java/de/tudbut/darkreflection/unsafe/IOffsetGetter.java b/src/main/java/de/tudbut/darkreflection/unsafe/IOffsetGetter.java new file mode 100644 index 0000000..b5e7434 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/unsafe/IOffsetGetter.java @@ -0,0 +1,13 @@ +package de.tudbut.darkreflection.unsafe; + +import java.lang.reflect.Field; + +public interface IOffsetGetter { + long objectFieldOffset(Field f); + long objectFieldOffset(Class clazz, String name); + long staticFieldOffset(Field f); + long staticFieldOffset(Class clazz, String name); + + Object staticFieldBase(Field f); + Object staticFieldBase(Class clazz, String name); +} diff --git a/src/main/java/de/tudbut/darkreflection/unsafe/InternalUnsafeOffsetGetter.java b/src/main/java/de/tudbut/darkreflection/unsafe/InternalUnsafeOffsetGetter.java new file mode 100644 index 0000000..3b02144 --- /dev/null +++ b/src/main/java/de/tudbut/darkreflection/unsafe/InternalUnsafeOffsetGetter.java @@ -0,0 +1,26 @@ +package de.tudbut.darkreflection.unsafe; + +import de.tudbut.darkreflection.DarkMethod; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class InternalUnsafeOffsetGetter extends BasicOffsetGetter { + + private final Method objectFieldOffset0; + private final Object iUnsafe; + + public InternalUnsafeOffsetGetter(Class iUnsafeClass, Object iUnsafe) throws NoSuchMethodException { + this.objectFieldOffset0 = iUnsafeClass.getMethod("objectFieldOffset", Class.class, String.class); + this.iUnsafe = iUnsafe; + } + + @Override + public long objectFieldOffset(Class clazz, String name) { + try { + return DarkMethod.invoke(objectFieldOffset0, iUnsafe, clazz, name); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/Test.java b/src/test/java/Test.java new file mode 100644 index 0000000..2c20327 --- /dev/null +++ b/src/test/java/Test.java @@ -0,0 +1,9 @@ +import de.tudbut.darkreflection.DarkField; +import de.tudbut.darkreflection.Strategy; + +public class Test { + public static void main(String[] args) { + Strategy.detect(true); + DarkField.obtainByName(ClassLoader.class, "parent", false, ClassLoader.class).set(ClassLoader.getSystemClassLoader(), null); + } +}