diff --git a/build.gradle b/build.gradle index b97e08e5..07518b4a 100644 --- a/build.gradle +++ b/build.gradle @@ -43,16 +43,6 @@ targetCompatibility = '1.6' // Project repositories repositories { mavenCentral() - maven { - // for srg2source - name = "forge" - url = "http://files.minecraftforge.net/maven" - } - maven { - // because Srg2Source needs an eclipse dependency. - name = "eclipse" - url = "https://repo.eclipse.org/content/groups/eclipse/" - } maven { name = 'minecraft' url = 'https://libraries.minecraft.net/' @@ -92,6 +82,12 @@ sourceSets { fernflower { compileClasspath += main.output } + agent { + compileClasspath += main.output + } + bridge { + compileClasspath += main.output + } } // Dependencies for renamed ASM @@ -127,15 +123,16 @@ task renamedASM { } } } +eclipseClasspath.dependsOn(renamedASM) // Project dependencies dependencies { compile 'org.slf4j:slf4j-api:1.7.7' compile 'com.google.guava:guava:17.0' - compile 'net.minecraft:launchwrapper:1.11' compile 'com.google.code.gson:gson:2.2.4' compile 'commons-io:commons-io:2.4' compile 'commons-codec:commons-codec:1.9' + apCompile 'com.google.guava:guava:17.0' testCompile 'junit:junit:4.11' testCompile 'org.hamcrest:hamcrest-library:1.3' testCompile 'org.mockito:mockito-core:1.9.0' @@ -143,13 +140,10 @@ dependencies { // maven deployerJars 'org.apache.maven.wagon:wagon-ftp:2.7' - // for annotation processor - compile 'net.minecraftforge.srg2source:Srg2Source:3.2-SNAPSHOT' - apCompile 'net.minecraftforge.srg2source:Srg2Source:3.2-SNAPSHOT' - // remapped ASM compile tasks.renamedASM.outputs.files apCompile tasks.renamedASM.outputs.files + agentCompile tasks.renamedASM.outputs.files // fernflower bridge fernflowerCompile 'commons-io:commons-io:2.4' @@ -157,6 +151,14 @@ dependencies { fernflowerCompile 'com.google.guava:guava:17.0' fernflowerCompile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' compile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' + + compile 'net.minecraft:launchwrapper:1.11' + agentCompile 'net.minecraft:launchwrapper:1.11' + + // asm bridge + compile 'org.ow2.asm:asm-commons:5.0.3' + bridgeCompile 'org.ow2.asm:asm-commons:5.0.3' + bridgeCompile 'org.apache.logging.log4j:log4j-core:2.0-beta9' } // Filter, process, and include resources @@ -212,6 +214,12 @@ jar { // Include fernflower bridge from sourceSets.fernflower.output + + // Include hotswap agent + from sourceSets.agent.output + + // Bridge + from sourceSets.bridge.output // Renamed ASM from zipTree(tasks.renamedASM.outputs.files[0]) @@ -226,7 +234,12 @@ jar { "Created-By": System.properties['java.vm.version'] + " (" + System.properties['java.vm.vendor'] + ")", "Implementation-Title": name, "Implementation-Version": version + "+" + ciSystem + "-b" + buildNumber + ".git-" + commit, - "Implementation-Vendor": url) + "Implementation-Vendor": url, + // for hotswap agent + "Premain-Class": "org.spongepowered.tools.agent.MixinAgent", + "Agent-Class": "org.spongepowered.tools.agent.MixinAgent", + "Can-Redefine-Classes": true, + "Can-Retransform-Classes": true) } // generate shadow jar so we can use the AP standalone @@ -259,6 +272,10 @@ task sourceJar(type: Jar) { from sourceSets.ap.resources from sourceSets.fernflower.java from sourceSets.fernflower.resources + from sourceSets.agent.java + from sourceSets.agent.resources + from sourceSets.bridge.java + from sourceSets.bridge.resources classifier = "sources" } @@ -315,7 +332,20 @@ uploadArchives { } } } + whenConfigured { + dependencies = dependencies.findAll { + !it.artifactId.contains('fernflower') + } + } } } } } + +install.repositories.mavenInstaller.pom { + whenConfigured { + dependencies = dependencies.findAll { + !it.artifactId.contains('fernflower') + } + } +} diff --git a/checkstyle.xml b/checkstyle.xml index 25b8ebfd..b10493a1 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -1,171 +1,103 @@ - - + + - + This configuration file was written by the eclipse-cs plugin configuration editor +--> + - - - - - - - - + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/extra/formatter.xml b/extra/formatter.xml new file mode 100644 index 00000000..ff240005 --- /dev/null +++ b/extra/formatter.xml @@ -0,0 +1,295 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/extra/mixin.importorder b/extra/mixin.importorder new file mode 100644 index 00000000..44b374b5 --- /dev/null +++ b/extra/mixin.importorder @@ -0,0 +1,7 @@ +#Organize Import Order +#Thu Jan 07 16:47:26 GMT 2016 +4=com +3=org +2=javax +1=java +0=\# diff --git a/gradle.properties b/gradle.properties index 53acb410..8b9c1033 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,5 +4,5 @@ packaging=jar description=Mixin url=https://www.spongepowered.org organization=SpongePowered -buildVersion=0.4.5 +buildVersion=0.5.11 buildType=SNAPSHOT diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 3abfba7f..e7e56722 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-bin.zip diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java new file mode 100644 index 00000000..04bc68e6 --- /dev/null +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -0,0 +1,223 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.agent; + +import java.lang.instrument.ClassDefinition; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.lang.instrument.Instrumentation; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.mixin.transformer.MixinTransformer; +import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; +import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; + +import net.minecraft.launchwrapper.Launch; + +/** + * An agent that re-transforms a mixin's target classes if the mixin has been + * redefined. Basically this agent enables hot-swapping of mixins. + */ +public class MixinAgent implements IHotSwap { + + /** + * Class file transformer that re-transforms mixin's target classes if the + * mixin has been redefined. + */ + class Transformer implements ClassFileTransformer { + + @Override + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain domain, byte[] classfileBuffer) + throws IllegalClassFormatException { + if (classBeingRedefined == null) { + return null; + } + + byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined); + if (mixinBytecode != null) { + List targets = this.reloadMixin(className, classfileBuffer); + if (targets == null || !this.reApplyMixins(targets)) { + return MixinAgent.ERROR_BYTECODE; + } + + return mixinBytecode; + } + + try { + MixinAgent.logger.info("Redefining class " + className); + return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); + } catch (Throwable th) { + MixinAgent.logger.error("Error while re-transforming class " + className, th); + return MixinAgent.ERROR_BYTECODE; + } + } + + private List reloadMixin(String className, byte[] classfileBuffer) { + MixinAgent.logger.info("Redefining mixin {}", className); + try { + return MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); + } catch (MixinReloadException e) { + MixinAgent.logger.error("Mixin {} cannot be reloaded, needs a restart to be applied: {} ", e.getMixinInfo(), e.getMessage()); + } catch (Throwable th) { + // catch everything as otherwise it is ignored + MixinAgent.logger.error("Error while finding targets for mixin " + className, th); + } + return null; + } + + /** + * Re-apply all mixins to the supplied list of target classes. + * + * @param targets Target classes to re-transform + * @return true if all targets were transformed, false if transformation + * failed + */ + private boolean reApplyMixins(List targets) { + for (String target : targets) { + String targetName = target.replace('/', '.'); + MixinAgent.logger.debug("Re-transforming target class {}", target); + try { + Class targetClass = Launch.classLoader.findClass(targetName); + byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName); + if (targetBytecode == null) { + MixinAgent.logger.error("Target class {} bytecode is not registered", targetName); + return false; + } + targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode); + MixinAgent.instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode)); + } catch (Throwable th) { + MixinAgent.logger.error("Error while re-transforming target class " + target, th); + return false; + } + } + return true; + } + } + + /** + * Bytecode that signals an error. When returned from the class file + * transformer this causes a class file format exception and indicates in + * the ide that somethings went wrong. + */ + public static final byte[] ERROR_BYTECODE = new byte[]{1}; + + /** + * Class loader used to load mixin classes + */ + static final MixinAgentClassLoader classLoader = new MixinAgentClassLoader(); + + static final Logger logger = LogManager.getLogger("mixin.agent"); + + /** + * Instance used to register the transformer + */ + static Instrumentation instrumentation = null; + + /** + * Instances of all agents + */ + private static List agents = new ArrayList(); + + /** + * MixinTransformer instance to use to transform the mixin's target classes + */ + final MixinTransformer classTransformer; + + /** + * Constructs an agent from a class transformer in which it will use to + * transform mixin's target class. + * + * @param classTransformer Class transformer that will transform a mixin's + * target class + */ + public MixinAgent(MixinTransformer classTransformer) { + this.classTransformer = classTransformer; + MixinAgent.agents.add(this); + if (MixinAgent.instrumentation != null) { + this.initTransformer(); + } + } + + private void initTransformer() { + MixinAgent.instrumentation.addTransformer(new Transformer(), true); + } + + @Override + public void registerMixinClass(String name) { + MixinAgent.classLoader.addMixinClass(name); + } + + @Override + public void registerTargetClass(String name, byte[] bytecode) { + MixinAgent.classLoader.addTargetClass(name, bytecode); + } + + /** + * Sets the instrumentation instance so that the mixin agents can redefine + * mixins. + * + * @param instrumentation Instance to use to redefine the mixins + */ + public static void init(Instrumentation instrumentation) { + MixinAgent.instrumentation = instrumentation; + if (!MixinAgent.instrumentation.isRedefineClassesSupported()) { + MixinAgent.logger.error("The instrumentation doesn't support re-definition of classes"); + } + for (MixinAgent agent : MixinAgent.agents) { + agent.initTransformer(); + } + } + + /** + * Initialize the java agent + * + * This will be called automatically if the jar is in a -javaagent java + * command line argument + * + * @param arg Ignored + * @param instrumentation Instance to use to transform the mixins + */ + public static void premain(String arg, Instrumentation instrumentation) { + System.setProperty("mixin.hotSwap", "true"); + MixinAgent.init(instrumentation); + } + + /** + * Initialize the java agent + * + * This will be called automatically if the java agent is loaded after jvm + * startup + * + * @param arg Ignored + * @param instrumentation Instance to use to re-define the mixins + */ + public static void agentmain(String arg, Instrumentation instrumentation) { + MixinAgent.init(instrumentation); + } +} diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java new file mode 100644 index 00000000..3decd055 --- /dev/null +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java @@ -0,0 +1,130 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.agent; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.lib.ClassWriter; +import org.spongepowered.asm.lib.MethodVisitor; +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.util.Constants; + +/** + * Class loader that is used to load fake mixin classes so that they can be + * re-defined. + */ +class MixinAgentClassLoader extends ClassLoader { + + private static final Logger logger = LogManager.getLogger("mixin.agent"); + + /** + * Mapping of mixin mixin classes to their fake classes + */ + private Map, byte[]> mixins = new HashMap, byte[]>(); + + /** + * Mapping that keep track of bytecode for classes that are targeted by + * mixins + */ + private Map targets = new HashMap(); + + /** + * Add a fake mixin class + * + * @param name Name of the fake class + */ + void addMixinClass(String name) { + MixinAgentClassLoader.logger.debug("Mixin class {} added to class loader", name); + try { + byte[] bytes = this.materialise(name); + Class clazz = this.defineClass(name, bytes, 0, bytes.length); + // apparently the class needs to be instantiated at least once + // to be including in list returned by allClasses() method in jdi api + clazz.newInstance(); + this.mixins.put(clazz, bytes); + } catch (Throwable e) { + MixinAgentClassLoader.logger.catching(e); + } + } + + /** + * Registers the bytecode for a class targeted by a mixin + * + * @param name Name of the target clas + * @param bytecode Bytecode of the target class + */ + void addTargetClass(String name, byte[] bytecode) { + this.targets.put(name, bytecode); + } + + /** + * Gets the bytecode for a fake mixin class + * + * @param clazz Mixin class + * @return Bytecode of the fake mixin class + */ + byte[] getFakeMixinBytecode(Class clazz) { + return this.mixins.get(clazz); + } + + /** + * Gets the original bytecode for a target class + * + * @param name Name of the target class + * @return Original bytecode + */ + byte[] getOriginalTargetBytecode(String name) { + return this.targets.get(name); + } + + /** + * Generates the simplest possible class that is instantiable + * + * @param name Name of the generated class + * @return Bytecode of the generated class + */ + private byte[] materialise(String name) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + cw.visit(MixinEnvironment.getCompatibilityLevel().classVersion(), Opcodes.ACC_PUBLIC, name.replace('.', '/'), null, + Type.getInternalName(Object.class), null); + + // create init method + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, Constants.CTOR, "()V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), Constants.CTOR, "()V", false); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } +} diff --git a/src/ap/java/org/spongepowered/tools/MirrorUtils.java b/src/ap/java/org/spongepowered/tools/MirrorUtils.java index fff3cf40..3a683e0f 100644 --- a/src/ap/java/org/spongepowered/tools/MirrorUtils.java +++ b/src/ap/java/org/spongepowered/tools/MirrorUtils.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; @@ -40,13 +41,22 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; - +import javax.lang.model.type.TypeVariable; /** * Convenience functions for mirror */ public abstract class MirrorUtils { + /** + * Number of times to recurse into TypeMirrors when trying to determine the + * upper bound of a TYPEVAR + */ + private static final int MAX_GENERIC_RECURSION_DEPTH = 5; + + private static final String OBJECT_SIG = "java.lang.Object"; + private static final String OBJECT_REF = "java/lang/Object"; + // No instances for you private MirrorUtils() {} @@ -150,6 +160,61 @@ public abstract class MirrorUtils { return parent.getClass().getSimpleName(); } + + public static String getJavaSignature(Element element) { + if (element instanceof ExecutableElement) { + ExecutableElement method = (ExecutableElement)element; + StringBuilder desc = new StringBuilder().append("("); + boolean extra = false; + for (VariableElement arg : method.getParameters()) { + if (extra) { + desc.append(','); + } + desc.append(MirrorUtils.getTypeName(arg.asType())); + extra = true; + } + desc.append(')').append(method.getReturnType().toString()); + return desc.toString(); + } + return MirrorUtils.getTypeName(element.asType()); + } + + public static String stripGenerics(String type) { + StringBuilder sb = new StringBuilder(); + for (int pos = 0, depth = 0; pos < type.length(); pos++) { + char c = type.charAt(pos); + if (c == '<') { + depth++; + } + if (depth == 0) { + sb.append(c); + } else if (c == '>') { + depth--; + } + } + return sb.toString(); + } + + public static String getTypeName(TypeMirror type) { + switch (type.getKind()) { + case ARRAY: return MirrorUtils.getTypeName(((ArrayType)type).getComponentType()) + "[]"; + case DECLARED: return MirrorUtils.getTypeName((DeclaredType)type); + case TYPEVAR: return MirrorUtils.getTypeName(MirrorUtils.getUpperBound(type)); + case ERROR: return MirrorUtils.OBJECT_SIG; + default: return type.toString(); + } + } + + public static String getTypeName(DeclaredType type) { + if (type == null) { + return MirrorUtils.OBJECT_SIG; + } + return MirrorUtils.getTypeName((TypeElement)type.asElement()); + } + + private static String getTypeName(TypeElement elem) { + return MirrorUtils.getInternalName(elem).replace('/', '.'); + } public static String generateSignature(ExecutableElement method) { StringBuilder signature = new StringBuilder(); @@ -164,11 +229,12 @@ public abstract class MirrorUtils { public static String getInternalName(VariableElement var) { return MirrorUtils.getInternalName(var.asType()); } - + public static String getInternalName(TypeMirror type) { switch (type.getKind()) { case ARRAY: return "[" + MirrorUtils.getInternalName(((ArrayType)type).getComponentType()); case DECLARED: return "L" + MirrorUtils.getInternalName((DeclaredType)type) + ";"; + case TYPEVAR: return "L" + MirrorUtils.getInternalName(MirrorUtils.getUpperBound(type)) + ";"; case BOOLEAN: return "Z"; case BYTE: return "B"; case CHAR: return "C"; @@ -179,14 +245,50 @@ public abstract class MirrorUtils { case SHORT: return "S"; case VOID: return "V"; // TODO figure out a better way to not crash when we get here - case ERROR: return "Ljava/lang/Object;"; + case ERROR: return "L" + MirrorUtils.OBJECT_REF + ";"; default: } throw new IllegalArgumentException("Unable to parse type symbol " + type + " with " + type.getKind() + " to equivalent bytecode type"); } + private static DeclaredType getUpperBound(TypeMirror type) { + try { + return MirrorUtils.getUpperBound0(type, MirrorUtils.MAX_GENERIC_RECURSION_DEPTH); + } catch (IllegalStateException ex) { + throw new IllegalArgumentException("Type symbol \"" + type + "\" is too complex", ex); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Unable to compute upper bound of type symbol " + type, ex); + } + } + + private static DeclaredType getUpperBound0(TypeMirror type, int depth) { + if (depth == 0) { + throw new IllegalStateException("Generic symbol \"" + type + "\" is too complex, exceeded " + + MirrorUtils.MAX_GENERIC_RECURSION_DEPTH + " iterations attempting to determine upper bound"); + } + if (type instanceof DeclaredType) { + return (DeclaredType)type; + } + if (type instanceof TypeVariable) { + try { + TypeMirror upper = ((TypeVariable)type).getUpperBound(); + return MirrorUtils.getUpperBound0(upper, --depth); + } catch (IllegalStateException ex) { + throw ex; + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("Unable to compute upper bound of type symbol " + type); + } + } + return null; + } + public static String getInternalName(DeclaredType type) { + if (type == null) { + return MirrorUtils.OBJECT_REF; + } return MirrorUtils.getInternalName((TypeElement)type.asElement()); } @@ -204,4 +306,20 @@ public abstract class MirrorUtils { } return reference.toString(); } + + public static boolean isAssignable(ProcessingEnvironment processingEnv, TypeMirror targetType, TypeMirror superClass) { + boolean assignable = processingEnv.getTypeUtils().isAssignable(targetType, superClass); + if (!assignable && targetType instanceof DeclaredType && superClass instanceof DeclaredType) { + TypeMirror rawTargetType = MirrorUtils.toRawType(processingEnv, (DeclaredType)targetType); + TypeMirror rawSuperType = MirrorUtils.toRawType(processingEnv, (DeclaredType)superClass); + return processingEnv.getTypeUtils().isAssignable(rawTargetType, rawSuperType); + } + + return assignable; + } + + private static TypeMirror toRawType(ProcessingEnvironment processingEnv, DeclaredType targetType) { + return processingEnv.getElementUtils().getTypeElement(((TypeElement)targetType.asElement()).getQualifiedName()).asType(); + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 656a8ff0..2714c7c6 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -24,7 +24,6 @@ */ package org.spongepowered.tools.obfuscation; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -34,9 +33,10 @@ import java.util.List; import java.util.Map; import java.util.Set; +import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; -import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; @@ -44,186 +44,50 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; -import net.minecraftforge.srg2source.rangeapplier.MethodData; - import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.util.Constants; -import org.spongepowered.asm.util.ConstraintParser; -import org.spongepowered.asm.util.ConstraintParser.Constraint; -import org.spongepowered.asm.util.ConstraintViolationException; -import org.spongepowered.asm.util.InvalidConstraintException; import org.spongepowered.tools.MirrorUtils; -import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass; - +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; +import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass; +import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; +import org.spongepowered.tools.obfuscation.interfaces.ITypeHandleProvider; +import org.spongepowered.tools.obfuscation.struct.Message; /** * Information about a mixin stored during processing */ class AnnotatedMixin { - /** - * A name of an element which may have aliases - */ - static class AliasedElementName { - - /** - * The original name including any original prefix (the "actual" name) - */ - protected final String originalName; - - /** - * Aliases declared by the annotation (if any), never null - */ - private final List aliases; - - public AliasedElementName(Element element, AnnotationMirror annotation) { - this.originalName = element.getSimpleName().toString(); - List aliases = MirrorUtils.>getAnnotationValue(annotation, "aliases"); - this.aliases = MirrorUtils.unfold(aliases); - } - - /** - * Get whether this member has any aliases defined - */ - public boolean hasAliases() { - return this.aliases.size() > 0; - } - - /** - * Get this member's aliases - */ - public List getAliases() { - return this.aliases; - } - - /** - * Gets the original name of the member (including prefix) - */ - public String elementName() { - return this.originalName; - } - - public String baseName() { - return this.originalName; - } - - } - - /** - * Convenience class to store information about an - * {@link org.spongepowered.asm.mixin.Shadow}ed member's names - */ - static class ShadowElementName extends AliasedElementName { - - /** - * True if the real element is prefixed - */ - private final boolean hasPrefix; - - /** - * Expected prefix read from the annotation, this is set even if - * {@link #hasPrefix} is false - */ - private final String prefix; - - /** - * The base name without the prefix - */ - private final String baseName; - - /** - * Obfuscated name (once determined) - */ - private String obfuscated; - - ShadowElementName(Element element, AnnotationMirror shadow) { - super(element, shadow); - - this.prefix = MirrorUtils.getAnnotationValue(shadow, "prefix", "shadow$"); - - boolean hasPrefix = false; - String name = this.originalName; - if (name.startsWith(this.prefix)) { - hasPrefix = true; - name = name.substring(this.prefix.length()); - } - - this.hasPrefix = hasPrefix; - this.obfuscated = this.baseName = name; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return this.baseName; - } - - @Override - public String baseName() { - return this.baseName; - } - - /** - * Sets the obfuscated name for this element - * - * @param name New name - * @return fluent interface - */ - public ShadowElementName setObfuscatedName(String name) { - this.obfuscated = name.substring(name.lastIndexOf('/') + 1); - return this; - } - - /** - * Get the prefix (if set), does not return the expected prefix - */ - public String prefix() { - return this.hasPrefix ? this.prefix : ""; - } - - /** - * Get the base name - */ - public String name() { - return this.prefix(this.baseName); - } - - /** - * Gets the obfuscated name (including prefix where appropriate - */ - public String obfuscated() { - return this.prefix(this.obfuscated); - } - - /** - * Apply the prefix (if any) to the specified string - * - * @param name String to prefix - * @return Prefixed string or original string if no prefix - */ - public String prefix(String name) { - return this.hasPrefix ? this.prefix + name : name; - } - } - /** * Mixin annotation */ private final AnnotationMirror annotation; - /** + /** + * Messager + */ + private final Messager messager; + + /** + * Type handle provider + */ + private final ITypeHandleProvider typeProvider; + + /** * Manager */ - private final AnnotatedMixins mixins; + private final IObfuscationManager obf; /** * Mixin class */ private final TypeElement mixin; + /** + * Mixin class + */ + private final TypeHandle handle; + /** * Specified targets */ @@ -252,18 +116,35 @@ class AnnotatedMixin { /** * Stored (ordered) field mappings */ - private final Set fieldMappings = new LinkedHashSet(); + private final Map> fieldMappings = new HashMap>(); /** * Stored (ordered) method mappings */ - private final Set methodMappings = new LinkedHashSet(); + private final Map> methodMappings = new HashMap>(); + + /** + * Overwrite handler + */ + private final AnnotatedMixinOverwriteHandler overwrites; + + /** + * Shadow handler + */ + private final AnnotatedMixinShadowHandler shadows; + + /** + * Injector handler + */ + private final AnnotatedMixinInjectorHandler injectors; - public AnnotatedMixin(AnnotatedMixins mixins, TypeElement type) { - + public AnnotatedMixin(IMixinAnnotationProcessor ap, TypeElement type) { this.annotation = MirrorUtils.getAnnotation(type, Mixin.class); - this.mixins = mixins; + this.typeProvider = ap.getTypeProvider(); + this.obf = ap.getObfuscationManager(); + this.messager = ap; this.mixin = type; + this.handle = new TypeHandle(type); this.classRef = type.getQualifiedName().toString().replace('.', '/'); TypeHandle primaryTarget = this.initTargets(); @@ -276,6 +157,15 @@ class AnnotatedMixin { } this.remap = AnnotatedMixins.getRemapValue(this.annotation) && this.targets.size() > 0; + + for (ObfuscationType obfType : ObfuscationType.values()) { + this.fieldMappings.put(obfType, new LinkedHashSet()); + this.methodMappings.put(obfType, new LinkedHashSet()); + } + + this.overwrites = new AnnotatedMixinOverwriteHandler(ap, this); + this.shadows = new AnnotatedMixinShadowHandler(ap, this); + this.injectors = new AnnotatedMixinInjectorHandler(ap, this); } AnnotatedMixin runValidators(ValidationPass pass, Collection validators) { @@ -300,13 +190,13 @@ class AnnotatedMixin { if (this.targets.contains(type)) { continue; } - this.targets.add(type); + this.addTarget(type); if (primaryTarget == null) { primaryTarget = type; } } } catch (Exception ex) { - this.mixins.printMessage(Kind.WARNING, "Error processing public targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this); + this.printMessage(Kind.WARNING, "Error processing public targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this); } // Private targets, referenced by name @@ -314,33 +204,53 @@ class AnnotatedMixin { List privateTargets = MirrorUtils.>getAnnotationValue(this.annotation, "targets", Collections.emptyList()); for (String privateTarget : MirrorUtils.unfold(privateTargets)) { - TypeHandle type = this.mixins.getTypeHandle(privateTarget); + TypeHandle type = this.typeProvider.getTypeHandle(privateTarget); if (this.targets.contains(type)) { continue; } if (type == null) { - this.mixins.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this); + this.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this); return null; } else if (type.isPublic()) { - this.mixins.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " is public and must be specified in value", this); + this.printMessage(Kind.WARNING, "Mixin target " + privateTarget + " is public and must be specified in value", this); return null; } - this.targets.add(type); + this.addSoftTarget(type, privateTarget); if (primaryTarget == null) { primaryTarget = type; } } } catch (Exception ex) { - this.mixins.printMessage(Kind.WARNING, "Error processing private targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this); + this.printMessage(Kind.WARNING, "Error processing private targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this); } if (primaryTarget == null) { - this.mixins.printMessage(Kind.ERROR, "Mixin has no targets", this); + this.printMessage(Kind.ERROR, "Mixin has no targets", this); } return primaryTarget; } + + /** + * Print a message to the AP messager + */ + private void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) { + this.messager.printMessage(kind, msg, this.mixin, this.annotation); + } + + private void addSoftTarget(TypeHandle type, String reference) { + ObfuscationData obfClassData = this.obf.getObfClass(type); + if (!obfClassData.isEmpty()) { + this.obf.addClassMapping(this.classRef, reference, obfClassData); + } + + this.addTarget(type); + } + private void addTarget(TypeHandle type) { + this.targets.add(type); + } + @Override public String toString() { return this.mixin.getSimpleName().toString(); @@ -357,6 +267,41 @@ class AnnotatedMixin { return this.mixin; } + /** + * Get the type handle for the mixin class + */ + public TypeHandle getHandle() { + return this.handle; + } + + /** + * Get the mixin class reference + */ + public String getClassRef() { + return this.classRef; + } + + /** + * Get whether this is an interface mixin + */ + public boolean isInterface() { + return this.mixin.getKind() == ElementKind.INTERFACE; + } + + /** + * Get the primary target class reference + */ + public String getPrimaryTargetRef() { + return this.targetRef; + } + + /** + * Get the primary target + */ + public TypeHandle getPrimaryTarget() { + return this.targetType; + } + /** * Get the mixin's targets */ @@ -374,15 +319,15 @@ class AnnotatedMixin { /** * Get stored field mappings */ - public Set getFieldMappings() { - return this.fieldMappings; + public Set getFieldMappings(ObfuscationType type) { + return this.fieldMappings.get(type); } /** * Get stored method mappings */ - public Set getMethodMappings() { - return this.methodMappings; + public Set getMethodMappings(ObfuscationType type) { + return this.methodMappings.get(type); } /** @@ -393,347 +338,32 @@ class AnnotatedMixin { this.methodMappings.clear(); } - /** - * Validate method for {@link org.spongepowered.asm.mixin.Shadow} and - * {@link org.spongepowered.asm.mixin.Overwrite} registrations to check that - * only a single target is registered. Mixins containing annotated methods - * with these annotations cannot be multi-targetted. - */ - private boolean validateSingleTarget(String annotation, Element element) { - if (this.targetRef == null || this.targets.size() > 1) { - this.mixins.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", element); - this.mixins.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", this.mixin); - return false; - } - return true; - } - - /** - * Register an {@link org.spongepowered.asm.mixin.Overwrite} method - */ public void registerOverwrite(ExecutableElement method, AnnotationMirror overwrite) { - AliasedElementName name = new AliasedElementName(method, overwrite); - this.validateTargetMethod(method, overwrite, name, "@Overwrite"); - this.checkConstraints(method, overwrite); - - if (!this.remap || !this.validateSingleTarget("@Overwrite", method)) { - return; - } - - String mcpName = method.getSimpleName().toString(); - String mcpSignature = MirrorUtils.generateSignature(method); - MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + mcpName, mcpSignature)); - - if (obfMethod == null) { - Kind error = Kind.ERROR; - - try { - // Try to access isStatic from com.sun.tools.javac.code.Symbol - Method md = method.getClass().getMethod("isStatic"); - if (((Boolean)md.invoke(method)).booleanValue()) { - error = Kind.WARNING; - } - } catch (Exception ex) { - // well, we tried - } - - this.mixins.printMessage(error, "No obfuscation mapping for @Overwrite method", method); - return; - } - - String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1); - this.addMethodMapping(mcpName, obfName, mcpSignature, obfMethod.sig); + this.overwrites.registerOverwrite(method, overwrite); } - /** - * Register a {@link org.spongepowered.asm.mixin.Shadow} field - */ - public void registerShadow(VariableElement field, AnnotationMirror shadow, boolean remap) { - ShadowElementName name = new ShadowElementName(field, shadow); - this.validateTargetField(field, shadow, name, "@Shadow"); - - if (!remap || !this.validateSingleTarget("@Shadow", field)) { - return; - } - - String obfField = this.mixins.getObfField(this.targetRef + "/" + name); - - if (obfField == null) { - this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field, shadow); - return; - } - - this.addFieldMapping(name.setObfuscatedName(obfField)); + public void registerShadow(VariableElement field, AnnotationMirror shadow, boolean shouldRemap) { + this.shadows.registerShadow(field, shadow, shouldRemap); } - /** - * Register a {@link org.spongepowered.asm.mixin.Shadow} method - */ - public void registerShadow(ExecutableElement method, AnnotationMirror shadow, boolean remap) { - ShadowElementName name = new ShadowElementName(method, shadow); - this.validateTargetMethod(method, shadow, name, "@Shadow"); - - if (!remap || !this.validateSingleTarget("@Shadow", method)) { - return; - } - - String mcpSignature = MirrorUtils.generateSignature(method); - MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + name, mcpSignature)); - - if (obfMethod == null) { - this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method", method, shadow); - return; - } - - this.addMethodMapping(name.setObfuscatedName(obfMethod.name), mcpSignature, obfMethod.sig); + public void registerShadow(ExecutableElement method, AnnotationMirror shadow, boolean shouldRemap) { + this.shadows.registerShadow(method, shadow, shouldRemap); } - /** - * Register a {@link org.spongepowered.asm.mixin.injection.Inject} method - */ - public void registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) { - String originalReference = MirrorUtils.getAnnotationValue(inject, "method"); - MemberInfo targetMember = MemberInfo.parse(originalReference); - if (targetMember.name == null) { - return; - } - - if (targetMember.desc != null) { - this.validateReferencedTarget(method, inject, targetMember, "@Inject"); - } - - if (!remap || !this.validateSingleTarget("@Inject", method)) { - return; - } - - String desc = this.targetType.findDescriptor(targetMember); - if (desc == null) { - if (this.targetType.isImaginary()) { - this.mixins.printMessage(Kind.WARNING, "@Inject target requires method signature because enclosing type information is unavailable", - method, inject); - } else if (!Constants.INIT.equals(targetMember.name)) { - this.mixins.printMessage(Kind.WARNING, "Unable to determine signature for @Inject target method", method, inject); - } - return; - } - - MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc)); - if (obfMethod == null) { - Kind error = Constants.INIT.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR; - this.mixins.printMessage(error, "No obfuscation mapping for @Inject target " + targetMember.name, method, inject); - return; - } - - String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1); - MemberInfo remappedReference = new MemberInfo(obfName, this.targetRef, obfMethod.sig, false); - - this.mixins.getReferenceMapper().addMapping(this.classRef, originalReference, remappedReference.toString()); + public Message registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) { + return this.injectors.registerInjector(method, inject, remap); } - /** - * Register a {@link org.spongepowered.asm.mixin.injection.At} annotation - * and process the references - */ - public void registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) { - if (!AnnotatedMixins.getRemapValue(at)) { - return; - } - - String type = MirrorUtils.getAnnotationValue(at, "value"); - String target = MirrorUtils.getAnnotationValue(at, "target"); - this.remapReference(type + ".", target, element, inject, at); - - // Pattern for replacing references in args, not used yet -// if ("SOMETYPE".equals(type)) { -// Map args = AnnotatedMixin.getAtArgs(at); -// this.remapReference(type + ".args[target]", args.get("target")); -// } + public int registerInjectionPoint(ExecutableElement element, AnnotationMirror inject, AnnotationMirror at) { + return this.injectors.registerInjectionPoint(element, inject, at); } - private void remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) { - if (target == null) { - return; - } - - MemberInfo targetMember = MemberInfo.parse(target); - if (!targetMember.isFullyQualified()) { - String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature"); - this.mixins.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing, element, inject); - return; - } - - MemberInfo remappedReference = null; - if (targetMember.isField()) { - String obfField = this.mixins.getObfField(targetMember.toSrg()); - if (obfField == null) { - this.mixins.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target + "'", element, inject); - return; - } - remappedReference = MemberInfo.fromSrgField(obfField, targetMember.desc); - } else { - MethodData obfMethod = this.mixins.getObfMethod(targetMember); - if (obfMethod == null) { - if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) { - this.mixins.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target + "'", element, inject); - } - return; - } - remappedReference = targetMember.remapUsing(obfMethod, false); - } - - this.mixins.getReferenceMapper().addMapping(this.classRef, target, remappedReference.toString()); + void addFieldMapping(ObfuscationType type, String mapping) { + this.fieldMappings.get(type).add(mapping); } - /** - * Add a field mapping to the local table - */ - private void addFieldMapping(ShadowElementName name) { - String mapping = String.format("FD: %s %s", this.classRef + "/" + name.name(), this.classRef + "/" + name.obfuscated()); - this.fieldMappings.add(mapping); + void addMethodMapping(ObfuscationType type, String mapping) { + this.methodMappings.get(type).add(mapping); } - /** - * Add a method mapping to the local table - */ - private void addMethodMapping(ShadowElementName name, String mcpSignature, String obfSignature) { - this.addMethodMapping(name.name(), name.obfuscated(), mcpSignature, obfSignature); - } - - /** - * Add a method mapping to the local table - */ - private void addMethodMapping(String mcpName, String obfName, String mcpSignature, String obfSignature) { - String mapping = String.format("MD: %s %s %s %s", this.classRef + "/" + mcpName, mcpSignature, this.classRef + "/" + obfName, obfSignature); - this.methodMappings.add(mapping); - } - - /** - * Check constraints for the specified annotation based on token values in - * the current environment - * - * @param method Annotated method - * @param annotation Annotation to check constraints - */ - private void checkConstraints(ExecutableElement method, AnnotationMirror annotation) { - try { - Constraint constraint = ConstraintParser.parse(MirrorUtils.getAnnotationValue(annotation, "constraints")); - try { - constraint.check(this.mixins); - } catch (ConstraintViolationException ex) { - this.mixins.printMessage(Kind.ERROR, ex.getMessage(), method, annotation); - } - } catch (InvalidConstraintException ex) { - this.mixins.printMessage(Kind.WARNING, ex.getMessage(), method, annotation); - } - } - - /** - * Checks whether the specified method exists in all targets and raises - * warnings where appropriate - */ - private void validateTargetMethod(ExecutableElement method, AnnotationMirror annotation, AliasedElementName name, String type) { - String signature = TypeHandle.getElementSignature(method); - - for (TypeHandle target : this.targets) { - if (target.isImaginary()) { - continue; - } - - // Find method as-is - MethodHandle targetMethod = target.findMethod(method); - if (targetMethod != null) { - continue; - } - - if (!name.baseName().equals(name.elementName())) { - // Find method without prefix - targetMethod = target.findMethod(name.baseName(), signature); - if (targetMethod != null) { - continue; - } - } - - // Check aliases - for (String alias : name.getAliases()) { - if ((targetMethod = target.findMethod(alias, signature)) != null) { - break; - } - } - - if (targetMethod == null) { - this.mixins.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation); - } - } - } - - /** - * Checks whether the specified field exists in all targets and raises - * warnings where appropriate - */ - private void validateTargetField(VariableElement field, AnnotationMirror shadow, AliasedElementName name, String type) { - String fieldType = field.asType().toString(); - - for (TypeHandle target : this.targets) { - if (target.isImaginary()) { - continue; - } - - // Search for field - FieldHandle targetField = target.findField(field); - if (targetField != null) { - continue; - } - - // Try search by alias - List aliases = name.getAliases(); - for (String alias : aliases) { - if ((targetField = target.findField(alias, fieldType)) != null) { - break; - } - } - - if (targetField == null) { - this.mixins.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, shadow); - } - } - } - - /** - * Checks whether the referenced method exists in all targets and raises - * warnings where appropriate - */ - private void validateReferencedTarget(ExecutableElement method, AnnotationMirror inject, MemberInfo reference, String type) { - String signature = reference.toDescriptor(); - - for (TypeHandle target : this.targets) { - if (target.isImaginary()) { - continue; - } - - MethodHandle targetMethod = target.findMethod(reference.name, signature); - if (targetMethod == null) { - this.mixins.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject); - } - } - } - - static Map getAtArgs(AnnotationMirror at) { - Map args = new HashMap(); - List argv = MirrorUtils.>getAnnotationValue(at, "args"); - if (argv != null) { - for (AnnotationValue av : argv) { - String arg = (String)av.getValue(); - if (arg == null) { - continue; - } - int eqPos = arg.indexOf('='); - if (eqPos > -1) { - args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1)); - } else { - args.put(arg, ""); - } - } - } - return args; - } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java new file mode 100644 index 00000000..41ed260e --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -0,0 +1,410 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.util.List; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.VariableElement; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.asm.util.ConstraintParser; +import org.spongepowered.asm.util.ConstraintParser.Constraint; +import org.spongepowered.asm.util.throwables.ConstraintViolationException; +import org.spongepowered.asm.util.throwables.InvalidConstraintException; +import org.spongepowered.tools.MirrorUtils; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; + +/** + * Base class for module for {@link AnnotatedMixin} which handle different + * aspects of mixin target classes + */ +abstract class AnnotatedMixinElementHandler { + + /** + * A name of an element which may have aliases + */ + static class AliasedElementName { + + /** + * The original name including any original prefix (the "actual" name) + */ + protected final String originalName; + + /** + * Aliases declared by the annotation (if any), never null + */ + private final List aliases; + + public AliasedElementName(Element element, AnnotationMirror annotation) { + this.originalName = element.getSimpleName().toString(); + List aliases = MirrorUtils.>getAnnotationValue(annotation, "aliases"); + this.aliases = MirrorUtils.unfold(aliases); + } + + /** + * Get whether this member has any aliases defined + */ + public boolean hasAliases() { + return this.aliases.size() > 0; + } + + /** + * Get this member's aliases + */ + public List getAliases() { + return this.aliases; + } + + /** + * Gets the original name of the member (including prefix) + */ + public String elementName() { + return this.originalName; + } + + public String baseName() { + return this.originalName; + } + + } + + /** + * Convenience class to store information about an + * {@link org.spongepowered.asm.mixin.Shadow}ed member's names + */ + static class ShadowElementName extends AliasedElementName { + + /** + * True if the real element is prefixed + */ + private final boolean hasPrefix; + + /** + * Expected prefix read from the annotation, this is set even if + * {@link #hasPrefix} is false + */ + private final String prefix; + + /** + * The base name without the prefix + */ + private final String baseName; + + /** + * Obfuscated name (once determined) + */ + private String obfuscated; + + ShadowElementName(Element element, AnnotationMirror shadow) { + super(element, shadow); + + this.prefix = MirrorUtils.getAnnotationValue(shadow, "prefix", "shadow$"); + + boolean hasPrefix = false; + String name = this.originalName; + if (name.startsWith(this.prefix)) { + hasPrefix = true; + name = name.substring(this.prefix.length()); + } + + this.hasPrefix = hasPrefix; + this.obfuscated = this.baseName = name; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return this.baseName; + } + + @Override + public String baseName() { + return this.baseName; + } + + /** + * Sets the obfuscated name for this element + * + * @param name New name + * @return fluent interface + */ + public ShadowElementName setObfuscatedName(String name) { + this.obfuscated = name.substring(name.lastIndexOf('/') + 1); + return this; + } + + /** + * Get the prefix (if set), does not return the expected prefix + */ + public String prefix() { + return this.hasPrefix ? this.prefix : ""; + } + + /** + * Get the base name + */ + public String name() { + return this.prefix(this.baseName); + } + + /** + * Gets the obfuscated name (including prefix where appropriate + */ + public String obfuscated() { + return this.prefix(this.obfuscated); + } + + /** + * Apply the prefix (if any) to the specified string + * + * @param name String to prefix + * @return Prefixed string or original string if no prefix + */ + public String prefix(String name) { + return this.hasPrefix ? this.prefix + name : name; + } + + } + + /** + * Mixin + */ + protected final AnnotatedMixin mixin; + + protected final String classRef; + + /** + * Annotation processor + */ + protected final IMixinAnnotationProcessor ap; + + /** + * Manager + */ + protected final IObfuscationManager obf; + + AnnotatedMixinElementHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + this.ap = ap; + this.mixin = mixin; + this.classRef = mixin.getClassRef(); + this.obf = ap.getObfuscationManager(); + } + + protected final boolean remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) { + if (target == null) { + return false; + } + + MemberInfo targetMember = MemberInfo.parse(target); + if (!targetMember.isFullyQualified()) { + String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature"); + this.ap.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing, element, inject); + return false; + } + + try { + targetMember.validate(); + } catch (InvalidMemberDescriptorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), element, inject); + } + + if (targetMember.isField()) { + ObfuscationData obfFieldData = this.obf.getObfFieldRecursive(targetMember); + if (obfFieldData.isEmpty()) { + this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target + "'", element, inject); + return false; + } + this.obf.addFieldMapping(this.classRef, target, targetMember, obfFieldData); + } else { + ObfuscationData obfMethodData = this.obf.getObfMethodRecursive(targetMember); + if (obfMethodData.isEmpty()) { + if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) { + this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target + "'", element, inject); + } + } + this.obf.addMethodMapping(this.classRef, target, targetMember, obfMethodData); + } + return true; + } + + /** + * Add a field mapping to the local table + */ + protected final void addFieldMapping(ObfuscationType type, ShadowElementName name) { + String mapping = String.format("FD: %s %s", this.classRef + "/" + name.name(), this.classRef + "/" + name.obfuscated()); + this.mixin.addFieldMapping(type, mapping); + } + + /** + * Add a method mapping to the local table + */ + protected final void addMethodMapping(ObfuscationType type, ShadowElementName name, String mcpSignature, String obfSignature) { + this.addMethodMapping(type, name.name(), name.obfuscated(), mcpSignature, obfSignature); + } + + /** + * Add a method mapping to the local table + */ + protected final void addMethodMapping(ObfuscationType type, String mcpName, String obfName, String mcpSignature, String obfSignature) { + String mapping = String.format("MD: %s %s %s %s", this.classRef + "/" + mcpName, mcpSignature, this.classRef + "/" + obfName, obfSignature); + this.mixin.addMethodMapping(type, mapping); + } + + /** + * Validate method for {@link org.spongepowered.asm.mixin.Shadow} and + * {@link org.spongepowered.asm.mixin.Overwrite} registrations to check that + * only a single target is registered. Mixins containing annotated methods + * with these annotations cannot be multi-targetted. + */ + protected final boolean validateSingleTarget(String annotation, Element element) { + if (this.mixin.getPrimaryTargetRef() == null || this.mixin.getTargets().size() > 1) { + this.ap.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", element); + this.ap.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", this.mixin.getMixin()); + return false; + } + return true; + } + + /** + * Check constraints for the specified annotation based on token values in + * the current environment + * + * @param method Annotated method + * @param annotation Annotation to check constraints + */ + protected final void checkConstraints(ExecutableElement method, AnnotationMirror annotation) { + try { + Constraint constraint = ConstraintParser.parse(MirrorUtils.getAnnotationValue(annotation, "constraints")); + try { + constraint.check(this.ap.getTokenProvider()); + } catch (ConstraintViolationException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), method, annotation); + } + } catch (InvalidConstraintException ex) { + this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation); + } + } + + /** + * Checks whether the specified method exists in all targets and raises + * warnings where appropriate + */ + protected final void validateTargetMethod(ExecutableElement method, AnnotationMirror annotation, AliasedElementName name, String type) { + String signature = MirrorUtils.getJavaSignature(method); + + for (TypeHandle target : this.mixin.getTargets()) { + if (target.isImaginary()) { + continue; + } + + // Find method as-is + MethodHandle targetMethod = target.findMethod(method); + if (targetMethod != null) { + continue; + } + + if (!name.baseName().equals(name.elementName())) { + // Find method without prefix + targetMethod = target.findMethod(name.baseName(), signature); + if (targetMethod != null) { + continue; + } + } + + // Check aliases + for (String alias : name.getAliases()) { + if ((targetMethod = target.findMethod(alias, signature)) != null) { + break; + } + } + + if (targetMethod == null) { + this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation); + } + } + } + + /** + * Checks whether the specified field exists in all targets and raises + * warnings where appropriate + */ + protected final void validateTargetField(VariableElement field, AnnotationMirror shadow, AliasedElementName name, String type) { + String fieldType = field.asType().toString(); + + for (TypeHandle target : this.mixin.getTargets()) { + if (target.isImaginary()) { + continue; + } + + // Search for field + FieldHandle targetField = target.findField(field); + if (targetField != null) { + continue; + } + + // Try search by alias + List aliases = name.getAliases(); + for (String alias : aliases) { + if ((targetField = target.findField(alias, fieldType)) != null) { + break; + } + } + + if (targetField == null) { + this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, shadow); + } + } + } + + /** + * Checks whether the referenced method exists in all targets and raises + * warnings where appropriate + */ + protected final void validateReferencedTarget(ExecutableElement method, AnnotationMirror inject, MemberInfo reference, String type) { + String signature = reference.toDescriptor(); + + for (TypeHandle target : this.mixin.getTargets()) { + if (target.isImaginary()) { + continue; + } + + MethodHandle targetMethod = target.findMethod(reference.name, signature); + if (targetMethod == null) { + this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject); + } + } + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinInjectorHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinInjectorHandler.java new file mode 100644 index 00000000..075c34e0 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinInjectorHandler.java @@ -0,0 +1,155 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.tools.MirrorUtils; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.struct.Message; + +/** + * A module for {@link AnnotatedMixin} whic handles injectors + */ +class AnnotatedMixinInjectorHandler extends AnnotatedMixinElementHandler { + + AnnotatedMixinInjectorHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + super(ap, mixin); + } + + /** + * Register a {@link org.spongepowered.asm.mixin.injection.Inject} method + * + * @param method Callback method + * @param inject Inject annotation + * @param remap + * @return pending error message or null if no error condition + */ + public Message registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) { + if (this.mixin.isInterface()) { + this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", method); + } + + String originalReference = MirrorUtils.getAnnotationValue(inject, "method"); + MemberInfo targetMember = MemberInfo.parse(originalReference); + if (targetMember.name == null) { + return null; + } + + try { + targetMember.validate(); + } catch (InvalidMemberDescriptorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), method, inject); + } + + String type = "@" + inject.getAnnotationType().asElement().getSimpleName() + ""; + if (targetMember.desc != null) { + this.validateReferencedTarget(method, inject, targetMember, type); + } + + if (!remap || !this.validateSingleTarget(type, method)) { + return null; + } + + String desc = this.mixin.getPrimaryTarget().findDescriptor(targetMember); + if (desc == null) { + if (this.mixin.getPrimaryTarget().isImaginary()) { + this.ap.printMessage(Kind.WARNING, type + " target requires method signature because enclosing type information is unavailable", + method, inject); + } else if (!Constants.CTOR.equals(targetMember.name)) { + this.ap.printMessage(Kind.WARNING, "Unable to determine signature for " + type + " target method", method, inject); + } + return null; + } + + ObfuscationData obfData = this.obf.getObfMethod(new SrgMethod(this.mixin.getPrimaryTargetRef() + "/" + targetMember.name, desc)); + if (obfData.isEmpty()) { + Kind error = Constants.CTOR.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR; + return new Message(error, "No obfuscation mapping for " + type + " target " + targetMember.name, method, inject); + } + + this.obf.addMethodMapping(this.classRef, originalReference, obfData); + return null; + } + + /** + * Register a {@link org.spongepowered.asm.mixin.injection.At} annotation + * and process the references + */ + public int registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) { + if (this.mixin.isInterface()) { + this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", element); + } + + if (!AnnotatedMixins.getRemapValue(at)) { + return 0; + } + + String type = MirrorUtils.getAnnotationValue(at, "value"); + String target = MirrorUtils.getAnnotationValue(at, "target"); + int remapped = this.remapReference(type + ".", target, element, inject, at) ? 1 : 0; + + // Pattern for replacing references in args, not used yet +// if ("SOMETYPE".equals(type)) { +// Map args = InjectorHandler.getAtArgs(at); +// this.remapReference(type + ".args[target]", args.get("target")); +// } + + return remapped; + } + + static Map getAtArgs(AnnotationMirror at) { + Map args = new HashMap(); + List argv = MirrorUtils.>getAnnotationValue(at, "args"); + if (argv != null) { + for (AnnotationValue av : argv) { + String arg = (String)av.getValue(); + if (arg == null) { + continue; + } + int eqPos = arg.indexOf('='); + if (eqPos > -1) { + args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1)); + } else { + args.put(arg, ""); + } + } + } + return args; + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinOverwriteHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinOverwriteHandler.java new file mode 100644 index 00000000..1c3ebf5e --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinOverwriteHandler.java @@ -0,0 +1,101 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.lang.reflect.Method; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.tools.MirrorUtils; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; + +/** + * A module for {@link AnnotatedMixin} which handles method overwrites + */ +class AnnotatedMixinOverwriteHandler extends AnnotatedMixinElementHandler { + + AnnotatedMixinOverwriteHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + super(ap, mixin); + } + + void registerOverwrite(ExecutableElement method, AnnotationMirror overwrite) { + AliasedElementName name = new AliasedElementName(method, overwrite); + this.validateTargetMethod(method, overwrite, name, "@Overwrite"); + this.checkConstraints(method, overwrite); + + if (!this.mixin.remap() || !this.validateSingleTarget("@Overwrite", method)) { + return; + } + + String mcpName = method.getSimpleName().toString(); + String mcpSignature = MirrorUtils.generateSignature(method); + ObfuscationData obfData = this.obf.getObfMethod(new SrgMethod(this.mixin.getPrimaryTargetRef() + "/" + mcpName, mcpSignature)); + + if (obfData.isEmpty()) { + Kind error = Kind.ERROR; + + try { + // Try to access isStatic from com.sun.tools.javac.code.Symbol + Method md = method.getClass().getMethod("isStatic"); + if (((Boolean)md.invoke(method)).booleanValue()) { + error = Kind.WARNING; + } + } catch (Exception ex) { + // well, we tried + } + + this.ap.printMessage(error, "No obfuscation mapping for @Overwrite method", method); + return; + } + + for (ObfuscationType type : obfData) { + SrgMethod obfMethod = obfData.get(type); + this.addMethodMapping(type, mcpName, obfMethod.getSimpleName(), mcpSignature, obfMethod.getDesc()); + } + + if (!"true".equalsIgnoreCase(this.ap.getOption(SupportedOptions.DISABLE_OVERWRITE_CHECKER))) { + Kind overwriteErrorKind = "error".equalsIgnoreCase(this.ap.getOption(SupportedOptions.OVERWRITE_ERROR_LEVEL)) + ? Kind.ERROR : Kind.WARNING; + + String javadoc = this.ap.getJavadocProvider().getJavadoc(method); + if (javadoc == null) { + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", method); + return; + } + + if (!javadoc.toLowerCase().contains("@author")) { + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", method); + } + + if (!javadoc.toLowerCase().contains("@reason")) { + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", method); + } + } + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinShadowHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinShadowHandler.java new file mode 100644 index 00000000..e470d299 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinShadowHandler.java @@ -0,0 +1,94 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.VariableElement; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.tools.MirrorUtils; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; + +/** + * A module for {@link AnnotatedMixin} which handles shadowed fields and methods + */ +class AnnotatedMixinShadowHandler extends AnnotatedMixinElementHandler { + + AnnotatedMixinShadowHandler(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { + super(ap, mixin); + } + + /** + * Register a {@link org.spongepowered.asm.mixin.Shadow} field + */ + public void registerShadow(VariableElement field, AnnotationMirror shadow, boolean remap) { + ShadowElementName name = new ShadowElementName(field, shadow); + this.validateTargetField(field, shadow, name, "@Shadow"); + + if (!remap || !this.validateSingleTarget("@Shadow", field)) { + return; + } + + ObfuscationData obfFieldData = this.obf.getObfField(this.mixin.getPrimaryTargetRef() + "/" + name); + + if (obfFieldData.isEmpty()) { + this.ap.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field, shadow); + return; + } + + for (ObfuscationType type : obfFieldData) { + String fieldName = obfFieldData.get(type); + this.addFieldMapping(type, name.setObfuscatedName(fieldName)); + } + } + + /** + * Register a {@link org.spongepowered.asm.mixin.Shadow} method + */ + public void registerShadow(ExecutableElement method, AnnotationMirror shadow, boolean remap) { + ShadowElementName name = new ShadowElementName(method, shadow); + this.validateTargetMethod(method, shadow, name, "@Shadow"); + + if (!remap || !this.validateSingleTarget("@Shadow", method)) { + return; + } + + String mcpSignature = MirrorUtils.generateSignature(method); + ObfuscationData obfData = this.obf.getObfMethod(new SrgMethod(this.mixin.getPrimaryTargetRef() + "/" + name, mcpSignature)); + + if (obfData.isEmpty()) { + this.ap.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method", method, shadow); + return; + } + + for (ObfuscationType type : obfData) { + SrgMethod obfMethod = obfData.get(type); + this.addMethodMapping(type, name.setObfuscatedName(obfMethod.getName()), mcpSignature, obfMethod.getDesc()); + } + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index 7b880e03..c07715aa 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -27,20 +27,16 @@ package org.spongepowered.tools.obfuscation; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.processing.Filer; -import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; @@ -50,7 +46,6 @@ import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; -import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.tools.Diagnostic; @@ -60,26 +55,32 @@ import javax.tools.StandardLocation; import org.spongepowered.asm.launch.MixinBootstrap; import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper; import org.spongepowered.asm.util.ITokenProvider; import org.spongepowered.tools.MirrorUtils; -import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass; +import org.spongepowered.tools.obfuscation.interfaces.IJavadocProvider; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; +import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass; +import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; +import org.spongepowered.tools.obfuscation.interfaces.ITypeHandleProvider; +import org.spongepowered.tools.obfuscation.struct.Message; import org.spongepowered.tools.obfuscation.validation.ParentValidator; import org.spongepowered.tools.obfuscation.validation.TargetValidator; import com.google.common.collect.ImmutableList; -import net.minecraftforge.srg2source.rangeapplier.MethodData; -import net.minecraftforge.srg2source.rangeapplier.SrgContainer; - - /** * Mixin info manager, stores all of the mixin info during processing and also * manages access to the srgs */ -class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { +class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITypeHandleProvider, IJavadocProvider { + private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid"; + + /** + * Detected compiler argument, specifies the behaviour of some operations + * for compatibility purposes. + */ static enum CompilerEnvironment { /** * Default environment @@ -115,24 +116,9 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { private final List mixinsForPass = new ArrayList(); /** - * Name of the resource to write generated srgs to + * Obfuscation manager */ - private final String outSrgFileName; - - /** - * Name of the resource to write remapped refs to - */ - private final String outRefMapFileName; - - /** - * File containing the reobfd srgs - */ - private final String reobfSrgFileName; - - /** - * Reference mapper for reference mapping - */ - private final ReferenceMapper refMapper = new ReferenceMapper(); + private final ObfuscationManager obf; /** * Rule validators @@ -145,15 +131,9 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { private final Map tokenCache = new HashMap(); /** - * SRG container for mcp->srg mappings + * Serialisable mixin target map */ - private SrgContainer srgs; - - /** - * True once we've tried to initialise the srgs, initially false so that we - * can do srg init lazily - */ - private boolean initDone; + private final TargetMap targets; /** * Properties file used to specify options when AP options cannot be @@ -167,19 +147,31 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { private AnnotatedMixins(ProcessingEnvironment processingEnv) { this.env = this.detectEnvironment(processingEnv); this.processingEnv = processingEnv; + this.targets = this.initTargetMap(); + this.obf = new ObfuscationManager(this); this.printMessage(Kind.NOTE, "SpongePowered Mixin Annotation Processor v" + MixinBootstrap.VERSION); - - this.reobfSrgFileName = this.getOption("reobfSrgFile"); - this.outSrgFileName = this.getOption("outSrgFile"); - this.outRefMapFileName = this.getOption("outRefMapFile"); - + this.validators = ImmutableList.of( - new ParentValidator(processingEnv, this, this), - new TargetValidator(processingEnv, this, this) + new ParentValidator(this), + new TargetValidator(this) ); - this.initTokenCache(this.getOption("tokens")); + this.initTokenCache(this.getOption(SupportedOptions.TOKENS)); + } + + protected TargetMap initTargetMap() { + TargetMap targets = TargetMap.create(System.getProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY)); + System.setProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY, targets.getSessionId()); + String targetsFileName = this.getOption(SupportedOptions.DEPENDENCY_TARGETS_FILE); + if (targetsFileName != null) { + try { + targets.readImports(new File(targetsFileName)); + } catch (IOException ex) { + this.printMessage(Kind.WARNING, "Could not read from specified imports file: " + targetsFileName); + } + } + return targets; } private void initTokenCache(String tokens) { @@ -195,6 +187,31 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { } } } + + @Override + public ITypeHandleProvider getTypeProvider() { + return this; + } + + @Override + public ITokenProvider getTokenProvider() { + return this; + } + + @Override + public IObfuscationManager getObfuscationManager() { + return this.obf; + } + + @Override + public IJavadocProvider getJavadocProvider() { + return this; + } + + @Override + public ProcessingEnvironment getProcessingEnvironment() { + return this.processingEnv; + } @Override public Integer getToken(String token) { @@ -252,123 +269,20 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { return CompilerEnvironment.JAVAC; } - /** - * Lazy initialisation for srgs, so that we only initialise the srgs if - * they're actually required. - */ - private boolean initSrgs() { - if (!this.initDone) { - this.initDone = true; - - if (this.reobfSrgFileName == null) { - this.printMessage(Kind.ERROR, "The reobfSrgFile argument was not supplied, obfuscation processing will not occur"); - return false; - } - - try { - File reobfSrgFile = new File(this.reobfSrgFileName); - this.printMessage(Kind.NOTE, "Loading SRGs from " + reobfSrgFile.getAbsolutePath()); - this.srgs = new SrgContainer().readSrg(reobfSrgFile); - } catch (Exception ex) { - ex.printStackTrace(); - this.printMessage(Kind.ERROR, "The specified SRG file could not be read, processing cannot continue"); - this.srgs = null; - } - } - - return this.srgs != null; - } - /** * Write out generated srgs */ public void writeSrgs() { - if (this.outSrgFileName == null) { - return; - } - - Set fieldMappings = new LinkedHashSet(); - Set methodMappings = new LinkedHashSet(); - - for (AnnotatedMixin mixin : this.mixins.values()) { - fieldMappings.addAll(mixin.getFieldMappings()); - methodMappings.addAll(mixin.getMethodMappings()); - } - - PrintWriter writer = null; - - try { - writer = this.openFileWriter(this.outSrgFileName, "output SRGs"); - for (String fieldMapping : fieldMappings) { - writer.println(fieldMapping); - } - for (String methodMapping : methodMappings) { - writer.println(methodMapping); - } - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception ex) { - // oh well - } - } - } - } - - /** - * Open a writer for an output file - */ - private PrintWriter openFileWriter(String fileName, String description) throws IOException { - if (fileName.matches("^.*[\\\\/:].*$")) { - File outSrgFile = new File(fileName); - outSrgFile.getParentFile().mkdirs(); - this.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath()); - return new PrintWriter(outSrgFile); - } - - Filer filer = this.processingEnv.getFiler(); - FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName); - this.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath()); - return new PrintWriter(outSrg.openWriter()); + this.obf.writeSrgs(this.mixins); } /** * Write out stored mappings */ public void writeRefs() { - if (this.outRefMapFileName == null) { - return; - } - - PrintWriter writer = null; - - try { - writer = this.openFileWriter(this.outRefMapFileName, "refmap"); - this.refMapper.write(writer); - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception ex) { - // oh well - } - } - } - + this.obf.writeRefs(); } - /** - * Get the reference mapper - */ - public ReferenceMapper getReferenceMapper() { - return this.refMapper; - } - /** * Clear all registered mixins */ @@ -384,6 +298,7 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { if (!this.mixins.containsKey(name)) { AnnotatedMixin mixin = new AnnotatedMixin(this, mixinType); + this.targets.registerTargets(mixin); mixin.runValidators(ValidationPass.EARLY, this.validators); this.mixins.put(name, mixin); this.mixinsForPass.add(mixin); @@ -411,12 +326,10 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { public Collection getMixinsTargeting(TypeElement targetType) { List minions = new ArrayList(); - for (AnnotatedMixin mixin : this.mixins.values()) { - for (TypeHandle mixinTarget : mixin.getTargets()) { - if (targetType.equals(mixinTarget.getElement())) { - minions.add(mixin.getMixin().asType()); - break; - } + for (TypeReference mixin : this.targets.getMixinsTargeting(targetType)) { + TypeHandle handle = mixin.getHandle(this.processingEnv); + if (handle != null) { + minions.add(handle.getType()); } } @@ -443,7 +356,7 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { * Register a {@link org.spongepowered.asm.mixin.Shadow} field * * @param mixinType Mixin class - * @param method Shadow field + * @param field Shadow field * @param shadow {@link org.spongepowered.asm.mixin.Shadow} annotation */ public void registerShadow(TypeElement mixinType, VariableElement field, AnnotationMirror shadow) { @@ -484,12 +397,14 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { public void registerInjector(TypeElement mixinType, ExecutableElement method, AnnotationMirror inject) { AnnotatedMixin mixinClass = this.getMixin(mixinType); if (mixinClass == null) { - this.printMessage(Kind.ERROR, "Found @Inject annotation on a non-mixin method", method); + String type = "@" + inject.getAnnotationType().asElement().getSimpleName() + ""; + this.printMessage(Kind.ERROR, "Found " + type + " annotation on a non-mixin method", method); return; } boolean remap = this.shouldRemap(mixinClass, inject); - mixinClass.registerInjector(method, inject, remap); + Message errorMessage = mixinClass.registerInjector(method, inject, remap); + int remappedAts = 0; if (remap) { Object ats = MirrorUtils.getAnnotationValue(inject, "at"); @@ -501,21 +416,28 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { at = ((AnnotationValue)at).getValue(); } if (at instanceof AnnotationMirror) { - mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at); + remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at); } else { this.printMessage(Kind.WARNING, "No annotation mirror on " + at.getClass().getName()); } } } else if (ats instanceof AnnotationMirror) { - mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats); + remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats); } else if (ats instanceof AnnotationValue) { // Fix for JDT Object mirror = ((AnnotationValue)ats).getValue(); if (mirror instanceof AnnotationMirror) { - mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror); + remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror); } } } + + // The annotation was *not* marked as remap=false and failed so we + // checked for remappable @At annotations, if that failed as well then + // we raise the original error. + if (remappedAts == 0 && errorMessage != null) { + errorMessage.sendTo(this); + } } /** @@ -530,6 +452,10 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { * Called from each AP when a pass is completed */ public void onPassCompleted() { + if (!"true".equalsIgnoreCase(this.getOption(SupportedOptions.DISABLE_TARGET_EXPORT))) { + this.targets.write(true); + } + for (AnnotatedMixin mixin : this.mixinsForPass) { mixin.runValidators(ValidationPass.LATE, this.validators); } @@ -580,17 +506,11 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value); } - /** - * Print a message to the AP messager - */ - public void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) { - this.processingEnv.getMessager().printMessage(kind, msg, mixin.getMixin(), mixin.getAnnotation()); - } - /** * Get a TypeHandle representing another type in the current processing * environment */ + @Override public TypeHandle getTypeHandle(String name) { name = name.replace('/', '.'); @@ -615,51 +535,15 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider { return null; } - - /** - * Get an obfuscation mapping for a method - */ - public MethodData getObfMethod(MemberInfo method) { - MethodData obfd = this.getObfMethod(method.asMethodData()); - if (obfd != null || !method.isFullyQualified()) { - return obfd; - } - - // Get a type handle for the declared method owner - TypeHandle type = this.getTypeHandle(method.owner); - if (type.isImaginary()) { - return null; - } - - // See if we can get the superclass from the reference - TypeMirror superClass = type.getElement().getSuperclass(); - if (superClass.getKind() != TypeKind.DECLARED) { - return null; - } - - // Well we found it, let's inflect the class name and recurse the search - String superClassName = ((TypeElement)((DeclaredType)superClass).asElement()).getQualifiedName().toString(); - return this.getObfMethod(new MemberInfo(method.name, superClassName.replace('.', '/'), method.desc, method.matchAll)); - } - /** - * Get an obfuscation mapping for a method + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IJavadocProvider + * #getJavadoc(javax.lang.model.element.Element) */ - public MethodData getObfMethod(MethodData method) { - if (this.initSrgs()) { - return this.srgs.methodMap.get(method); - } - return null; - } - - /** - * Get an obfuscation mapping for a field - */ - public String getObfField(String field) { - if (this.initSrgs()) { - return this.srgs.fieldMap.get(field); - } - return null; + @Override + public String getJavadoc(Element element) { + Elements elements = this.processingEnv.getElementUtils(); + return elements.getDocComment(element); } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java index 3de475ca..bb08b9dd 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/FieldHandle.java @@ -26,7 +26,6 @@ package org.spongepowered.tools.obfuscation; import javax.lang.model.element.VariableElement; - /** * Retrieved from a {@link TypeHandle} when searching for fields */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java index e07acb5a..832b5600 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java @@ -29,9 +29,6 @@ import java.util.Set; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedOptions; -import javax.annotation.processing.SupportedSourceVersion; -import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; @@ -39,8 +36,11 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic.Kind; +import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.tools.MirrorUtils; @@ -48,14 +48,12 @@ import org.spongepowered.tools.MirrorUtils; * Annotation processor which finds {@link Inject} and {@link At} annotations in * mixin classes and generates SRG mappings */ -@SupportedSourceVersion(SourceVersion.RELEASE_6) @SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.injection.Inject", "org.spongepowered.asm.mixin.injection.ModifyArg", "org.spongepowered.asm.mixin.injection.Redirect", "org.spongepowered.asm.mixin.injection.At" }) -@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile" }) public class InjectionObfuscationProcessor extends MixinProcessor { /* (non-Javadoc) @@ -66,13 +64,15 @@ public class InjectionObfuscationProcessor extends MixinProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { - return false; + return true; } this.processMixins(roundEnv); this.processInjectors(roundEnv, Inject.class); this.processInjectors(roundEnv, ModifyArg.class); this.processInjectors(roundEnv, Redirect.class); + this.processInjectors(roundEnv, ModifyVariable.class); + this.processInjectors(roundEnv, ModifyConstant.class); this.postProcess(roundEnv); return true; diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java index 9dacb904..8b6c6312 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MethodHandle.java @@ -26,7 +26,6 @@ package org.spongepowered.tools.obfuscation; import javax.lang.model.element.ExecutableElement; - /** * Retrieved from a {@link TypeHandle} when searching for methods */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java index 880d1290..028eec49 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java @@ -24,9 +24,12 @@ */ package org.spongepowered.tools.obfuscation; +import java.util.Set; + import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; @@ -34,8 +37,11 @@ import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.Mixin; +/** + * Base class for mixin annotation processor modules + */ public abstract class MixinProcessor extends AbstractProcessor { - + /** * Mixin info manager */ @@ -58,10 +64,10 @@ public abstract class MixinProcessor extends AbstractProcessor { this.mixins.onPassStarted(); for (Element elem : roundEnv.getElementsAnnotatedWith(Mixin.class)) { - if (elem.getKind() == ElementKind.CLASS) { + if (elem.getKind() == ElementKind.CLASS || elem.getKind() == ElementKind.INTERFACE) { this.mixins.registerMixin((TypeElement)elem); } else { - this.mixins.printMessage(Kind.ERROR, "Found an @Mixin annotation on an element which is not a class", elem); + this.mixins.printMessage(Kind.ERROR, "Found an @Mixin annotation on an element which is not a class or interface", elem); } } } @@ -70,4 +76,20 @@ public abstract class MixinProcessor extends AbstractProcessor { this.mixins.onPassCompleted(); } + @Override + public SourceVersion getSupportedSourceVersion() { + try { + return SourceVersion.valueOf("RELEASE_8"); + } catch (IllegalArgumentException ex) { + // Java 8 not supported + } + + return super.getSupportedSourceVersion(); + } + + @Override + public Set getSupportedOptions() { + return SupportedOptions.all; + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java index 8b9a2efc..3dbab5c1 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java @@ -34,6 +34,9 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; +import org.spongepowered.tools.obfuscation.interfaces.IOptionProvider; /** * Base class for mixin validators @@ -64,15 +67,13 @@ public abstract class MixinValidator implements IMixinValidator { /** * ctor * - * @param processingEnv Processing environment - * @param messager Messager to use - * @param options Option provider + * @param ap Processing environment * @param pass Validation pass being performed */ - public MixinValidator(ProcessingEnvironment processingEnv, Messager messager, IOptionProvider options, ValidationPass pass) { - this.processingEnv = processingEnv; - this.messager = messager; - this.options = options; + public MixinValidator(IMixinAnnotationProcessor ap, ValidationPass pass) { + this.processingEnv = ap.getProcessingEnvironment(); + this.messager = ap; + this.options = ap; this.pass = pass; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationData.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationData.java new file mode 100644 index 00000000..232bbca2 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationData.java @@ -0,0 +1,93 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.spongepowered.asm.obfuscation.SrgMethod; + +/** + * Return value struct for various obfuscation queries performed by the mixin + * annotation processor. + * + *

When obfuscation queries are performed by the AP, the returned data are + * encapsulated in an ObfuscationData object which contains a mapping + * of the different obfuscation types to the respective remapped value of the + * original entry for that environment.

+ * + *

The returned data are iterable over the keys, consumers should call + * {@link #get} to retrieve the remapped entries for each key.

+ * + * @param Contained type of the data, usually {@link String} for field + * and type obfuscations, and {@link SrgMethod} for methods. + */ +public class ObfuscationData implements Iterable { + + private final Map data = new HashMap(); + + private final T defaultValue; + + public ObfuscationData() { + this(null); + } + + public ObfuscationData(T defaultValue) { + this.defaultValue = defaultValue; + } + + public void add(ObfuscationType type, T value) { + this.data.put(type, value); + } + + public boolean isEmpty() { + return this.data.isEmpty(); + } + + public T get(ObfuscationType type) { + T value = this.data.get(type); + return value != null ? value : this.defaultValue; + } + + @Override + public Iterator iterator() { + return this.data.keySet().iterator(); + } + + @Override + public String toString() { + return String.format("ObfuscationData[%sDEFAULT=%s]", this.listValues(), this.defaultValue); + } + + private String listValues() { + StringBuilder sb = new StringBuilder(); + for (ObfuscationType type : this.data.keySet()) { + sb.append(type.name()).append('=').append(this.data.get(type)).append(','); + } + return sb.toString(); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationManager.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationManager.java new file mode 100644 index 00000000..f4a071e4 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationManager.java @@ -0,0 +1,389 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.tools.Diagnostic.Kind; +import javax.tools.FileObject; +import javax.tools.StandardLocation; + +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.obfuscation.SrgField; +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager; + +/** + * Obfuscation Manager for mixin Annotation Processor + */ +public class ObfuscationManager implements IObfuscationManager { + + /** + * Annotation processor + */ + private final IMixinAnnotationProcessor ap; + + /** + * Name of the resource to write remapped refs to + */ + private final String outRefMapFileName; + + /** + * Target obfuscation environments + */ + private final List targetEnvironments = new ArrayList(); + + /** + * Reference mapper for reference mapping + */ + private final ReferenceMapper refMapper = new ReferenceMapper(); + + public ObfuscationManager(IMixinAnnotationProcessor ap) { + this.ap = ap; + this.outRefMapFileName = this.ap.getOption(SupportedOptions.OUT_REFMAP_FILE); + for (ObfuscationType obfType : ObfuscationType.values()) { + if (obfType.isSupported(this.ap)) { + this.targetEnvironments.add(new TargetObfuscationEnvironment(ap, obfType, this.refMapper)); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getReferenceMapper() + */ + @Override + public ReferenceMapper getReferenceMapper() { + return this.refMapper; + } + + /** + * Write out generated srgs + */ + public void writeSrgs(Map mixins) { + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + targetEnv.writeSrgs(this.ap.getProcessingEnvironment().getFiler(), mixins); + } + } + + /** + * Write out stored mappings + */ + public void writeRefs() { + if (this.outRefMapFileName == null) { + return; + } + + PrintWriter writer = null; + + try { + writer = this.newWriter(this.outRefMapFileName, "refmap"); + this.refMapper.write(writer); + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (Exception ex) { + // oh well + } + } + } + } + + /** + * Open a writer for an output file + */ + private PrintWriter newWriter(String fileName, String description) throws IOException { + if (fileName.matches("^.*[\\\\/:].*$")) { + File outSrgFile = new File(fileName); + outSrgFile.getParentFile().mkdirs(); + this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath()); + return new PrintWriter(outSrgFile); + } + + FileObject outSrg = this.ap.getProcessingEnvironment().getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", fileName); + this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath()); + return new PrintWriter(outSrg.openWriter()); + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfEntryRecursive( + * org.spongepowered.asm.mixin.injection.struct.MemberInfo) + */ + @Override + @SuppressWarnings("unchecked") + public ObfuscationData getObfEntryRecursive(final MemberInfo targetMember) { + MemberInfo currentTarget = targetMember; + ObfuscationData obfTargetNames = this.getObfClass(currentTarget.owner); + ObfuscationData obfData = this.getObfEntry(currentTarget); + try { + while (obfData.isEmpty()) { + TypeHandle targetType = this.ap.getTypeProvider().getTypeHandle(currentTarget.owner); + if (targetType == null) { + return obfData; + } + TypeHandle superClass = targetType.getSuperclass(); + if (superClass == null) { + return obfData; + } + currentTarget = currentTarget.move(superClass.getName()); + obfData = this.getObfEntry(currentTarget); + if (!obfData.isEmpty()) { + for (ObfuscationType type : obfData) { + String obfClass = obfTargetNames.get(type); + T obfMember = obfData.get(type); + if (currentTarget.isField()) { + obfData.add(type, (T)MemberInfo.fromSrgField(obfMember.toString(), "").move(obfClass).toSrg()); + } else { + obfData.add(type, (T)MemberInfo.fromSrgMethod((SrgMethod)obfMember).move(obfClass).asSrgMethod()); + } + } + } + } + } catch (Exception ex) { + return this.getObfEntry(targetMember); + } + return obfData; + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfEntry( + * org.spongepowered.asm.mixin.injection.struct.MemberInfo) + */ + @Override + @SuppressWarnings("unchecked") + public ObfuscationData getObfEntry(MemberInfo targetMember) { + if (targetMember.isField()) { + return (ObfuscationData)this.getObfField(targetMember.toSrg()); + } + return (ObfuscationData)this.getObfMethod(targetMember.asSrgMethod()); + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfMethodRecursive( + * org.spongepowered.asm.mixin.injection.struct.MemberInfo) + */ + @Override + public ObfuscationData getObfMethodRecursive(MemberInfo targetMember) { + return this.getObfEntryRecursive(targetMember); + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfMethod( + * org.spongepowered.asm.mixin.injection.struct.MemberInfo) + */ + @Override + public ObfuscationData getObfMethod(MemberInfo method) { + ObfuscationData data = new ObfuscationData(); + + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + SrgMethod obfMethod = targetEnv.getObfMethod(method); + if (obfMethod != null) { + data.add(targetEnv.getType(), obfMethod); + } + } + + if (!data.isEmpty() || !Constants.CTOR.equals(method.name)) { + return data; + } + + return this.remapDescriptor(data, method); + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager + * #getObfMethod(org.spongepowered.asm.obfuscation.SrgMethod) + */ + @Override + public ObfuscationData getObfMethod(SrgMethod method) { + ObfuscationData data = new ObfuscationData(); + + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + SrgMethod obfMethod = targetEnv.getObfMethod(method); + if (obfMethod != null) { + data.add(targetEnv.getType(), obfMethod); + } + } + + if (!data.isEmpty() || !Constants.CTOR.equals(method.getSimpleName())) { + return data; + } + + return this.remapDescriptor(data, new MemberInfo(method)); + } + + /** + * Remap a method owner and descriptor only, used for remapping ctors + * + * @param data Output method data collection + * @param method Method to remap + * @return data + */ + public ObfuscationData remapDescriptor(ObfuscationData data, MemberInfo method) { + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + MemberInfo obfMethod = targetEnv.remapDescriptor(method); + if (obfMethod != null) { + data.add(targetEnv.getType(), obfMethod.asSrgMethod()); + } + } + + return data; + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfFieldRecursive( + * org.spongepowered.asm.mixin.injection.struct.MemberInfo) + */ + @Override + public ObfuscationData getObfFieldRecursive(MemberInfo targetMember) { + return this.getObfEntryRecursive(targetMember); + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfField(java.lang.String) + */ + @Override + public ObfuscationData getObfField(String field) { + ObfuscationData data = new ObfuscationData(); + + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + SrgField obfField = targetEnv.getObfField(field); + if (obfField != null) { + data.add(targetEnv.getType(), obfField.toString()); + } + } + + return data; + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfClass(org.spongepowered.tools.obfuscation.TypeHandle) + */ + @Override + public ObfuscationData getObfClass(TypeHandle type) { + return this.getObfClass(type.getName()); + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.IObfuscationManager + * #getObfClass(java.lang.String) + */ + @Override + public ObfuscationData getObfClass(String className) { + ObfuscationData data = new ObfuscationData(className); + + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + String obfClass = targetEnv.getObfClass(className); + if (obfClass != null) { + data.add(targetEnv.getType(), obfClass); + } + } + + return data; + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager + * #addMethodMapping(java.lang.String, java.lang.String, + * org.spongepowered.tools.obfuscation.ObfuscationData) + */ + @Override + public void addMethodMapping(String className, String reference, ObfuscationData obfMethodData) { + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + SrgMethod obfMethod = obfMethodData.get(targetEnv.getType()); + if (obfMethod != null) { + MemberInfo remappedReference = new MemberInfo(obfMethod); + targetEnv.addMapping(className, reference, remappedReference.toString()); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager + * #addMethodMapping(java.lang.String, java.lang.String, + * org.spongepowered.asm.mixin.injection.struct.MemberInfo, + * org.spongepowered.tools.obfuscation.ObfuscationData) + */ + @Override + public void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData obfMethodData) { + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + SrgMethod obfMethod = obfMethodData.get(targetEnv.getType()); + if (obfMethod != null) { + MemberInfo remappedReference = context.remapUsing(obfMethod, true); + targetEnv.addMapping(className, reference, remappedReference.toString()); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager + * #addFieldMapping(java.lang.String, java.lang.String, + * org.spongepowered.asm.mixin.injection.struct.MemberInfo, + * org.spongepowered.tools.obfuscation.ObfuscationData) + */ + @Override + public void addFieldMapping(String className, String reference, MemberInfo context, ObfuscationData obfFieldData) { + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + String obfField = obfFieldData.get(targetEnv.getType()); + if (obfField != null) { + MemberInfo remappedReference = MemberInfo.fromSrgField(obfField, targetEnv.remapDescriptor(context.desc)); + targetEnv.addMapping(className, reference, remappedReference.toString()); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.tools.obfuscation.interfaces.IObfuscationManager + * #addClassMapping(java.lang.String, java.lang.String, + * org.spongepowered.tools.obfuscation.ObfuscationData) + */ + @Override + public void addClassMapping(String className, String reference, ObfuscationData obfClassData) { + for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) { + String remapped = obfClassData.get(targetEnv.getType()); + if (remapped != null) { + targetEnv.addMapping(className, reference, remapped); + } + } + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java new file mode 100644 index 00000000..679a122b --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java @@ -0,0 +1,132 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.util.List; + +import org.spongepowered.tools.obfuscation.interfaces.IOptionProvider; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; + +/** + * Obfuscation types supported by the annotation processor + */ +enum ObfuscationType { + + /** + * "SEARGE" mappings, these are unique mappings used by MCP and derived + * projects + */ + SRG("searge", SupportedOptions.REOBF_SRG_FILE, SupportedOptions.REOBF_EXTRA_SRG_FILES, SupportedOptions.OUT_SRG_SRG_FILE), + + /** + * "NOTCH" mappings, internal to minecraft only + */ + NOTCH("notch", SupportedOptions.REOBF_NOTCH_FILE, SupportedOptions.REOBF_EXTRA_NOTCH_FILES, SupportedOptions.OUT_NOTCH_SRG_FILE); + + /** + * Refmap key for this mapping type + */ + private final String key; + + /** + * The name of the Annotation Processor argument which contains the file + * name to read the SRGs for this obfuscation type from + */ + private final String srgFileArgName; + + /** + * The name of the Annotation Processor argument which contains the file + * name to read the extra SRGs for this obfuscation type from + */ + private final String extraSrgFilesArgName; + + /** + * The name of the Annotation Processor argument which contains the file + * name to write generated SRG mappings to + */ + private final String outSrgFileArgName; + + private ObfuscationType(String displayName, String srgFileArgName, String extraSrgFilesArgName, String outSrgFileArgName) { + this.key = displayName; + this.srgFileArgName = srgFileArgName; + this.extraSrgFilesArgName = extraSrgFilesArgName; + this.outSrgFileArgName = outSrgFileArgName; + } + + @Override + public String toString() { + return this.key; + } + + public String getKey() { + return this.key; + } + + public String getSrgFileOption() { + return this.srgFileArgName; + } + + public String getExtraSrgFilesOption() { + return this.extraSrgFilesArgName; + } + + public String getOutputSrgFileOption() { + return this.outSrgFileArgName; + } + + public boolean isDefault(IOptionProvider options) { + String defaultEnv = options.getOption(SupportedOptions.DEFAULT_OBFUSCATION_ENV); + return (defaultEnv == null && this == ObfuscationType.SRG) || (defaultEnv != null && this.key.equals(defaultEnv.toLowerCase())); + } + + public boolean isSupported(IOptionProvider options) { + return this.getSrgFileNames(options).size() > 0; + } + + public List getSrgFileNames(IOptionProvider options) { + Builder builder = ImmutableList.builder(); + + String srgFile = options.getOption(this.srgFileArgName); + if (srgFile != null) { + builder.add(srgFile); + } + + String extraSrgFiles = options.getOption(this.extraSrgFilesArgName); + if (extraSrgFiles != null) { + for (String extraSrgFile : extraSrgFiles.split(";")) { + builder.add(extraSrgFile.trim()); + } + } + + return builder.build(); + } + + public String getOutputSrgFileName(IOptionProvider options) { + return options.getOption(this.outSrgFileArgName); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java new file mode 100644 index 00000000..ac1252d0 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java @@ -0,0 +1,71 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.util.Set; + +import com.google.common.collect.ImmutableSet; + +/** + * Supported options for the annotation processor. Not an enum mainly so that + * the string tokens can be inlined. + */ +public final class SupportedOptions { + + public static final String TOKENS = "tokens"; + public static final String REOBF_SRG_FILE = "reobfSrgFile"; + public static final String REOBF_EXTRA_SRG_FILES = "reobfSrgFiles"; + public static final String REOBF_NOTCH_FILE = "reobfNotchSrgFile"; + public static final String REOBF_EXTRA_NOTCH_FILES = "reobfNotchSrgFiles"; + public static final String OUT_SRG_SRG_FILE = "outSrgFile"; + public static final String OUT_NOTCH_SRG_FILE = "outNotchSrgFile"; + public static final String OUT_REFMAP_FILE = "outRefMapFile"; + public static final String DISABLE_TARGET_VALIDATOR = "disableTargetValidator"; + public static final String DISABLE_TARGET_EXPORT = "disableTargetExport"; + public static final String DISABLE_OVERWRITE_CHECKER = "disableOverwriteChecker"; + public static final String OVERWRITE_ERROR_LEVEL = "overwriteErrorLevel"; + public static final String DEFAULT_OBFUSCATION_ENV = "defaultObfuscationEnv"; + public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile"; + + public static final Set all = ImmutableSet.of( + SupportedOptions.TOKENS, + SupportedOptions.REOBF_SRG_FILE, + SupportedOptions.REOBF_EXTRA_SRG_FILES, + SupportedOptions.REOBF_NOTCH_FILE, + SupportedOptions.REOBF_EXTRA_NOTCH_FILES, + SupportedOptions.OUT_SRG_SRG_FILE, + SupportedOptions.OUT_NOTCH_SRG_FILE, + SupportedOptions.OUT_REFMAP_FILE, + SupportedOptions.DISABLE_TARGET_VALIDATOR, + SupportedOptions.DISABLE_TARGET_EXPORT, + SupportedOptions.DISABLE_OVERWRITE_CHECKER, + SupportedOptions.OVERWRITE_ERROR_LEVEL, + SupportedOptions.DEFAULT_OBFUSCATION_ENV, + SupportedOptions.DEPENDENCY_TARGETS_FILE + ); + + private SupportedOptions() {} + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java b/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java new file mode 100644 index 00000000..aa7d9773 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java @@ -0,0 +1,282 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.charset.Charset; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.lang.model.element.TypeElement; + +import com.google.common.io.Files; + +/** + * Serialisable map of classes to their associated mixins, used so that we can + * pass target information for supermixins from one compiler session to another + */ +public class TargetMap extends HashMap> { + + private static final long serialVersionUID = 1L; + + /** + * Session ID, used to identify the temp file + */ + private final String sessionId; + + /** + * Create a new TargetMap with a session ID based on the current system time + */ + private TargetMap() { + this(String.valueOf(System.currentTimeMillis())); + } + + /** + * Create a TargetMap with the specified session ID + * + * @param sessionId + */ + private TargetMap(String sessionId) { + this.sessionId = sessionId; + } + + /** + * Get the session ID + */ + public String getSessionId() { + return this.sessionId; + } + + /** + * Register target classes for the specified mixin + * + * @param mixin mixin to add targets for + */ + public void registerTargets(AnnotatedMixin mixin) { + this.registerTargets(mixin.getTargets(), mixin.getHandle()); + } + + /** + * Register target classes for the supplied mixin + * + * @param targets List of targets + * @param mixin Mixin class + */ + public void registerTargets(List targets, TypeHandle mixin) { + for (TypeHandle target : targets) { + this.addMixin(target, mixin); + } + } + + /** + * Register the specified mixin against the specified target + * + * @param target Target class + * @param mixin Mixin class + */ + public void addMixin(TypeHandle target, TypeHandle mixin) { + this.addMixin(target.getReference(), mixin.getReference()); + } + + /** + * Register the specified mixin against the specified target + * + * @param target Target class + * @param mixin Mixin class + */ + public void addMixin(String target, String mixin) { + this.addMixin(new TypeReference(target), new TypeReference(mixin)); + } + + /** + * Register the specified mixin against the specified target + * + * @param target Target class + * @param mixin Mixin class + */ + public void addMixin(TypeReference target, TypeReference mixin) { + Set mixins = this.getMixinsFor(target); + mixins.add(mixin); + } + + /** + * Get mixin classes which target the specified class + * + * @param target Target class + * @return Collection of mixins registered as targetting the specified class + */ + public Collection getMixinsTargeting(TypeElement target) { + return this.getMixinsTargeting(new TypeHandle(target)); + } + + /** + * Get mixin classes which target the specified class + * + * @param target Target class + * @return Collection of mixins registered as targetting the specified class + */ + public Collection getMixinsTargeting(TypeHandle target) { + return this.getMixinsTargeting(target.getReference()); + } + + /** + * Get mixin classes which target the specified class + * + * @param target Target class + * @return Collection of mixins registered as targetting the specified class + */ + public Collection getMixinsTargeting(TypeReference target) { + return Collections.unmodifiableCollection(this.getMixinsFor(target)); + } + + /** + * Get mixin set for specified class + * + * @param target Target class + * @return Set of mixins registered as targetting the specified class + */ + private Set getMixinsFor(TypeReference target) { + Set mixins = this.get(target); + if (mixins == null) { + mixins = new HashSet(); + this.put(target, mixins); + } + return mixins; + } + + /** + * Read upstream library mixins from a file + * + * @param file File to read from + * @throws IOException if an error occurs whilst reading the file + */ + public void readImports(File file) throws IOException { + if (!file.isFile()) { + return; + } + + for (String line : Files.readLines(file, Charset.defaultCharset())) { + String[] parts = line.split("\t"); + if (parts.length == 2) { + this.addMixin(parts[1], parts[0]); + } + } + } + + /** + * Write this target map to temporary session file + * + * @param temp Set "delete on exit" for the file + */ + public void write(boolean temp) { + ObjectOutputStream oos = null; + FileOutputStream fout = null; + try { + File sessionFile = TargetMap.getSessionFile(this.sessionId); + if (temp) { + sessionFile.deleteOnExit(); + } + fout = new FileOutputStream(sessionFile, true); + oos = new ObjectOutputStream(fout); + oos.writeObject(this); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + if (oos != null) { + try { + oos.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + } + + /** + * Attemp to deserialise a TargetMap from the specified file + * + * @param sessionFile File to read + * @return deserialised map or null if deserialisation failed + */ + private static TargetMap read(File sessionFile) { + ObjectInputStream objectinputstream = null; + FileInputStream streamIn = null; + try { + streamIn = new FileInputStream(sessionFile); + objectinputstream = new ObjectInputStream(streamIn); + TargetMap map = (TargetMap)objectinputstream.readObject(); + return map; + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (objectinputstream != null) { + try { + objectinputstream .close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + return null; + } + + /** + * Create a TargetMap for the specified session id. Generate new map if + * the session id is invalid or the file cannot be read. Session ID can be + * null + * + * @param sessionId session to deserialise, can be null to create new + * session + * @return new TargetMap + */ + public static TargetMap create(String sessionId) { + if (sessionId != null) { + File sessionFile = TargetMap.getSessionFile(sessionId); + if (sessionFile.exists()) { + TargetMap map = TargetMap.read(sessionFile); + if (map != null) { + return map; + } + } + } + + return new TargetMap(); + } + + private static File getSessionFile(String sessionId) { + File tempDir = new File(System.getProperty("java.io.tmpdir")); + return new File(tempDir, String.format("mixin-targetdb-%s.tmp", sessionId)); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationEnvironment.java b/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationEnvironment.java new file mode 100644 index 00000000..1ec418d2 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationEnvironment.java @@ -0,0 +1,378 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.annotation.processing.Filer; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.tools.Diagnostic.Kind; +import javax.tools.FileObject; +import javax.tools.StandardLocation; + +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.asm.obfuscation.SrgContainer; +import org.spongepowered.asm.obfuscation.SrgField; +import org.spongepowered.asm.util.ObfuscationUtil; +import org.spongepowered.asm.util.ObfuscationUtil.IClassRemapper; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; + +/** + * Stores information relevant to a particular target obfuscation environment. + * + *

We classify different types of possible obfuscation (eg. "searge", "notch" + * ) as obfuscation environments and store related information such as + * the input SRG mappings, generated refmap, generated SRGs, here.

+ */ +class TargetObfuscationEnvironment { + + /** + * Remapping proxy for remapping descriptors + */ + final class RemapperProxy implements IClassRemapper { + + @Override + public String map(String typeName) { + if (TargetObfuscationEnvironment.this.srgs == null) { + return null; + } + return TargetObfuscationEnvironment.this.srgs.getClassMapping(typeName); + } + + @Override + public String unmap(String typeName) { + if (TargetObfuscationEnvironment.this.srgs == null) { + return null; + } + return TargetObfuscationEnvironment.this.srgs.getClassMapping(typeName); + } + + } + + /** + * SRG container for mcp->? mappings + */ + protected SrgContainer srgs; + + private final RemapperProxy remapper = new RemapperProxy(); + + /** + * Type + */ + private final ObfuscationType type; + + /** + * Annotation processor + */ + private final IMixinAnnotationProcessor ap; + + /** + * Name of the resource to write generated srgs to + */ + private final String outSrgFileName; + + /** + * File containing the reobfd srgs + */ + private final List reobfSrgFileNames; + + /** + * Reference mapper for reference mapping + */ + private final ReferenceMapper refMapper; + + /** + * True once we've tried to initialise the srgs, initially false so that we + * can do srg init lazily + */ + private boolean initDone; + + public TargetObfuscationEnvironment(IMixinAnnotationProcessor ap, ObfuscationType type, ReferenceMapper refMapper) { + this.ap = ap; + this.type = type; + this.refMapper = refMapper; + + this.reobfSrgFileNames = type.getSrgFileNames(ap); + this.outSrgFileName = type.getOutputSrgFileName(ap); + } + + private boolean initSrgs() { + if (!this.initDone) { + this.initDone = true; + + if (this.reobfSrgFileNames == null) { + this.ap.printMessage(Kind.ERROR, "The " + this.type.getSrgFileOption() + + " argument was not supplied, obfuscation processing will not occur"); + return false; + } + + int successCount = 0; + this.srgs = new SrgContainer(); + + for (String srgFileName : this.reobfSrgFileNames) { + File reobfSrgFile = new File(srgFileName); + try { + if (reobfSrgFile.isFile()) { + this.ap.printMessage(Kind.NOTE, "Loading " + this.type + " mappings from " + reobfSrgFile.getAbsolutePath()); + this.srgs.readSrg(reobfSrgFile); + successCount++; + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + if (successCount < 1) { + this.ap.printMessage(Kind.ERROR, "No valid SRG files for " + this.type + " could be read, processing may not be sucessful."); + this.srgs = null; + } + } + + return this.srgs != null; + } + + /** + * Get the type + */ + public ObfuscationType getType() { + return this.type; + } + + public void addMapping(String className, String reference, String newReference) { + this.refMapper.addMapping(this.type.getKey(), className, reference, newReference); + if (this.type.isDefault(this.ap)) { + this.refMapper.addMapping(null, className, reference, newReference); + } + } + + /** + * Get an obfuscation mapping for a method + */ + public SrgMethod getObfMethod(MemberInfo method) { + SrgMethod obfd = this.getObfMethod(method.asSrgMethod()); + if (obfd != null || !method.isFullyQualified()) { + return obfd; + } + + // Get a type handle for the declared method owner + TypeHandle type = this.ap.getTypeProvider().getTypeHandle(method.owner); + if (type == null || type.isImaginary()) { + return null; + } + + // See if we can get the superclass from the reference + TypeMirror superClass = type.getElement().getSuperclass(); + if (superClass.getKind() != TypeKind.DECLARED) { + return null; + } + + // Well we found it, let's inflect the class name and recurse the search + String superClassName = ((TypeElement)((DeclaredType)superClass).asElement()).getQualifiedName().toString(); + return this.getObfMethod(new MemberInfo(method.name, superClassName.replace('.', '/'), method.desc, method.matchAll)); + } + + /** + * Get an obfuscation mapping for a method + */ + public SrgMethod getObfMethod(SrgMethod method) { + return this.getObfMethod(method, true); + } + + /** + * Get an obfuscation mapping for a method + */ + public SrgMethod getObfMethod(SrgMethod method, boolean srgOnly) { + if (this.initSrgs()) { + boolean remapped = true; + SrgMethod originalMethod = method.copy(); + SrgMethod methodMapping = this.srgs.getMethodMapping(method); + // If no obf mapping, we can attempt to remap the owner class + if (methodMapping == null) { + if (srgOnly) { + return null; + } + methodMapping = originalMethod; + remapped = false; + } + String remappedOwner = this.getObfClass(methodMapping.getOwner()); + if (remappedOwner == null || remappedOwner.equals(method.getOwner()) || remappedOwner.equals(methodMapping.getOwner())) { + return remapped ? methodMapping : null; + } + if (remapped) { + return methodMapping.move(remappedOwner); + } + return new SrgMethod(remappedOwner, methodMapping.getSimpleName(), ObfuscationUtil.mapDescriptor(methodMapping.getDesc(), this.remapper)); + } + return null; + } + + /** + * Remap only the owner and descriptor of the specified method + * + * @param method method to remap + * @return remapped method or null if no remapping occurred + */ + public MemberInfo remapDescriptor(MemberInfo method) { + boolean transformed = false; + + String owner = method.owner; + if (owner != null) { + String newOwner = this.remapper.map(owner); + if (newOwner != null) { + owner = newOwner; + transformed = true; + } + } + + String desc = method.desc; + if (desc != null) { + String newDesc = ObfuscationUtil.mapDescriptor(method.desc, this.remapper); + if (!newDesc.equals(method.desc)) { + desc = newDesc; + transformed = true; + } + } + + return transformed ? new MemberInfo(method.name, owner, desc, method.matchAll) : null; + } + + /** + * Remap a single descriptor in the context of this environment + * + * @param desc descriptor to remap + * @return remapped descriptor, may return the original descriptor if no + * remapping occurred + */ + public String remapDescriptor(String desc) { + return ObfuscationUtil.mapDescriptor(desc, this.remapper); + } + + /** + * Get an obfuscation mapping for a field + */ + public SrgField getObfField(String field) { + return this.getObfField(field, true); + } + + /** + * Get an obfuscation mapping for a field + */ + public SrgField getObfField(String field, boolean srgOnly) { + if (this.initSrgs()) { + SrgField originalField = new SrgField(field); + SrgField fieldMapping = this.srgs.getFieldMapping(originalField); + // If no obf mapping, we can attempt to remap the owner class + if (fieldMapping == null) { + if (srgOnly) { + return null; + } + fieldMapping = originalField; + } + String remappedOwner = this.getObfClass(fieldMapping.getOwner()); + if (remappedOwner == null || remappedOwner.equals(originalField.getOwner()) || remappedOwner.equals(fieldMapping.getOwner())) { + return fieldMapping != originalField ? fieldMapping : null; + } + return fieldMapping.move(remappedOwner); + } + return null; + } + + /** + * Get an obfuscation mapping for a class + */ + public String getObfClass(String className) { + if (this.initSrgs()) { + return this.srgs.getClassMapping(className); + } + return null; + } + + /** + * Write out generated srgs + */ + public void writeSrgs(Filer filer, Map mixins) { + if (this.outSrgFileName == null) { + return; + } + + Set fieldMappings = new LinkedHashSet(); + Set methodMappings = new LinkedHashSet(); + + for (AnnotatedMixin mixin : mixins.values()) { + fieldMappings.addAll(mixin.getFieldMappings(this.type)); + methodMappings.addAll(mixin.getMethodMappings(this.type)); + } + + PrintWriter writer = null; + + try { + writer = this.openFileWriter(filer, this.outSrgFileName, this.type + " output SRGs"); + for (String fieldMapping : fieldMappings) { + writer.println(fieldMapping); + } + for (String methodMapping : methodMappings) { + writer.println(methodMapping); + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (Exception ex) { + // oh well + } + } + } + } + + /** + * Open a writer for an output file + */ + private PrintWriter openFileWriter(Filer filer, String fileName, String description) throws IOException { + if (fileName.matches("^.*[\\\\/:].*$")) { + File outSrgFile = new File(fileName); + outSrgFile.getParentFile().mkdirs(); + this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath()); + return new PrintWriter(outSrgFile); + } + + FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName); + this.ap.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath()); + return new PrintWriter(outSrg.openWriter()); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java index fdbd7ff3..53201a87 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java @@ -28,9 +28,6 @@ import java.util.Set; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedOptions; -import javax.annotation.processing.SupportedSourceVersion; -import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; @@ -47,9 +44,7 @@ import org.spongepowered.tools.MirrorUtils; * Annotation processor which finds {@link Shadow} and {@link Overwrite} * annotations in mixin classes and generates SRG mappings */ -@SupportedSourceVersion(SourceVersion.RELEASE_6) @SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.Mixin", "org.spongepowered.asm.mixin.Shadow", "org.spongepowered.asm.mixin.Overwrite" }) -@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile", "disableTargetValidator" }) public class TargetObfuscationProcessor extends MixinProcessor { /* (non-Javadoc) @@ -60,7 +55,7 @@ public class TargetObfuscationProcessor extends MixinProcessor { @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { - return false; + return true; } this.processMixins(roundEnv); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java index 8950ae9c..98fe3ed3 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java @@ -35,12 +35,12 @@ import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.tools.MirrorUtils; - /** * A wrapper for TypeElement which gives us a soft-failover mechanism when * dealing with classes that are inaccessible via mirror (such as anonymous @@ -63,6 +63,11 @@ public class TypeHandle { * Actual type element, this is null for inaccessible classes */ private final TypeElement element; + + /** + * Reference to this handle, for serialisation + */ + private TypeReference reference; /** * Ctor for imaginary elements, require the enclosing package and the FQ @@ -140,6 +145,23 @@ public class TypeHandle { public TypeMirror getType() { return this.element != null ? this.element.asType() : null; } + + /** + * Returns the enclosed element's superclass if available, or null if this + * class does not have a superclass + */ + public TypeHandle getSuperclass() { + if (this.element == null) { + return null; + } + + TypeMirror superClass = this.element.getSuperclass(); + if (superClass == null || superClass.getKind() == TypeKind.NONE) { + return null; + } + + return new TypeHandle((DeclaredType)superClass); + } /** * Get whether the element is probably public @@ -154,6 +176,13 @@ public class TypeHandle { public boolean isImaginary() { return this.element == null; } + + public TypeReference getReference() { + if (this.reference == null) { + this.reference = new TypeReference(this); + } + return this.reference; + } public String findDescriptor(MemberInfo memberInfo) { String desc = memberInfo.desc; @@ -180,7 +209,7 @@ public class TypeHandle { * @return handle to the discovered field if matched or null if no match */ public FieldHandle findField(VariableElement element) { - return this.findField(element.getSimpleName().toString(), element.asType().toString()); + return this.findField(element.getSimpleName().toString(), MirrorUtils.getTypeName(element.asType())); } /** @@ -192,7 +221,7 @@ public class TypeHandle { * @return handle to the discovered field if matched or null if no match */ public FieldHandle findField(String name, String type) { - String rawType = type.replaceAll("<[^>]+>", ""); + String rawType = MirrorUtils.stripGenerics(type); for (Element element : this.getEnclosedElements()) { if (element.getKind() != ElementKind.FIELD) { @@ -218,7 +247,7 @@ public class TypeHandle { * @return handle to the discovered method if matched or null if no match */ public MethodHandle findMethod(ExecutableElement element) { - return this.findMethod(element.getSimpleName().toString(), TypeHandle.getElementSignature(element)); + return this.findMethod(element.getSimpleName().toString(), MirrorUtils.getJavaSignature(element)); } /** @@ -230,7 +259,7 @@ public class TypeHandle { * @return handle to the discovered method if matched or null if no match */ public MethodHandle findMethod(String name, String signature) { - String rawSignature = signature.replaceAll("<[^>]+>", ""); + String rawSignature = MirrorUtils.stripGenerics(signature); for (Element element : this.getEnclosedElements()) { switch (element.getKind()) { @@ -256,30 +285,12 @@ public class TypeHandle { private boolean compareElement(Element elem, String name, String type) { try { String elementName = elem.getSimpleName().toString(); - String elementType = TypeHandle.getElementSignature(elem); - return name.equals(elementName) && (type.length() == 0 || type.equals(elementType)); + String elementType = MirrorUtils.getJavaSignature(elem); + String rawElementType = MirrorUtils.stripGenerics(elementType); + return name.equals(elementName) && (type.length() == 0 || type.equals(elementType) || type.equals(rawElementType)); } catch (NullPointerException ex) { return false; } } - - static String getElementSignature(Element element) { - if (element instanceof ExecutableElement) { - ExecutableElement method = (ExecutableElement)element; - StringBuilder desc = new StringBuilder().append("("); - boolean extra = false; - for (VariableElement arg : method.getParameters()) { - if (extra) { - desc.append(','); - } - desc.append(arg.asType().toString()); - extra = true; - } - desc.append(')').append(method.getReturnType().toString()); - return desc.toString(); - } - - return element.asType().toString(); - } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java b/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java new file mode 100644 index 00000000..40e28c9a --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java @@ -0,0 +1,123 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +import java.io.Serializable; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.TypeElement; + +/** + * Soft wrapper for a {@link TypeHandle} so that we can serialise it + */ +public class TypeReference implements Serializable, Comparable { + + private static final long serialVersionUID = 1L; + + /** + * Class name, used to recreate the handle on the other side + */ + private final String name; + + /** + * Transient handle, not serialised, regenerated when required + */ + private transient TypeHandle handle; + + /** + * Create a new soft wrapper for the specified type handle + * + * @param handle handle to wrap + */ + public TypeReference(TypeHandle handle) { + this.name = handle.getName(); + this.handle = handle; + } + + /** + * Create a type reference with no handle + * + * @param name Name of the type + */ + TypeReference(String name) { + this.name = name; + } + + /** + * Get the class name (internal format) + */ + public String getName() { + return this.name; + } + + /** + * Get the FQ class name (dotted format) + */ + public String getClassName() { + return this.name.replace('/', '.'); + } + + /** + * Fetch or attempt to generate the type handle + * + * @param processingEnv environment to create handle if it needs to be + * regenerated + * @return type handle + */ + public TypeHandle getHandle(ProcessingEnvironment processingEnv) { + if (this.handle == null) { + TypeElement element = processingEnv.getElementUtils().getTypeElement(this.getClassName()); + try { + this.handle = new TypeHandle(element); + } catch (Exception ex) { + // Class probably doesn't exist in scope :/ + ex.printStackTrace(); + } + } + + return this.handle; + } + + @Override + public String toString() { + return String.format("TypeReference[%s]", this.name); + } + + @Override + public int compareTo(TypeReference other) { + return other == null ? -1 : this.name.compareTo(other.name); + } + + @Override + public boolean equals(Object other) { + return other instanceof TypeReference && this.compareTo((TypeReference)other) == 0; + } + + @Override + public int hashCode() { + return this.name.hashCode(); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IJavadocProvider.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IJavadocProvider.java new file mode 100644 index 00000000..9dae68b7 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IJavadocProvider.java @@ -0,0 +1,42 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.interfaces; + +import javax.lang.model.element.Element; + +/** + * Provides javadoc. What else did you expect? + */ +public interface IJavadocProvider { + + /** + * Get javadoc on element + * + * @param element Element to fetch javadoc for + * @return javadoc + */ + public abstract String getJavadoc(Element element); + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java new file mode 100644 index 00000000..1abf502f --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.interfaces; + +import javax.annotation.processing.Messager; +import javax.annotation.processing.ProcessingEnvironment; + +import org.spongepowered.asm.util.ITokenProvider; + +/** + * Interface for annotation processor core + */ +public interface IMixinAnnotationProcessor extends Messager, IOptionProvider { + + /** + * Get the underlying processing environment + */ + public abstract ProcessingEnvironment getProcessingEnvironment(); + + /** + * Get the obfuscation manager + */ + public abstract IObfuscationManager getObfuscationManager(); + + /** + * Get the token provider + */ + public abstract ITokenProvider getTokenProvider(); + + /** + * Get the type handle provider + */ + public abstract ITypeHandleProvider getTypeProvider(); + + /** + * Get the javadoc provider + */ + public abstract IJavadocProvider getJavadocProvider(); + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/IMixinValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java similarity index 93% rename from src/ap/java/org/spongepowered/tools/obfuscation/IMixinValidator.java rename to src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java index 6ce4f6c0..3b5488df 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/IMixinValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinValidator.java @@ -22,13 +22,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.tools.obfuscation; +package org.spongepowered.tools.obfuscation.interfaces; import java.util.Collection; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; +import org.spongepowered.tools.obfuscation.TypeHandle; /** * A mixin validator module, basically just a way of making the various sanity @@ -36,6 +37,9 @@ import javax.lang.model.element.TypeElement; */ public interface IMixinValidator { + /** + * Validation pass + */ public enum ValidationPass { EARLY, LATE diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationManager.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationManager.java new file mode 100644 index 00000000..846233b2 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationManager.java @@ -0,0 +1,154 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.interfaces; + +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.obfuscation.SrgMethod; +import org.spongepowered.tools.obfuscation.ObfuscationData; +import org.spongepowered.tools.obfuscation.TypeHandle; + +/** + * Manages obfuscation things + */ +public interface IObfuscationManager { + + /** + * Get the underlying reference mapper + */ + public abstract ReferenceMapper getReferenceMapper(); + + /** + * Attempts to resolve an obfuscation entry by recursively enumerating + * superclasses of the target member until a match is found. If a match is + * found in a superclass then the reference is remapped to the original + * owner class. + * + * @param targetMember Member to search for + * @return ObfuscationData with remapped owner class corresponding to the + * original owner class + */ + public abstract ObfuscationData getObfEntryRecursive(MemberInfo targetMember); + + /** + * Resolves a field or method reference to an ObfuscationData set + * + * @param targetMember member to search for + * @return obfuscation data (by type) for the supplied member + */ + public abstract ObfuscationData getObfEntry(MemberInfo targetMember); + + /** + * Attempts to resolve an obfuscated method by recursively enumerating + * superclasses of the target method until a match is found. If a match is + * found in a superclass then the method owner is remapped to the obfuscated + * name of the original owner class. + * + * @param method Method to search for + * @return ObfuscationData with remapped owner class corresponding to the + * original owner class + */ + public abstract ObfuscationData getObfMethodRecursive(MemberInfo method); + + /** + * Get an obfuscation mapping for a method + */ + public abstract ObfuscationData getObfMethod(MemberInfo method); + + /** + * Get an obfuscation mapping for a method + */ + public abstract ObfuscationData getObfMethod(SrgMethod method); + + /** + * Attempts to resolve an obfuscated field by recursively enumerating + * superclasses of the target field until a match is found. If a match is + * found in a superclass then the field owner is remapped to the obfuscated + * name of the original owner class. + * + * @param field Field to search for + * @return ObfuscationData with remapped owner class corresponding to the + * original owner class + */ + public abstract ObfuscationData getObfFieldRecursive(MemberInfo field); + + /** + * Get an obfuscation mapping for a field + */ + public abstract ObfuscationData getObfField(String field); + + /** + * Get an obfuscation mapping for a class + */ + public abstract ObfuscationData getObfClass(TypeHandle type); + + /** + * Get an obfuscation mapping for a class + */ + public abstract ObfuscationData getObfClass(String className); + + /** + * Adds a method mapping to the internal refmap + * + * @param className Mixin class name which owns the refmap entry + * @param reference Original reference, as it appears in the annotation + * @param obfMethodData Method data to add for this mapping + */ + public abstract void addMethodMapping(String className, String reference, ObfuscationData obfMethodData); + + /** + * Adds a method mapping to the internal refmap, generates refmap entries + * using the supplied parsed memberinfo as context + * + * @param className Mixin class name which owns the refmap entry + * @param reference Original reference, as it appears in the annotation + * @param context The context for this mapping entry, remapped using the + * supplied obfuscation data + * @param obfMethodData Method data to add for this mapping + */ + public abstract void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData obfMethodData); + + /** + * Adds a field mapping to the internal refmap, generates refmap entries + * using the supplied parsed memberinfo as context + * + * @param className Mixin class name which owns the refmap entry + * @param reference Original reference, as it appears in the annotation + * @param context The context for this mapping entry, remapped using the + * supplied obfuscation data + * @param obfFieldData Field data to add for this mapping + */ + public abstract void addFieldMapping(String className, String reference, MemberInfo context, ObfuscationData obfFieldData); + + /** + * Adds a class mapping to the internal refmap + * + * @param className Mixin class name which owns the refmap entry + * @param reference Original reference, as it appears in the annotation + * @param obfClassData Class obf names + */ + public abstract void addClassMapping(String className, String reference, ObfuscationData obfClassData); + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/IOptionProvider.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java similarity index 96% rename from src/ap/java/org/spongepowered/tools/obfuscation/IOptionProvider.java rename to src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java index 81f3f3ac..e0bbd48a 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/IOptionProvider.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java @@ -22,7 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.tools.obfuscation; +package org.spongepowered.tools.obfuscation.interfaces; /** * An object which can provide option values to consumers diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/ITypeHandleProvider.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/ITypeHandleProvider.java new file mode 100644 index 00000000..48556bec --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/ITypeHandleProvider.java @@ -0,0 +1,42 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.interfaces; + +import org.spongepowered.tools.obfuscation.TypeHandle; + +/** + * Manager object which cann supply {@link TypeHandle} instances + */ +public interface ITypeHandleProvider { + + /** + * Generate a type handle for the specified type + * + * @param name Type name (class name) + * @return A new type handle + */ + public abstract TypeHandle getTypeHandle(String name); + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java b/src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java new file mode 100644 index 00000000..c18cb8fc --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java @@ -0,0 +1,114 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.struct; + +import javax.annotation.processing.Messager; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.tools.Diagnostic; + +/** + * Wrapper for Annotation Processor messages, used to enable messages to be + * easily queued and manipulated + */ +public class Message { + + private Diagnostic.Kind kind; + private CharSequence msg; + private final Element element; + private final AnnotationMirror annotation; + private final AnnotationValue value; + + public Message(Diagnostic.Kind kind, CharSequence msg) { + this(kind, msg, null, null, null); + } + + public Message(Diagnostic.Kind kind, CharSequence msg, Element element) { + this(kind, msg, element, null, null); + } + + public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation) { + this(kind, msg, element, annotation, null); + } + + public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value) { + this.kind = kind; + this.msg = msg; + this.element = element; + this.annotation = annotation; + this.value = value; + } + + public Message sendTo(Messager messager) { + if (this.value != null) { + messager.printMessage(this.kind, this.msg, this.element, this.annotation, this.value); + } else if (this.annotation != null) { + messager.printMessage(this.kind, this.msg, this.element, this.annotation); + } else if (this.element != null) { + messager.printMessage(this.kind, this.msg, this.element); + } else { + messager.printMessage(this.kind, this.msg); + } + return this; + } + + + public Diagnostic.Kind getKind() { + return this.kind; + } + + + public Message setKind(Diagnostic.Kind kind) { + this.kind = kind; + return this; + } + + + public CharSequence getMsg() { + return this.msg; + } + + + public Message setMsg(CharSequence msg) { + this.msg = msg; + return this; + } + + + public Element getElement() { + return this.element; + } + + + public AnnotationMirror getAnnotation() { + return this.annotation; + } + + + public AnnotationValue getValue() { + return this.value; + } +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/validation/ParentValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/validation/ParentValidator.java index 9b251693..a2ebd5be 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/validation/ParentValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/validation/ParentValidator.java @@ -26,17 +26,14 @@ package org.spongepowered.tools.obfuscation.validation; import java.util.Collection; -import javax.annotation.processing.Messager; -import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; -import org.spongepowered.tools.obfuscation.IOptionProvider; import org.spongepowered.tools.obfuscation.MixinValidator; import org.spongepowered.tools.obfuscation.TypeHandle; - +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; /** * Validator which checks that the mixin parent is sane @@ -46,12 +43,10 @@ public class ParentValidator extends MixinValidator { /** * ctor * - * @param processingEnv Processing environment - * @param messager Messager - * @param options Option provider + * @param ap Processing environment */ - public ParentValidator(ProcessingEnvironment processingEnv, Messager messager, IOptionProvider options) { - super(processingEnv, messager, options, ValidationPass.EARLY); + public ParentValidator(IMixinAnnotationProcessor ap) { + super(ap, ValidationPass.EARLY); } /* (non-Javadoc) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java index 06bb658e..bb4c23e9 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java @@ -26,18 +26,18 @@ package org.spongepowered.tools.obfuscation.validation; import java.util.Collection; -import javax.annotation.processing.Messager; -import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; -import org.spongepowered.tools.obfuscation.IOptionProvider; +import org.spongepowered.tools.MirrorUtils; import org.spongepowered.tools.obfuscation.MixinValidator; +import org.spongepowered.tools.obfuscation.SupportedOptions; import org.spongepowered.tools.obfuscation.TypeHandle; - +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; /** * Validator which checks that the mixin targets are sane @@ -47,12 +47,10 @@ public class TargetValidator extends MixinValidator { /** * ctor * - * @param processingEnv Processing environment - * @param messager Messager - * @param options Option provider + * @param ap Processing environment */ - public TargetValidator(ProcessingEnvironment processingEnv, Messager messager, IOptionProvider options) { - super(processingEnv, messager, options, ValidationPass.LATE); + public TargetValidator(IMixinAnnotationProcessor ap) { + super(ap, ValidationPass.LATE); } /* (non-Javadoc) @@ -62,10 +60,29 @@ public class TargetValidator extends MixinValidator { */ @Override public boolean validate(TypeElement mixin, AnnotationMirror annotation, Collection targets) { - if ("true".equalsIgnoreCase(this.options.getOption("disableTargetValidator"))) { + if ("true".equalsIgnoreCase(this.options.getOption(SupportedOptions.DISABLE_TARGET_VALIDATOR))) { return true; } + if (mixin.getKind() == ElementKind.INTERFACE) { + this.validateInterfaceMixin(mixin, targets); + } else { + this.validateClassMixin(mixin, targets); + } + + return true; + } + + private void validateInterfaceMixin(TypeElement mixin, Collection targets) { + for (TypeHandle target : targets) { + TypeElement targetType = target.getElement(); + if (targetType != null && !(targetType.getKind() == ElementKind.INTERFACE)) { + this.error("Targetted type '" + target + " of " + mixin + " is not an interface", mixin); + } + } + } + + private void validateClassMixin(TypeElement mixin, Collection targets) { TypeMirror superClass = mixin.getSuperclass(); for (TypeHandle target : targets) { @@ -74,12 +91,10 @@ public class TargetValidator extends MixinValidator { this.error("Superclass " + superClass + " of " + mixin + " was not found in the hierarchy of target class " + targetType, mixin); } } - - return true; } private boolean validateSuperClass(TypeMirror targetType, TypeMirror superClass) { - if (this.isAssignable(targetType, superClass)) { + if (MirrorUtils.isAssignable(this.processingEnv, targetType, superClass)) { return true; } @@ -91,6 +106,10 @@ public class TargetValidator extends MixinValidator { return false; } + if (MirrorUtils.isAssignable(this.processingEnv, targetType, superClass)) { + return true; + } + TypeElement targetElement = (TypeElement)((DeclaredType)targetType).asElement(); TypeMirror targetSuper = targetElement.getSuperclass(); if (targetSuper.getKind() == TypeKind.NONE) { @@ -106,15 +125,11 @@ public class TargetValidator extends MixinValidator { private boolean checkMixinsFor(TypeMirror targetType, TypeMirror superClass) { for (TypeMirror mixinType : this.getMixinsTargeting(targetType)) { - if (this.isAssignable(mixinType, superClass)) { + if (MirrorUtils.isAssignable(this.processingEnv, mixinType, superClass)) { return true; } } return false; } - - protected final boolean isAssignable(TypeMirror targetType, TypeMirror superClass) { - return this.processingEnv.getTypeUtils().isAssignable(targetType, superClass); - } } diff --git a/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java b/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java new file mode 100644 index 00000000..11eae88f --- /dev/null +++ b/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java @@ -0,0 +1,98 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.bridge; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.commons.Remapper; +import org.spongepowered.asm.mixin.extensibility.IRemapper; +import org.spongepowered.asm.util.ObfuscationUtil; +import org.spongepowered.asm.util.ObfuscationUtil.IClassRemapper; + +/** + * Base impl of remapper + */ +public abstract class RemapperAdapter implements IRemapper, IClassRemapper { + + protected final Logger logger = LogManager.getLogger("mixin"); + protected final Remapper remapper; + + public RemapperAdapter(Remapper remapper) { + this.remapper = remapper; + } + + @Override + public String toString() { + return this.getClass().getSimpleName(); + } + + @Override + public String mapMethodName(String owner, String name, String desc) { + this.logger.debug("{} is remapping method {}{} for {}", this, name, desc, owner); + String newName = this.remapper.mapMethodName(owner, name, desc); + if (!newName.equals(name)) { + return newName; + } + String obfOwner = this.unmap(owner); + String obfDesc = this.unmapDesc(desc); + this.logger.debug("{} is remapping obfuscated method {}{} for {}", this, name, obfDesc, obfOwner); + return this.remapper.mapMethodName(obfOwner, name, obfDesc); + } + + @Override + public String mapFieldName(String owner, String name, String desc) { + this.logger.debug("{} is remapping field {}{} for {}", this, name, desc, owner); + String newName = this.remapper.mapFieldName(owner, name, desc); + if (!newName.equals(name)) { + return newName; + } + String obfOwner = this.unmap(owner); + String obfDesc = this.unmapDesc(desc); + this.logger.debug("{} is remapping obfuscated field {}{} for {}", this, name, obfDesc, obfOwner); + return this.remapper.mapFieldName(obfOwner, name, obfDesc); + } + + @Override + public String map(String typeName) { + this.logger.debug("{} is remapping class {}", this, typeName); + return this.remapper.map(typeName); + } + + @Override + public String unmap(String typeName) { + return typeName; + } + + @Override + public String mapDesc(String desc) { + return this.remapper.mapDesc(desc); + } + + @Override + public String unmapDesc(String desc) { + return ObfuscationUtil.unmapDescriptor(desc, this); + } + +} diff --git a/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapterFML.java b/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapterFML.java new file mode 100644 index 00000000..97750e1a --- /dev/null +++ b/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapterFML.java @@ -0,0 +1,80 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.bridge; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.objectweb.asm.commons.Remapper; +import org.spongepowered.asm.mixin.extensibility.IRemapper; + +/** + * Remapper adapter which remaps using FML's deobfuscating remapper + */ +public class RemapperAdapterFML extends RemapperAdapter { + + private final Method mdUnmap; + + private RemapperAdapterFML(Remapper remapper, Method mdUnmap) { + super(remapper); + this.logger.info("Initialised Mixin FML Remapper Adapter with {}", remapper); + this.mdUnmap = mdUnmap; + } + + @Override + public String unmap(String typeName) { + try { + return this.mdUnmap.invoke(this.remapper, typeName).toString(); + } catch (Exception ex) { + return typeName; + } + } + + public static IRemapper create() { + try { + Class clDeobfRemapper = RemapperAdapterFML.getFMLDeobfuscatingRemapper(); + Field singletonField = clDeobfRemapper.getDeclaredField("INSTANCE"); + Method mdUnmap = clDeobfRemapper.getDeclaredMethod("unmap", String.class); + Remapper remapper = (Remapper)singletonField.get(null); + return new RemapperAdapterFML(remapper, mdUnmap); + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + /** + * Attempt to get the FML Deobfuscating Remapper, tries the post-1.8 + * namespace first and falls back to 1.7.10 if class lookup fails + */ + private static Class getFMLDeobfuscatingRemapper() throws ClassNotFoundException { + try { + return Class.forName("net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper"); + } catch (ClassNotFoundException ex) { + return Class.forName("cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper"); + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/Blackboard.java b/src/main/java/org/spongepowered/asm/launch/Blackboard.java new file mode 100644 index 00000000..bc6ea837 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/Blackboard.java @@ -0,0 +1,78 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +import net.minecraft.launchwrapper.Launch; + +/** + * Abstractions for working with {@link Launch#blackboard} + */ +public final class Blackboard { + + /** + * Blackboard keys + */ + public static final class Keys { + + public static final String TWEAKCLASSES = "TweakClasses"; + public static final String TWEAKS = "Tweaks"; + + public static final String INIT = "mixin.initialised"; + public static final String AGENTS = "mixin.agents"; + public static final String CONFIGS = "mixin.configs"; + public static final String TRANSFORMER = "mixin.transformer"; + + public static final String FML_LOAD_CORE_MOD = "mixin.launch.fml.loadcoremodmethod"; + public static final String FML_GET_REPARSEABLE_COREMODS = "mixin.launch.fml.reparseablecoremodsmethod"; + public static final String FML_CORE_MOD_MANAGER = "mixin.launch.fml.coremodmanagerclass"; + public static final String FML_GET_IGNORED_MODS = "mixin.launch.fml.ignoredmodsmethod"; + + private Keys() {} + + } + + private Blackboard() {} + + @SuppressWarnings("unchecked") + public static T get(String key) { + return (T)Launch.blackboard.get(key); + } + + public static void put(String key, Object value) { + Launch.blackboard.put(key, value); + } + + @SuppressWarnings("unchecked") + public static T get(String key, T defaultValue) { + Object value = Launch.blackboard.get(key); + return value != null ? (T)value : defaultValue; + } + + public static String getString(String key, String defaultValue) { + Object value = Launch.blackboard.get(key); + return value != null ? value.toString() : defaultValue; + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index 8aa58ebd..2407da88 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -26,13 +26,15 @@ package org.spongepowered.asm.launch; import java.util.List; -import net.minecraft.launchwrapper.Launch; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.platform.MixinPlatformManager; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; + /** * Bootstaps the mixin subsystem. This class acts as a bridge between the mixin * subsystem and the tweaker or coremod which is boostrapping it. Without this @@ -60,13 +62,7 @@ public abstract class MixinBootstrap { /** * Subsystem version */ - public static final String VERSION = "0.4.5"; - - /** - * Blackboard key where the subsystem version will be stored to indicate - * successful bootstrap - */ - public static final String INIT_KEY = "mixin.initialised"; + public static final String VERSION = "0.5.11"; // Consts private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; @@ -82,7 +78,7 @@ public abstract class MixinBootstrap { // These are Klass local, with luck this shouldn't be a problem private static boolean initialised = false; - private static boolean injectStateTweaker = true; + private static boolean initState = true; // Static initialiser, add classloader exclusions as early as possible static { @@ -94,6 +90,8 @@ public abstract class MixinBootstrap { // Only needed in dev, in production this would be handled by the tweaker Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.LAUNCH_PACKAGE); } + + private static MixinPlatformManager platformManager = new MixinPlatformManager(); private MixinBootstrap() {} @@ -104,22 +102,29 @@ public abstract class MixinBootstrap { Launch.classLoader.registerTransformer(MixinBootstrap.TRANSFORMER_PROXY_CLASS); } + /** + * Get the platform manager + */ + public static MixinPlatformManager getPlatform() { + return MixinBootstrap.platformManager; + } + /** * Initialise the mixin subsystem */ public static void init() { - if (!MixinBootstrap.preInit()) { + if (!MixinBootstrap.start()) { return; } - MixinBootstrap.register(); + MixinBootstrap.doInit(null); } /** * Phase 1 of mixin initialisation */ - static boolean preInit() { - Object registeredVersion = Launch.blackboard.get(MixinBootstrap.INIT_KEY); + static boolean start() { + Object registeredVersion = Blackboard.get(Blackboard.Keys.INIT); if (registeredVersion != null) { if (!registeredVersion.equals(MixinBootstrap.VERSION)) { throw new MixinInitialisationError("Mixin subsystem version " + registeredVersion @@ -129,15 +134,21 @@ public abstract class MixinBootstrap { return false; } - Launch.blackboard.put(MixinBootstrap.INIT_KEY, MixinBootstrap.VERSION); + Blackboard.put(Blackboard.Keys.INIT, MixinBootstrap.VERSION); if (!MixinBootstrap.initialised) { MixinBootstrap.initialised = true; - + + String command = System.getProperty("sun.java.command"); + if (command != null && command.contains("GradleStart")) { + System.setProperty("mixin.env.disableRefMap", "true"); + } + if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") > 132) { MixinBootstrap.logger.error("Initialising mixin subsystem after game pre-init phase! Some mixins may be skipped."); MixinEnvironment.init(Phase.DEFAULT); - MixinBootstrap.injectStateTweaker = false; + MixinBootstrap.getPlatform().prepare(null); + MixinBootstrap.initState = false; } else { MixinEnvironment.init(Phase.PREINIT); } @@ -149,26 +160,37 @@ public abstract class MixinBootstrap { } /** - * Phase 2 of mixin initialisation, register the state tweaker + * Phase 2 of mixin initialisation, initialise the phases */ - static void register() { + static void doInit(List args) { if (!MixinBootstrap.initialised) { - throw new IllegalStateException("MixinBootstrap.register() called before MixinBootstrap.preInit()"); + throw new IllegalStateException("MixinBootstrap.doInit() called before MixinBootstrap.preInit()"); } - if (MixinBootstrap.injectStateTweaker) { + MixinBootstrap.getPlatform().getPhaseProviderClasses(); +// for (String platformProviderClass : MixinBootstrap.getPlatform().getPhaseProviderClasses()) { +// System.err.printf("Registering %s\n", platformProviderClass); +// MixinEnvironment.registerPhaseProvider(platformProviderClass); +// } + + if (MixinBootstrap.initState) { + MixinBootstrap.getPlatform().prepare(args); + if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") < 4) { - MixinBootstrap.logger.warn("MixinBootstrap.register() called during a tweak constructor. Expect CoModificationException in 5.. 4.."); + MixinBootstrap.logger.warn("MixinBootstrap.doInit() called during a tweak constructor. Expect CoModificationException in 5.. 4.."); } - @SuppressWarnings("unchecked") - List tweakClasses = (List)Launch.blackboard.get("TweakClasses"); + List tweakClasses = Blackboard.>get(Blackboard.Keys.TWEAKCLASSES); if (tweakClasses != null) { tweakClasses.add(MixinEnvironment.class.getName() + "$EnvironmentStateTweaker"); } } } + static void injectIntoClassLoader(LaunchClassLoader classLoader) { + MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader); + } + private static int findInStackTrace(String className, String methodName) { Thread currentThread = Thread.currentThread(); @@ -185,4 +207,5 @@ public abstract class MixinBootstrap { return 0; } + } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java b/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java index 8a46ae01..8d32df36 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java @@ -24,7 +24,9 @@ */ package org.spongepowered.asm.launch; - +/** + * Error raised when mixin subsystem initialisation fails + */ public class MixinInitialisationError extends Error { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java b/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java index eb6fbcbc..d87904db 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java @@ -25,23 +25,11 @@ package org.spongepowered.asm.launch; import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.Phase; - - /** * TweakClass for running mixins in production. Being a tweaker ensures that we * get injected into the AppClassLoader but does mean that we will need to @@ -49,84 +37,20 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase; */ public class MixinTweaker implements ITweaker { - private static final String MFATT_TWEAKER = "TweakClass"; - private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main"; - - /** - * Make with the logging already - */ - private static final Logger logger = LogManager.getLogger("mixin"); - - /** - * Tweak containers - */ - private final Map containers = new LinkedHashMap(); - - /** - * Tracks whether {@link #acceptOptions} was called yet, if true, causes new - * launch agents to be prepared immediately - */ - private boolean prepared = false; - /** * Hello world */ public MixinTweaker() { - MixinBootstrap.preInit(); - - // Add agents for the tweak container - URI uri = null; - try { - uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI(); - if (uri != null) { - this.addContainer(uri); - } - } catch (URISyntaxException ex) { - ex.printStackTrace(); - } + MixinBootstrap.start(); } - public final void addContainer(URI uri) { - if (this.containers.containsKey(uri)) { - return; - } - - MixinTweaker.logger.debug("Adding mixin launch agents for container {}", uri); - MixinTweakContainer container = new MixinTweakContainer(uri); - this.containers.put(uri, container); - - if (this.prepared) { - container.prepare(); - } - } - /* (non-Javadoc) * @see net.minecraft.launchwrapper.ITweaker#acceptOptions(java.util.List, * java.io.File, java.io.File, java.lang.String) */ @Override public final void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - MixinBootstrap.register(); - this.prepared = true; - for (MixinTweakContainer container : this.containers.values()) { - container.prepare(); - } - this.parseArgs(args); - } - - /** - * Read and parse command-line arguments - * - * @param args command-line arguments - */ - private void parseArgs(List args) { - boolean captureNext = false; - for (String arg : args) { - if (captureNext) { - MixinTweaker.addConfig(arg); - } - captureNext = "--mixin".equals(arg); - } + MixinBootstrap.doInit(args); } /* (non-Javadoc) @@ -135,42 +59,7 @@ public class MixinTweaker implements ITweaker { */ @Override public final void injectIntoClassLoader(LaunchClassLoader classLoader) { - this.scanClasspath(); - MixinTweaker.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size()); - for (MixinTweakContainer container : this.containers.values()) { - try { - container.injectIntoClassLoader(classLoader); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - /** - * Scan the classpath for mixin containers (containers which declare the - * mixin tweaker in their manifest) and add agents for them - */ - private void scanClasspath() { - for (URL url : Launch.classLoader.getSources()) { - try { - URI uri = url.toURI(); - if (this.containers.containsKey(uri)) { - continue; - } - MixinTweaker.logger.debug("Scanning {} for mixin tweaker", uri); - if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) { - continue; - } - MainAttributes attributes = MainAttributes.of(uri); - String tweaker = attributes.get(MixinTweaker.MFATT_TWEAKER); - if (MixinTweaker.class.getName().equals(tweaker)) { - MixinTweaker.logger.debug("{} contains a mixin tweaker, adding agents", uri); - this.addContainer(uri); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } + MixinBootstrap.injectIntoClassLoader(classLoader); } /* (non-Javadoc) @@ -178,14 +67,7 @@ public class MixinTweaker implements ITweaker { */ @Override public String getLaunchTarget() { - for (MixinTweakContainer container : this.containers.values()) { - String mainClass = container.getLaunchTarget(); - if (mainClass != null) { - return mainClass; - } - } - - return MixinTweaker.DEFAULT_MAIN_CLASS; + return MixinBootstrap.getPlatform().getLaunchTarget(); } /* (non-Javadoc) @@ -195,52 +77,5 @@ public class MixinTweaker implements ITweaker { public String[] getLaunchArguments() { return new String[]{}; } - - /** - * Add a config from a jar manifest source or the command line. Supports - * config declarations in the form filename.json or alternatively - * filename.json@PHASE where PHASE is a - * case-sensitive string token representing an environment phase. - * - * @param config config resource name, does not require a leading / - */ - static void addConfig(String config) { - if (config.endsWith(".json")) { - MixinTweaker.logger.debug("Registering mixin config: {}", config); - MixinEnvironment.getDefaultEnvironment().addConfiguration(config); - } else if (config.contains(".json@")) { - int pos = config.indexOf(".json@"); - String phaseName = config.substring(pos + 6); - config = config.substring(0, pos + 5); - Phase phase = Phase.forName(phaseName); - if (phase != null) { - MixinTweaker.logger.debug("Registering mixin config: {}", config); - MixinEnvironment.getEnvironment(phase).addConfiguration(config); - } - } - } - - /** - * Add a token provider class from a jar manifest source. Supports either - * bare class names in the form blah.package.ClassName or - * alternatively blah.package.ClassName@PHASE where - * PHASE is a case-sensitive string token representing an - * environment phase name. - * - * @param provider provider class name, optionally suffixed with @PHASE - */ - static void addTokenProvider(String provider) { - if (provider.contains("@")) { - String[] parts = provider.split("@", 2); - Phase phase = Phase.forName(parts[1]); - if (phase != null) { - MixinTweaker.logger.debug("Registering token provider class: {}", parts[0]); - MixinEnvironment.getEnvironment(phase).registerTokenProviderClass(parts[0]); - } - return; - } - - MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass(provider); - } } diff --git a/src/main/java/org/spongepowered/asm/launch/IMixinLaunchAgent.java b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java similarity index 69% rename from src/main/java/org/spongepowered/asm/launch/IMixinLaunchAgent.java rename to src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java index 4bf108b7..abdad43d 100644 --- a/src/main/java/org/spongepowered/asm/launch/IMixinLaunchAgent.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java @@ -22,21 +22,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.launch; +package org.spongepowered.asm.launch.platform; import net.minecraft.launchwrapper.LaunchClassLoader; /** - * Base interface for launch agents. Launch agents are environment-specific - * launch handlers which are used by the {@link MixinTweaker mixin tweaker} to - * perform launch tasks required by that environment without having to fill the - * tweaker itself with a bunch of environment-specific cruft. + * Base interface for platform agents. Platform agents are environment-specific + * handlers which are used by the Mixin subsystem to perform platform-specific + * tasks required by different environments without having to litter the Mixin + * codebase with a bunch of environment-specific cruft. * - *

Agents handle mixin environment launch tasks on a per-container basis, + *

Platform Agents handle mixin environment tasks on a per-container basis, * with each container in the environment being assigned one of each available * type of agent to handle those tasks on behalf of the container.

*/ -interface IMixinLaunchAgent { +public interface IMixinPlatformAgent { + + /** + * Get the phase provider for this agent + */ + public abstract String getPhaseProvider(); /** * Called during pre-initialisation, after all tweakers and tweak containers @@ -44,6 +49,13 @@ interface IMixinLaunchAgent { */ public abstract void prepare(); + /** + * Called from injectIntoClassLoader in the parent tweaker but + * only called on the primary tweak container. This is useful if the + * agent needs to perform some environment-specific setup just once. + */ + public abstract void initPrimaryContainer(); + /** * Called from injectIntoClassLoader in the parent tweaker * @@ -56,4 +68,5 @@ interface IMixinLaunchAgent { * custom target is available. */ public abstract String getLaunchTarget(); + } diff --git a/src/main/java/org/spongepowered/asm/launch/MainAttributes.java b/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java similarity index 98% rename from src/main/java/org/spongepowered/asm/launch/MainAttributes.java rename to src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java index 7b8938ca..574bd9f3 100644 --- a/src/main/java/org/spongepowered/asm/launch/MainAttributes.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java @@ -22,7 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.launch; +package org.spongepowered.asm.launch.platform; import java.io.File; import java.io.IOException; diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java similarity index 53% rename from src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java rename to src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index a5809cb6..0c274329 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -22,46 +22,51 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.launch; +package org.spongepowered.asm.launch.platform; import java.lang.reflect.Constructor; import java.net.URI; import java.util.ArrayList; +import java.util.Collection; import java.util.List; -import net.minecraft.launchwrapper.Launch; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.Blackboard; + import net.minecraft.launchwrapper.LaunchClassLoader; - /** - * A collection of {@link IMixinLaunchAgent launch agents) + * A collection of {@link IMixinPlatformAgent} platform agents) */ -public class MixinTweakContainer { +public class MixinContainer { public static final List agentClasses = new ArrayList(); static { - Launch.blackboard.put("mixin.agents", MixinTweakContainer.agentClasses); - MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentFML"); - MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentDefault"); + Blackboard.put(Blackboard.Keys.AGENTS, MixinContainer.agentClasses); + MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentFML"); + MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentDefault"); } + private final Logger logger = LogManager.getLogger("mixin"); + private final URI uri; - private final List agents = new ArrayList(); + private final List agents = new ArrayList(); - public MixinTweakContainer(URI uri) { + public MixinContainer(MixinPlatformManager manager, URI uri) { this.uri = uri; - for (String agentClass : MixinTweakContainer.agentClasses) { + for (String agentClass : MixinContainer.agentClasses) { try { @SuppressWarnings("unchecked") - Class clazz = (Class)Class.forName(agentClass); - Constructor ctor = clazz.getDeclaredConstructor(URI.class); - IMixinLaunchAgent agent = ctor.newInstance(uri); + Class clazz = (Class)Class.forName(agentClass); + Constructor ctor = clazz.getDeclaredConstructor(MixinPlatformManager.class, URI.class); + IMixinPlatformAgent agent = ctor.newInstance(manager, uri); this.agents.add(agent); } catch (Exception ex) { - ex.printStackTrace(); + this.logger.catching(ex); } } } @@ -73,26 +78,44 @@ public class MixinTweakContainer { return this.uri; } + public Collection getPhaseProviders() { + List phaseProviders = new ArrayList(); + for (IMixinPlatformAgent agent : this.agents) { + String phaseProvider = agent.getPhaseProvider(); + if (phaseProvider != null) { + phaseProviders.add(phaseProvider); + } + } + return phaseProviders; + } + /** * */ public void prepare() { - for (IMixinLaunchAgent agent : this.agents) { + for (IMixinPlatformAgent agent : this.agents) { agent.prepare(); } } + + public void initPrimaryContainer() { + for (IMixinPlatformAgent agent : this.agents) { + this.logger.debug("Processing launch tasks for {}", agent); + agent.initPrimaryContainer(); + } + } /** * @param classLoader */ public void injectIntoClassLoader(LaunchClassLoader classLoader) { - for (IMixinLaunchAgent agent : this.agents) { + for (IMixinPlatformAgent agent : this.agents) { agent.injectIntoClassLoader(classLoader); } } public String getLaunchTarget() { - for (IMixinLaunchAgent agent : this.agents) { + for (IMixinPlatformAgent agent : this.agents) { String launchTarget = agent.getLaunchTarget(); if (launchTarget != null) { return launchTarget; diff --git a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentAbstract.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java similarity index 70% rename from src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentAbstract.java rename to src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java index da7833a6..c32924dd 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentAbstract.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java @@ -22,17 +22,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.launch; +package org.spongepowered.asm.launch.platform; import java.io.File; import java.net.URI; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** - * Launch agent base class + * Platform agent base class */ -public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent { +public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent { + /** + * Logger + */ + protected static final Logger logger = LogManager.getLogger("mixin"); + + protected final MixinPlatformManager manager; + /** * URI to the container */ @@ -49,11 +58,12 @@ public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent { protected final MainAttributes attributes; /** - * Create a new launch agent for the specified URI + * Create a new platform agent for the specified URI * * @param uri */ - public MixinLaunchAgentAbstract(URI uri) { + public MixinPlatformAgentAbstract(MixinPlatformManager manager, URI uri) { + this.manager = manager; this.uri = uri; this.container = this.uri != null ? new File(this.uri) : null; this.attributes = MainAttributes.of(uri); @@ -61,7 +71,12 @@ public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent { @Override public String toString() { - return String.format("LaunchAgent[%s:%s]", this.getClass().getSimpleName(), this.uri); + return String.format("PlatformAgent[%s:%s]", this.getClass().getSimpleName(), this.uri); } + @Override + public String getPhaseProvider() { + return null; + } + } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java similarity index 62% rename from src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java rename to src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java index ae3e978e..fd6aae9b 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java @@ -22,42 +22,50 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.launch; +package org.spongepowered.asm.launch.platform; import java.net.URI; +import org.spongepowered.asm.util.Constants.ManifestAttributes; + import net.minecraft.launchwrapper.LaunchClassLoader; - /** - * Default launch agent, handles the MixinConfigs manifest key + * Default platform agent, handles the mixin manifest keys such as + * MixinConfigs and MixinTokenProviders. */ -public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract { +public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract { - protected static final String MFATT_MIXINCONFIGS = "MixinConfigs"; - protected static final String MFATT_TOKENPROVIDERS = "MixinTokenProviders"; - protected static final String MFATT_MAINCLASS = "Main-Class"; - - public MixinLaunchAgentDefault(URI uri) { - super(uri); + public MixinPlatformAgentDefault(MixinPlatformManager manager, URI uri) { + super(manager, uri); } @Override public void prepare() { - String mixinConfigs = this.attributes.get(MixinLaunchAgentDefault.MFATT_MIXINCONFIGS); + @SuppressWarnings("deprecation") + String compatibilityLevel = this.attributes.get(ManifestAttributes.COMPATIBILITY); + if (compatibilityLevel != null) { + this.manager.setCompatibilityLevel(compatibilityLevel); + } + + String mixinConfigs = this.attributes.get(ManifestAttributes.MIXINCONFIGS); if (mixinConfigs != null) { for (String config : mixinConfigs.split(",")) { - MixinTweaker.addConfig(config.trim()); + this.manager.addConfig(config.trim()); } } - String tokenProviders = this.attributes.get(MixinLaunchAgentDefault.MFATT_TOKENPROVIDERS); + String tokenProviders = this.attributes.get(ManifestAttributes.TOKENPROVIDERS); if (tokenProviders != null) { for (String provider : tokenProviders.split(",")) { - MixinTweaker.addTokenProvider(provider.trim()); + this.manager.addTokenProvider(provider.trim()); } } } + + @Override + public void initPrimaryContainer() { + } @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { @@ -65,7 +73,7 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract { @Override public String getLaunchTarget() { - return this.attributes.get(MixinLaunchAgentDefault.MFATT_MAINCLASS); + return this.attributes.get(ManifestAttributes.MAINCLASS); } } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java similarity index 60% rename from src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java rename to src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java index 099b0778..404e4b76 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java @@ -22,28 +22,46 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.launch; +package org.spongepowered.asm.launch.platform; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; +//import java.util.Collection; +import java.util.Collections; import java.util.List; +import org.apache.logging.log4j.Level; +import org.spongepowered.asm.launch.Blackboard; +import org.spongepowered.asm.mixin.MixinEnvironment; +//import org.spongepowered.asm.mixin.environment.IPhaseProvider; +//import org.spongepowered.asm.mixin.environment.PhaseDefinition; +//import org.spongepowered.asm.mixin.environment.phase.OnLogMessage; +import org.spongepowered.asm.mixin.extensibility.IRemapper; + +//import com.google.common.collect.ImmutableList; + import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; - /** - * Launch agent for use under FML. + * Platform agent for use under FML. * *

When FML is present we scan containers for the manifest entries which are * inhibited by the tweaker, in particular the FMLCorePlugin and * FMLCorePluginContainsFMLMod entries. This is required because FML * performs no further processing of containers if they contain a tweaker!

*/ -public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { +public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { + + private static final String LOAD_CORE_MOD_METHOD = "loadCoreMod"; + private static final String GET_REPARSEABLE_COREMODS_METHOD = "getReparseableCoremods"; + private static final String CORE_MOD_MANAGER_CLASS = "net.minecraftforge.fml.relauncher.CoreModManager"; + private static final String GET_IGNORED_MODS_METHOD = "getIgnoredMods"; + + private static final String FML_REMAPPER_ADAPTER_CLASS = "org.spongepowered.asm.bridge.RemapperAdapterFML"; private static final String MFATT_FORCELOADASMOD = "ForceLoadAsMod"; private static final String MFATT_FMLCOREPLUGIN = "FMLCorePlugin"; @@ -72,8 +90,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { /** * @param uri */ - public MixinLaunchAgentFML(URI uri) { - super(uri); + public MixinPlatformAgentFML(MixinPlatformManager manager, URI uri) { + super(manager, uri); this.fileName = this.container.getName(); this.coreModWrapper = this.initFMLCoreMod(); } @@ -83,17 +101,16 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { */ private ITweaker initFMLCoreMod() { try { - this.clCoreModManager = MixinLaunchAgentFML.getCoreModManagerClass(); + this.clCoreModManager = MixinPlatformAgentFML.getCoreModManagerClass(); - if ("true".equalsIgnoreCase(this.attributes.get(MixinLaunchAgentFML.MFATT_FORCELOADASMOD))) { + if ("true".equalsIgnoreCase(this.attributes.get(MixinPlatformAgentFML.MFATT_FORCELOADASMOD))) { this.loadAsMod(); } return this.injectCorePlugin(); } catch (Exception ex) { - ex.printStackTrace(); + return null; } - return null; } /** @@ -109,15 +126,12 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { */ private void loadAsMod() { try { - Method mdGetLoadedCoremods = this.clCoreModManager.getDeclaredMethod("getLoadedCoremods"); - @SuppressWarnings("unchecked") - List loadedCoremods = (List)mdGetLoadedCoremods.invoke(null); - loadedCoremods.remove(this.fileName); + MixinPlatformAgentFML.getIgnoredMods(this.clCoreModManager).remove(this.fileName); } catch (Exception ex) { - ex.printStackTrace(); + MixinPlatformAgentAbstract.logger.catching(ex); } - if (this.attributes.get(MixinLaunchAgentFML.MFATT_COREMODCONTAINSMOD) != null) { + if (this.attributes.get(MixinPlatformAgentFML.MFATT_COREMODCONTAINSMOD) != null) { this.addReparseableJar(); } } @@ -128,7 +142,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { */ private void addReparseableJar() { try { - Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod("getReparseableCoremods"); + Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod(Blackboard.getString( + Blackboard.Keys.FML_GET_REPARSEABLE_COREMODS, MixinPlatformAgentFML.GET_REPARSEABLE_COREMODS_METHOD)); @SuppressWarnings("unchecked") List reparsedCoremods = (List)mdGetReparsedCoremods.invoke(null); if (!reparsedCoremods.contains(this.fileName)) { @@ -140,12 +155,13 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { } private ITweaker injectCorePlugin() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { - String coreModName = this.attributes.get(MixinLaunchAgentFML.MFATT_FMLCOREPLUGIN); + String coreModName = this.attributes.get(MixinPlatformAgentFML.MFATT_FMLCOREPLUGIN); if (coreModName == null) { return null; } - Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod("loadCoreMod", LaunchClassLoader.class, String.class, File.class); + Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod(Blackboard.getString( + Blackboard.Keys.FML_LOAD_CORE_MOD, MixinPlatformAgentFML.LOAD_CORE_MOD_METHOD), LaunchClassLoader.class, String.class, File.class); mdLoadCoreMod.setAccessible(true); ITweaker wrapper = (ITweaker)mdLoadCoreMod.invoke(null, Launch.classLoader, coreModName, this.container); if (wrapper == null) { @@ -154,16 +170,44 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { return wrapper; } + + @Override + public String getPhaseProvider() { + return MixinPlatformAgentFML.class.getName() + "$PhaseProvider"; + } /* (non-Javadoc) - * @see org.spongepowered.asm.launch.IMixinLaunchAgent#prepare() + * @see org.spongepowered.asm.launch.IMixinPlatformAgent#prepare() */ @Override public void prepare() { } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.IMixinPlatformAgent + * #initPrimaryContainer() + */ + @Override + public void initPrimaryContainer() { + if (this.clCoreModManager != null) { +// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFML.class.getName() + "$PhaseProvider"); + this.injectRemapper(); + } + } + + private void injectRemapper() { + try { + Class clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFML.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader); + Method mdCreate = clFmlRemapperAdapter.getDeclaredMethod("create"); + IRemapper remapper = (IRemapper)mdCreate.invoke(null); + MixinEnvironment.getDefaultEnvironment().getRemappers().add(remapper); + } catch (Exception ex) { + MixinPlatformAgentAbstract.logger.debug("Failed instancing FML remapper adapter, things will probably go horribly for notch-obf'd mods!"); + } + } /* (non-Javadoc) - * @see org.spongepowered.asm.launch.IMixinLaunchAgent + * @see org.spongepowered.asm.launch.IMixinPlatformAgent * #injectIntoClassLoader(net.minecraft.launchwrapper.LaunchClassLoader) */ @Override @@ -174,13 +218,13 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { } /* (non-Javadoc) - * @see org.spongepowered.asm.launch.IMixinLaunchAgent#getLaunchTarget() + * @see org.spongepowered.asm.launch.IMixinPlatformAgent#getLaunchTarget() */ @Override public String getLaunchTarget() { return null; } - + /** * Performs a naive check which attempts to discover whether we are pre or * post FML's main injection. If we are pre, then we must not @@ -193,9 +237,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { * * @return true if FML was already injected */ - @SuppressWarnings("unchecked") protected final boolean isFMLInjected() { - for (String tweaker : (List)Launch.blackboard.get("TweakClasses")) { + for (String tweaker : Blackboard.>get(Blackboard.Keys.TWEAKCLASSES)) { if (tweaker.endsWith("FMLDeobfTweaker")) { return true; } @@ -209,10 +252,31 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract { */ private static Class getCoreModManagerClass() throws ClassNotFoundException { try { - return Class.forName("net.minecraftforge.fml.relauncher.CoreModManager"); + return Class.forName(Blackboard.getString( + Blackboard.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS)); } catch (ClassNotFoundException ex) { return Class.forName("cpw.mods.fml.relauncher.CoreModManager"); } } + @SuppressWarnings("unchecked") + private static List getIgnoredMods(Class clCoreModManager) throws IllegalAccessException, InvocationTargetException { + Method mdGetIgnoredMods = null; + + try { + mdGetIgnoredMods = clCoreModManager.getDeclaredMethod(Blackboard.getString( + Blackboard.Keys.FML_GET_IGNORED_MODS, MixinPlatformAgentFML.GET_IGNORED_MODS_METHOD)); + } catch (NoSuchMethodException ex1) { + try { + // Legacy name + mdGetIgnoredMods = clCoreModManager.getDeclaredMethod("getLoadedCoremods"); + } catch (NoSuchMethodException ex2) { + MixinPlatformAgentAbstract.logger.catching(Level.DEBUG, ex2); + return Collections.emptyList(); + } + } + + return (List)mdGetIgnoredMods.invoke(null); + } + } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java new file mode 100644 index 00000000..efde7e32 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java @@ -0,0 +1,287 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform; + +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +//import org.spongepowered.asm.launch.MixinBootstrap.Delegate; +import org.spongepowered.asm.launch.MixinTweaker; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.mixin.Mixins; + +//import com.google.common.collect.ImmutableList; + +import net.minecraft.launchwrapper.Launch; +import net.minecraft.launchwrapper.LaunchClassLoader; + +/** + * Handler for platform-specific behaviour required in different mixin + * environments. + */ +public class MixinPlatformManager { + + private static final String MFATT_TWEAKER = "TweakClass"; + private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main"; + + /** + * Make with the logging already + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Bootstrap delegate + */ +// private final Delegate delegate; + + /** + * Tweak containers + */ + private final Map containers = new LinkedHashMap(); + + /** + * Container for this tweaker + */ + private MixinContainer primaryContainer; + + /** + * Tracks whether {@link #acceptOptions} was called yet, if true, causes new + * agents to be prepared immediately + */ + private boolean prepared = false; + + /** + * Tracks whether {@link #injectIntoClassLoader} was called yet + */ + private boolean injected; + + public MixinPlatformManager() { //Delegate delegate) { +// this.delegate = delegate; + + // Add agents for the tweak container + URI uri = null; + try { + uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI(); + if (uri != null) { + this.primaryContainer = this.addContainer(uri); + } + } catch (URISyntaxException ex) { + ex.printStackTrace(); + } + } + + public Collection getPhaseProviderClasses() { + Collection phaseProviders = this.primaryContainer.getPhaseProviders(); + if (phaseProviders != null) { + return Collections.unmodifiableCollection(phaseProviders); + } + + return Collections.emptyList(); + } + + public final MixinContainer addContainer(URI uri) { + MixinContainer existingContainer = this.containers.get(uri); + if (existingContainer != null) { + return existingContainer; + } + + MixinPlatformManager.logger.debug("Adding mixin platform agents for container {}", uri); + MixinContainer container = new MixinContainer(this, uri); + this.containers.put(uri, container); + + if (this.prepared) { + container.prepare(); + } + return container; + } + + public final void prepare(List args) { + this.prepared = true; + for (MixinContainer container : this.containers.values()) { + container.prepare(); + } + if (args != null) { + this.parseArgs(args); + } else { + String argv = System.getProperty("sun.java.command"); + if (argv != null) { + this.parseArgs(Arrays.asList(argv.split(" "))); + } + } + } + + /** + * Read and parse command-line arguments + * + * @param args command-line arguments + */ + private void parseArgs(List args) { + boolean captureNext = false; + for (String arg : args) { + if (captureNext) { + this.addConfig(arg); + } + captureNext = "--mixin".equals(arg); + } + } + + public final void injectIntoClassLoader(LaunchClassLoader classLoader) { + if (this.injected) { + return; + } + this.injected = true; + + if (this.primaryContainer != null) { + this.primaryContainer.initPrimaryContainer(); + } + + this.scanClasspath(); + MixinPlatformManager.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size()); + for (MixinContainer container : this.containers.values()) { + try { + container.injectIntoClassLoader(classLoader); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + /** + * Scan the classpath for mixin containers (containers which declare the + * mixin tweaker in their manifest) and add agents for them + */ + private void scanClasspath() { + for (URL url : Launch.classLoader.getSources()) { + try { + URI uri = url.toURI(); + if (this.containers.containsKey(uri)) { + continue; + } + MixinPlatformManager.logger.debug("Scanning {} for mixin tweaker", uri); + if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) { + continue; + } + MainAttributes attributes = MainAttributes.of(uri); + String tweaker = attributes.get(MixinPlatformManager.MFATT_TWEAKER); + if (MixinTweaker.class.getName().equals(tweaker)) { + MixinPlatformManager.logger.debug("{} contains a mixin tweaker, adding agents", uri); + this.addContainer(uri); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + public String getLaunchTarget() { + for (MixinContainer container : this.containers.values()) { + String mainClass = container.getLaunchTarget(); + if (mainClass != null) { + return mainClass; + } + } + + return MixinPlatformManager.DEFAULT_MAIN_CLASS; + } + + /** + * Set the desired compatibility level as a string, used by agents to set + * compatibility level from jar manifest + * + * @param level compatibility level as a string + */ + @SuppressWarnings("deprecation") + final void setCompatibilityLevel(String level) { + try { + CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase()); + MixinPlatformManager.logger.debug("Setting mixin compatibility level: {}", value); + MixinEnvironment.setCompatibilityLevel(value); + } catch (IllegalArgumentException ex) { + MixinPlatformManager.logger.warn("Invalid compatibility level specified: {}", level); + } + } + + /** + * Add a config from a jar manifest source or the command line. Supports + * config declarations in the form filename.json or alternatively + * filename.json@PHASE where PHASE is a + * case-sensitive string token representing an environment phase. + * + * @param config config resource name, does not require a leading / + */ + @SuppressWarnings("deprecation") + final void addConfig(String config) { + if (config.endsWith(".json")) { + MixinPlatformManager.logger.debug("Registering mixin config: {}", config); + Mixins.addConfiguration(config); + } else if (config.contains(".json@")) { + int pos = config.indexOf(".json@"); + String phaseName = config.substring(pos + 6); + config = config.substring(0, pos + 5); + Phase phase = Phase.forName(phaseName); + if (phase != null) { + MixinPlatformManager.logger.warn("Setting config phase via manifest is deprecated: {}. Specify target in config instead", config); + MixinPlatformManager.logger.debug("Registering mixin config: {}", config); + MixinEnvironment.getEnvironment(phase).addConfiguration(config); + } + } + } + + /** + * Add a token provider class from a jar manifest source. Supports either + * bare class names in the form blah.package.ClassName or + * alternatively blah.package.ClassName@PHASE where + * PHASE is a case-sensitive string token representing an + * environment phase name. + * + * @param provider provider class name, optionally suffixed with @PHASE + */ + final void addTokenProvider(String provider) { + if (provider.contains("@")) { + String[] parts = provider.split("@", 2); + Phase phase = Phase.forName(parts[1]); + if (phase != null) { + MixinPlatformManager.logger.debug("Registering token provider class: {}", parts[0]); + MixinEnvironment.getEnvironment(phase).registerTokenProviderClass(parts[0]); + } + return; + } + + MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass(provider); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/Debug.java b/src/main/java/org/spongepowered/asm/mixin/Debug.java new file mode 100644 index 00000000..cfea8ddd --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/Debug.java @@ -0,0 +1,64 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Anotation used to decorate items you might wish to examine after mixin + * application. + */ +@Target({ ElementType.TYPE, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Debug { + + /** + * Only applicable for classes, use this to decorate mixins that you wish + * to export even if mixin.debug.export is not enabled. This is + * useful if you wish to export only the target of the mixin you are working + * on without enabling export globally. + * + *

Note that if mixin.debug.export is not true + * then the decompiler is not initialised (even if present on the + * classpath) and thus you must set mixin.debug.export.decompile to + * true in order to have force-exported classes decompiled.

+ * + * @return whether to export the decorated target class + */ + public boolean export() default false; + + /** + * Print the method bytecode to the console after mixin application. This + * setting is only used if the mixin.debug.verbose option is + * enabled. + * + * @return whether to print the class or method to the console. + */ + public boolean print() default false; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/Final.java b/src/main/java/org/spongepowered/asm/mixin/Final.java new file mode 100644 index 00000000..73834c13 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/Final.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; + +/** + * This annotation has two uses: + * + *
    + *
  • + * On an {@link Shadow} field, it can be used to raise an error-level log + * message if any write occurrences appear in the mixin bytecode. This can + * be used in place of declaring the field as actually final. This + * is required since it is normally desirable to remove the final + * modifier from shadow fields to avoid unwanted field initialisers. If + * {@link Option#DEBUG_VERIFY} is true, then an + * {@link InvalidMixinException} is thrown. + *
  • + *
  • + * On an {@link Inject injector} or {@link Overwrite overwritten} method, + * it is equivalent to setting the priority of the containing mixin to + * {@link Integer#MAX_VALUE} but applies only to the annotated method. This + * allows methods to mark themselves as effectively final, preventing their + * replacement by later mixins with higher priority. + *
  • + *
+ */ +@Target({ ElementType.METHOD, ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Final { + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/Interface.java b/src/main/java/org/spongepowered/asm/mixin/Interface.java index 9c9be4c4..791c9286 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Interface.java +++ b/src/main/java/org/spongepowered/asm/mixin/Interface.java @@ -53,4 +53,12 @@ public @interface Interface { */ public String prefix(); + /** + * If set to true, all methods implementing this interface are + * treated as if they were individually decorated with {@link Unique} + * + * @return true to mark all implementing methods as unique + */ + public boolean unique() default false; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java index 8bb58387..721e513b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java +++ b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java @@ -29,7 +29,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * This annotation allows fine-tuning of the overwrite policy for a * soft-implemented interface member method. diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index f9f3466f..bf7210c2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -25,23 +25,36 @@ package org.spongepowered.asm.mixin; import java.io.File; +import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import javax.annotation.Resource; + +import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.helpers.Booleans; +import org.spongepowered.asm.launch.Blackboard; import org.spongepowered.asm.launch.MixinBootstrap; +import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.mixin.transformer.MixinTransformer; +import org.spongepowered.asm.obfuscation.RemapperChain; import org.spongepowered.asm.util.ITokenProvider; +import org.spongepowered.asm.util.JavaVersion; import org.spongepowered.asm.util.PrettyPrinter; import com.google.common.collect.ImmutableList; @@ -53,12 +66,11 @@ import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; - /** * The mixin environment manages global state information for the mixin * subsystem. */ -public class MixinEnvironment implements ITokenProvider { +public final class MixinEnvironment implements ITokenProvider { /** * Environment phase, deliberately not implemented as an enum @@ -76,16 +88,22 @@ public class MixinEnvironment implements ITokenProvider { */ public static final Phase PREINIT = new Phase(0, "PREINIT"); + /** + * "Initialisation" phase, after FML's deobf transformer has loaded + */ + public static final Phase INIT = new Phase(1, "INIT"); + /** * "Default" phase, during runtime */ - public static final Phase DEFAULT = new Phase(1, "DEFAULT"); + public static final Phase DEFAULT = new Phase(2, "DEFAULT"); /** * All phases */ static final List phases = ImmutableList.of( Phase.PREINIT, + Phase.INIT, Phase.DEFAULT ); @@ -175,11 +193,10 @@ public class MixinEnvironment implements ITokenProvider { protected abstract boolean detect(); - @SuppressWarnings("unchecked") protected final String getSideName() { // Using this method first prevents us from accidentally loading FML classes // too early when using the tweaker in dev - for (ITweaker tweaker : (List)Launch.blackboard.get("Tweaks")) { + for (ITweaker tweaker : Blackboard.>get(Blackboard.Keys.TWEAKS)) { if (tweaker.getClass().getName().endsWith(".common.launcher.FMLServerTweaker")) { return "SERVER"; } else if (tweaker.getClass().getName().endsWith(".common.launcher.FMLTweaker")) { @@ -197,7 +214,7 @@ public class MixinEnvironment implements ITokenProvider { return name; } - name = this.getSideName("com.mumfrey.liteloader.core.LiteLoader", "getEnvironmentType"); + name = this.getSideName("com.mumfrey.liteloader.launch.LiteLoaderTweaker", "getEnvironmentType"); if (name != null) { return name; } @@ -246,10 +263,22 @@ public class MixinEnvironment implements ITokenProvider { *
?
Matches exactly one character
* */ - DEBUG_EXPORT_FILTER(Option.DEBUG_EXPORT, "filter"), + DEBUG_EXPORT_FILTER(Option.DEBUG_EXPORT, "filter", false), /** - * Run the CheckClassAdapter on all classes after mixins are applied + * Allow fernflower to be disabled even if it is found on the classpath + */ + DEBUG_EXPORT_DECOMPILE(Option.DEBUG_EXPORT, "decompile") { + @Override + boolean getBooleanValue() { + return Booleans.parseBoolean(System.getProperty(this.property), super.getBooleanValue()); + } + }, + + /** + * Run the CheckClassAdapter on all classes after mixins are applied, + * also enables stricter checks on mixins for use at dev-time, promotes + * some warning-level messages to exceptions */ DEBUG_VERIFY(Option.DEBUG_ALL, "verify"), @@ -259,6 +288,44 @@ public class MixinEnvironment implements ITokenProvider { */ DEBUG_VERBOSE(Option.DEBUG_ALL, "verbose"), + /** + * Elevates failed injections to an error condition, see + * {@link Inject#expect} for details + */ + DEBUG_INJECTORS(Option.DEBUG_ALL, "countInjections"), + + /** + * Enable strict checks + */ + DEBUG_STRICT(Option.DEBUG_ALL, "strict") { + @Override + boolean getBooleanValue() { + return Booleans.parseBoolean(System.getProperty(this.property), false); + } + }, + + /** + * If false (default), {@link Unique} public methods merely raise a + * warning when encountered and are not merged into the target. If true, + * an exception is thrown instead + */ + DEBUG_UNIQUE(Option.DEBUG_STRICT, "unique"), + + /** + * Enable strict checking for mixin targets + */ + DEBUG_TARGETS(Option.DEBUG_STRICT, "targets"), + + /** + * Disable the injector handler remapper + */ + DEBUG_DISABLE_HANDLER_REMAP(Option.DEBUG_ALL, "disableHandlerRename") { + @Override + boolean getBooleanValue() { + return Booleans.parseBoolean(System.getProperty(this.property), super.getBooleanValue()); + } + }, + /** * Dumps the bytecode for the target class to disk when mixin * application fails @@ -279,8 +346,38 @@ public class MixinEnvironment implements ITokenProvider { /** * Ignore all constraints on mixin annotations, output warnings instead */ - IGNORE_CONSTRAINTS("ignoreConstraints"); + IGNORE_CONSTRAINTS("ignoreConstraints"), + + /** + * Enables the hot-swap agent + */ + HOT_SWAP("hotSwap"), + /** + * Parent for environment settings + */ + ENVIRONMENT("env") { + @Override + boolean getBooleanValue() { + return false; + } + }, + + /** + * Force refmap obf type when required + */ + OBFUSCATION_TYPE(Option.ENVIRONMENT, "obf"), + + /** + * Disable refmap when required + */ + DISABLE_REFMAP(Option.ENVIRONMENT, "disableRefMap"), + + /** + * Default compatibility level to operate at + */ + DEFAULT_COMPATIBILITY_LEVEL(Option.ENVIRONMENT, "compatLevel"); + /** * Prefix for mixin options */ @@ -296,14 +393,38 @@ public class MixinEnvironment implements ITokenProvider { * Java property name */ final String property; + + /** + * Whether this property is boolean or not + */ + final boolean flag; + + /** + * Number of parents + */ + final int depth; private Option(String property) { - this(null, property); + this(null, property, true); + } + + private Option(String property, boolean flag) { + this(null, property, flag); } private Option(Option parent, String property) { + this(parent, property, true); + } + + private Option(Option parent, String property, boolean flag) { this.parent = parent; this.property = (parent != null ? parent.property : Option.PREFIX) + "." + property; + this.flag = flag; + int depth = 0; + for (; parent != null; depth++) { + parent = parent.parent; + } + this.depth = depth; } Option getParent() { @@ -314,6 +435,11 @@ public class MixinEnvironment implements ITokenProvider { return this.property; } + @Override + public String toString() { + return this.flag ? String.valueOf(this.getBooleanValue()) : this.getStringValue(); + } + boolean getBooleanValue() { return Booleans.parseBoolean(System.getProperty(this.property), false) || (this.parent != null && this.parent.getBooleanValue()); @@ -322,6 +448,93 @@ public class MixinEnvironment implements ITokenProvider { String getStringValue() { return (this.parent == null || this.parent.getBooleanValue()) ? System.getProperty(this.property) : null; } + + @SuppressWarnings("unchecked") + > E getEnumValue(E defaultValue) { + String value = System.getProperty(this.property, defaultValue.name()); + try { + return (E) Enum.valueOf(defaultValue.getClass(), value); + } catch (IllegalArgumentException ex) { + return defaultValue; + } + } + } + + /** + * Operational compatibility level for the mixin subsystem + */ + public static enum CompatibilityLevel { + + JAVA_6(6, Opcodes.V1_6, false), + + JAVA_7(7, Opcodes.V1_7, false) { + + @Override + boolean isSupported() { + return JavaVersion.current() >= 1.7; + } + + }, + + JAVA_8(8, Opcodes.V1_8, true) { + + @Override + boolean isSupported() { + return JavaVersion.current() >= 1.8; + } + + }; + + private final int ver; + + private final int classVersion; + + private final boolean supportsMethodsInInterfaces; + + private CompatibilityLevel maxCompatibleLevel; + + private CompatibilityLevel(int ver, int classVersion, boolean resolveMethodsInInterfaces) { + this.ver = ver; + this.classVersion = classVersion; + this.supportsMethodsInInterfaces = resolveMethodsInInterfaces; + } + + @SuppressWarnings("unused") + private void setMaxCompatibleLevel(CompatibilityLevel maxCompatibleLevel) { + this.maxCompatibleLevel = maxCompatibleLevel; + } + + boolean isSupported() { + return true; + } + + public int classVersion() { + return this.classVersion; + } + + public boolean supportsMethodsInInterfaces() { + return this.supportsMethodsInInterfaces; + } + + public boolean isAtLeast(CompatibilityLevel level) { + return this.ver >= level.ver; + } + + public boolean canElevateTo(CompatibilityLevel level) { + if (level == null || this.maxCompatibleLevel == null) { + return true; + } + return level.ver <= this.maxCompatibleLevel.ver; + } + + public boolean canSupport(CompatibilityLevel level) { + if (level == null) { + return true; + } + + return level.canElevateTo(this); + } + } /** @@ -336,6 +549,7 @@ public class MixinEnvironment implements ITokenProvider { @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader); } @Override @@ -392,6 +606,39 @@ public class MixinEnvironment implements ITokenProvider { } + /** + * Temporary + */ + static class MixinLogger { + + static MixinAppender appender = new MixinAppender("MixinLogger", null, null); + + public MixinLogger() { + org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML"); + appender.start(); + log.addAppender(appender); + } + + /** + * Temporary + */ + static class MixinAppender extends AbstractAppender { + + protected MixinAppender(String name, Filter filter, Layout layout) { + super(name, filter, layout); + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() == Level.DEBUG && "Validating minecraft".equals(event.getMessage().getFormat())) { + // transition to INIT + MixinEnvironment.gotoPhase(Phase.INIT); + } + } + + } + } + /** * Known re-entrant transformers, other re-entrant transformers will * detected automatically @@ -403,10 +650,6 @@ public class MixinEnvironment implements ITokenProvider { "cpw.mods.fml.common.asm.transformers.TerminalTransformer" ); - // Blackboard keys - private static final String CONFIGS_KEY = "mixin.configs"; - private static final String TRANSFORMER_KEY = "mixin.transformer"; - /** * Currently active environment */ @@ -418,6 +661,11 @@ public class MixinEnvironment implements ITokenProvider { */ private static Phase currentPhase = Phase.NOT_INITIALISED; + /** + * Current compatibility level + */ + private static CompatibilityLevel compatibility = Option.DEFAULT_COMPATIBILITY_LEVEL.getEnumValue(CompatibilityLevel.JAVA_6); + /** * Show debug header info on first environment construction */ @@ -426,7 +674,7 @@ public class MixinEnvironment implements ITokenProvider { /** * Logger */ - private final Logger logger = LogManager.getLogger("mixin"); + private static final Logger logger = LogManager.getLogger("mixin"); /** * The phase for this environment @@ -443,10 +691,7 @@ public class MixinEnvironment implements ITokenProvider { */ private final boolean[] options; - /** - * Error handlers for environment - */ - private final Set errorHandlers = new LinkedHashSet(); +// private final Map configs; /** * List of token provider classes @@ -462,6 +707,11 @@ public class MixinEnvironment implements ITokenProvider { * Internal tokens defined by this environment */ private final Map internalTokens = new HashMap(); + + /** + * Remappers for this environment + */ + private final RemapperChain remappers = new RemapperChain(); /** * Detected side @@ -481,19 +731,24 @@ public class MixinEnvironment implements ITokenProvider { */ private IClassNameTransformer nameTransformer; + /** + * Obfuscation context (refmap key to use in this environment) + */ + private String obfuscationContext = null; + MixinEnvironment(Phase phase) { this.phase = phase; - this.configsKey = MixinEnvironment.CONFIGS_KEY + "." + this.phase.name.toLowerCase(); + this.configsKey = Blackboard.Keys.CONFIGS + "." + this.phase.name.toLowerCase(); // Sanity check - Object version = Launch.blackboard.get(MixinBootstrap.INIT_KEY); + Object version = this.getVersion(); if (version == null || !MixinBootstrap.VERSION.equals(version)) { - throw new RuntimeException("Environment conflict, mismatched versions or you didn't call MixinBootstrap.init()"); + throw new MixinException("Environment conflict, mismatched versions or you didn't call MixinBootstrap.init()"); } // Also sanity check if (this.getClass().getClassLoader() != Launch.class.getClassLoader()) { - throw new RuntimeException("Attempted to init the mixin environment in the wrong classloader"); + throw new MixinException("Attempted to init the mixin environment in the wrong classloader"); } this.options = new boolean[Option.values().length]; @@ -510,17 +765,22 @@ public class MixinEnvironment implements ITokenProvider { private void printHeader(Object version) { Side side = this.getSide(); String codeSource = this.getCodeSource(); - this.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side); + MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side); if (this.getOption(Option.DEBUG_VERBOSE)) { PrettyPrinter printer = new PrettyPrinter(32); printer.add("SpongePowered MIXIN (Verbose debugging enabled)").centre().hr(); - printer.add("%25s : %s", "Code source", codeSource); - printer.add("%25s : %s", "Internal Version", version).hr(); + printer.kv("Code source", codeSource); + printer.kv("Internal Version", version); + printer.kv("Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr(); for (Option option : Option.values()) { - printer.add("%25s : %s%s", option.property, option.parent == null ? "" : " - ", this.getOption(option)); + StringBuilder indent = new StringBuilder(); + for (int i = 0; i < option.depth; i++) { + indent.append("- "); + } + printer.kv(option.property, "%s<%s>", indent, option); } - printer.hr().add("%25s : %s", "Detected Side", side); + printer.hr().kv("Detected Side", side); printer.print(System.err); } } @@ -546,10 +806,11 @@ public class MixinEnvironment implements ITokenProvider { * Get mixin configurations from the blackboard * * @return list of registered mixin configs + * @deprecated no replacement */ + @Deprecated public List getMixinConfigs() { - @SuppressWarnings("unchecked") - List mixinConfigs = (List) Launch.blackboard.get(this.configsKey); + List mixinConfigs = Blackboard.>get(this.configsKey); if (mixinConfigs == null) { mixinConfigs = new ArrayList(); Launch.blackboard.put(this.configsKey, mixinConfigs); @@ -562,23 +823,32 @@ public class MixinEnvironment implements ITokenProvider { * * @param config Name of configuration resource to add * @return fluent interface + * @deprecated use Mixins::addConfiguration instead */ + @Deprecated public MixinEnvironment addConfiguration(String config) { + MixinEnvironment.logger.warn("MixinEnvironment::addConfiguration is deprecated and will be removed. Use Mixins::addConfiguration instead!"); + Mixins.addConfiguration(config, this); + return this; + } + + void registerConfig(String config) { List configs = this.getMixinConfigs(); if (!configs.contains(config)) { configs.add(config); } - return this; } - + /** * Add a new error handler class to this environment * * @param handlerName Handler class to add * @return fluent interface + * @deprecated use Mixins::registerErrorHandlerClass */ + @Deprecated public MixinEnvironment registerErrorHandlerClass(String handlerName) { - this.errorHandlers.add(handlerName); + Mixins.registerErrorHandlerClass(handlerName); return this; } @@ -597,7 +867,7 @@ public class MixinEnvironment implements ITokenProvider { IEnvironmentTokenProvider provider = providerClass.newInstance(); this.registerTokenProvider(provider); } catch (Throwable th) { - this.logger.error("Error instantiating " + providerName, th); + MixinEnvironment.logger.error("Error instantiating " + providerName, th); } } return this; @@ -613,7 +883,7 @@ public class MixinEnvironment implements ITokenProvider { if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) { String providerName = provider.getClass().getName(); TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this); - this.logger.info("Adding new token provider {} to {}", providerName, this); + MixinEnvironment.logger.info("Adding new token provider {} to {}", providerName, this); this.tokenProviders.add(wrapper); this.tokenProviderClasses.add(providerName); Collections.sort(this.tokenProviders); @@ -647,9 +917,11 @@ public class MixinEnvironment implements ITokenProvider { * Get all registered error handlers for this environment * * @return set of error handler class names + * @deprecated use Mixins::getErrorHandlerClasses */ + @Deprecated public Set getErrorHandlerClasses() { - return Collections.unmodifiableSet(this.errorHandlers); + return Mixins.getErrorHandlerClasses(); } /** @@ -658,7 +930,7 @@ public class MixinEnvironment implements ITokenProvider { * @return active mixin transformer instance */ public Object getActiveTransformer() { - return Launch.blackboard.get(MixinEnvironment.TRANSFORMER_KEY); + return Blackboard.get(Blackboard.Keys.TRANSFORMER); } /** @@ -668,7 +940,7 @@ public class MixinEnvironment implements ITokenProvider { */ public void setActiveTransformer(IClassTransformer transformer) { if (transformer != null) { - Launch.blackboard.put(MixinEnvironment.TRANSFORMER_KEY, transformer); + Blackboard.put(Blackboard.Keys.TRANSFORMER, transformer); } } @@ -709,7 +981,7 @@ public class MixinEnvironment implements ITokenProvider { * @return current version */ public String getVersion() { - return (String)Launch.blackboard.get(MixinBootstrap.INIT_KEY); + return Blackboard.get(Blackboard.Keys.INIT); } /** @@ -742,6 +1014,40 @@ public class MixinEnvironment implements ITokenProvider { return option.getStringValue(); } + /** + * Set the obfuscation context + * + * @param context + */ + public void setObfuscationContext(String context) { + this.obfuscationContext = context; + } + + /** + * Get the current obfuscation context + */ + public String getObfuscationContext() { + return this.obfuscationContext; + } + + /** + * Get the current obfuscation context + */ + public String getRefmapObfuscationContext() { + String overrideObfuscationType = Option.OBFUSCATION_TYPE.getStringValue(); + if (overrideObfuscationType != null) { + return overrideObfuscationType; + } + return this.obfuscationContext; + } + + /** + * Get the remapper chain for this environment + */ + public RemapperChain getRemappers() { + return this.remappers; + } + /** * Invoke a mixin environment audit process */ @@ -804,7 +1110,7 @@ public class MixinEnvironment implements ITokenProvider { * list just once per environment and cache the result. */ private void buildTransformerDelegationList() { - this.logger.debug("Rebuilding transformer delegation list:"); + MixinEnvironment.logger.debug("Rebuilding transformer delegation list:"); this.transformers = new ArrayList(); for (IClassTransformer transformer : Launch.classLoader.getTransformers()) { String transformerName = transformer.getClass().getName(); @@ -815,19 +1121,20 @@ public class MixinEnvironment implements ITokenProvider { break; } } - if (include && !transformerName.contains(MixinTransformer.class.getName())) { - this.logger.debug(" Adding: {}", transformerName); + boolean ignoreTransformer = transformer.getClass().getAnnotation(Resource.class) != null; + if (include && !ignoreTransformer && !transformerName.contains(MixinTransformer.class.getName())) { + MixinEnvironment.logger.debug(" Adding: {}", transformerName); this.transformers.add(transformer); } else { - this.logger.debug(" Excluding: {}", transformerName); + MixinEnvironment.logger.debug(" Excluding: {}", transformerName); } } - this.logger.debug("Transformer delegation list created with {} entries", this.transformers.size()); + MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size()); for (IClassTransformer transformer : Launch.classLoader.getTransformers()) { if (transformer instanceof IClassNameTransformer) { - this.logger.debug("Found name transformer: {}", transformer.getClass().getName()); + MixinEnvironment.logger.debug("Found name transformer: {}", transformer.getClass().getName()); this.nameTransformer = (IClassNameTransformer) transformer; } } @@ -861,6 +1168,9 @@ public class MixinEnvironment implements ITokenProvider { if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) { MixinEnvironment.currentPhase = phase; MixinEnvironment.getEnvironment(phase); + + @SuppressWarnings("unused") + MixinLogger logSpy = new MixinLogger(); } } @@ -899,6 +1209,37 @@ public class MixinEnvironment implements ITokenProvider { return MixinEnvironment.currentEnvironment; } + /** + * Get the current compatibility level + */ + public static CompatibilityLevel getCompatibilityLevel() { + return MixinEnvironment.compatibility; + } + + /** + * Set desired compatibility level for the entire environment + * + * @param level Level to set, ignored if less than the current level + * @throws IllegalArgumentException if the specified level is not supported + * @deprecated set compatibility level in configuration + */ + @Deprecated + public static void setCompatibilityLevel(CompatibilityLevel level) throws IllegalArgumentException { + StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); + if (!"org.spongepowered.asm.mixin.transformer.MixinConfig".equals(stackTrace[2].getClassName())) { + MixinEnvironment.logger.warn("MixinEnvironment::setCompatibilityLevel is deprecated and will be removed. Set level via config instead!"); + } + + if (level != MixinEnvironment.compatibility && level.isAtLeast(MixinEnvironment.compatibility)) { + if (!level.isSupported()) { + throw new IllegalArgumentException("The requested compatibility level " + level + " could not be set. Level is not supported"); + } + + MixinEnvironment.compatibility = level; + MixinEnvironment.logger.info("Compatibility level set to {}", level); + } + } + /** * Internal callback * @@ -913,6 +1254,12 @@ public class MixinEnvironment implements ITokenProvider { MixinBootstrap.addProxy(); } + if (phase == Phase.DEFAULT) { + // remove appender + org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML"); + log.removeAppender(MixinLogger.appender); + } + MixinEnvironment.currentPhase = phase; MixinEnvironment.currentEnvironment = MixinEnvironment.getEnvironment(MixinEnvironment.getCurrentPhase()); } diff --git a/src/main/java/org/spongepowered/asm/mixin/Mixins.java b/src/main/java/org/spongepowered/asm/mixin/Mixins.java new file mode 100644 index 00000000..b45c6184 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/Mixins.java @@ -0,0 +1,139 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.Blackboard; +import org.spongepowered.asm.mixin.transformer.Config; + +import net.minecraft.launchwrapper.Launch; + +/** + * Entry point for registering global mixin resources. Compatibility with + * pre-0.6 versions is maintained via the methods on {@link MixinEnvironment} + * delegating to the methods here. + */ +public final class Mixins { + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Blackboard key storing mixin configs which are pending + */ + private static final String CONFIGS_KEY = Blackboard.Keys.CONFIGS + ".queue"; + + /** + * Error handlers for environment + */ + private static final Set errorHandlers = new LinkedHashSet(); + + private Mixins() {} + + public static void addConfigurations(String... configFiles) { + MixinEnvironment fallback = MixinEnvironment.getDefaultEnvironment(); + for (String configFile : configFiles) { + Mixins.createConfiguration(configFile, fallback); + } + } + + /** + * Add a mixin configuration resource + * + * @param configFile path to configuration resource + */ + public static void addConfiguration(String configFile) { + Mixins.createConfiguration(configFile, MixinEnvironment.getDefaultEnvironment()); + } + + @Deprecated + static void addConfiguration(String configFile, MixinEnvironment fallback) { + Mixins.createConfiguration(configFile, fallback); + } + + @SuppressWarnings("deprecation") + private static void createConfiguration(String configFile, MixinEnvironment fallback) { + Config config = null; + + try { + config = Config.create(configFile, fallback); + } catch (Exception ex) { + Mixins.logger.error("Error encountered reading mixin config " + configFile + ": " + ex.getClass().getName() + " " + ex.getMessage(), ex); + } + + Mixins.registerConfiguration(config); + } + + private static void registerConfiguration(Config config) { + if (config == null) { + return; + } + + MixinEnvironment env = config.getEnvironment(); + if (env != null) { + env.registerConfig(config.getName()); + } + Mixins.getConfigs().add(config); + } + + /** + * Get current pending configs set, only configs which have yet to be + * consumed are present in this set + */ + public static Set getConfigs() { + Set mixinConfigs = Blackboard.>get(Mixins.CONFIGS_KEY); + if (mixinConfigs == null) { + mixinConfigs = new LinkedHashSet(); + Launch.blackboard.put(Mixins.CONFIGS_KEY, mixinConfigs); + } + return mixinConfigs; + } + + /** + * Register a gloabl error handler class + * + * @param handlerName Fully qualified class name + */ + public static void registerErrorHandlerClass(String handlerName) { + if (handlerName != null) { + Mixins.errorHandlers.add(handlerName); + } + } + + /** + * Get current error handlers + */ + public static Set getErrorHandlerClasses() { + return Collections.unmodifiableSet(Mixins.errorHandlers); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/Mutable.java b/src/main/java/org/spongepowered/asm/mixin/Mutable.java new file mode 100644 index 00000000..0852426c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/Mutable.java @@ -0,0 +1,40 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Use in conjunction with {@link Final} to indicate that whilst a field is + * final in the target class, mutation within the mixin is intentional. + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Mutable { + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/Shadow.java b/src/main/java/org/spongepowered/asm/mixin/Shadow.java index d43eac06..79aadd1f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Shadow.java +++ b/src/main/java/org/spongepowered/asm/mixin/Shadow.java @@ -29,7 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.spongepowered.asm.mixin.transformer.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; /** * Used to indicate a Mixin class member which is acting as a placeholder for a diff --git a/src/main/java/org/spongepowered/asm/mixin/SoftOverride.java b/src/main/java/org/spongepowered/asm/mixin/SoftOverride.java index 05695ee1..5891ac77 100644 --- a/src/main/java/org/spongepowered/asm/mixin/SoftOverride.java +++ b/src/main/java/org/spongepowered/asm/mixin/SoftOverride.java @@ -29,7 +29,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Decorator for methods which override a method in a supermixin which the * containing mixin does not directly extend diff --git a/src/main/java/org/spongepowered/asm/mixin/Unique.java b/src/main/java/org/spongepowered/asm/mixin/Unique.java new file mode 100644 index 00000000..c23503fe --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/Unique.java @@ -0,0 +1,72 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation, when applied to a member method or field in a mixin, + * indicates that the member should never overwrite a matching membver in + * the target class. This indicates that the member differs from the normal + * "overlay-like" behaviour of mixins in general, and should only ever be + * added to the target. For public fields, the annotation has no + * effect. + * + *

Typical usage of this annotation would be to decorate a utility method in + * a mixin, or mark an interface-implementing method which must not overwrite a + * target if it exists (consider appropriate use of {@link Intrinsic} in these + * situations).

+ * + *

Because of the mixed usage, this annotation has different implications for + * methods with differing visibility:

+ * + *
+ *
public methods
+ *
public methods marked with this annotation are discarded if a + * matching target exists. A warning-level message is generated.
+ *
private and protected methods
+ *
non-public methods are renamed if a matching target method is + * found, this allows utility methods to be safely assigned meaningful names + * in code, but renamed if a conflict occurs when a mixin is applied.
+ *
+ * + *

Notes

+ * + *
    + *
  • To mark all methods in a mixin as unique, apply the annotation to the + * mixin itself
  • + *
  • Uniqueness can be defined on a per-interface basis by using an + * {@link Implements} annotation with unique set to true + *
  • + *
+ */ +@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Unique { + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IEnvironmentTokenProvider.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IEnvironmentTokenProvider.java index 3a9b9937..ba78f23f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IEnvironmentTokenProvider.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IEnvironmentTokenProvider.java @@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.extensibility; import org.spongepowered.asm.mixin.MixinEnvironment; - /** * Provides a token value into the attached environment */ diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfig.java index d14f49ad..0e39783c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfig.java @@ -26,6 +26,8 @@ package org.spongepowered.asm.mixin.extensibility; import java.util.Set; +import org.spongepowered.asm.mixin.MixinEnvironment; + /** * Interface for loaded mixin configurations */ @@ -35,6 +37,13 @@ public interface IMixinConfig { * Default priority for mixin configs and mixins */ public static final int DEFAULT_PRIORITY = 1000; + + /** + * Get the parent environment of this config + * + * @return the parent environment + */ + public abstract MixinEnvironment getEnvironment(); /** * Get the name of the file from which this configuration object was diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinErrorHandler.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinErrorHandler.java index 80111834..551b7a7b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinErrorHandler.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinErrorHandler.java @@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.extensibility; import org.apache.logging.log4j.Level; - /** * Interface for objects which want to perform custom behaviour when fatal mixin * errors occur. For example displaying a user-friendly error message @@ -52,8 +51,9 @@ public interface IMixinErrorHandler { WARN(Level.WARN), /** - * Throw a {@link org.spongepowered.asm.mixin.MixinApplyError} to halt - * further processing if possible + * Throw a + * {@link org.spongepowered.asm.mixin.throwables.MixinApplyError} to + * halt further processing if possible */ ERROR(Level.FATAL); @@ -64,6 +64,33 @@ public interface IMixinErrorHandler { } } + /** + * Called when an error occurs whilst initialising a mixin config. This + * allows the plugin to display more user-friendly error messages if + * required. + * + *

By default, when a critical error occurs the mixin processor will + * raise a warning if the config is not marked as "required" and will throw + * an {@link Error} if it is. This behaviour can be altered by returning + * different values from this method.

+ * + *

The original throwable which was caught is passed in via the + * th parameter and the default action is passed in to the + * action parameter. A plugin can choose to output a friendly message + * but leave the original behaviour intact (by returning null + * or returning action directly. Alternatively it may throw a + * different exception or error, or can reduce the severity of the error by + * returning a different {@link ErrorAction}.

+ * + * @param config Config being prepared when the error occurred + * @param th Throwable which was caught + * @param mixin Mixin which was being applied at the time of the error + * @param action Default action + * @return null to perform the default action (or return action) or new + * action to take + */ + public abstract ErrorAction onPrepareError(IMixinConfig config, Throwable th, IMixinInfo mixin, ErrorAction action); + /** * Called when an error occurs applying a mixin. This allows * the plugin to display more user-friendly error messages if required. @@ -88,6 +115,6 @@ public interface IMixinErrorHandler { * @return null to perform the default action (or return action) or new * action to take */ - public abstract ErrorAction onError(String targetClassName, Throwable th, IMixinInfo mixin, ErrorAction action); + public abstract ErrorAction onApplyError(String targetClassName, Throwable th, IMixinInfo mixin, ErrorAction action); } diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java index e5237400..a5612820 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java @@ -29,6 +29,9 @@ import java.util.List; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +/** + * Interface for MixinInfo, used in extensibility API + */ public interface IMixinInfo { /** @@ -102,4 +105,5 @@ public interface IMixinInfo { * @return the phase */ public abstract Phase getPhase(); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IRemapper.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IRemapper.java new file mode 100644 index 00000000..69a412b0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IRemapper.java @@ -0,0 +1,84 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.extensibility; + +/** + * Interface for remap chain participants + */ +public interface IRemapper { + + /** + * Map method name to the new name. Subclasses can override. + * + * @param owner owner of the method. + * @param name name of the method. + * @param desc descriptor of the method. + * @return new name of the method + */ + public abstract String mapMethodName(String owner, String name, String desc); + + /** + * Map field name to the new name. Subclasses can override. + * + * @param owner owner of the field. + * @param name name of the field + * @param desc descriptor of the field + * @return new name of the field. + */ + public abstract String mapFieldName(String owner, String name, String desc); + + /** + * Map type name to the new name. Subclasses can override. + * + * @param typeName Class name to convert + * @return new name for the class + */ + public abstract String map(String typeName); + + /** + * Convert a mapped type name back to the original obfuscated name + * + * @param typeName Class name to convert + * @return old name for the class + */ + public abstract String unmap(String typeName); + + /** + * Convert a descriptor to remapped form + * + * @param desc descriptor to convert + * @return new descriptor + */ + public abstract String mapDesc(String desc); + + /** + * Convert a descriptor back to the original obfuscated form + * + * @param desc descriptor to convert + * @return old descriptor + */ + public abstract String unmapDesc(String desc); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java b/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java index 3721a03a..149c156f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java @@ -27,7 +27,6 @@ package org.spongepowered.asm.mixin.injection; import java.lang.annotation.ElementType; import java.lang.annotation.Target; - /** * Indicates that a local capture injector should coerce top-level primitive * types to covariant types. diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java new file mode 100644 index 00000000..8600d46e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java @@ -0,0 +1,111 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Annotation for specifying the injection point for an {@link ModifyConstant} + * injector. Leaving all values unset causes the injection point to match all + * constants with the same type as the {@link ModifyConstant} handler's return + * type. + * + *

To match a specific constant, specify the appropriate value for the + * appropriate argument. Specifying values of different types will cause an + * error to be raised by the injector.

+ */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Constant { + + /** + * Causes this injector to match ACONST_NULL (null object) literals + * + * @return true to match null + */ + public boolean nullValue() default false; + + /** + * Specify an integer constant to match, includes byte and short values + * + * @return integer value to match + */ + public int intValue() default 0; + + /** + * Specify a float constant to match + * + * @return float value to match + */ + public float floatValue() default 0.0F; + + /** + * Specify a long constant to match + * + * @return long value to match + */ + public long longValue() default 0L; + + /** + * Specify a double constant to match + * + * @return double value to match + */ + public double doubleValue() default 0.0; + + /** + * Specify a String constant to match + * + * @return string value to match + */ + public String stringValue() default ""; + + /** + * Specify a type literal to match + * + * @return type literal to match + */ + public Class classValue() default Object.class; + + /** + * Ordinal offset. Many InjectionPoints will return every opcode matching + * their criteria, specifying ordinal allows a particular opcode to + * be identified from the returned list. The default value of -1 does not + * alter the behaviour and returns all matching opcodes. Specifying a value + * of 0 or higher returns only the requested opcode (if one exists: + * for example specifying an ordinal of 4 when only 2 opcodes are matched by + * the InjectionPoint is not going to work particularly well!) + * + * @return ordinal value for supported InjectionPoint types + */ + public int ordinal() default -1; + + /** + * @return true to enable verbose debug logging for this injection point + */ + public boolean log() default false; +} + + diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Group.java b/src/main/java/org/spongepowered/asm/mixin/injection/Group.java new file mode 100644 index 00000000..fa3c2712 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Group.java @@ -0,0 +1,65 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation can be used on any injector callback to define a value for + * total required injections across multiple callbacks. Much like + * {@link Inject#require()} it can be used to treat an injection failure as a + * critical error, however the require value specified applies to all + * injectors in the group. This can be used, for example, for 'surrogate' + * injectors where multiple injectors exist but only one is expected to succeed. + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.CLASS) +public @interface Group { + + /** + * The name of the injector group, any string + * + * @return group name + */ + public String name() default ""; + + /** + * Minimum required injections for this injector group + * + * @return required min value + */ + public int min() default -1; + + /** + * Maximum allowed injections for this injector group + * + * @return allowed max value + */ + public int max() default -1; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java index d49b4c16..aa7f25a1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java @@ -29,8 +29,12 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ConstraintParser.Constraint; /** * Specifies that this mixin method should inject a callback (or @@ -41,6 +45,15 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Retention(RetentionPolicy.RUNTIME) public @interface Inject { + /** + * The identifier for this injector, can be retrieved via the + * {@link CallbackInfo#getId} accessor. If not specified, the ID defaults to + * the target method name. + * + * @return the injector id to use + */ + public String id() default ""; + /** * String representation of a * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo @@ -111,7 +124,6 @@ public @interface Inject { */ public LocalCapture locals() default LocalCapture.NO_CAPTURE; - /** * By default, the annotation processor will attempt to locate an * obfuscation mapping for all {@link Inject} methods since it is @@ -128,4 +140,47 @@ public @interface Inject { * obfuscation mappings for this annotation */ public boolean remap() default true; + + /** + * In general, injectors are intended to "fail soft" in that a failure to + * locate the injection point in the target method is not considered an + * error condition. Another transformer may have changed the method + * structure or any number of reasons may cause an injection to fail. This + * also makes it possible to define several injections to achieve the same + * task given expected mutation of the target class and the + * injectors which fail are simply ignored. + * + *

However, this behaviour is not always desirable. For example, if your + * application depends on a particular injection succeeding you may wish to + * detect the injection failure as an error condition. This argument is thus + * provided to allow you to stipulate a minimum number of successful + * injections for this callback handler. If the number of injections + * specified is not achieved then an {@link InjectionError} is thrown at + * application time. Use this option with care.

+ * + * @return Minimum required number of injected callbacks, default specified + * by the containing config + */ + public int require() default -1; + + /** + * Like {@link #require()} but only enabled if the + * {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set + * to true and defaults to 1. Use this option during debugging to + * perform simple checking of your injectors. Causes the injector to throw + * a {@link InvalidInjectionException} if the expected number of injections + * is not realised. + * + * @return Minimum number of expected callbacks, default 1 + */ + public int expect() default 1; + + /** + * Returns constraints which must be validated for this injector to + * succeed. See {@link Constraint} for details of constraint formats. + * + * @return Constraints for this annotation + */ + public String constraints() default ""; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java new file mode 100644 index 00000000..006e9cec --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionNodes.java @@ -0,0 +1,262 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Used to keep track of instruction nodes in a {@link Target} method which are + * targetted by various types of injector. This collection is populated during + * the first injector pass and allows injectors to keep track of their targets + * even when the target method is being manipulated by other injectors. + */ +public class InjectionNodes extends ArrayList { + + /** + * Never gonna give you up + */ + private static final long serialVersionUID = 1L; + + /** + * A node targetted by one or more injectors. Using this wrapper allows + * injectors to be aware of when their target node is removed or replace by + * another injector. It also allows injectors to decorate certain nodes with + * custom metadata to allow arbitration between injectors to take place. + */ + public static class InjectionNode implements Comparable { + + /** + * The original node targetted + */ + private final AbstractInsnNode originalTarget; + + /** + * Initially set to the {@link #originalTarget}, if an injector removes + * or replaces this node then points to the current target. Can be null + * if the node is removed. + */ + private AbstractInsnNode currentTarget; + + /** + * Injector decorations on this node + */ + private Map decorations; + + /** + * Create a new node wrapper for the specified target node + * + * @param node target node + */ + public InjectionNode(AbstractInsnNode node) { + this.currentTarget = this.originalTarget = node; + } + + /** + * Get the original target of this node + */ + public AbstractInsnNode getOriginalTarget() { + return this.originalTarget; + } + + /** + * Get the current target of this node, can be null if the node was + * replaced + */ + public AbstractInsnNode getCurrentTarget() { + return this.currentTarget; + } + + /** + * Replace this node with the specified target + * + * @param target new node + */ + public InjectionNode replace(AbstractInsnNode target) { + this.currentTarget = target; + return this; + } + + /** + * Remove the node + */ + public InjectionNode remove() { + this.currentTarget = null; + return this; + } + + /** + * Checks whether the original or current target of this node match the + * specified node + * + * @param node node to check + * @return true if the supplied node matches either of this node's + * internal identities + */ + public boolean matches(AbstractInsnNode node) { + return this.originalTarget == node || this.currentTarget == node; + } + + /** + * Get whether this node has been replaced + */ + public boolean isReplaced() { + return this.originalTarget != this.currentTarget; + } + + /** + * Get whether this node has been removed + */ + public boolean isRemoved() { + return this.currentTarget == null; + } + + /** + * Decorate this node with arbitrary metadata for injector arbitration + * + * @param key meta key + * @param value meta value + */ + public InjectionNode decorate(K key, V value) { + if (this.decorations == null) { + this.decorations = new HashMap(); + } + this.decorations.put(key, value); + return this; + } + + /** + * Get whether this node is decorated with the specified key + * + * @param key meta key + * @return true if the specified decoration exists + */ + public boolean hasDecoration(K key) { + return this.decorations != null && this.decorations.get(key) != null; + } + + /** + * Get the specified decoration + * + * @param key meta key + * @return decoration value or null if absent + */ + @SuppressWarnings("unchecked") + public V getDecoration(K key) { + return (V) (this.decorations == null ? null : this.decorations.get(key)); + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(InjectionNode other) { + return other == null ? Integer.MAX_VALUE : this.hashCode() - other.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("InjectionNode[%s]", ASMHelper.getNodeDescriptionForDebug(this.currentTarget)); + } + + } + + /** + * Add a tracked node to this collection if it does not already exist + * + * @param node Instruction node to add + * @return wrapper for the specified node + */ + public InjectionNode add(AbstractInsnNode node) { + InjectionNode injectionNode = this.get(node); + if (injectionNode == null) { + injectionNode = new InjectionNode(node); + this.add(injectionNode); + } + return injectionNode; + } + + /** + * Get a tracked node from this collection if it already exists, returns + * null if the node is not tracked + * + * @param node instruction node + * @return wrapper node or null if not tracked + */ + public InjectionNode get(AbstractInsnNode node) { + for (InjectionNode injectionNode : this) { + if (injectionNode.matches(node)) { + return injectionNode; + } + } + return null; + } + + /** + * Get whether this collection contains a mapping for the specified insn + * + * @param node instruction node to check + * @return true if a wrapper exists for the node + */ + public boolean contains(AbstractInsnNode node) { + return this.get(node) != null; + } + + /** + * Replace the specified node with the new node, does not update the wrapper + * if no wrapper exists for oldNode + * + * @param oldNode node being replaced + * @param newNode node to replace with + */ + public void replace(AbstractInsnNode oldNode, AbstractInsnNode newNode) { + InjectionNode injectionNode = this.get(oldNode); + if (injectionNode != null) { + injectionNode.replace(newNode); + } + } + + /** + * Mark the specified node as removed, does not update the wrapper if no + * wrapper exists + * + * @param node node being removed + */ + public void remove(AbstractInsnNode node) { + InjectionNode injectionNode = this.get(node); + if (injectionNode != null) { + injectionNode.remove(); + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index ff135a4a..8bec0619 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.mixin.injection; +import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; @@ -31,9 +32,14 @@ import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; +import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; +import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.points.AfterInvoke; import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; import org.spongepowered.asm.mixin.injection.points.BeforeInvoke; @@ -43,6 +49,7 @@ import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke; import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint; import org.spongepowered.asm.mixin.injection.points.MethodHead; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; @@ -143,12 +150,12 @@ public abstract class InjectionPoint { super(points); } + @SuppressWarnings("unchecked") @Override public boolean find(String desc, InsnList insns, Collection nodes) { boolean found = false; - @SuppressWarnings({ "unchecked", "rawtypes" }) - ArrayList[] allNodes = new ArrayList[this.components.length]; + ArrayList[] allNodes = (ArrayList[]) Array.newInstance(ArrayList.class, this.components.length); for (int i = 0; i < this.components.length; i++) { allNodes[i] = new ArrayList(); @@ -308,12 +315,15 @@ public abstract class InjectionPoint { * * @param mixin Data for the mixin containing the annotation, used to obtain * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation * @param at {@link At} annotation to parse information from * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ - public static InjectionPoint parse(MixinTargetContext mixin, At at) { - return InjectionPoint.parse(mixin, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode()); + public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, At at) { + List args = Arrays.asList(at.args()); + return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), args, at.target(), at.ordinal(), at.opcode()); } /** @@ -322,11 +332,13 @@ public abstract class InjectionPoint { * * @param mixin Data for the mixin containing the annotation, used to obtain * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation * @param node {@link At} annotation to parse information from * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ - public static InjectionPoint parse(MixinTargetContext mixin, AnnotationNode node) { + public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, AnnotationNode node) { String at = ASMHelper.getAnnotationValue(node, "value"); List args = ASMHelper.>getAnnotationValue(node, "args"); String target = ASMHelper.getAnnotationValue(node, "target", ""); @@ -339,7 +351,7 @@ public abstract class InjectionPoint { args = ImmutableList.of(); } - return InjectionPoint.parse(mixin, at, shift, by, args, target, ordinal, opcode); + return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, ordinal, opcode); } /** @@ -348,6 +360,8 @@ public abstract class InjectionPoint { * * @param mixin Data for the mixin containing the annotation, used to obtain * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation * @param at Injection point specifier * @param shift Shift type to apply * @param by Amount of shift to apply for the BY shift type @@ -358,9 +372,9 @@ public abstract class InjectionPoint { * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ - public static InjectionPoint parse(MixinTargetContext mixin, String at, At.Shift shift, int by, + public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, At.Shift shift, int by, List args, String target, int ordinal, int opcode) { - InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode); + InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, ordinal, opcode); InjectionPoint point = null; if (BeforeFieldAccess.CODE.equals(at)) { @@ -379,6 +393,12 @@ public abstract class InjectionPoint { point = new MethodHead(data); } else if (AfterInvoke.CODE.equals(at)) { point = new AfterInvoke(data); + } else if (BeforeLoadLocal.CODE.equals(at)) { + LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent); + point = new BeforeLoadLocal(mixin, Type.getReturnType(method.desc), discriminator, data); + } else if (AfterStoreLocal.CODE.equals(at)) { + LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent); + point = new AfterStoreLocal(mixin, Type.getReturnType(method.desc), discriminator, data); } else if (at.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { try { @SuppressWarnings("unchecked") Class cls = (Class) Class.forName(at); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectorGroupInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectorGroupInfo.java new file mode 100644 index 00000000..e0442e2c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectorGroupInfo.java @@ -0,0 +1,274 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Information store for injector groups + */ +public class InjectorGroupInfo { + + /** + * Storage for injector groups + */ + public static final class Map extends HashMap { + + private static final long serialVersionUID = 1L; + + private static final InjectorGroupInfo NO_GROUP = new InjectorGroupInfo("NONE", true); + + @Override + public InjectorGroupInfo get(Object key) { + return this.forName(key.toString()); + } + + /** + * Get group for the specified name, creates the group in this map if + * it does not already exist + * + * @param name Name of group to fetch + * @return Existing group or new group if none was previously declared + */ + public InjectorGroupInfo forName(String name) { + InjectorGroupInfo value = super.get(name); + if (value == null) { + value = new InjectorGroupInfo(name); + this.put(name, value); + } + return value; + } + + /** + * Parse a group from the specified method, use the default group name + * if no group name is specified on the annotation + * + * @param method (Possibly) annotated method + * @param defaultGroup Default group name to use + * @return Group or NO_GROUP if no group + */ + public InjectorGroupInfo parseGroup(MethodNode method, String defaultGroup) { + return this.parseGroup(ASMHelper.getInvisibleAnnotation(method, Group.class), defaultGroup); + } + + /** + * Parse a group from the specified annotation, use the default group + * name if no group name is specified on the annotation + * + * @param annotation Annotation or null + * @param defaultGroup Default group name to use + * @return Group or NO_GROUP if no group + */ + public InjectorGroupInfo parseGroup(AnnotationNode annotation, String defaultGroup) { + if (annotation == null) { + return InjectorGroupInfo.Map.NO_GROUP; + } + + String name = ASMHelper.getAnnotationValue(annotation, "name"); + if (name == null || name.isEmpty()) { + name = defaultGroup; + } + InjectorGroupInfo groupInfo = this.forName(name); + + Integer min = ASMHelper.getAnnotationValue(annotation, "min"); + if (min != null && min.intValue() != -1) { + groupInfo.setMinRequired(min.intValue()); + } + + Integer max = ASMHelper.getAnnotationValue(annotation, "max"); + if (max != null && max.intValue() != -1) { + groupInfo.setMaxAllowed(max.intValue()); + } + + return groupInfo; + } + + /** + * Validate all groups in this collection + * + * @throws InjectionValidationException if validation fails + */ + public void validateAll() throws InjectionValidationException { + for (InjectorGroupInfo group : this.values()) { + group.validate(); + } + } + + } + + /** + * Group name + */ + private final String name; + + /** + * Members of this group + */ + private final List members = new ArrayList(); + + /** + * True if this is the default group + */ + private final boolean isDefault; + + /** + * Number of callbacks we require injected across this group + */ + private int minCallbackCount = -1; + + /** + * Maximum number of callbacks allowed across this group + */ + private int maxCallbackCount = Integer.MAX_VALUE; + + public InjectorGroupInfo(String name) { + this(name, false); + } + + InjectorGroupInfo(String name, boolean flag) { + this.name = name; + this.isDefault = flag; + } + + @Override + public String toString() { + return String.format("@Group(name=%s, min=%d, max=%d)", this.getName(), this.getMinRequired(), this.getMaxAllowed()); + } + + public boolean isDefault() { + return this.isDefault; + } + + public String getName() { + return this.name; + } + + public int getMinRequired() { + return Math.max(this.minCallbackCount, 1); + } + + public int getMaxAllowed() { + return Math.min(this.maxCallbackCount, Integer.MAX_VALUE); + } + + /** + * Get all members of this group as a read-only collection + * + * @return read-only view of group members + */ + public Collection getMembers() { + return Collections.unmodifiableCollection(this.members); + } + + /** + * Set the required minimum value for this group. Since this is normally + * done on the first {@link Group} annotation it is considered a + * warning-level event if a later annotation sets a different value. The + * highest value specified on all annotations is always used. + * + * @param min new value for min required + */ + public void setMinRequired(int min) { + if (min < 1) { + throw new IllegalArgumentException("Cannot set zero or negative value for injector group min count. Attempted to set min=" + + min + " on " + this); + } + if (this.minCallbackCount > 0 && this.minCallbackCount != min) { + LogManager.getLogger("mixin").warn("Conflicting min value '{}' on @Group({}), previously specified {}", min, this.name, + this.minCallbackCount); + } + this.minCallbackCount = Math.max(this.minCallbackCount, min); + } + + /** + * Set the required minimum value for this group. Since this is normally + * done on the first {@link Group} annotation it is considered a + * warning-level event if a later annotation sets a different value. The + * highest value specified on all annotations is always used. + * + * @param max new value for max allowed + */ + public void setMaxAllowed(int max) { + if (max < 1) { + throw new IllegalArgumentException("Cannot set zero or negative value for injector group max count. Attempted to set max=" + + max + " on " + this); + } + if (this.maxCallbackCount < Integer.MAX_VALUE && this.maxCallbackCount != max) { + LogManager.getLogger("mixin").warn("Conflicting max value '{}' on @Group({}), previously specified {}", max, this.name, + this.maxCallbackCount); + } + this.maxCallbackCount = Math.min(this.maxCallbackCount, max); + } + + /** + * Add a new member to this group + * + * @param member injector to add + * @return fluent interface + */ + public InjectorGroupInfo add(InjectionInfo member) { + this.members.add(member); + return this; + } + + /** + * Validate all members in this group + * + * @return fluent interface + * @throws InjectionValidationException if validation fails + */ + public InjectorGroupInfo validate() throws InjectionValidationException { + if (this.members.size() == 0) { + // I have no idea how we got here, but it's not an error :/ + return this; + } + + int total = 0; + for (InjectionInfo member : this.members) { + total += member.getInjectedCallbackCount(); + } + + int min = this.getMinRequired(); + int max = this.getMaxAllowed(); + if (total < min) { + throw new InjectionValidationException(this, String.format("expected %d invocation(s) but only %d succeeded", min, total)); + } else if (total > max) { + throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total)); + } + + return this; + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java index 0ce6f5da..d976ed9e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -29,6 +29,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ConstraintParser.Constraint; + /** * Specifies that this mixin method should inject an argument modifier to itself * in the target method(s) identified by {@link #method}. @@ -86,4 +91,47 @@ public @interface ModifyArg { * obfuscation mappings for this annotation */ public boolean remap() default true; + + /** + * In general, injectors are intended to "fail soft" in that a failure to + * locate the injection point in the target method is not considered an + * error condition. Another transformer may have changed the method + * structure or any number of reasons may cause an injection to fail. This + * also makes it possible to define several injections to achieve the same + * task given expected mutation of the target class and the + * injectors which fail are simply ignored. + * + *

However, this behaviour is not always desirable. For example, if your + * application depends on a particular injection succeeding you may wish to + * detect the injection failure as an error condition. This argument is thus + * provided to allow you to stipulate a minimum number of successful + * injections for this callback handler. If the number of injections + * specified is not achieved then an {@link InjectionError} is thrown at + * application time. Use this option with care.

+ * + * @return Minimum required number of injected callbacks, default specified + * by the containing config + */ + public int require() default -1; + + /** + * Like {@link #require()} but only enabled if the + * {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set + * to true and defaults to 1. Use this option during debugging to + * perform simple checking of your injectors. Causes the injector to throw + * a {@link InvalidInjectionException} if the expected number of injections + * is not realised. + * + * @return Minimum number of expected callbacks, default 1 + */ + public int expect() default 1; + + /** + * Returns constraints which must be validated for this injector to + * succeed. See {@link Constraint} for details of constraint formats. + * + * @return Constraints for this annotation + */ + public String constraints() default ""; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java new file mode 100644 index 00000000..a5146bad --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java @@ -0,0 +1,135 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ConstraintParser.Constraint; + +/** + * Specifies that this mixin method should inject a constant modifier callback + * to itself in the target method(s) identified by {@link #method} at the + * specified LDC (or specialised const opcode) instruction in order to adjust + * the constant value returned. + * + *

ModifyConstant callbacks should always take one argument of the + * appropriate constant type and return the same type. For example a + * ModifyConstant for a local of type {@link String} should have the + * signature:

+ * + * private String methodName(String variable) { ... + * + *

The callback receives the original value of the constant, and should + * return the new value.

+ */ + +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ModifyConstant { + + /** + * String representation of a + * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo + * MemberInfo} which identifies the target method. + * + * @return method to inject into + */ + public String method(); + + /** + * Discriminator for the constant to match (injection point), if not + * specified then all constants matching the annotated handler's return type + * are matched + * + * @return the constant discriminator + */ + public Constant constant() default @Constant; + + /** + * By default, the annotation processor will attempt to locate an + * obfuscation mapping for all {@link ModifyConstant} methods since it is + * anticipated that in general the target of a {@link ModifyConstant} + * annotation will be an obfuscated method in the target class. However + * since it is possible to also apply mixins to non-obfuscated targets (or + * non- obfuscated methods in obfuscated targets, such as methods added by + * Forge) it may be necessary to suppress the compiler error which would + * otherwise be generated. Setting this value to false will cause + * the annotation processor to skip this annotation when attempting to build + * the obfuscation table for the mixin. + * + * @return True to instruct the annotation processor to search for + * obfuscation mappings for this annotation + */ + public boolean remap() default true; + + /** + * In general, injectors are intended to "fail soft" in that a failure to + * locate the injection point in the target method is not considered an + * error condition. Another transformer may have changed the method + * structure or any number of reasons may cause an injection to fail. This + * also makes it possible to define several injections to achieve the same + * task given expected mutation of the target class and the + * injectors which fail are simply ignored. + * + *

However, this behaviour is not always desirable. For example, if your + * application depends on a particular injection succeeding you may wish to + * detect the injection failure as an error condition. This argument is thus + * provided to allow you to stipulate a minimum number of successful + * injections for this callback handler. If the number of injections + * specified is not achieved then an {@link InjectionError} is thrown at + * application time. Use this option with care.

+ * + * @return Minimum required number of injected callbacks, default specified + * by the containing config + */ + public int require() default -1; + + /** + * Like {@link #require()} but only enabled if the + * {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set + * to true and defaults to 1. Use this option during debugging to + * perform simple checking of your injectors. Causes the injector to throw + * a {@link InvalidInjectionException} if the expected number of injections + * is not realised. + * + * @return Minimum number of expected callbacks, default 1 + */ + public int expect() default 1; + + /** + * Returns constraints which must be validated for this injector to + * succeed. See {@link Constraint} for details of constraint formats. + * + * @return Constraints for this annotation + */ + public String constraints() default ""; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java new file mode 100644 index 00000000..6d3c0cd8 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -0,0 +1,198 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ConstraintParser.Constraint; + +/** + * Specifies that this mixin method should inject a variable modifier callback + * to itself in the target method(s) identified by {@link #method}. + * + *

ModifyVariable callbacks should always take one argument of the + * type to capture and return the same type. For example a ModifyVariable + * for a local of type {@link String} should have the signature:

+ * + * private String methodName(String variable) { ... + * + *

The callback receives the current value of the local variable, and should + * return the new value.

+ * + *

The injector has two operating modes, explicit and implicit + * , and can operate either on the entire LVT or on the method arguments + * only

. + * + *

In explicit mode, the variable to capture can be specified by + * specifying values for the discriminator arguments {@link #ordinal}, + * {@link #index} and {@link #name}. The injector uses the discriminators in + * order to attempt to locate the variable to capture. If no local variable + * matches any discriminators, the capture fails.

+ * + *

If no values for the capture discrimiators are specified, the injector + * operates in implicit mode. If exactly one variable of the capture + * type exists in the target LVT, then capture will succeed. However, if more + * than one variable of the required type is encountered in the LVT then an + * {@link InvalidInjectionException} is thrown.

+ */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ModifyVariable { + + /** + * String representation of a + * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo + * MemberInfo} which identifies the target method. + * + * @return target method + */ + public String method(); + + /** + * An {@link At} annotation which describes the {@link InjectionPoint} in + * the target method. The specified {@link InjectionPoint} must only + * return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances + * and an exception will be thrown if this is not the case. + * + * @return {@link At} which identifies the target method invocation + */ + public At at(); + + /** + * When creating a {@link ModifyVariable} callback, you may wish to first + * inspect the local variable table in the target method at the injection + * point. Set this value to true to print the local variable table + * and perform no injection. + * + * @return true to print the LVT to the console + */ + public boolean print() default false; + + /** + * Gets the local variable ordinal by type. For example, if there are 3 + * {@link String} arguments in the local variable table, ordinal 0 specifies + * the first, 1 specifies the second, etc. Use ordinal when the + * index within the LVT is known. Takes precedence over {@link #index}. + * + * @return variable ordinal + */ + public int ordinal() default -1; + + /** + * Gets the absolute index of the local variable within the local variable + * table to capture. The local variable at the specified index must be of + * the same type as the capture. Takes precedence over {@link #name}. + * + * @return argument index to modify or -1 for automatic + */ + public int index() default -1; + + /** + * Gets the name of the variable to capture. Only used if the variable + * cannot be located via {@link #ordinal} or {@link #index}. + * + * @return possible names to capture, only useful when the LVT in the target + * method is known to be complete. + */ + public String[] name() default {}; + + /** + * Under normal circumstances the injector will consider all local variables + * including method arguments and all other local variables. This involves + * reading (and possibly generating) the local variable table for the method + * which can have mixed results. Set this value to true to only + * consider method arguments. + * + * @return true if this injector should only consider method arguments and + * not all locals. + */ + public boolean argsOnly() default false; + + /** + * By default, the annotation processor will attempt to locate an + * obfuscation mapping for all {@link ModifyVariable} methods since it is + * anticipated that in general the target of a {@link ModifyVariable} + * annotation will be an obfuscated method in the target class. However + * since it is possible to also apply mixins to non-obfuscated targets (or + * non- obfuscated methods in obfuscated targets, such as methods added by + * Forge) it may be necessary to suppress the compiler error which would + * otherwise be generated. Setting this value to false will cause + * the annotation processor to skip this annotation when attempting to build + * the obfuscation table for the mixin. + * + * @return True to instruct the annotation processor to search for + * obfuscation mappings for this annotation + */ + public boolean remap() default true; + + /** + * In general, injectors are intended to "fail soft" in that a failure to + * locate the injection point in the target method is not considered an + * error condition. Another transformer may have changed the method + * structure or any number of reasons may cause an injection to fail. This + * also makes it possible to define several injections to achieve the same + * task given expected mutation of the target class and the + * injectors which fail are simply ignored. + * + *

However, this behaviour is not always desirable. For example, if your + * application depends on a particular injection succeeding you may wish to + * detect the injection failure as an error condition. This argument is thus + * provided to allow you to stipulate a minimum number of successful + * injections for this callback handler. If the number of injections + * specified is not achieved then an {@link InjectionError} is thrown at + * application time. Use this option with care.

+ * + * @return Minimum required number of injected callbacks, default specified + * by the containing config + */ + public int require() default -1; + + /** + * Like {@link #require()} but only enabled if the + * {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set + * to true and defaults to 1. Use this option during debugging to + * perform simple checking of your injectors. Causes the injector to throw + * a {@link InvalidInjectionException} if the expected number of injections + * is not realised. + * + * @return Minimum number of expected callbacks, default 1 + */ + public int expect() default 1; + + /** + * Returns constraints which must be validated for this injector to + * succeed. See {@link Constraint} for details of constraint formats. + * + * @return Constraints for this annotation + */ + public String constraints() default ""; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 19198901..8ffe9ced 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -29,9 +29,16 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ConstraintParser.Constraint; + /** *

Specifies that this mixin method should redirect the specified - * {@link #method} call to the method decorated with this annotation.

+ * method call or field access to the method decorated with this annotation.

+ * + *

Method Redirect Mode

* *

The handler method signature must match the hooked method precisely * but prepended with an arg of the owning object's type to accept the @@ -68,6 +75,42 @@ import java.lang.annotation.Target; *

public boolean barProxy(Foo someObject, int abc, int def,
  *   int someInt, String someString)
* + * + *

Field Access Redirect Mode

+ * + *

The handler method signature varies depending on whether the redirector is + * handling a field write (PUTFIELD, PUTSTATIC) or a + * field read (GETFIELD, GETSTATIC).

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Operation (OPCODE)Handler signature
Read static field (GETSTATIC)private FieldType getFieldValue()
Read instance field (GETFIELD)private FieldType getFieldValue(OwnerType + * owner)
Write static field (PUTSTATIC)private void setFieldValue(FieldType value)
Write instance field (PUTFIELD)private void getFieldValue(OwnerType + * owner, FieldType value)
+ * + *

It is also possible to capture the arguments of the target method in + * addition to the arguments being passed to the method call (for example in + * the code above this would be the someInt and someString + * arguments) by appending the arguments to the method signature.

*/ @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @@ -108,4 +151,47 @@ public @interface Redirect { * obfuscation mappings for this annotation */ public boolean remap() default true; + + /** + * In general, injectors are intended to "fail soft" in that a failure to + * locate the injection point in the target method is not considered an + * error condition. Another transformer may have changed the method + * structure or any number of reasons may cause an injection to fail. This + * also makes it possible to define several injections to achieve the same + * task given expected mutation of the target class and the + * injectors which fail are simply ignored. + * + *

However, this behaviour is not always desirable. For example, if your + * application depends on a particular injection succeeding you may wish to + * detect the injection failure as an error condition. This argument is thus + * provided to allow you to stipulate a minimum number of successful + * injections for this callback handler. If the number of injections + * specified is not achieved then an {@link InjectionError} is thrown at + * application time. Use this option with care.

+ * + * @return Minimum required number of injected callbacks, default specified + * by the containing config + */ + public int require() default -1; + + /** + * Like {@link #require()} but only enabled if the + * {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set + * to true and defaults to 1. Use this option during debugging to + * perform simple checking of your injectors. Causes the injector to throw + * a {@link InvalidInjectionException} if the expected number of injections + * is not realised. + * + * @return Minimum number of expected callbacks, default 1 + */ + public int expect() default 1; + + /** + * Returns constraints which must be validated for this injector to + * succeed. See {@link Constraint} for details of constraint formats. + * + * @return Constraints for this annotation + */ + public String constraints() default ""; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Surrogate.java b/src/main/java/org/spongepowered/asm/mixin/injection/Surrogate.java index ee583064..e8c6f54b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Surrogate.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Surrogate.java @@ -29,7 +29,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Annotation used to decorate surrogate injector methods. See * {@link Inject#locals()} for information. diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java index fc3735a6..e05cee7e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java @@ -25,6 +25,8 @@ package org.spongepowered.asm.mixin.injection.callback; import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.util.Constants; /** * CallbackInfo instances are passed to callbacks in order to provide @@ -34,9 +36,6 @@ import org.spongepowered.asm.lib.Type; */ public class CallbackInfo implements Cancellable { - protected static final String STRING = "Ljava/lang/String;"; - protected static final String OBJECT = "Ljava/lang/Object;"; - /** * Method name being injected into, this is useful if a single callback is * injecting into multiple methods. @@ -65,11 +64,13 @@ public class CallbackInfo implements Cancellable { } /** - * Get the method name where this callback originated + * Get the ID of the injector which defined this callback. This defaults to + * the method name but can be overridden by specifying the {@link Inject#id} + * parameter on the injector * - * @return the name of the calling method + * @return the injector ID */ - public String getName() { + public String getId() { return this.name; } @@ -118,15 +119,15 @@ public class CallbackInfo implements Cancellable { return CallbackInfo.getConstructorDescriptor(); } - if (returnType.getSort() == Type.OBJECT) { - return String.format("(%sZ%s)V", CallbackInfo.STRING, CallbackInfo.OBJECT); + if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { + return String.format("(%sZ%s)V", Constants.STRING, Constants.OBJECT); } - return String.format("(%sZ%s)V", CallbackInfo.STRING, returnType.getDescriptor()); + return String.format("(%sZ%s)V", Constants.STRING, returnType.getDescriptor()); } static String getConstructorDescriptor() { - return String.format("(%sZ)V", CallbackInfo.STRING); + return String.format("(%sZ)V", Constants.STRING); } static String getIsCancelledMethodName() { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java index b0e769e9..588baf42 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.injection.callback; import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.util.Constants; /** * For callbacks with a non-void return type, a CallbackInfoReturnable is passed @@ -124,7 +125,7 @@ public class CallbackInfoReturnable extends CallbackInfo { // CHECKSTYLE:ON static String getReturnAccessor(Type returnType) { - if (returnType.getSort() == Type.OBJECT) { + if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { return "getReturnValue"; } @@ -132,8 +133,8 @@ public class CallbackInfoReturnable extends CallbackInfo { } static String getReturnDescriptor(Type returnType) { - if (returnType.getSort() == Type.OBJECT) { - return String.format("()%s", CallbackInfo.OBJECT); + if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { + return String.format("()%s", Constants.OBJECT); } return String.format("()%s", returnType.getDescriptor()); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index cda89b68..84b22bb7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -27,26 +27,27 @@ package org.spongepowered.asm.mixin.injection.callback; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.*; import org.spongepowered.asm.mixin.injection.Coerce; -import org.spongepowered.asm.mixin.injection.InjectionError; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; -import org.spongepowered.asm.mixin.injection.InvalidInjectionException; import org.spongepowered.asm.mixin.injection.Surrogate; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.points.BeforeReturn; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ASMHelper; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.Locals; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.asm.util.SignaturePrinter; +import com.google.common.base.Strings; + /** * This class is responsible for generating the bytecode for injected callbacks */ @@ -148,10 +149,10 @@ public class CallbackInjector extends Injector { */ private boolean captureArgs = true; - Callback(MethodNode handler, Target target, final AbstractInsnNode node, final LocalVariableNode[] locals, boolean captureLocals) { + Callback(MethodNode handler, Target target, final InjectionNode node, final LocalVariableNode[] locals, boolean captureLocals) { this.handler = handler; this.target = target; - this.node = node; + this.node = node.getCurrentTarget(); this.locals = locals; this.localTypes = locals != null ? new Type[locals.length] : null; this.frameSize = ASMHelper.getFirstNonArgLocalIndex(target.arguments, !CallbackInjector.this.isStatic()); @@ -260,7 +261,7 @@ public class CallbackInjector extends Injector { return false; // No @Coerce specified, types must match } - boolean canCoerce = CallbackInjector.canCoerce(inTypes[arg], myTypes[arg]); + boolean canCoerce = Injector.canCoerce(inTypes[arg], myTypes[arg]); if (!canCoerce) { return false; // Can't coerce source type to local type, give up } @@ -277,8 +278,6 @@ public class CallbackInjector extends Injector { } } - private final Logger logger = LogManager.getLogger("mixin"); - /** * True if cancellable */ @@ -289,6 +288,11 @@ public class CallbackInjector extends Injector { */ private final LocalCapture localCapture; + /** + * ID to return from callbackinfo + */ + private final String identifier; + /** * Make a new CallbackInjector with the supplied args * @@ -297,10 +301,11 @@ public class CallbackInjector extends Injector { * be cancellable * @param localCapture Local variable capture behaviour */ - public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture) { + public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture, String identifier) { super(info); this.cancellable = cancellable; this.localCapture = localCapture; + this.identifier = identifier; } /* (non-Javadoc) @@ -310,15 +315,17 @@ public class CallbackInjector extends Injector { */ @Override protected void sanityCheck(Target target, List injectionPoints) { + super.sanityCheck(target, injectionPoints); + if (ASMHelper.methodIsStatic(target.method) != this.isStatic) { - throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this.methodNode.name); + throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this); } - if (Constants.INIT.equals(target.method.name)) { + if (Constants.CTOR.equals(target.method.name)) { for (InjectionPoint injectionPoint : injectionPoints) { if (!injectionPoint.getClass().equals(BeforeReturn.class)) { throw new InvalidInjectionException(this.info, "Found injection point type " + injectionPoint.getClass().getSimpleName() - + " targetting a ctor in " + this.classNode.name + ". Only RETURN allowed for a ctor target"); + + " targetting a ctor in " + this + ". Only RETURN allowed for a ctor target"); } } } @@ -330,11 +337,11 @@ public class CallbackInjector extends Injector { * org.objectweb.asm.tree.AbstractInsnNode) */ @Override - protected void inject(Target target, AbstractInsnNode node) { + protected void inject(Target target, InjectionNode node) { LocalVariableNode[] locals = null; if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) { - locals = Locals.getLocalsAt(this.classNode, target.method, node); + locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget()); } this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals())); @@ -357,7 +364,7 @@ public class CallbackInjector extends Injector { MethodNode callbackMethod = this.methodNode; if (!callback.checkDescriptor(this.methodNode.desc)) { - if (this.info.getTargets().size() != 0) { + if (this.info.getTargets().size() > 1) { return; // Look for a match in other targets before failing } @@ -367,24 +374,24 @@ public class CallbackInjector extends Injector { // signature for the current locals. This allows silent failover // if changes to the local variable table are EXPECTED for some // reason. - MethodNode handler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor()); - if (handler != null && ASMHelper.getVisibleAnnotation(handler, Surrogate.class) != null) { + MethodNode surrogateHandler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor()); + if (surrogateHandler != null && ASMHelper.getVisibleAnnotation(surrogateHandler, Surrogate.class) != null) { // Found a matching method, use it - callbackMethod = handler; + callbackMethod = surrogateHandler; } else { // No matching method, generate a message to bitch about it String message = this.generateBadLVTMessage(callback); switch (this.localCapture) { case CAPTURE_FAILEXCEPTION: - this.logger.error("Injection error: {}", message); + Injector.logger.error("Injection error: {}", message); callbackMethod = this.generateErrorMethod(callback, "org/spongepowered/asm/mixin/injection/InjectionError", message); break; case CAPTURE_FAILSOFT: - this.logger.warn("Injection warning: {}", message); + Injector.logger.warn("Injection warning: {}", message); return; default: - this.logger.error("Critical injection failure: {}", message); + Injector.logger.error("Critical injection failure: {}", message); throw new InjectionError(message); } } @@ -397,20 +404,29 @@ public class CallbackInjector extends Injector { if (callback.checkDescriptor(returnableSig)) { // Switching out CallbackInfo for CallbackInfoReturnable // worked, so notify the user that they done derped - throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: CallbackInfoReturnable is required!"); + throw new InvalidInjectionException(this.info, "Invalid descriptor on " + this.info + "! CallbackInfoReturnable is required!"); } - throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: expected " + callback.getDescriptor() - + " but found " + this.methodNode.desc); + MethodNode surrogateHandler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor()); + if (surrogateHandler != null && ASMHelper.getVisibleAnnotation(surrogateHandler, Surrogate.class) != null) { + // Found a matching surrogate method, use it + callbackMethod = surrogateHandler; + } else { + throw new InvalidInjectionException(this.info, "Invalid descriptor on " + this.info + "! Expected " + callback.getDescriptor() + + " but found " + this.methodNode.desc); + } } } - this.createCallbackInfo(callback); + this.dupReturnValue(callback); + if (this.cancellable) { + this.createCallbackInfo(callback, true); + } this.invokeCallback(callback, callbackMethod); this.injectCancellationCode(callback); callback.inject(); - this.info.getTargets().clear(); + this.info.notifyInjected(callback.target); } /** @@ -422,9 +438,9 @@ public class CallbackInjector extends Injector { private String generateBadLVTMessage(final Callback callback) { int position = callback.target.method.instructions.indexOf(callback.node); List expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1); - List found = CallbackInjector.summariseLocals(callback.localTypes, callback.frameSize); - String message = String.format("LVT in %s::%s has incompatible changes at opcode %d in callback %s%s.\nExpected: %s\n Found:%s", - this.classNode.name, callback.target.method.name, position, this.methodNode.name, this.methodNode.desc, expected, found); + List found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), callback.frameSize); + String message = String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s", + callback.target, position, this, expected, found); return message; } @@ -444,7 +460,7 @@ public class CallbackInjector extends Injector { insns.add(new TypeInsnNode(Opcodes.NEW, errorClass)); insns.add(new InsnNode(Opcodes.DUP)); insns.add(new LdcInsnNode(message)); - insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, Constants.INIT, "(Ljava/lang/String;)V", false)); + insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, Constants.CTOR, "(Ljava/lang/String;)V", false)); insns.add(new InsnNode(Opcodes.ATHROW)); return method; } @@ -461,12 +477,12 @@ public class CallbackInjector extends Injector { handlerSig.setModifiers(this.methodNode); PrettyPrinter printer = new PrettyPrinter(); - printer.add("%20s : %s", "Target Class", this.classNode.name.replace('/', '.')); - printer.add("%20s : %s", "Target Method", methodSig); - printer.add("%20s : %d", "Target Max LOCALS", callback.target.getMaxLocals()); - printer.add("%20s : %d", "Initial Frame Size", callback.frameSize); - printer.add("%20s : %s", "Callback Name", this.methodNode.name); - printer.add("%20s : %s %s", "Instruction", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode())); + printer.kv("Target Class", this.classNode.name.replace('/', '.')); + printer.kv("Target Method", methodSig); + printer.kv("Target Max LOCALS", callback.target.getMaxLocals()); + printer.kv("Initial Frame Size", callback.frameSize); + printer.kv("Callback Name", this.methodNode.name); + printer.kv("Instruction", "%s %s", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode())); printer.hr(); if (callback.locals.length > callback.frameSize) { printer.add(" %s %20s %s", "LOCAL", "TYPE", "NAME"); @@ -489,15 +505,27 @@ public class CallbackInjector extends Injector { /** * @param callback callback handle + * @param store store the callback info in a local variable */ - private void createCallbackInfo(final Callback callback) { - this.dupReturnValue(callback); - - callback.add(new TypeInsnNode(Opcodes.NEW, callback.target.callbackInfoClass), true, false); + private void createCallbackInfo(final Callback callback, boolean store) { + callback.add(new TypeInsnNode(Opcodes.NEW, callback.target.callbackInfoClass), true, !store); callback.add(new InsnNode(Opcodes.DUP), true, true); - this.invokeCallbackInfoCtor(callback); - callback.add(new VarInsnNode(Opcodes.ASTORE, callback.marshallVar)); + this.invokeCallbackInfoCtor(callback, store); + if (store) { + callback.add(new VarInsnNode(Opcodes.ASTORE, callback.marshallVar)); + } + } + + /** + * @param callback callback handle + */ + private void loadOrCreateCallbackInfo(final Callback callback) { + if (this.cancellable) { + callback.add(new VarInsnNode(Opcodes.ALOAD, callback.marshallVar), false, true); + } else { + this.createCallbackInfo(callback, false); + } } /** @@ -519,18 +547,20 @@ public class CallbackInjector extends Injector { /** * @param callback callback handle + * @param store true if storing in a local, false if this is happening at an + * invoke */ - protected void invokeCallbackInfoCtor(final Callback callback) { - callback.add(new LdcInsnNode(callback.target.method.name), true, false); - callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, false); + protected void invokeCallbackInfoCtor(final Callback callback, boolean store) { + callback.add(new LdcInsnNode(this.getIdentifier(callback)), true, !store); + callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, !store); if (callback.isAtReturn) { - callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar)); + callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar), true, !store); callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, - callback.target.callbackInfoClass, Constants.INIT, CallbackInfo.getConstructorDescriptor(callback.target.returnType), false)); + callback.target.callbackInfoClass, Constants.CTOR, CallbackInfo.getConstructorDescriptor(callback.target.returnType), false)); } else { callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, - callback.target.callbackInfoClass, Constants.INIT, CallbackInfo.getConstructorDescriptor(), false)); + callback.target.callbackInfoClass, Constants.CTOR, CallbackInfo.getConstructorDescriptor(), false)); } } @@ -540,7 +570,7 @@ public class CallbackInjector extends Injector { private void invokeCallback(final Callback callback, final MethodNode callbackMethod) { // Push "this" onto the stack if the callback is not static if (!this.isStatic) { - callback.add(new VarInsnNode(Opcodes.ALOAD, 0)); + callback.add(new VarInsnNode(Opcodes.ALOAD, 0), false, true); } // Push the target method's parameters onto the stack @@ -549,7 +579,7 @@ public class CallbackInjector extends Injector { } // Push the callback info onto the stack - callback.add(new VarInsnNode(Opcodes.ALOAD, callback.marshallVar), false, true); + this.loadOrCreateCallbackInfo(callback); // (Maybe) push the locals onto the stack if (callback.canCaptureLocals) { @@ -557,7 +587,19 @@ public class CallbackInjector extends Injector { } // Call the callback! - this.invokeMethod(callback, callbackMethod); + this.invokeHandler(callback, callbackMethod); + } + + /** + * Get the identifier to use for the specified callback. If an id was + * specified by the end user on the annotation then use the value specified, + * otherwise defaults to the target method name. + * + * @param callback Callback being injected + * @return Identifier to use + */ + private String getIdentifier(Callback callback) { + return Strings.isNullOrEmpty(this.identifier) ? callback.target.method.name : this.identifier; } /** @@ -631,21 +673,5 @@ public class CallbackInjector extends Injector { } return list; } - - public static boolean canCoerce(Type from, Type to) { - return CallbackInjector.canCoerce(from.getDescriptor(), to.getDescriptor()); - } - - public static boolean canCoerce(String from, String to) { - if (from.length() > 1 || to.length() > 1) { - return false; - } - - return CallbackInjector.canCoerce(from.charAt(0), to.charAt(0)); - } - - public static boolean canCoerce(char from, char to) { - return to == 'I' && "IBSCZ".indexOf(from) > -1; - } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java index 615f2b55..a544fdd5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.injection.callback; - /** * Interface for things which can be cancelled */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java index d9fdcb10..c2c27639 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java @@ -24,6 +24,10 @@ */ package org.spongepowered.asm.mixin.injection.callback; +/** + * Exception thrown when a consumer attemtps to call cancel() on a + * callback not marked as cancellable. + */ public class CancellationException extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/LocalCapture.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/LocalCapture.java index c64273ec..f44baafd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/LocalCapture.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/LocalCapture.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.injection.callback; - /** * Specifies the behaviour for capturing local variables at an injection point. * diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 52956fb2..51b6cedc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -30,6 +30,8 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AbstractInsnNode; @@ -37,19 +39,26 @@ import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ASMHelper; import com.google.common.base.Joiner; - /** * Base class for bytecode injectors */ public abstract class Injector { + /** + * Log more things + */ + protected static final Logger logger = LogManager.getLogger("mixin"); + /** * Injection info */ @@ -64,6 +73,16 @@ public abstract class Injector { * Callback method */ protected final MethodNode methodNode; + + /** + * Arguments of the handler method + */ + protected final Type[] methodArgs; + + /** + * Return type of the handler method + */ + protected final Type returnType; /** * True if the callback method is static @@ -89,20 +108,46 @@ public abstract class Injector { private Injector(ClassNode classNode, MethodNode methodNode) { this.classNode = classNode; this.methodNode = methodNode; + this.methodArgs = Type.getArgumentTypes(this.methodNode.desc); + this.returnType = Type.getReturnType(this.methodNode.desc); this.isStatic = ASMHelper.methodIsStatic(this.methodNode); } + + @Override + public String toString() { + return String.format("%s::%s", this.classNode.name, this.methodNode.name); + } /** - * Inject into the specified method at the specified injection points + * ... * * @param target Target method to inject into * @param injectionPoints InjectionPoint instances which will identify * target insns in the target method + * @return discovered injection points */ - public final void injectInto(Target target, List injectionPoints) { + public final List find(Target target, List injectionPoints) { this.sanityCheck(target, injectionPoints); - + + List myNodes = new ArrayList(); for (AbstractInsnNode node : this.findTargetNodes(target.method, injectionPoints)) { + this.addTargetNode(target, myNodes, node); + } + return myNodes; + } + + protected void addTargetNode(Target target, List myNodes, AbstractInsnNode node) { + myNodes.add(target.injectionNodes.add(node)); + } + + public final void inject(Target target, List nodes) { + for (InjectionNode node : nodes) { + if (node.isRemoved()) { + if (this.info.getContext().getEnvironment().getOption(Option.DEBUG_VERBOSE)) { + Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target); + } + continue; + } this.inject(target, node); } } @@ -125,7 +170,7 @@ public abstract class Injector { for (InjectionPoint injectionPoint : injectionPoints) { nodes.clear(); - if (injectionPoint.find(into.desc, insns, nodes)) { + if (this.findTargetNodes(into, injectionPoint, insns, nodes)) { targetNodes.addAll(nodes); } } @@ -134,28 +179,63 @@ public abstract class Injector { return targetNodes; } - protected void sanityCheck(Target target, List injectionPoints) { - // stub for subclasses + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { + return injectionPoint.find(into.desc, insns, nodes); } - protected abstract void inject(Target target, AbstractInsnNode node); + protected void sanityCheck(Target target, List injectionPoints) { + if (target.classNode != this.classNode) { + throw new InvalidInjectionException(this.info, "Target class does not match injector class in " + this); + } + } + + protected abstract void inject(Target target, InjectionNode node); /** * Invoke the handler method * * @param insns Instruction list to inject into + * @return injected insn node */ - protected void invokeHandler(InsnList insns) { - this.invokeMethod(insns, this.methodNode); + protected AbstractInsnNode invokeHandler(InsnList insns) { + return this.invokeHandler(insns, this.methodNode); } - protected void invokeMethod(InsnList insns, MethodNode methodNode) { - boolean isPrivate = (methodNode.access & Opcodes.ACC_PRIVATE) != 0; + /** + * Invoke a handler method + * + * @param insns Instruction list to inject into + * @param handler Actual method to invoke (may be different if using a + * surrogate) + * @return injected insn node + */ + protected AbstractInsnNode invokeHandler(InsnList insns, MethodNode handler) { + boolean isPrivate = (handler.access & Opcodes.ACC_PRIVATE) != 0; int invokeOpcode = this.isStatic ? Opcodes.INVOKESTATIC : isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL; - insns.add(new MethodInsnNode(invokeOpcode, this.classNode.name, methodNode.name, methodNode.desc, false)); + MethodInsnNode insn = new MethodInsnNode(invokeOpcode, this.classNode.name, handler.name, handler.desc, false); + insns.add(insn); + this.info.addCallbackInvocation(handler); + return insn; } protected static String printArgs(Type[] args) { return "(" + Joiner.on("").join(args) + ")"; } + + public static boolean canCoerce(Type from, Type to) { + return Injector.canCoerce(from.getDescriptor(), to.getDescriptor()); + } + + public static boolean canCoerce(String from, String to) { + if (from.length() > 1 || to.length() > 1) { + return false; + } + + return Injector.canCoerce(from.charAt(0), to.charAt(0)); + } + + public static boolean canCoerce(char from, char to) { + return to == 'I' && "IBSCZ".indexOf(from) > -1; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java index d6f2ea1d..c53355f7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java @@ -32,27 +32,18 @@ import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; -import org.spongepowered.asm.mixin.injection.InvalidInjectionException; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; /** * Base class for injectors which inject at method invokes */ public abstract class InvokeInjector extends Injector { - /** - * Arguments of the handler method - */ - protected final Type[] methodArgs; - - /** - * Return type of the handler method - */ - protected final Type returnType; - protected final String annotationType; /** @@ -61,8 +52,6 @@ public abstract class InvokeInjector extends Injector { */ public InvokeInjector(InjectionInfo info, String annotationType) { super(info); - this.methodArgs = Type.getArgumentTypes(this.methodNode.desc); - this.returnType = Type.getReturnType(this.methodNode.desc); this.annotationType = annotationType; } @@ -73,8 +62,18 @@ public abstract class InvokeInjector extends Injector { */ @Override protected void sanityCheck(Target target, List injectionPoints) { + super.sanityCheck(target, injectionPoints); + this.checkTarget(target); + } + + /** + * Sanity checks on target + * + * @param target target + */ + protected void checkTarget(Target target) { if (target.isStatic != this.isStatic) { - throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this.methodNode.name); + throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this); } } @@ -84,13 +83,13 @@ public abstract class InvokeInjector extends Injector { * org.objectweb.asm.tree.AbstractInsnNode) */ @Override - protected void inject(Target target, AbstractInsnNode node) { - if (!(node instanceof MethodInsnNode)) { - throw new InvalidInjectionException(this.info, this.annotationType + " annotation is targetting a non-method insn in " + target - + " in " + this.classNode.name); + protected void inject(Target target, InjectionNode node) { + if (!(node.getCurrentTarget() instanceof MethodInsnNode)) { + throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting a non-method insn in " + target + + " in " + this); } - this.inject(target, (MethodInsnNode)node); + this.injectAtInvoke(target, node); } /** @@ -99,15 +98,16 @@ public abstract class InvokeInjector extends Injector { * @param target Target to inject into * @param node Discovered instruction node */ - protected abstract void inject(Target target, MethodInsnNode node); + protected abstract void injectAtInvoke(Target target, InjectionNode node); /** * @param args handler arguments * @param insns InsnList to inject insns into * @param argMap Mapping of args to local variables + * @return injected insn node */ - protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) { - this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length); + protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) { + return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length); } /** @@ -116,13 +116,14 @@ public abstract class InvokeInjector extends Injector { * @param argMap Mapping of args to local variables * @param startArg Starting arg to consume * @param endArg Ending arg to consume + * @return injected insn node */ - protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) { + protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) { if (!this.isStatic) { insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); } this.pushArgs(args, insns, argMap, startArg, endArg); - this.invokeHandler(insns); + return this.invokeHandler(insns); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java index 5a9de998..cb093bae 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java @@ -31,10 +31,11 @@ import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; -import org.spongepowered.asm.mixin.injection.InvalidInjectionException; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; /** * A bytecode injector which allows a single argument of a chosen method call to @@ -76,18 +77,30 @@ public class ModifyArgInjector extends InvokeInjector { if (this.singleArgMode) { if (!this.methodArgs[0].equals(this.returnType)) { - throw new InvalidInjectionException(this.info, "@ModifyArg return type must match the parameter type." + throw new InvalidInjectionException(this.info, "@ModifyArg return type on " + this + " must match the parameter type." + " ARG=" + this.methodArgs[0] + " RETURN=" + this.returnType); } } } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.invoke.InvokeInjector + * #checkTarget(org.spongepowered.asm.mixin.injection.struct.Target) + */ + @Override + protected void checkTarget(Target target) { + if (!this.isStatic && target.isStatic) { + throw new InvalidInjectionException(this.info, "non-static callback method " + this + " targets a static method which is not supported"); + } + } + /** * Do the injection */ @Override - protected void inject(Target target, MethodInsnNode node) { - Type[] args = Type.getArgumentTypes(node.desc); + protected void injectAtInvoke(Target target, InjectionNode node) { + MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget(); + Type[] args = Type.getArgumentTypes(methodNode.desc); int argIndex = this.findArgIndex(target, args); InsnList insns = new InsnList(); int extraLocals = 0; @@ -98,7 +111,7 @@ public class ModifyArgInjector extends InvokeInjector { extraLocals = this.injectMultiArgHandler(target, args, argIndex, insns); } - target.insns.insertBefore(node, insns); + target.insns.insertBefore(methodNode, insns); target.addToLocals(extraLocals); target.addToStack(2 - (extraLocals - 1)); } @@ -110,7 +123,7 @@ public class ModifyArgInjector extends InvokeInjector { int[] argMap = this.storeArgs(target, args, insns, argIndex); this.invokeHandlerWithArgs(args, insns, argMap, argIndex, argIndex + 1); this.pushArgs(args, insns, argMap, argIndex + 1, args.length); - return (target.getCurrentMaxLocals() - argMap[argMap.length - 1]) + 1 + args[args.length - 1].getSize(); + return (argMap[argMap.length - 1] - target.getMaxLocals()) + args[args.length - 1].getSize(); } /** @@ -118,7 +131,7 @@ public class ModifyArgInjector extends InvokeInjector { */ private int injectMultiArgHandler(Target target, Type[] args, int argIndex, InsnList insns) { if (!Arrays.equals(args, this.methodArgs)) { - throw new InvalidInjectionException(this.info, "@ModifyArg method targets a method with an invalid signature " + throw new InvalidInjectionException(this.info, "@ModifyArg method " + this + " targets a method with an invalid signature " + Injector.printArgs(args) + ", expected " + Injector.printArgs(this.methodArgs)); } @@ -126,14 +139,14 @@ public class ModifyArgInjector extends InvokeInjector { this.pushArgs(args, insns, argMap, 0, argIndex); this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length); this.pushArgs(args, insns, argMap, argIndex + 1, args.length); - return (target.getCurrentMaxLocals() - argMap[argMap.length - 1]) + 1 + args[args.length - 1].getSize(); + return (argMap[argMap.length - 1] - target.getMaxLocals()) + args[args.length - 1].getSize(); } protected int findArgIndex(Target target, Type[] args) { if (this.index > -1) { if (this.index >= args.length || !args[this.index].equals(this.returnType)) { throw new InvalidInjectionException(this.info, "Specified index " + this.index + " for @ModifyArg is invalid for args " - + Injector.printArgs(args) + ", expected " + this.returnType); + + Injector.printArgs(args) + ", expected " + this.returnType + " on " + this); } return this.index; } @@ -147,8 +160,7 @@ public class ModifyArgInjector extends InvokeInjector { if (argIndex != -1) { throw new InvalidInjectionException(this.info, "Found duplicate args with index [" + argIndex + ", " + arg + "] matching type " - + this.returnType + " for @ModifyArg target " + target + " in " + this.classNode.name - + ". Please specify index of desired arg."); + + this.returnType + " for @ModifyArg target " + target + " in " + this + ". Please specify index of desired arg."); } argIndex = arg; @@ -156,7 +168,7 @@ public class ModifyArgInjector extends InvokeInjector { if (argIndex == -1) { throw new InvalidInjectionException(this.info, "Could not find arg matching type " + this.returnType + " for @ModifyArg target " - + target + " in " + this.classNode.name); + + target + " in " + this); } return argIndex; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java new file mode 100644 index 00000000..dca2f087 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -0,0 +1,94 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.invoke; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ASMHelper; + +/** + * A bytecode injector which allows a specific + */ +public class ModifyConstantInjector extends RedirectInjector { + + /** + * @param info Injection info + */ + public ModifyConstantInjector(InjectionInfo info) { + super(info, "@ModifyConstant"); + } + + @Override + protected void inject(Target target, InjectionNode node) { + if (!this.preInject(node)) { + return; + } + + if (node.isReplaced()) { + throw new UnsupportedOperationException("Target failure for " + this.info); + } + + if (ASMHelper.isConstant(node.getCurrentTarget())) { + this.injectConstantModifier(target, node); + return; + } + + throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in " + + target + " in " + this); + } + + private void injectConstantModifier(Target target, InjectionNode node) { + final AbstractInsnNode constNode = node.getCurrentTarget(); + final Type constantType = ASMHelper.getConstantType(constNode); + final InsnList before = new InsnList(); + final InsnList after = new InsnList(); + AbstractInsnNode invoke = this.invokeConstantHandler(constNode, constantType, target, before, after); + target.wrapNode(constNode, invoke, before, after); + } + + private AbstractInsnNode invokeConstantHandler(AbstractInsnNode targetNode, Type constantType, Target target, InsnList before, InsnList after) { + final String handlerDesc = ASMHelper.generateDescriptor(constantType, constantType); + final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); + + if (!this.isStatic) { + before.add(new VarInsnNode(Opcodes.ALOAD, 0)); + target.addToStack(1); + } + + if (withArgs) { + this.pushArgs(target.arguments, after, target.argIndices, 0, target.arguments.length); + target.addToStack(ASMHelper.getArgsSize(target.arguments)); + } + + return this.invokeHandler(after); + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index 0a0675d7..49bab166 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -24,25 +24,36 @@ */ package org.spongepowered.asm.mixin.injection.invoke; +import java.util.List; + import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.mixin.injection.InvalidInjectionException; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ASMHelper; +import com.google.common.base.Joiner; import com.google.common.collect.ObjectArrays; import com.google.common.primitives.Ints; /** - *

A bytecode injector which allows a method call to be redirected to the - * annotated handler method. The handler method signature must match the hooked - * method precisely but prepended with an arg of the owning object's type - * to accept the object instance the method was going to be invoked on. For - * example when hooking the following call:

+ *

A bytecode injector which allows a method call or field access to be + * redirected to the annotated handler method. For method redirects, the handler + * method signature must match the hooked method precisely but prepended + * with an arg of the owning object's type to accept the object instance the + * method was going to be invoked on. For example when hooking the following + * call:

* *
  *   int abc = 0;
@@ -62,27 +73,125 @@ import com.google.common.primitives.Ints;
  * 

For obvious reasons this does not apply for static methods, for static * methods it is sufficient that the signature simply match the hooked method. *

+ * + *

For field redirections, see the details in {@link Redirect} for the + * required signature of the handler method.

*/ public class RedirectInjector extends InvokeInjector { + + /** + * Meta decoration object for redirector target nodes + */ + class Meta { + + public static final String KEY = "redirector"; + + final int priority; + + final boolean isFinal; + + final String name; + + final String desc; + + public Meta(int priority, boolean isFinal, String name, String desc) { + this.priority = priority; + this.isFinal = isFinal; + this.name = name; + this.desc = desc; + } + + RedirectInjector getOwner() { + return RedirectInjector.this; + } + + } + + protected Meta meta; /** * @param info Injection info */ public RedirectInjector(InjectionInfo info) { - super(info, "@Redirect"); + this(info, "@Redirect"); + } + + protected RedirectInjector(InjectionInfo info, String annotationType) { + super(info, annotationType); + + int priority = info.getContext().getPriority(); + boolean isFinal = ASMHelper.getVisibleAnnotation(this.methodNode, Final.class) != null; + this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc); + } + + @Override + protected void addTargetNode(Target target, List myNodes, AbstractInsnNode insn) { + InjectionNode node = target.injectionNodes.get(insn); + + if (node != null ) { + Meta other = node.getDecoration(Meta.KEY); + + if (other != null && other.getOwner() != this) { + if (other.priority >= this.meta.priority) { + Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}", + this.annotationType, this.info, this.meta.priority, other.name, other.priority); + return; + } else if (other.isFinal) { + throw new InvalidInjectionException(this.info, this.annotationType + " conflict: " + this + + " failed because target was already remapped by " + other.name); + } + } + } + + myNodes.add(target.injectionNodes.add(insn).decorate(Meta.KEY, this.meta)); + } + + @Override + protected void inject(Target target, InjectionNode node) { + if (!this.preInject(node)) { + return; + } + + if (node.isReplaced()) { + throw new UnsupportedOperationException("Redirector target failure for " + this.info); + } + + if (node.getCurrentTarget() instanceof MethodInsnNode) { + this.injectAtInvoke(target, node); + return; + } + + if (node.getCurrentTarget() instanceof FieldInsnNode) { + this.injectAtFieldAccess(target, node); + return; + } + + throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in " + + target + " in " + this); + } + + protected boolean preInject(InjectionNode node) { + Meta other = node.getDecoration(Meta.KEY); + if (other.getOwner() != this) { + Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}", + this.annotationType, this.info, this.meta.priority, other.name, other.priority); + return false; + } + return true; } /** - * Do the injection + * Redirect a method invocation */ @Override - protected void inject(Target target, MethodInsnNode node) { + protected void injectAtInvoke(Target target, InjectionNode node) { + final MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget(); + final boolean targetIsStatic = methodNode.getOpcode() == Opcodes.INVOKESTATIC; + final Type ownerType = Type.getType("L" + methodNode.owner + ";"); + final Type returnType = Type.getReturnType(methodNode.desc); + final Type[] args = Type.getArgumentTypes(methodNode.desc); + final Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args); boolean injectTargetParams = false; - boolean targetIsStatic = node.getOpcode() == Opcodes.INVOKESTATIC; - Type ownerType = Type.getType("L" + node.owner + ";"); - Type returnType = Type.getReturnType(node.desc); - Type[] args = Type.getArgumentTypes(node.desc); - Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args); String desc = Injector.printArgs(stackVars) + returnType; if (!desc.equals(this.methodNode.desc)) { @@ -90,23 +199,125 @@ public class RedirectInjector extends InvokeInjector { if (alternateDesc.equals(this.methodNode.desc)) { injectTargetParams = true; } else { - throw new InvalidInjectionException(this.info, "@Redirect handler method has an invalid signature " - + ", expected " + desc + " found " + this.methodNode.desc); + throw new InvalidInjectionException(this.info, this.annotationType + " handler method " + this + + " has an invalid signature, expected " + desc + " found " + this.methodNode.desc); } } InsnList insns = new InsnList(); int extraLocals = ASMHelper.getArgsSize(stackVars) + 1; + int extraStack = 1; // Normally only need 1 extra stack pos to store target ref int[] argMap = this.storeArgs(target, stackVars, insns, 0); if (injectTargetParams) { - extraLocals += ASMHelper.getArgsSize(target.arguments); + int argSize = ASMHelper.getArgsSize(target.arguments); + extraLocals += argSize; + extraStack += argSize; argMap = Ints.concat(argMap, target.argIndices); } - this.invokeHandlerWithArgs(this.methodArgs, insns, argMap); - - target.insns.insertBefore(node, insns); - target.insns.remove(node); + AbstractInsnNode insn = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap); + target.replaceNode(methodNode, insn, insns); target.addToLocals(extraLocals); - target.addToStack(1); + target.addToStack(extraStack); } + + /** + * Redirect a field get or set operation + */ + private void injectAtFieldAccess(Target target, InjectionNode node) { + final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget(); + final int opCode = fieldNode.getOpcode(); + final boolean staticField = opCode == Opcodes.GETSTATIC || opCode == Opcodes.PUTSTATIC; + final Type ownerType = Type.getType("L" + fieldNode.owner + ";"); + final Type fieldType = Type.getType(fieldNode.desc); + + AbstractInsnNode invoke = null; + InsnList insns = new InsnList(); + if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) { + invoke = this.injectAtGetField(insns, target, fieldNode, staticField, ownerType, fieldType); + } else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) { + invoke = this.injectAtPutField(insns, target, fieldNode, staticField, ownerType, fieldType); + } else { + throw new InvalidInjectionException(this.info, "Unspported opcode " + opCode + " on FieldInsnNode for " + this.info); + } + + target.replaceNode(fieldNode, invoke, insns); + } + + /** + * Inject opcodes to redirect a field getter. The injection will vary based + * on the staticness of the field and the handler thus there are four + * possible scenarios based on the possible combinations of static on the + * handler and the field itself. + */ + private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) { + final String handlerDesc = staticField ? ASMHelper.generateDescriptor(fieldType) : ASMHelper.generateDescriptor(fieldType, owner); + final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); + + if (!this.isStatic) { + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + if (!staticField) { + insns.add(new InsnNode(Opcodes.SWAP)); + } + } + + if (withArgs) { + this.pushArgs(target.arguments, insns, target.argIndices, 0, target.arguments.length); + target.addToStack(ASMHelper.getArgsSize(target.arguments)); + } + + target.addToStack(this.isStatic ? 0 : 1); + return this.invokeHandler(insns); + } + + /** + * Inject opcodes to redirect a field setter. The injection will vary based + * on the staticness of the field and the handler thus there are four + * possible scenarios based on the possible combinations of static on the + * handler and the field itself. + */ + private AbstractInsnNode injectAtPutField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) { + String handlerDesc = staticField ? ASMHelper.generateDescriptor(null, fieldType) : ASMHelper.generateDescriptor(null, owner, fieldType); + boolean withArgs = this.checkDescriptor(handlerDesc, target, "setter"); + + if (!this.isStatic) { + if (staticField) { + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + insns.add(new InsnNode(Opcodes.SWAP)); + } else { + int marshallVar = target.allocateLocals(fieldType.getSize()); + insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ISTORE), marshallVar)); + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + insns.add(new InsnNode(Opcodes.SWAP)); + insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ILOAD), marshallVar)); + } + } + + if (withArgs) { + this.pushArgs(target.arguments, insns, target.argIndices, 0, target.arguments.length); + target.addToStack(ASMHelper.getArgsSize(target.arguments)); + } + + target.addToStack(!this.isStatic && !staticField ? 1 : 0); + return this.invokeHandler(insns); + } + + /** + * Check that the handler descriptor matches the calculated descriptor for + * the field access being redirected. + */ + protected boolean checkDescriptor(String desc, Target target, String type) { + if (this.methodNode.desc.equals(desc)) { + return false; + } + + int pos = desc.indexOf(')'); + String alternateDesc = String.format("%s%s%s", desc.substring(0, pos), Joiner.on("").join(target.arguments), desc.substring(pos)); + if (this.methodNode.desc.equals(alternateDesc)) { + return true; + } + + throw new InvalidInjectionException(this.info, this.annotationType + " method " + type + " " + this + + " has an invalid signature. Expected " + desc + " but found " + this.methodNode.desc); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java new file mode 100644 index 00000000..2ed1e3e0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java @@ -0,0 +1,81 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + *

This injection point is a companion for the {@link ModifyVariable} + * injector which searches for STORE operations which match the local variables + * described by the injector's defined discriminators.

+ * + *

This allows you consumers to specify an injection immediately after a + * local variable is written in a method. Specify an ordinal of n + * to match the n + 1th access of the variable in + * question.

+ * + *
+ *
ordinal
+ *
The ordinal position of the STORE opcode for the matching local + * variable to search for, if not specified then the injection point returns + * all opcodes for which the parent annotation's discriminators + * match. The default value is -1 which supresses ordinal checking. + *
+ *
+ * + *

Example:

+ *
+ *   @ModifyVariable(
+ *       method = "md",
+ *       ordinal = 1,
+ *       at = @At(
+ *           value = "STORE",
+ *           ordinal = 0
+ *       )
+ *   )
+ *
+ *

Note that if value is the only parameter specified, it can be + * omitted:

+ *
+ *   @At("STORE")
+ *
+ * + *

Important Note: Unlike other standard injection points, this class + * matches the insn immediately after the matching point.

+ */ +public class AfterStoreLocal extends BeforeLoadLocal { + + @SuppressWarnings("hiding") + public static final String CODE = "STORE"; + + public AfterStoreLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator local, InjectionPointData data) { + super(mixin, returnType, local, data, Opcodes.ISTORE, true); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java new file mode 100644 index 00000000..b00c0e6f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java @@ -0,0 +1,212 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import java.util.Collection; +import java.util.ListIterator; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.ContextualInjectionPoint; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + *

This injection point is a companion for the {@link ModifyVariable} + * injector which searches for LOAD operations which match the local variables + * described by the injector's defined discriminators.

+ * + *

This allows you consumers to specify an injection immediately before a + * local variable is accessed in a method. Specify an ordinal of n + * to match the n + 1th access of the variable in + * question.

+ * + *
+ *
ordinal
+ *
The ordinal position of the LOAD opcode for the matching local variable + * to search for, if not specified then the injection point returns all + * opcodes for which the parent annotation's discriminators match. The + * default value is -1 which supresses ordinal checking.
+ *
+ * + *

Example:

+ *
+ *   @ModifyVariable(
+ *       method = "md",
+ *       ordinal = 1,
+ *       at = @At(
+ *           value = "LOAD",
+ *           ordinal = 0
+ *       )
+ *   )
+ *
+ *

Note that if value is the only parameter specified, it can be + * omitted:

+ *
+ *   @At("LOAD")
+ *
+ */ +public class BeforeLoadLocal extends ContextualInjectionPoint { + + /** + * Keeps track of state within {@link #find} + */ + static class SearchState { + + /** + * The target ordinal from the injection point + */ + private final int targetOrdinal; + + /** + * The current ordinal + */ + private int ordinal = 0; + + /** + * Flag to defer a {@link check} to the next opcode, to honour the after + * semantics of {@link AfterStoreLocal}. + */ + private boolean pendingCheck = false; + + /** + * True if one or more opcodes was matched + */ + private boolean found = false; + + /** + * Var node, captured for when deferring processing to the next opcode + */ + private VarInsnNode varNode; + + SearchState(int targetOrdinal) { + this.targetOrdinal = targetOrdinal; + } + + boolean success() { + return this.found; + } + + boolean isPendingCheck() { + return this.pendingCheck; + } + + void setPendingCheck() { + this.pendingCheck = true; + } + + void register(VarInsnNode node) { + this.varNode = node; + } + + void check(Collection nodes, AbstractInsnNode insn, int local) { + this.pendingCheck = false; + if (local != this.varNode.var) { + return; + } + + if (this.targetOrdinal == -1 || this.targetOrdinal == this.ordinal) { + nodes.add(insn); + this.found = true; + } + + this.ordinal++; + this.varNode = null; + } + + } + + public static final String CODE = "LOAD"; + + /** + * Return type of the handler, also the type of the local variable we're + * interested in + */ + private final Type returnType; + + /** + * Discriminator, parsed from parent annotation + */ + private final LocalVariableDiscriminator discriminator; + + /** + * Target opcode, inflected from return type + */ + private final int opcode; + + /** + * Target ordinal + */ + private final int ordinal; + + /** + * True if this injection point should capture the opcode after a matching + * opcode, used by {@link AfterStoreLocal}. + */ + private boolean opcodeAfter; + + public BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data) { + this(mixin, returnType, discriminator, data, Opcodes.ILOAD, false); + } + + protected BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data, + int opcode, boolean opcodeAfter) { + super(mixin); + this.returnType = returnType; + this.discriminator = discriminator; + this.opcode = data.getOpcode(returnType.getOpcode(opcode)); + this.ordinal = data.getOrdinal(); + this.opcodeAfter = opcodeAfter; + } + + @Override + boolean find(Target target, Collection nodes) { + SearchState state = new SearchState(this.ordinal); + + ListIterator iter = target.method.instructions.iterator(); + while (iter.hasNext()) { + AbstractInsnNode insn = iter.next(); + if (state.isPendingCheck()) { + int local = this.discriminator.findLocal(this.returnType, this.discriminator.isArgsOnly(), target, insn); + state.check(nodes, insn, local); + } else if (insn instanceof VarInsnNode && insn.getOpcode() == this.opcode && (this.ordinal == -1 || !state.success())) { + state.register((VarInsnNode)insn); + if (this.opcodeAfter) { + state.setPendingCheck(); + } else { + int local = this.discriminator.findLocal(this.returnType, this.discriminator.isArgsOnly(), target, insn); + state.check(nodes, insn, local); + } + } + } + + return state.success(); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/InvalidImplicitDiscriminatorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/InvalidImplicitDiscriminatorException.java new file mode 100644 index 00000000..4848eaaf --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/InvalidImplicitDiscriminatorException.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Thrown when an implicit discriminator (no args) fails to identify + * a unique candidate. + */ +public class InvalidImplicitDiscriminatorException extends MixinException { + + private static final long serialVersionUID = 1L; + + public InvalidImplicitDiscriminatorException(String message) { + super(message); + } + + public InvalidImplicitDiscriminatorException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java new file mode 100644 index 00000000..6691ca91 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java @@ -0,0 +1,348 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.LocalVariableNode; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.Locals; +import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.SignaturePrinter; + +/** + * Encapsulates logic for identifying a local variable in a target method using + * 3 criteria: ordinal, index and name. This is used + * by the {@link ModifyVariableInjector} and its associated injection points. + */ +public class LocalVariableDiscriminator { + + /** + * Discriminator context information, wraps all relevant information about + * a target location for use when performing discrimination + */ + public static class Context implements org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable { + + /** + * Information about a local variable in the LVT, used during + * discrimination + */ + public class Local { + + /** + * Ordinal value of this local variable type + */ + int ord = 0; + + /** + * Local variable name + */ + String name; + + /** + * Local variable type + */ + Type type; + + public Local(String name, Type type) { + this.name = name; + this.type = type; + } + + @Override + public String toString() { + return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type); + } + + } + + /** + * Target method for this context + */ + final Target target; + + /** + * The return type of the handler in question, also the type of the + * local variable that we care about + */ + final Type returnType; + + /** + * Injection point + */ + final AbstractInsnNode node; + + /** + * Base argument index, for static methods this is 0, for instance + * methods this is 1 + */ + final int baseArgIndex; + + /** + * Enumerated locals in this context + */ + final Local[] locals; + + /** + * True if the handler (and target) are static + */ + private final boolean isStatic; + + public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + this.isStatic = ASMHelper.methodIsStatic(target.method); + this.returnType = returnType; + this.target = target; + this.node = node; + this.baseArgIndex = this.isStatic ? 0 : 1; + this.locals = this.initLocals(target, argsOnly, node); + this.initOrdinals(); + } + + private Local[] initLocals(Target target, boolean argsOnly, AbstractInsnNode node) { + if (!argsOnly) { + LocalVariableNode[] locals = Locals.getLocalsAt(target.classNode, target.method, node); + if (locals != null) { + Local[] lvt = new Local[locals.length]; + for (int l = 0; l < locals.length; l++) { + if (locals[l] != null) { + lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc)); + } + } + return lvt; + } + } + + Local[] lvt = new Local[this.baseArgIndex + target.arguments.length]; + if (!this.isStatic) { + lvt[0] = new Local("this", Type.getType(target.classNode.name)); + } + for (int local = this.baseArgIndex; local < lvt.length; local++) { + Type arg = target.arguments[local - this.baseArgIndex]; + lvt[local] = new Local("arg" + local, arg); + } + return lvt; + } + + private void initOrdinals() { + Map ordinalMap = new HashMap(); + for (int l = 0; l < this.locals.length; l++) { + Integer ordinal = Integer.valueOf(0); + if (this.locals[l] != null) { + ordinal = ordinalMap.get(this.locals[l].type); + ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1)); + this.locals[l].ord = ordinal.intValue(); + } + } + } + + @Override + public void print(PrettyPrinter printer) { + printer.add("%5s %7s %30s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE"); + for (int l = this.baseArgIndex; l < this.locals.length; l++) { + Local local = this.locals[l]; + if (local != null) { + Type localType = local.type; + String localName = local.name; + int ordinal = local.ord; + String candidate = this.returnType.equals(localType) ? "YES" : "-"; + printer.add("[%3d] [%3d] %30s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate); + } else if (l > 0) { + Local prevLocal = this.locals[l - 1]; + boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1; + printer.add("[%3d] %30s", l, isTop ? "" : "-"); + } + } + } + + } + + /** + * True to consider only method args + */ + private final boolean argsOnly; + + /** + * Ordinal of the target variable or -1 to fail over to {@link index} + */ + private final int ordinal; + + /** + * Ordinal of the target variable or -1 to fail over to {@link names} + */ + private final int index; + + /** + * Candidate names for the local variable, if empty fails over to matching + * single local by type + */ + private final Set names; + + /** + * @param argsOnly + * @param ordinal target variable ordinal + * @param index target variable index + * @param names target variable names + */ + public LocalVariableDiscriminator(boolean argsOnly, int ordinal, int index, Set names) { + this.argsOnly = argsOnly; + this.ordinal = ordinal; + this.index = index; + this.names = Collections.unmodifiableSet(names); + } + + /** + * True if this discriminator will examine only the target method args and + * won't consider the rest of the LVT at the target location + */ + public boolean isArgsOnly() { + return this.argsOnly; + } + + /** + * Get the local variable ordinal (nth variable of type) + */ + public int getOrdinal() { + return this.ordinal; + } + + /** + * Get the local variable absolute index + */ + public int getIndex() { + return this.index; + } + + /** + * Get valid names for consideration + */ + public Set getNames() { + return this.names; + } + + /** + * Returns true if names is not empty + */ + public boolean hasNames() { + return !this.names.isEmpty(); + } + + /** + * If the user specifies no values for ordinal, index or + * names then we are considered to be operating in "implicit mode" + * where only a single local variable of the specified type is expected to + * exist. + * + * @param context Target context + * @return true if operating in implicit mode + */ + protected boolean isImplicit(final Context context) { + return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty(); + } + + public int findLocal(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + try { + return this.findLocal(new Context(returnType, argsOnly, target, node)); + } catch (InvalidImplicitDiscriminatorException ex) { + return -1; + } + } + + public int findLocal(Context context) { + if (this.isImplicit(context)) { + return this.findImplicitLocal(context); + } + return this.findExplicitLocal(context); + } + + private int findImplicitLocal(final Context context) { + int found = 0; + int count = 0; + for (int index = context.baseArgIndex; index < context.locals.length; index++) { + Local local = context.locals[index]; + if (local == null || !local.type.equals(context.returnType)) { + continue; + } + count++; + found = index; + } + + if (count == 1) { + return found; + } + + throw new InvalidImplicitDiscriminatorException("Found " + count + " candidate variables but exactly 1 is required."); + } + + private int findExplicitLocal(final Context context) { + for (int index = context.baseArgIndex; index < context.locals.length; index++) { + Local local = context.locals[index]; + if (local == null || !local.type.equals(context.returnType)) { + continue; + } + if (this.ordinal > -1) { + if (this.ordinal == local.ord) { + return index; + } + continue; + } + if (this.index >= context.baseArgIndex) { + if (this.index == index) { + return index; + } + continue; + } + if (this.names.contains(local.name)) { + return index; + } + } + + return -1; + } + + public static LocalVariableDiscriminator parse(AnnotationNode annotation) { + boolean argsOnly = ASMHelper.getAnnotationValue(annotation, "argsOnly", Boolean.FALSE).booleanValue(); + int ordinal = ASMHelper.getAnnotationValue(annotation, "ordinal", -1); + int index = ASMHelper.getAnnotationValue(annotation, "index", -1); + + Set names = new HashSet(); + List namesList = ASMHelper.>getAnnotationValue(annotation, "name", (List)null); + if (namesList != null) { + names.addAll(namesList); + } + + return new LocalVariableDiscriminator(argsOnly, ordinal, index, names); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java new file mode 100644 index 00000000..d6a078a5 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -0,0 +1,209 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import java.util.Collection; +import java.util.List; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.SignaturePrinter; + +/** + * A bytecode injector which allows a single local variable in the target method + * to be captured and altered. See also {@link LocalVariableDiscriminator} and + * {@link ModifyVariable}. + */ +public class ModifyVariableInjector extends Injector { + + /** + * Target context information + */ + static class Context extends LocalVariableDiscriminator.Context { + + /** + * Instructions to inject + */ + final InsnList insns = new InsnList(); + + public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + super(returnType, argsOnly, target, node); + } + + } + + /** + * Specialised injection point which uses a target-aware search pattern + */ + abstract static class ContextualInjectionPoint extends InjectionPoint { + + protected final MixinTargetContext mixin; + + ContextualInjectionPoint(MixinTargetContext mixin) { + this.mixin = mixin; + } + + @Override + public boolean find(String desc, InsnList insns, Collection nodes) { + throw new InvalidInjectionException(this.mixin, "STORE injection point must be used in conjunction with @ModifyVariable"); + } + + abstract boolean find(Target target, Collection nodes); + + } + + /** + * Print LVT + */ + private final boolean print; + + /** + * True to consider only method args + */ + private final LocalVariableDiscriminator discriminator; + + /** + * @param info Injection info + * @param print + */ + public ModifyVariableInjector(InjectionInfo info, boolean print, LocalVariableDiscriminator discriminator) { + super(info); + this.print = print; + this.discriminator = discriminator; + } + + @Override + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { + if (injectionPoint instanceof ContextualInjectionPoint) { + return ((ContextualInjectionPoint)injectionPoint).find(this.info.getContext().getTargetMethod(into), nodes); + } + return injectionPoint.find(into.desc, insns, nodes); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector + * #sanityCheck(org.spongepowered.asm.mixin.injection.callback.Target, + * java.util.List) + */ + @Override + protected void sanityCheck(Target target, List injectionPoints) { + super.sanityCheck(target, injectionPoints); + + if (target.isStatic != this.isStatic) { + throw new InvalidInjectionException(this.info, "'static' of variable modifier method does not match target in " + this); + } + + int ordinal = this.discriminator.getOrdinal(); + if (ordinal < -1) { + throw new InvalidInjectionException(this.info, "Invalid ordinal " + ordinal + " specified in " + this); + } + + if (this.discriminator.getIndex() == 0 && !this.isStatic) { + throw new InvalidInjectionException(this.info, "Invalid index 0 specified in non-static variable modifier " + this); + } + } + + /** + * Do the injection + */ + @Override + protected void inject(Target target, InjectionNode node) { + if (node.isReplaced()) { + throw new InvalidInjectionException(this.info, "Variable modifier target for " + this + " was removed by another injector"); + } + + Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget()); + + if (this.print) { + this.printLocals(context); + } + + try { + int local = this.discriminator.findLocal(context); + if (local > -1) { + this.inject(context, local); + } + } catch (InvalidImplicitDiscriminatorException ex) { + throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this, ex); + } + + target.insns.insertBefore(context.node, context.insns); + target.addToStack(this.isStatic ? 1 : 2); + } + + /** + * Pretty-print local variable information to stderr + */ + private void printLocals(final Context context) { + SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, this.returnType, this.methodArgs, new String[] { "var" }); + handlerSig.setModifiers(this.methodNode); + + new PrettyPrinter() + .kvWidth(20) + .kv("Target Class", this.classNode.name.replace('/', '.')) + .kv("Target Method", context.target.method.name) + .kv("Callback Name", this.methodNode.name) + .kv("Capture Type", SignaturePrinter.getTypeName(this.returnType, false)) + .kv("Instruction", "%s %s", context.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(context.node.getOpcode())).hr() + .kv("Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)") + .kv("Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal()) + .kv("Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex()) + .kv("Match name(s)", this.discriminator.hasNames() ? this.discriminator.getNames() : "any") + .kv("Args only", this.discriminator.isArgsOnly()).hr() + .add(context) + .print(System.err); + } + + /** + * Perform the injection + * + * @param context target context + * @param local local variable to capture + */ + private void inject(final Context context, final int local) { + if (!this.isStatic) { + context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + } + + context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local)); + this.invokeHandler(context.insns); + context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local)); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java index 3c9bb9f1..fc975c18 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java @@ -35,7 +35,6 @@ import org.spongepowered.asm.lib.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; - /** *

This injection point searches for INVOKEVIRTUAL, INVOKESTATIC and * INVOKESPECIAL opcodes matching its arguments and returns a list of insns diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index e57b4af8..9249322d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -71,9 +71,9 @@ public class BeforeInvoke extends InjectionPoint { protected final MemberInfo target; /** - * This strategy can be used to identify a particular invokation if the same + * This strategy can be used to identify a particular invocation if the same * method is invoked at multiple points, if this value is -1 then the - * strategy returns all invokations of the method. + * strategy returns all invocations of the method. */ protected final int ordinal; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java index 80149326..a6689266 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java @@ -26,12 +26,16 @@ package org.spongepowered.asm.mixin.injection.struct; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; +/** + * Information about a callback to inject, usually specified by {@link Inject} + */ public class CallbackInjectionInfo extends InjectionInfo { protected CallbackInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { @@ -39,10 +43,12 @@ public class CallbackInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { boolean cancellable = ASMHelper.getAnnotationValue(injectAnnotation, "cancellable", false); LocalCapture locals = ASMHelper.getAnnotationValue(injectAnnotation, "locals", LocalCapture.class, LocalCapture.NO_CAPTURE); + String identifier = ASMHelper.getAnnotationValue(injectAnnotation, "id", ""); - return new CallbackInjector(this, cancellable, locals); + return new CallbackInjector(this, cancellable, locals, identifier); } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 3170d598..9de737f8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -28,24 +28,34 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; -import org.spongepowered.asm.mixin.injection.InvalidInjectionException; +import org.spongepowered.asm.mixin.injection.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; -import org.spongepowered.asm.mixin.transformer.InvalidMixinException; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.ASMHelper; - /** * Contructs information about an injection from an {@link Inject} annotation * and allows the injection to be processed. @@ -68,8 +78,7 @@ public abstract class InjectionInfo { * Mixin data */ protected final MixinTargetContext mixin; - - + /** * Annotated method is static */ @@ -86,16 +95,41 @@ public abstract class InjectionInfo { */ protected final List injectionPoints = new ArrayList(); + /** + * Map of lists of nodes enumerated by calling {@link #prepare} + */ + protected final Map> targetNodes = new LinkedHashMap>(); + /** * Bytecode injector */ protected Injector injector; + /** + * Injection group + */ + protected InjectorGroupInfo group; + /** * Methods injected by injectors */ private final List injectedMethods = new ArrayList(0); + /** + * Number of callbacks we expect to inject into targets + */ + private int expectedCallbackCount = 1; + + /** + * Number of callbacks we require injected + */ + private int requiredCallbackCount = 0; + + /** + * Actual number of injected callbacks + */ + private int injectedCallbackCount = 0; + /** * ctor * @@ -104,10 +138,10 @@ public abstract class InjectionInfo { * @param annotation Annotation to parse */ protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { - this.annotation = annotation; - this.method = method; this.mixin = mixin; - this.classNode = mixin.getTargetClass(); + this.method = method; + this.annotation = annotation; + this.classNode = mixin.getTargetClassNode(); this.isStatic = ASMHelper.methodIsStatic(method); this.readAnnotation(); } @@ -115,55 +149,78 @@ public abstract class InjectionInfo { /** * Parse the info from the supplied annotation */ - @SuppressWarnings("unchecked") protected void readAnnotation() { if (this.annotation == null) { return; } - String type = "@" + this.annotation.desc.substring(this.annotation.desc.lastIndexOf('/') + 1, this.annotation.desc.length() - 1); - + String type = "@" + ASMHelper.getSimpleName(this.annotation); + List injectionPoints = this.readInjectionPoints(type); + this.findMethods(this.parseTarget(type), type); + this.parseInjectionPoints(injectionPoints); + this.parseRequirements(); + this.injector = this.parseInjector(this.annotation); + } + + protected MemberInfo parseTarget(String type) { String method = ASMHelper.getAnnotationValue(this.annotation, "method"); if (method == null) { throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing method name"); } - List ats = null; + try { + MemberInfo targetMember = MemberInfo.parseAndValidate(method, this.mixin); + if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) { + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '" + + targetMember.owner + "', which is not supported"); + } + return targetMember; + } catch (InvalidMemberDescriptorException ex) { + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + ", has invalid target descriptor: \"" + + method + "\""); + } + } + + @SuppressWarnings("unchecked") + protected List readInjectionPoints(String type) { Object atValue = ASMHelper.getAnnotationValue(this.annotation, "at"); if (atValue instanceof List) { - ats = (List)atValue; + return (List)atValue; } else if (atValue instanceof AnnotationNode) { - ats = new ArrayList(); + List ats = new ArrayList(); ats.add((AnnotationNode)atValue); - } else { - throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)"); + return ats; } - - MemberInfo targetMember = MemberInfo.parse(method, this.mixin); - - if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) { - throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '" - + targetMember.owner + "', which is not supported"); - } - - this.findMethods(targetMember); - - if (this.targets.size() == 0) { - throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'"); - } - + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)"); + } + + protected void parseInjectionPoints(List ats) { for (AnnotationNode at : ats) { - InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, at); + InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at); if (injectionPoint != null) { this.injectionPoints.add(injectionPoint); } } + } + + protected void parseRequirements() { + this.group = this.mixin.getInjectorGroups().parseGroup(this.method, this.mixin.getDefaultInjectorGroup()).add(this); - this.injector = this.initInjector(this.annotation); + Integer expect = ASMHelper.getAnnotationValue(this.annotation, "expect"); + if (expect != null) { + this.expectedCallbackCount = expect.intValue(); + } + + Integer require = ASMHelper.getAnnotationValue(this.annotation, "require"); + if (require != null && require.intValue() > -1) { + this.requiredCallbackCount = require.intValue(); + } else if (this.group.isDefault()) { + this.requiredCallbackCount = this.mixin.getDefaultRequiredInjections(); + } } // stub - protected abstract Injector initInjector(AnnotationNode injectAnnotation); + protected abstract Injector parseInjector(AnnotationNode injectAnnotation); /** * Get whether there is enough valid information in this info to actually @@ -176,13 +233,24 @@ public abstract class InjectionInfo { } /** - * Perform the injection + * Discover injection points + */ + public void prepare() { + this.targetNodes.clear(); + for (MethodNode targetMethod : this.targets) { + Target target = this.mixin.getTargetMethod(targetMethod); + this.targetNodes.put(target, this.injector.find(target, this.injectionPoints)); + } + } + + /** + * Perform injections */ public void inject() { - while (this.targets.size() > 0) { - Target target = this.mixin.getTargetMethod(this.targets.removeFirst()); - this.injector.injectInto(target, this.injectionPoints); + for (Entry> entry : this.targetNodes.entrySet()) { + this.injector.inject(entry.getKey(), entry.getValue()); } + this.targets.clear(); } /** @@ -192,6 +260,30 @@ public abstract class InjectionInfo { for (MethodNode method : this.injectedMethods) { this.classNode.methods.add(method); } + + if ((MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) { + throw new InvalidInjectionException(this, + String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded", + this.getDescription(), this.method.name, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount)); + } else if (this.injectedCallbackCount < this.requiredCallbackCount) { + throw new InjectionError( + String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded", + this.getDescription(), this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount)); + } + } + + public void notifyInjected(Target target) { +// this.targets.remove(target.method); + } + + + protected String getDescription() { + return "Callback method"; + } + + @Override + public String toString() { + return InjectionInfo.describeInjector(this.mixin, this.annotation, this.method); } /** @@ -238,6 +330,15 @@ public abstract class InjectionInfo { public Collection getTargets() { return this.targets; } + + /** + * Get the injected callback count + * + * @return the injected callback count + */ + public int getInjectedCallbackCount() { + return this.injectedCallbackCount; + } /** * Inject a method into the target class @@ -254,41 +355,66 @@ public abstract class InjectionInfo { return method; } + /** + * Notify method, called by injector when adding a callback into a target + * + * @param handler callback handler being invoked + */ + public void addCallbackInvocation(MethodNode handler) { + this.injectedCallbackCount++; + } + /** * Finds methods in the target class which match searchFor * * @param searchFor member info to search for + * @param type annotation type */ - private void findMethods(MemberInfo searchFor) { + private void findMethods(MemberInfo searchFor, String type) { this.targets.clear(); int ordinal = 0; for (MethodNode target : this.classNode.methods) { if (searchFor.matches(target.name, target.desc, ordinal)) { - if (searchFor.matchAll && ASMHelper.methodIsStatic(target) != this.isStatic) { + boolean isMixinMethod = ASMHelper.getVisibleAnnotation(target, MixinMerged.class) != null; + if (searchFor.matchAll && (ASMHelper.methodIsStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { continue; } - AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class); - if (merged != null) { - throw new InvalidInjectionException(this, "Cannot inject into a mixin method"); - } - + this.checkTarget(target); + this.targets.add(target); ordinal++; } } + + if (this.targets.size() == 0) { + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + searchFor.name + "'"); + } + } + + private void checkTarget(MethodNode target) { + AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class); + if (merged == null) { + return; + } + + String owner = ASMHelper.getAnnotationValue(merged, "mixin"); + int priority = ASMHelper.getAnnotationValue(merged, "priority"); + + if (priority >= this.mixin.getPriority() && !owner.equals(this.mixin.getClassName())) { + throw new InvalidInjectionException(this, this + " cannot inject into " + this.classNode.name + "::" + target.name + target.desc + + " merged by " + owner + " with priority " + priority); + } + + if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) { + throw new InvalidInjectionException(this, this + " cannot inject into @Final method " + this.classNode.name + "::" + target.name + + target.desc + " merged by " + owner); + } } - @SuppressWarnings("unchecked") public static InjectionInfo parse(MixinTargetContext mixin, MethodNode method) { - AnnotationNode annotation = null; - try { - annotation = ASMHelper.getSingleVisibleAnnotation(method, Inject.class, ModifyArg.class, Redirect.class); - } catch (IllegalArgumentException ex) { - throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": " - + ex.getMessage()); - } + AnnotationNode annotation = InjectionInfo.getInjectorAnnotation(mixin, method); if (annotation == null) { return null; @@ -300,8 +426,50 @@ public abstract class InjectionInfo { return new ModifyArgInjectionInfo(mixin, method, annotation); } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { return new RedirectInjectionInfo(mixin, method, annotation); + } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { + return new ModifyVariableInjectionInfo(mixin, method, annotation); + } else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) { + return new ModifyConstantInjectionInfo(mixin, method, annotation); } return null; } + + @SuppressWarnings("unchecked") + public static AnnotationNode getInjectorAnnotation(MixinTargetContext mixin, MethodNode method) { + AnnotationNode annotation = null; + try { + annotation = ASMHelper.getSingleVisibleAnnotation(method, + Inject.class, + ModifyArg.class, + Redirect.class, + ModifyVariable.class, + ModifyConstant.class + ); + } catch (IllegalArgumentException ex) { + throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": " + + ex.getMessage()); + } + return annotation; + } + + public static String getInjectorPrefix(AnnotationNode annotation) { + if (annotation != null) { + if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) { + return "modify"; + } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { + return "redirect"; + } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { + return "localvar"; + } else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) { + return "constant"; + } + } + return "handler"; + } + + static String describeInjector(MixinTargetContext mixin, AnnotationNode annotation, MethodNode method) { + return String.format("%s->@%s::%s%s", mixin.toString(), ASMHelper.getSimpleName(annotation), method.name, method.desc); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index 57222c07..8566b356 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -28,8 +28,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.spongepowered.asm.mixin.transformer.IReferenceMapperContext; - +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; /** * Data read from an {@link org.spongepowered.asm.mixin.injection.At} annotation @@ -45,8 +48,23 @@ public class InjectionPointData { /** * Mixin */ - private final IReferenceMapperContext mixin; + private final MixinTargetContext mixin; + /** + * Injector callback + */ + private MethodNode method; + + /** + * Parent annotation + */ + private AnnotationNode parent; + + /** + * At arg + */ + private String at; + /** * Target */ @@ -62,8 +80,12 @@ public class InjectionPointData { */ private final int opcode; - public InjectionPointData(IReferenceMapperContext mixin, List args, String target, int ordinal, int opcode) { + public InjectionPointData(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, List args, String target, + int ordinal, int opcode) { this.mixin = mixin; + this.method = method; + this.parent = parent; + this.at = at; this.target = target; this.ordinal = Math.max(-1, ordinal); this.opcode = opcode; @@ -76,6 +98,9 @@ public class InjectionPointData { } private void parseArgs(List args) { + if (args == null) { + return; + } for (String arg : args) { if (arg != null) { int eqPos = arg.indexOf('='); @@ -87,6 +112,18 @@ public class InjectionPointData { } } } + + public MixinTargetContext getMixin() { + return this.mixin; + } + + public MethodNode getMethod() { + return this.method; + } + + public AnnotationNode getParent() { + return this.parent; + } public String get(String key, String defaultValue) { String value = this.args.get(key); @@ -102,7 +139,12 @@ public class InjectionPointData { } public MemberInfo get(String key) { - return MemberInfo.parse(this.get(key, ""), this.mixin); + try { + return MemberInfo.parseAndValidate(this.get(key, ""), this.mixin); + } catch (InvalidMemberDescriptorException ex) { + throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s", + this.at, key, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method)); + } } private int parseInt(String string, int defaultValue) { @@ -122,7 +164,12 @@ public class InjectionPointData { } public MemberInfo getTarget() { - return MemberInfo.parse(this.target, this.mixin); + try { + return MemberInfo.parseAndValidate(this.target, this.mixin); + } catch (InvalidMemberDescriptorException ex) { + throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\") descriptor \"%s\" on %s", + this.at, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method)); + } } public int getOrdinal() { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java new file mode 100644 index 00000000..15be6346 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java @@ -0,0 +1,48 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Thrown when a {@link MemberInfo} fails basic syntax validation + */ +public class InvalidMemberDescriptorException extends MixinException { + + private static final long serialVersionUID = 1L; + + public InvalidMemberDescriptorException(String message) { + super(message); + } + + public InvalidMemberDescriptorException(Throwable cause) { + super(cause); + } + + public InvalidMemberDescriptorException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index 2019777f..956f47fc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -24,15 +24,16 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import net.minecraftforge.srg2source.rangeapplier.MethodData; - +import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.FieldInsnNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.mixin.transformer.IReferenceMapperContext; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.obfuscation.SrgMethod; import org.spongepowered.asm.util.SignaturePrinter; - /** *

Information bundle about a member (method or field) parsed from a String * token in another annotation, this is used where target members need to be @@ -164,31 +165,42 @@ public class MemberInfo { } /** - * Initialise a MemberInfo using the supplied MethodData object + * Initialise a MemberInfo using the supplied SrgMethod object * - * @param methodData MethodData object to copy values from + * @param srgMethod SrgMethod object to copy values from */ - private MemberInfo(MethodData methodData) { - int slashPos = methodData.name.lastIndexOf('/'); - this.owner = methodData.name.substring(0, slashPos); - this.name = methodData.name.substring(slashPos + 1); - this.desc = methodData.sig; + public MemberInfo(SrgMethod srgMethod) { + this.owner = srgMethod.getOwner(); + this.name = srgMethod.getSimpleName(); + this.desc = srgMethod.getDesc(); this.matchAll = false; } /** - * Initialise a remapped MemberInfo using the supplied MethodData object + * Initialise a remapped MemberInfo using the supplied SrgMethod object * - * @param methodData MethodData object to copy values from + * @param srgMethod SrgMethod object to copy values from */ - private MemberInfo(MemberInfo remapped, MethodData methodData, boolean setOwner) { - int slashPos = methodData.name.lastIndexOf('/'); - this.owner = setOwner ? methodData.name.substring(0, slashPos) : remapped.owner; - this.name = methodData.name.substring(slashPos + 1); - this.desc = remapped.desc; - this.matchAll = false; + private MemberInfo(MemberInfo remapped, SrgMethod srgMethod, boolean setOwner) { + this.owner = setOwner ? srgMethod.getOwner() : remapped.owner; + this.name = srgMethod.getSimpleName(); + this.desc = srgMethod.getDesc(); + this.matchAll = remapped.matchAll; } + /** + * Initialise a remapped MemberInfo with a new name + * + * @param original Original MemberInfo + * @param owner new owner + */ + private MemberInfo(MemberInfo original, String owner) { + this.owner = owner; + this.name = original.name; + this.desc = original.desc; + this.matchAll = original.matchAll; + } + /* (non-Javadoc) * @see java.lang.Object#toString() */ @@ -209,7 +221,7 @@ public class MemberInfo { */ public String toSrg() { if (!this.isFullyQualified()) { - throw new RuntimeException("Cannot convert unqalified reference to SRG mapping"); + throw new MixinException("Cannot convert unqualified reference to SRG mapping"); } if (this.desc.startsWith("(")) { @@ -227,16 +239,16 @@ public class MemberInfo { return new SignaturePrinter(this).setFullyQualified(true).toDescriptor(); } - public MethodData asMethodData() { + public SrgMethod asSrgMethod() { if (!this.isFullyQualified()) { - throw new RuntimeException("Cannot convert unqalified reference to MethodData"); + throw new MixinException("Cannot convert unqualified reference to SrgMethod"); } if (this.isField()) { - throw new RuntimeException("Cannot convert a non-method reference to MethodData"); + throw new MixinException("Cannot convert a non-method reference to SrgMethod"); } - return new MethodData(this.owner + "/" + this.name, this.desc); + return new SrgMethod(this.owner + "/" + this.name, this.desc); } /** @@ -257,6 +269,64 @@ public class MemberInfo { public boolean isField() { return this.desc != null && !this.desc.startsWith("("); } + + /** + * Perform ultra-simple validation of the descriptor, checks that the parts + * of the descriptor are basically sane. + * + * @return fluent + * + * @throws InvalidMemberDescriptorException if any validation check fails + */ + public MemberInfo validate() throws InvalidMemberDescriptorException { + // Extremely naive class name validation, just to spot really egregious errors + if (this.owner != null) { + if (!this.owner.matches("(?i)^[\\w\\p{Sc}/]+$")) { + throw new InvalidMemberDescriptorException("Invalid owner: " + this.owner); + } + try { + if (!this.owner.equals(Type.getType(this.owner).getDescriptor())) { + throw new InvalidMemberDescriptorException("Invalid owner type specified: " + this.owner); + } + } catch (Exception ex) { + throw new InvalidMemberDescriptorException("Invalid owner type specified: " + this.owner); + } + } + + // Also naive validation, we're looking for stupid errors here + if (this.name != null && !this.name.matches("(?i)^?$")) { + throw new InvalidMemberDescriptorException("Invalid name: " + this.name); + } + + if (this.desc != null) { + if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[?[\\w\\p{Sc}/;]+$")) { + throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + } + if (this.isField()) { + if (!this.desc.equals(Type.getType(this.desc).getDescriptor())) { + throw new InvalidMemberDescriptorException("Invalid field type in descriptor: " + this.desc); + } + } else { + try { + Type.getArgumentTypes(this.desc); + } catch (Exception ex) { + throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + } + + String retString = this.desc.substring(this.desc.indexOf(')') + 1); + try { + Type retType = Type.getType(retString); + if (!retString.equals(retType.getDescriptor())) { + throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + } + } catch (Exception ex) { + throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + } + } + } + + return this; + } /** * Test whether this MemberInfo matches the supplied values. Null values are @@ -327,15 +397,48 @@ public class MemberInfo { && (ordinal == 0 || this.matchAll); } + /** + * Create a new version of this member with a different owner + * + * @param newOwner New owner for this member + */ + public MemberInfo move(String newOwner) { + if (newOwner.equals(this.owner)) { + return this; + } + return new MemberInfo(this, newOwner); + } + /** * Create a remapped version of this member using the supplied method data * - * @param methodData Method data to use + * @param srgMethod SRG method data to use * @param setOwner True to set the owner as well as the name * @return New MethodInfo with remapped values */ - public MemberInfo remapUsing(MethodData methodData, boolean setOwner) { - return new MemberInfo(this, methodData, setOwner); + public MemberInfo remapUsing(SrgMethod srgMethod, boolean setOwner) { + return new MemberInfo(this, srgMethod, setOwner); + } + + /** + * Parse a MemberInfo from a string and perform validation + * + * @param string String to parse MemberInfo from + * @return parsed MemberInfo + */ + public static MemberInfo parseAndValidate(String string) throws InvalidMemberDescriptorException { + return MemberInfo.parse(string, null, null).validate(); + } + + /** + * Parse a MemberInfo from a string and perform validation + * + * @param string String to parse MemberInfo from + * @param context Context to use for reference mapping + * @return parsed MemberInfo + */ + public static MemberInfo parseAndValidate(String string, IReferenceMapperContext context) throws InvalidMemberDescriptorException { + return MemberInfo.parse(string, context.getReferenceMapper(), context.getClassRef()).validate(); } /** @@ -367,10 +470,12 @@ public class MemberInfo { * @param mixinClass Mixin class to use for remapping * @return parsed MemberInfo */ - public static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) { + private static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) { String desc = null; String owner = null; + name = name.replaceAll("\\s", ""); + if (refMapper != null) { name = refMapper.remap(mixinClass, name); } @@ -414,7 +519,7 @@ public class MemberInfo { return new MemberInfo(name, owner, desc, false); } - public static MemberInfo fromSrgMethod(MethodData methodData) { - return new MemberInfo(methodData); + public static MemberInfo fromSrgMethod(SrgMethod srgMethod) { + return new MemberInfo(srgMethod); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java index 76031d9d..681f5466 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java @@ -26,11 +26,15 @@ package org.spongepowered.asm.mixin.injection.struct; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.ModifyArgInjector; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; +/** + * Information about a {@link ModifyArg} injector + */ public class ModifyArgInjectionInfo extends InjectionInfo { public ModifyArgInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { @@ -38,9 +42,15 @@ public class ModifyArgInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { int index = ASMHelper.getAnnotationValue(injectAnnotation, "index", -1); return new ModifyArgInjector(this, index); } + + @Override + protected String getDescription() { + return "Argument modifier method"; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java new file mode 100644 index 00000000..36e52a5d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -0,0 +1,222 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.ListIterator; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.invoke.ModifyConstantInjector; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.Constants; + +/** + * Information about a constant modifier injector + */ +public class ModifyConstantInjectionInfo extends InjectionInfo { + + /** + * Special injection point which is defined by an {@link Constant} + * annotation. + */ + static class BeforeConstant extends InjectionPoint { + + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Ordinal of the target insn + */ + private final int ordinal; + + private final boolean nullValue; + private final Integer intValue; + private final Float floatValue; + private final Long longValue; + private final Double doubleValue; + private final String stringValue; + private final Type typeValue; + + private final String matchByType; + + private final boolean log; + + public BeforeConstant(InjectionInfo info, AnnotationNode node, String returnType) { + Boolean empty = ASMHelper.getAnnotationValue(node, "nullValue", (Boolean)null); + this.ordinal = ASMHelper.getAnnotationValue(node, "ordinal", Integer.valueOf(-1)); + this.nullValue = empty != null ? empty.booleanValue() : false;; + this.intValue = ASMHelper.getAnnotationValue(node, "intValue", (Integer)null); + this.floatValue = ASMHelper.getAnnotationValue(node, "floatValue", (Float)null); + this.longValue = ASMHelper.getAnnotationValue(node, "longValue", (Long)null); + this.doubleValue = ASMHelper.getAnnotationValue(node, "doubleValue", (Double)null); + this.stringValue = ASMHelper.getAnnotationValue(node, "stringValue", (String)null); + this.typeValue = ASMHelper.getAnnotationValue(node, "classValue", (Type)null); + + int c = BeforeConstant.count(empty, this.intValue, this.floatValue, this.longValue, this.doubleValue, this.stringValue, this.typeValue); + if (c == 1) { + returnType = null; + } else if (c > 1) { + throw new InvalidInjectionException(info, "Conflicting constant discriminators specified on @Constant annotation for " + info); + } + + this.matchByType = returnType; + + this.log = ASMHelper.getAnnotationValue(node, "log", Boolean.FALSE).booleanValue(); + } + + @Override + public boolean find(String desc, InsnList insns, Collection nodes) { + boolean found = false; + + if (this.log) { + BeforeConstant.logger.info("BeforeConstant is searching for an constants in method with descriptor {}", desc); + } + + ListIterator iter = insns.iterator(); + for (int ordinal = 0; iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + + boolean matchesInsn = this.matchesInsn(insn); + if (matchesInsn) { + if (this.log) { + String byType = this.matchByType != null ? " TYPE" : " value"; + BeforeConstant.logger.info(" BeforeConstant found a matching constant{} at ordinal {}", byType, ordinal); + } + if (this.ordinal == -1 || this.ordinal == ordinal) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found {}", ASMHelper.getNodeDescriptionForDebug(insn).trim()); + } + nodes.add(insn); + found = true; + } + ordinal++; + } + } + + return found; + } + + private boolean matchesInsn(AbstractInsnNode insn) { + if (!ASMHelper.isConstant(insn)) { + return false; + } + + Object value = ASMHelper.getConstant(insn); + if (value == null) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue); + } + return this.nullValue || Constants.OBJECT.equals(this.matchByType); + } else if (value instanceof Integer) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found INTEGER constant: value = {}, intValue = {}", value, this.intValue); + } + return value.equals(this.intValue) || "I".equals(this.matchByType); + } else if (value instanceof Float) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found FLOAT constant: value = {}, floatValue = {}", value, this.floatValue); + } + return value.equals(this.floatValue) || "F".equals(this.matchByType); + } else if (value instanceof Long) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found LONG constant: value = {}, longValue = {}", value, this.longValue); + } + return value.equals(this.longValue) || "J".equals(this.matchByType); + } else if (value instanceof Double) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found DOUBLE constant: value = {}, doubleValue = {}", value, this.doubleValue); + } + return value.equals(this.doubleValue) || "D".equals(this.matchByType); + } else if (value instanceof String) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found STRING constant: value = {}, stringValue = {}", value, this.stringValue); + } + return value.equals(this.stringValue) || Constants.STRING.equals(this.matchByType); + } else if (value instanceof Type) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found CLASS constant: value = {}, typeValue = {}", value, this.typeValue); + } + return value.equals(this.typeValue) || Constants.CLASS.equals(this.matchByType); + } + + return false; + } + + private static int count(Object... values) { + int counter = 0; + for (Object value : values) { + if (value != null) { + counter++; + } + } + return counter; + } + + } + + public ModifyConstantInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected List readInjectionPoints(String type) { + AnnotationNode constantAnnotation = ASMHelper.getAnnotationValue(this.annotation, "constant"); + List ats = new ArrayList(); + ats.add(constantAnnotation); + return ats; + } + + @Override + protected void parseInjectionPoints(List ats) { + Type returnType = Type.getReturnType(this.method.desc); + + for (AnnotationNode at : ats) { + this.injectionPoints.add(new BeforeConstant(this, at, returnType.getDescriptor())); + } + } + + @Override + protected Injector parseInjector(AnnotationNode injectAnnotation) { + return new ModifyConstantInjector(this); + } + + @Override + protected String getDescription() { + return "Constant modifier method"; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java new file mode 100644 index 00000000..0c254f82 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java @@ -0,0 +1,56 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; +import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Information about a {@link ModifyVariable} injector + */ +public class ModifyVariableInjectionInfo extends InjectionInfo { + + public ModifyVariableInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected Injector parseInjector(AnnotationNode injectAnnotation) { + boolean print = ASMHelper.getAnnotationValue(injectAnnotation, "print", Boolean.FALSE).booleanValue(); + return new ModifyVariableInjector(this, print, LocalVariableDiscriminator.parse(injectAnnotation)); + } + + @Override + protected String getDescription() { + return "Variable modifier method"; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java index fba241ff..f46332f3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java @@ -30,6 +30,9 @@ import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +/** + * Information about a redirector injector + */ public class RedirectInjectionInfo extends InjectionInfo { public RedirectInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { @@ -37,7 +40,13 @@ public class RedirectInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { return new RedirectInjector(this); } + + @Override + protected String getDescription() { + return "Redirector"; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ReferenceMapper.java deleted file mode 100644 index f2c5122a..00000000 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ReferenceMapper.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This file is part of Mixin, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.asm.mixin.injection.struct; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.launchwrapper.Launch; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public final class ReferenceMapper implements Serializable { - - private static final long serialVersionUID = 1L; - - public static final String DEFAULT_RESOURCE = "mixin.refmap.json"; - - private final Map> mappings; - - public ReferenceMapper() { - this(new HashMap>()); - } - - public ReferenceMapper(Map> mappings) { - this.mappings = mappings; - } - - public String remap(String className, String reference) { - if (className == null) { - for (Map mappings : this.mappings.values()) { - if (mappings.containsKey(reference)) { - return mappings.get(reference); - } - } - } - - Map classMappings = this.mappings.get(className); - if (classMappings == null) { - return reference; - } - String remappedReference = classMappings.get(reference); - return remappedReference != null ? remappedReference : reference; - } - - public void addMapping(String className, String reference, String newReference) { - Map classMappings = this.mappings.get(className); - if (classMappings == null) { - classMappings = new HashMap(); - this.mappings.put(className, classMappings); - } - classMappings.put(reference, newReference); - } - - public void write(Appendable writer) { - new GsonBuilder().setPrettyPrinting().create().toJson(this, writer); - } - - public static ReferenceMapper read(String resource) { - Reader reader = null; - try { - reader = new InputStreamReader(Launch.classLoader.getResourceAsStream(resource)); - return ReferenceMapper.read(reader); - } catch (Exception ex) { - return new ReferenceMapper(); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ex) { - // don't really care - } - } - } - } - - public static ReferenceMapper read(Reader reader) { - return new Gson().fromJson(reader, ReferenceMapper.class); - } -} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java index 210a36ea..21c6e0dd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java @@ -25,17 +25,21 @@ package org.spongepowered.asm.mixin.injection.struct; import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.InjectionNodes; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.util.ASMHelper; - /** * Information about the current injection target, mainly just convenience * rather than passing a bunch of values around. */ -public class Target { +public class Target implements Comparable { + + public final ClassNode classNode; /** * Target method @@ -67,16 +71,6 @@ public class Target { */ public final Type returnType; - /** - * Method's (original) MAXS - */ - private final int maxStack; - - /** - * Method's original max locals - */ - private final int maxLocals; - /** * Callback method descriptor based on this target */ @@ -86,13 +80,29 @@ public class Target { * Callback info class */ public final String callbackInfoClass; + + /** + * Nodes targetted by injectors + */ + public final InjectionNodes injectionNodes = new InjectionNodes(); + + /** + * Method's (original) MAXS + */ + private final int maxStack; + + /** + * Method's original max locals + */ + private final int maxLocals; /** * Make a new Target for the supplied method * * @param method target method */ - public Target(MethodNode method) { + public Target(ClassNode classNode, MethodNode method) { + this.classNode = classNode; this.method = method; this.insns = method.instructions; this.isStatic = ASMHelper.methodIsStatic(method); @@ -255,9 +265,10 @@ public class Target { } String descriptor = this.callbackDescriptor.substring(0, this.callbackDescriptor.indexOf(')')); - for (int l = startIndex; l < locals.length && l < (startIndex + extra); l++) { + for (int l = startIndex; l < locals.length && extra > 0; l++) { if (locals[l] != null) { descriptor += locals[l].getDescriptor(); + extra--; } } @@ -266,6 +277,79 @@ public class Target { @Override public String toString() { - return this.method.name + this.method.desc; + return String.format("%s::%s%s", this.classNode.name, this.method.name, this.method.desc); } + + @Override + public int compareTo(Target o) { + if (o == null) { + return Integer.MAX_VALUE; + } + return this.toString().compareTo(o.toString()); + } + + /** + * Replace an instruction in this target with the specified instruction and + * mark the node as replaced for other injectors + * + * @param location Instruction to replace + * @param insn Instruction to replace with + */ + public void replaceNode(AbstractInsnNode location, AbstractInsnNode insn) { + this.insns.insertBefore(location, insn); + this.insns.remove(location); + this.injectionNodes.replace(location, insn); + } + + /** + * Replace an instruction in this target with the specified instructions and + * mark the node as replaced with the specified champion node from the list. + * + * @param location Instruction to replace + * @param champion Instruction which notionally replaces the original insn + * @param insns Instructions to actually insert (must contain champion) + */ + public void replaceNode(AbstractInsnNode location, AbstractInsnNode champion, InsnList insns) { + this.insns.insertBefore(location, insns); + this.insns.remove(location); + this.injectionNodes.replace(location, champion); + } + + /** + * Wrap instruction in this target with the specified instructions and mark + * the node as replaced with the specified champion node from the list. + * + * @param location Instruction to replace + * @param champion Instruction which notionally replaces the original insn + * @param before Instructions to actually insert (must contain champion) + */ + public void wrapNode(AbstractInsnNode location, AbstractInsnNode champion, InsnList before, InsnList after) { + this.insns.insertBefore(location, before); + this.insns.insert(location, after); + this.injectionNodes.replace(location, champion); + } + + /** + * Replace an instruction in this target with the specified instructions and + * mark the original node as removed + * + * @param location Instruction to replace + * @param insns Instructions to replace with + */ + public void replaceNode(AbstractInsnNode location, InsnList insns) { + this.insns.insertBefore(location, insns); + this.removeNode(location); + } + + /** + * Remove the specified instruction from the target and mark it as removed + * for injections + * + * @param insn instruction to remove + */ + public void removeNode(AbstractInsnNode insn) { + this.insns.remove(insn); + this.injectionNodes.remove(insn); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionError.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java similarity index 96% rename from src/main/java/org/spongepowered/asm/mixin/injection/InjectionError.java rename to src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java index bd53925f..518cf649 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionError.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java @@ -22,8 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.injection; - +package org.spongepowered.asm.mixin.injection.throwables; /** * Error to throw for critical injection problems diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionValidationException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionValidationException.java new file mode 100644 index 00000000..e9b9c9dd --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionValidationException.java @@ -0,0 +1,47 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.throwables; + +import org.spongepowered.asm.mixin.injection.InjectorGroupInfo; + +/** + * Thrown when an injector group fails an injection check + */ +public class InjectionValidationException extends Exception { + + private static final long serialVersionUID = 1L; + + private final InjectorGroupInfo group; + + public InjectionValidationException(InjectorGroupInfo group, String message) { + super(message); + this.group = group; + } + + public InjectorGroupInfo getGroup() { + return this.group; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java similarity index 62% rename from src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java rename to src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java index a698cd90..630a1f4c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java @@ -22,39 +22,54 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.injection; +package org.spongepowered.asm.mixin.injection.throwables; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; -import org.spongepowered.asm.mixin.transformer.InvalidMixinException; -import org.spongepowered.asm.mixin.transformer.MixinTargetContext; - +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +/** + * Thrown when an injector fails a state check, for example if an injector + * handler signature is invalid, an invalid opcode is targetted, etc. + */ public class InvalidInjectionException extends InvalidMixinException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2L; + + private final InjectionInfo info; - public InvalidInjectionException(MixinTargetContext mixin, String message) { - super(mixin, message); + public InvalidInjectionException(IReferenceMapperContext context, String message) { + super(context, message); + this.info = null; } public InvalidInjectionException(InjectionInfo info, String message) { super(info.getContext(), message); + this.info = info; } - public InvalidInjectionException(MixinTargetContext mixin, Throwable cause) { - super(mixin, cause); + public InvalidInjectionException(IReferenceMapperContext context, Throwable cause) { + super(context, cause); + this.info = null; } public InvalidInjectionException(InjectionInfo info, Throwable cause) { super(info.getContext(), cause); + this.info = info; } - public InvalidInjectionException(MixinTargetContext mixin, String message, Throwable cause) { - super(mixin, message, cause); + public InvalidInjectionException(IReferenceMapperContext context, String message, Throwable cause) { + super(context, message, cause); + this.info = null; } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) { super(info.getContext(), message, cause); + this.info = info; + } + + public InjectionInfo getInjectionInfo() { + return this.info; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionPointException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionPointException.java new file mode 100644 index 00000000..e27ce55f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionPointException.java @@ -0,0 +1,53 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.throwables; + +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; + +/** + * Thrown when an injection point cannot be parsed due to invalid data + */ +public class InvalidInjectionPointException extends InvalidInjectionException { + + private static final long serialVersionUID = 2L; + + public InvalidInjectionPointException(IReferenceMapperContext context, String format, Object... args) { + super(context, String.format(format, args)); + } + + public InvalidInjectionPointException(InjectionInfo info, String format, Object... args) { + super(info, String.format(format, args)); + } + + public InvalidInjectionPointException(IReferenceMapperContext context, Throwable cause, String format, Object... args) { + super(context, String.format(format, args), cause); + } + + public InvalidInjectionPointException(InjectionInfo info, Throwable cause, String format, Object... args) { + super(info, String.format(format, args), cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IReferenceMapperContext.java b/src/main/java/org/spongepowered/asm/mixin/refmap/IReferenceMapperContext.java similarity index 89% rename from src/main/java/org/spongepowered/asm/mixin/transformer/IReferenceMapperContext.java rename to src/main/java/org/spongepowered/asm/mixin/refmap/IReferenceMapperContext.java index 0e54d166..c1656897 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/IReferenceMapperContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/IReferenceMapperContext.java @@ -22,14 +22,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; +package org.spongepowered.asm.mixin.refmap; -import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; /** * Context for performing reference mapping */ public interface IReferenceMapperContext { + + /** + * Get the mixin info + */ + public abstract IMixinInfo getMixin(); /** * Get the internal mixin class name diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java new file mode 100644 index 00000000..81199606 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java @@ -0,0 +1,247 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.refmap; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import net.minecraft.launchwrapper.Launch; + +/** + * Stores runtime information allowing field, method and type references which + * cannot be hard remapped by the reobfuscation process to be remapped in a + * "soft" manner at runtime. Refmaps are generated by the Annotation + * Processor at compile time and must be bundled with an obfuscated binary + * to allow obfuscated references in injectors and other String-defined targets + * to be remapped to the target obfsucation environment as appropriate. If the + * refmap is absent the environment is assumed to be deobfuscated (eg. dev-time) + * and injections and other transformations will fail if this is not the case. + */ +public final class ReferenceMapper implements Serializable { + + private static final long serialVersionUID = 2L; + + /** + * Resource to attempt to load if no source is specified explicitly + */ + public static final String DEFAULT_RESOURCE = "mixin.refmap.json"; + + /** + * Passthrough mapper, used as failover + */ + public static final ReferenceMapper DEFAULT_MAPPER = new ReferenceMapper(true); + + /** + * "Default" mappings. The set of mappings to use as "default" is specified + * by the AP. Each entry is keyed by the owning mixin, with the value map + * containing the actual remappings for each owner + */ + private final Map> mappings = Maps.newHashMap(); + + /** + * All mapping sets, keyed by environment type, eg. "notch", "searge". The + * format of each map within this map is the same as for {@link #mappings} + */ + private final Map>> data = Maps.newHashMap(); + + /** + * True if this refmap cannot be written. Only true for the + * {@link #DEFAULT_MAPPER} + */ + private final transient boolean readOnly; + + /** + * Current remapping context, used as the key into {@link data} + */ + private transient String context = null; + + /** + * Create an empty refmap + */ + public ReferenceMapper() { + this(false); + } + + /** + * Create a readonly refmap, only used by {@link #DEFAULT_MAPPER} + * + * @param readOnly flag to indicate read-only + */ + private ReferenceMapper(boolean readOnly) { + this.readOnly = readOnly; + } + + /** + * Get the current context + * + * @return current context key, can be null + */ + public String getContext() { + return this.context; + } + + /** + * Set the current remap context, can be null + * + * @param context remap context + */ + public void setContext(String context) { + this.context = context; + } + + /** + * Remap a reference for the specified owning class in the current context + * + * @param className Owner class + * @param reference Reference to remap + * @return remapped reference, returns original reference if not remapped + */ + public String remap(String className, String reference) { + return this.remapWithContext(this.context, className, reference); + } + + /** + * Remap a reference for the specified owning class in the specified context + * + * @param context Remap context to use + * @param className Owner class + * @param reference Reference to remap + * @return remapped reference, returns original reference if not remapped + */ + public String remapWithContext(String context, String className, String reference) { + Map> mappings = this.mappings; + if (context != null) { + mappings = this.data.get(context); + if (mappings == null) { + mappings = this.mappings; + } + } + return this.remap(mappings, className, reference); + } + + /** + * Remap the things + */ + private String remap(Map> mappings, String className, String reference) { + if (className == null) { + for (Map mapping : mappings.values()) { + if (mapping.containsKey(reference)) { + return mapping.get(reference); + } + } + } + + Map classMappings = mappings.get(className); + if (classMappings == null) { + return reference; + } + String remappedReference = classMappings.get(reference); + return remappedReference != null ? remappedReference : reference; + } + + /** + * Add a mapping to this refmap + * + * @param context Obfuscation context, can be null + * @param className Class which owns this mapping, cannot be null + * @param reference Reference to remap, cannot be null + * @param newReference Remapped value, cannot be null + */ + public void addMapping(String context, String className, String reference, String newReference) { + if (this.readOnly || reference == null || newReference == null || reference.equals(newReference)) { + return; + } + Map> mappings = this.mappings; + if (context != null) { + mappings = this.data.get(context); + if (mappings == null) { + mappings = Maps.newHashMap(); + this.data.put(context, mappings); + } + } + Map classMappings = mappings.get(className); + if (classMappings == null) { + classMappings = new HashMap(); + mappings.put(className, classMappings); + } + classMappings.put(reference, newReference); + } + + /** + * Write this refmap out to the specified writer + * + * @param writer Writer to write to + */ + public void write(Appendable writer) { + new GsonBuilder().setPrettyPrinting().create().toJson(this, writer); + } + + /** + * Read a new refmap from the specified resource + * + * @param resource Resource to read from + * @return new refmap or {@link #DEFAULT_MAPPER} if reading fails + */ + public static ReferenceMapper read(String resource) { + Reader reader = null; + try { + reader = new InputStreamReader(Launch.classLoader.getResourceAsStream(resource)); + return ReferenceMapper.read(reader); + } catch (Exception ex) { + return ReferenceMapper.DEFAULT_MAPPER; + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ex) { + // don't really care + } + } + } + } + + /** + * Read a new refmap instance from the specified reader + * + * @param reader Reader to read from + * @return new refmap + */ + public static ReferenceMapper read(Reader reader) { + try { + return new Gson().fromJson(reader, ReferenceMapper.class); + } catch (Exception ex) { + return ReferenceMapper.DEFAULT_MAPPER; + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/ClassAlreadyLoadedException.java b/src/main/java/org/spongepowered/asm/mixin/throwables/ClassAlreadyLoadedException.java new file mode 100644 index 00000000..375c8185 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/ClassAlreadyLoadedException.java @@ -0,0 +1,50 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/** + * + */ +package org.spongepowered.asm.mixin.throwables; + +/** + * Exception raised when a class was loaded before mixins were able to be + * applied. + */ +public class ClassAlreadyLoadedException extends MixinException { + + private static final long serialVersionUID = 1L; + + public ClassAlreadyLoadedException(String message) { + super(message); + } + + public ClassAlreadyLoadedException(Throwable cause) { + super(cause); + } + + public ClassAlreadyLoadedException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinApplyError.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java similarity index 97% rename from src/main/java/org/spongepowered/asm/mixin/MixinApplyError.java rename to src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java index 0803f8cd..a3fa7bfc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinApplyError.java +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java @@ -22,8 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin; - +package org.spongepowered.asm.mixin.throwables; /** * Error to throw for required mixins when mixing of the mixin fails diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassNode.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java similarity index 71% rename from src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassNode.java rename to src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java index b54c68c8..145f5452 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassNode.java +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java @@ -22,28 +22,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; - -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.ClassNode; +package org.spongepowered.asm.mixin.throwables; /** - * ClassNode for a MixinInfo + * Base class for all mixin processor exceptions */ -public class MixinClassNode extends ClassNode { - - private final MixinInfo mixin; +public class MixinException extends RuntimeException { - public MixinClassNode(MixinInfo mixin) { - this(Opcodes.ASM5, mixin); + private static final long serialVersionUID = 1L; + + public MixinException() { } - public MixinClassNode(int api, MixinInfo mixin) { - super(api); - this.mixin = mixin; + public MixinException(String message) { + super(message); } - public MixinInfo getMixin() { - return this.mixin; + public MixinException(Throwable cause) { + super(cause); } + + public MixinException(String message, Throwable cause) { + super(message, cause); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java new file mode 100644 index 00000000..f5e64c05 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java @@ -0,0 +1,46 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.throwables; + +/** + * Error to throw for required configs when initialising of the config fails + */ +public class MixinPrepareError extends Error { + + private static final long serialVersionUID = 1L; + + public MixinPrepareError(String message) { + super(message); + } + + public MixinPrepareError(Throwable cause) { + super(cause); + } + + public MixinPrepareError(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java index a86fa7ee..edc384f3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -43,89 +43,96 @@ import org.spongepowered.asm.lib.tree.FieldNode; import org.spongepowered.asm.lib.tree.FrameNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; +import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; +import org.spongepowered.asm.util.ASMHelper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; - /** * Information about a class, used as a way of keeping track of class hierarchy * information needed to support more complex mixin behaviour such as detached - * superclass and mixin inheritance. + * superclass and mixin inheritance. */ public class ClassInfo extends TreeInfo { - - public static final int INCLUDE_PRIVATE = 0x0002; - public static final int INCLUDE_STATIC = 0x0008; - + + public static final int INCLUDE_PRIVATE = Opcodes.ACC_PRIVATE; + public static final int INCLUDE_STATIC = Opcodes.ACC_STATIC; + public static final int INCLUDE_ALL = ClassInfo.INCLUDE_PRIVATE | ClassInfo.INCLUDE_STATIC; + /** *

To all intents and purposes, the "real" class hierarchy and the mixin * class hierarchy exist in parallel, this means that for some hierarchy * validation operations we need to walk across to the other * hierarchy in order to allow meaningful validation to occur.

- * + * *

This enum defines the type of traversal operations which are allowed * for a particular lookup.

- * + * *

Each traversal type has a next property which defines * the traversal type to use on the next step of the hierarchy - * validation. For example, the type {@link #IMMEDIATE} which requires an + * validation. For example, the type {@link #IMMEDIATE} which requires an * immediate match falls through to {@link #NONE} on the next step, which * prevents further traversals from occurring in the lookup.

*/ public static enum Traversal { - + /** * No traversals are allowed. */ NONE(null, false), - + /** * Traversal is allowed at all stages. */ ALL(null, true), - + /** * Traversal is allowed at the bottom of the hierarchy but no further. */ IMMEDIATE(Traversal.NONE, true), - + /** * Traversal is allowed only on superclasses and not at the bottom of * the hierarchy. */ SUPER(Traversal.ALL, false); - + private final Traversal next; - + private final boolean traverse; - + private Traversal(Traversal next, boolean traverse) { this.next = next != null ? next : this; this.traverse = traverse; } - + public Traversal next() { return this.next; } - + public boolean canTraverse() { return this.traverse; } } - + /** * Information about frames in a method */ public static class FrameData { - + private static final String[] FRAMETYPES = { "NEW", "FULL", "APPEND", "CHOP", "SAME", "SAME1" }; - + public final int index; - + public final int type; - + public final int locals; FrameData(int index, int type, int locals) { @@ -133,13 +140,13 @@ public class ClassInfo extends TreeInfo { this.type = type; this.locals = locals; } - + FrameData(int index, FrameNode frameNode) { this.index = index; this.type = frameNode.type; this.locals = frameNode.local != null ? frameNode.local.size() : 0; } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ @@ -148,54 +155,73 @@ public class ClassInfo extends TreeInfo { return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals); } } - + /** * Information about a member in this class */ abstract static class Member { - + + /** + * Member type + */ static enum Type { METHOD, FIELD } - + /** - * Member type + * Member type */ private final Type type; - + /** - * The original name of the member + * The original name of the member */ private final String memberName; - + /** * The member's signature */ private final String memberDesc; - + /** * True if this member was injected by a mixin, false if it was * originally part of the class */ private final boolean isInjected; - + /** * Access modifiers */ private final int modifiers; - + /** * Current name of the member, may be different from {@link #memberName} * if the member has been renamed */ private String currentName; + /** + * True if this member is decorated with {@link Final} + */ + private boolean decoratedFinal; + + /** + * True if this member is decorated with {@link Mutable} + */ + private boolean decoratedMutable; + + /** + * True if this member is decorated with {@link Unique} + */ + private boolean unique; + protected Member(Member member) { this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected); this.currentName = member.currentName; + this.unique = member.unique; } - + protected Member(Type type, String name, String desc, int access) { this(type, name, desc, access, false); } @@ -208,23 +234,23 @@ public class ClassInfo extends TreeInfo { this.currentName = name; this.modifiers = access; } - + public String getOriginalName() { return this.memberName; } - + public String getName() { return this.currentName; } - + public String getDesc() { return this.memberDesc; } - + public boolean isInjected() { return this.isInjected; } - + public boolean isRenamed() { return this.currentName != this.memberName; } @@ -236,7 +262,36 @@ public class ClassInfo extends TreeInfo { public boolean isStatic() { return (this.modifiers & Opcodes.ACC_STATIC) != 0; } + + public boolean isAbstract() { + return (this.modifiers & Opcodes.ACC_ABSTRACT) != 0; + } + + public boolean isFinal() { + return (this.modifiers & Opcodes.ACC_FINAL) != 0; + } + public boolean isUnique() { + return this.unique; + } + + public void setUnique(boolean unique) { + this.unique = unique; + } + + public boolean isDecoratedFinal() { + return this.decoratedFinal; + } + + public boolean isDecoratedMutable() { + return this.decoratedMutable; + } + + public void setDecoratedFinal(boolean decoratedFinal, boolean decoratedMutable) { + this.decoratedFinal = decoratedFinal; + this.decoratedMutable = decoratedMutable; + } + public boolean matchesFlags(int flags) { return (((~this.modifiers | (flags & ClassInfo.INCLUDE_PRIVATE)) & ClassInfo.INCLUDE_PRIVATE) != 0 && ((~this.modifiers | (flags & ClassInfo.INCLUDE_STATIC)) & ClassInfo.INCLUDE_STATIC) != 0); @@ -245,6 +300,10 @@ public class ClassInfo extends TreeInfo { // Abstract because this has to be static in order to contain the enum public abstract ClassInfo getOwner(); + public ClassInfo getImplementor() { + return this.getOwner(); + } + public int getAccess() { return this.modifiers; } @@ -252,47 +311,47 @@ public class ClassInfo extends TreeInfo { public void renameTo(String name) { this.currentName = name; } - + public boolean equals(String name, String desc) { return (this.memberName.equals(name) || this.currentName.equals(name)) && this.memberDesc.equals(desc); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof Member)) { return false; } - + Member other = (Member)obj; - return (other.memberName.equals(this.memberName) + return (other.memberName.equals(this.memberName) || other.currentName.equals(this.currentName)) && other.memberDesc.equals(this.memberDesc); } - + @Override public int hashCode() { return this.toString().hashCode(); } - + @Override public String toString() { - return this.memberName + this.memberDesc; + return String.format(this.getDisplayFormat(), this.memberName, this.memberDesc); } - - public boolean isAbstract() { - return (this.modifiers & Opcodes.ACC_ABSTRACT) != 0; + + protected String getDisplayFormat() { + return "%s%s"; } } - + /** * A method */ public class Method extends Member { - - private final List frames; + private final List frames; + public Method(Member member) { super(member); this.frames = member instanceof Method ? ((Method)member).frames : null; @@ -300,13 +359,14 @@ public class ClassInfo extends TreeInfo { public Method(MethodNode method) { this(method, false); + this.setUnique(ASMHelper.getVisibleAnnotation(method, Unique.class) != null); } - + public Method(MethodNode method, boolean injected) { super(Type.METHOD, method.name, method.desc, method.access, injected); this.frames = this.gatherFrames(method); } - + public Method(String name, String desc) { super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false); this.frames = null; @@ -321,7 +381,7 @@ public class ClassInfo extends TreeInfo { super(Type.METHOD, name, desc, access, injected); this.frames = null; } - + private List gatherFrames(MethodNode method) { List frames = new ArrayList(); for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { @@ -332,66 +392,104 @@ public class ClassInfo extends TreeInfo { } return frames; } - + public List getFrames() { return this.frames; } - + @Override public ClassInfo getOwner() { return ClassInfo.this; - } + } @Override public boolean equals(Object obj) { if (!(obj instanceof Method)) { return false; } - + return super.equals(obj); } } /** - * A field + * A method resolved in an interface via a class, return the member + * wrapped so that the implementing class can be retrieved. */ - class Field extends Member { + public class InterfaceMethod extends Method { - public Field(Member member) { + private final ClassInfo owner; + + public InterfaceMethod(Member member) { super(member); - } - - public Field(FieldNode field) { - this(field, false); - } - - public Field(FieldNode field, boolean injected) { - super(Type.FIELD, field.name, field.desc, field.access, injected); - } - - public Field(String name, String desc, int access) { - super(Type.FIELD, name, desc, access, false); - } - - public Field(String name, String desc, int access, boolean injected) { - super(Type.FIELD, name, desc, access, injected); + this.owner = member.getOwner(); } @Override public ClassInfo getOwner() { - return ClassInfo.this; - } + return this.owner; + } + @Override + public ClassInfo getImplementor() { + return ClassInfo.this; + } + + } + + /** + * A field + */ + class Field extends Member { + + public Field(Member member) { + super(member); + } + + public Field(FieldNode field) { + this(field, false); + } + + public Field(FieldNode field, boolean injected) { + super(Type.FIELD, field.name, field.desc, field.access, injected); + + this.setUnique(ASMHelper.getVisibleAnnotation(field, Unique.class) != null); + + if (ASMHelper.getVisibleAnnotation(field, Shadow.class) != null) { + boolean decoratedFinal = ASMHelper.getVisibleAnnotation(field, Final.class) != null; + boolean decoratedMutable = ASMHelper.getVisibleAnnotation(field, Mutable.class) != null; + this.setDecoratedFinal(decoratedFinal, decoratedMutable); + } + } + + public Field(String name, String desc, int access) { + super(Type.FIELD, name, desc, access, false); + } + + public Field(String name, String desc, int access, boolean injected) { + super(Type.FIELD, name, desc, access, injected); + } + + @Override + public ClassInfo getOwner() { + return ClassInfo.this; + } + @Override public boolean equals(Object obj) { if (!(obj instanceof Field)) { return false; } - + return super.equals(obj); } + + @Override + protected String getDisplayFormat() { + return "%s:%s"; + } } - + private static final Logger logger = LogManager.getLogger("mixin"); private static final String JAVA_LANG_OBJECT = "java/lang/Object"; @@ -401,90 +499,90 @@ public class ClassInfo extends TreeInfo { * information we generate */ private static final Map cache = new HashMap(); - + private static final ClassInfo OBJECT = new ClassInfo(); - + static { ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT); } - + /** * Class name (binary name) */ private final String name; - + /** * Class superclass name (binary name) */ private final String superName; - + /** * Outer class name */ private final String outerName; - + /** * True either if this is not an inner class or if it is an inner class but * does not contain a reference to its outer class. */ private final boolean isProbablyStatic; - + /** * Interfaces */ private final Set interfaces; - + /** - * Public and protected methods (instance) methods in this class + * Public and protected methods (instance) methods in this class */ private final Set methods; - + /** * Public and protected fields in this class */ private final Set fields; - + /** * Mixins which target this class */ private final Set mixins = new HashSet(); - + /** - * Map of mixin types to corresponding supertypes, to avoid repeated - * lookups + * Map of mixin types to corresponding supertypes, to avoid repeated + * lookups */ private final Map correspondingTypes = new HashMap(); - + /** - * Mixin info if this class is a mixin itself + * Mixin info if this class is a mixin itself */ private final MixinInfo mixin; - + /** - * True if this is a mixin rather than a class + * True if this is a mixin rather than a class */ private final boolean isMixin; - + /** - * True if this is an interface + * True if this is an interface */ private final boolean isInterface; - + /** * Access flags */ private final int access; - + /** - * Superclass reference, not initialised until required + * Superclass reference, not initialised until required */ private ClassInfo superClass; - + /** - * Outer class reference, not initialised until required + * Outer class reference, not initialised until required */ private ClassInfo outerClass; - + /** * Private constructor used to initialise the ClassInfo for {@link Object} */ @@ -513,10 +611,10 @@ public class ClassInfo extends TreeInfo { this.isMixin = false; this.mixin = null; } - + /** * Initialise a ClassInfo from the supplied {@link ClassNode} - * + * * @param classNode Class node to inspect */ private ClassInfo(ClassNode classNode) { @@ -531,7 +629,7 @@ public class ClassInfo extends TreeInfo { this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; this.interfaces.addAll(classNode.interfaces); - + for (MethodNode method : classNode.methods) { this.addMethod(method, this.isMixin); } @@ -548,18 +646,16 @@ public class ClassInfo extends TreeInfo { outerName = outerName.substring(1, outerName.length() - 1); } } - } - - if ((field.access & Opcodes.ACC_STATIC) == 0) { - this.fields.add(new Field(field, this.isMixin)); } + + this.fields.add(new Field(field, this.isMixin)); } } - + this.isProbablyStatic = isProbablyStatic; this.outerName = outerName; } - + void addInterface(String iface) { this.interfaces.add(iface); } @@ -573,7 +669,7 @@ public class ClassInfo extends TreeInfo { this.methods.add(new Method(method, injected)); } } - + /** * Add a mixin which targets this class */ @@ -583,21 +679,21 @@ public class ClassInfo extends TreeInfo { } this.mixins.add(mixin); } - + /** * Get all mixins which target this class */ public Set getMixins() { return Collections.unmodifiableSet(this.mixins); } - + /** * Get whether this class is a mixin */ public boolean isMixin() { return this.isMixin; } - + /** * Get whether this class has ACC_PUBLIC */ @@ -618,44 +714,44 @@ public class ClassInfo extends TreeInfo { public boolean isSynthetic() { return (this.access & Opcodes.ACC_SYNTHETIC) != 0; } - + /** - * Get whether this class is probably static (or is not an inner class) + * Get whether this class is probably static (or is not an inner class) */ public boolean isProbablyStatic() { return this.isProbablyStatic; } - + /** * Get whether this class is an inner class */ public boolean isInner() { return this.outerName != null; } - + /** * Get whether this is an interface or not */ public boolean isInterface() { return this.isInterface; } - + /** * Returns the answer to life, the universe and everything */ public Set getInterfaces() { return Collections.unmodifiableSet(this.interfaces); } - + @Override public String toString() { return this.name; } - + public int getAccess() { return this.access; } - + /** * Get the class name (binary name) */ @@ -663,13 +759,20 @@ public class ClassInfo extends TreeInfo { return this.name; } + /** + * Get the class name (java format) + */ + public String getClassName() { + return this.name.replace('/', '.'); + } + /** * Get the superclass name (binary name) */ public String getSuperName() { return this.superName; } - + /** * Get the superclass info, can return null if the superclass cannot be * resolved @@ -678,17 +781,17 @@ public class ClassInfo extends TreeInfo { if (this.superClass == null && this.superName != null) { this.superClass = ClassInfo.forName(this.superName); } - + return this.superClass; } - + /** * Get the name of the outer class, or null if this is not an inner class */ public String getOuterName() { return this.outerName; } - + /** * Get the outer class info, can return null if the outer class cannot be * resolved or if this is not an inner class @@ -697,10 +800,10 @@ public class ClassInfo extends TreeInfo { if (this.outerClass == null && this.outerName != null) { this.outerClass = ClassInfo.forName(this.outerName); } - + return this.outerClass; } - + /** * Class targets */ @@ -711,55 +814,59 @@ public class ClassInfo extends TreeInfo { targets.addAll(this.mixin.getTargets()); return targets; } - + return ImmutableList.of(this); } - + /** * Get class/interface methods - * + * * @return read-only view of class methods */ public Set getMethods() { return Collections.unmodifiableSet(this.methods); } - + /** * If this is an interface, returns a set containing all methods in this * interface and all super interfaces. If this is a class, returns a set * containing all methods for all interfaces implemented by this class and * all super interfaces of those interfaces. - * + * + * @param includeMixins Whether to include methods from mixins targeting + * this class info * @return read-only view of class methods */ - public Set getInterfaceMethods() { + public Set getInterfaceMethods(boolean includeMixins) { Set methods = new HashSet(); - ClassInfo superClass = this.addMethodsRecursive(methods); + ClassInfo superClass = this.addMethodsRecursive(methods, includeMixins); if (!this.isInterface) { while (superClass != null && superClass != ClassInfo.OBJECT) { - superClass = superClass.addMethodsRecursive(methods); + superClass = superClass.addMethodsRecursive(methods, includeMixins); } } - + // Remove default methods. for (Iterator it = methods.iterator(); it.hasNext();) { if (!it.next().isAbstract()) { it.remove(); } } - + return Collections.unmodifiableSet(methods); } /** * Recursive function used by {@link #getInterfaceMethods} to add all * interface methods to the supplied set - * + * * @param methods Method set to add to + * @param includeMixins Whether to include methods from mixins targeting + * this class info * @return superclass reference, used to make the code above more fluent */ - private ClassInfo addMethodsRecursive(Set methods) { + private ClassInfo addMethodsRecursive(Set methods, boolean includeMixins) { if (this.isInterface) { for (Method method : this.methods) { // Default methods take priority. They are removed later. @@ -769,22 +876,22 @@ public class ClassInfo extends TreeInfo { } methods.add(method); } - } else if (!this.isMixin) { + } else if (!this.isMixin && includeMixins) { for (MixinInfo mixin : this.mixins) { - mixin.getClassInfo().addMethodsRecursive(methods); + mixin.getClassInfo().addMethodsRecursive(methods, includeMixins); } } - + for (String iface : this.interfaces) { - ClassInfo.forName(iface).addMethodsRecursive(methods); + ClassInfo.forName(iface).addMethodsRecursive(methods, includeMixins); } - + return this.getSuperClass(); } - + /** * Test whether this class has the specified superclass in its hierarchy - * + * * @param superClass Name of the superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere @@ -795,7 +902,7 @@ public class ClassInfo extends TreeInfo { /** * Test whether this class has the specified superclass in its hierarchy - * + * * @param superClass Name of the superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy @@ -805,13 +912,13 @@ public class ClassInfo extends TreeInfo { if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) { return true; } - + return this.findSuperClass(superClass, traversal) != null; } - + /** * Test whether this class has the specified superclass in its hierarchy - * + * * @param superClass Superclass to search for in the hierarchy * @return true if the specified class appears in the class's hierarchy * anywhere @@ -822,7 +929,7 @@ public class ClassInfo extends TreeInfo { /** * Test whether this class has the specified superclass in its hierarchy - * + * * @param superClass Superclass to search for in the hierarchy * @param traversal Traversal type to allow during this lookup * @return true if the specified class appears in the class's hierarchy @@ -839,9 +946,9 @@ public class ClassInfo extends TreeInfo { /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null - * + * * @param superClass Superclass name to search for - * @return Matched superclass or null if not found + * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass) { return this.findSuperClass(superClass, Traversal.NONE); @@ -850,12 +957,20 @@ public class ClassInfo extends TreeInfo { /** * Search for the specified superclass in this class's hierarchy. If found * returns the ClassInfo, otherwise returns null - * + * * @param superClass Superclass name to search for * @param traversal Traversal type to allow during this lookup - * @return Matched superclass or null if not found + * @return Matched superclass or null if not found */ public ClassInfo findSuperClass(String superClass, Traversal traversal) { + if (ClassInfo.OBJECT.name == superClass) { + return null; + } + + return this.findSuperClass(superClass, traversal, new HashSet()); + } + + private ClassInfo findSuperClass(String superClass, Traversal traversal, Set traversed) { ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { List targets = superClassInfo.getTargets(); @@ -864,22 +979,31 @@ public class ClassInfo extends TreeInfo { return superClassInfo; } - ClassInfo found = superTarget.findSuperClass(superClass, traversal.next()); + ClassInfo found = superTarget.findSuperClass(superClass, traversal.next(), traversed); if (found != null) { return found; } } } - + if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { - ClassInfo targetSuper = mixin.getClassInfo().findSuperClass(superClass, traversal); + String mixinClassName = mixin.getClassName(); + if (traversed.contains(mixinClassName)) { + continue; + } + traversed.add(mixinClassName); + ClassInfo mixinClass = mixin.getClassInfo(); + if (superClass.equals(mixinClass.getName())) { + return mixinClass; + } + ClassInfo targetSuper = mixinClass.findSuperClass(superClass, Traversal.ALL, traversed); if (targetSuper != null) { return targetSuper; } } } - + return null; } @@ -888,7 +1012,7 @@ public class ClassInfo extends TreeInfo { * specified mixin. This is used during mixin application to translate a * mixin reference to a "real class" reference in the context of this * class. - * + * * @param mixin Mixin class to search for * @return corresponding (target) class for the specified mixin or null if * no corresponding mixin was found @@ -897,7 +1021,7 @@ public class ClassInfo extends TreeInfo { if (mixin == null || !mixin.isMixin || this.isMixin) { return null; } - + ClassInfo correspondingType = this.correspondingTypes.get(mixin); if (correspondingType == null) { correspondingType = this.findSuperTypeForMixin(mixin); @@ -912,24 +1036,24 @@ public class ClassInfo extends TreeInfo { */ private ClassInfo findSuperTypeForMixin(ClassInfo mixin) { ClassInfo superClass = this; - + while (superClass != null && superClass != ClassInfo.OBJECT) { for (MixinInfo minion : superClass.mixins) { if (minion.getClassInfo().equals(mixin)) { return superClass; } } - + superClass = superClass.getSuperClass(); } - + return null; } /** * Find out whether this (mixin) class has another mixin in its superclass * hierarchy. This method always returns false for non-mixin classes. - * + * * @return true if and only if one or more mixins are found in the hierarchy * of this mixin */ @@ -937,9 +1061,9 @@ public class ClassInfo extends TreeInfo { if (!this.isMixin) { return false; } - + ClassInfo superClass = this.getSuperClass(); - + while (superClass != null && superClass != ClassInfo.OBJECT) { if (superClass.isMixin) { return true; @@ -949,12 +1073,12 @@ public class ClassInfo extends TreeInfo { return false; } - + /** * Find out whether this (non-mixin) class has a mixin targetting * any of its superclasses. This method always returns false for * mixin classes. - * + * * @return true if and only if one or more classes in this class's hierarchy * are targetted by a mixin */ @@ -962,22 +1086,22 @@ public class ClassInfo extends TreeInfo { if (this.isMixin) { return false; } - + ClassInfo superClass = this.getSuperClass(); - + while (superClass != null && superClass != ClassInfo.OBJECT) { if (superClass.mixins.size() > 0) { return true; } superClass = superClass.getSuperClass(); } - + return false; } /** * Finds the specified private or protected method in this class's hierarchy - * + * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses @@ -989,7 +1113,7 @@ public class ClassInfo extends TreeInfo { /** * Finds the specified private or protected method in this class's hierarchy - * + * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses @@ -999,10 +1123,10 @@ public class ClassInfo extends TreeInfo { public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass, int flags) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, flags); } - + /** * Finds the specified public or protected method in this class's hierarchy - * + * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses @@ -1011,10 +1135,10 @@ public class ClassInfo extends TreeInfo { public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE); } - + /** * Finds the specified public or protected method in this class's hierarchy - * + * * @param method Method to search for * @param includeThisClass True to return this class if the method exists * here, or false to search only superclasses @@ -1024,10 +1148,10 @@ public class ClassInfo extends TreeInfo { public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass, int flags) { return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, flags); } - + /** * Finds the specified public or protected method in this class's hierarchy - * + * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists @@ -1040,7 +1164,7 @@ public class ClassInfo extends TreeInfo { /** * Finds the specified public or protected method in this class's hierarchy - * + * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists @@ -1051,10 +1175,10 @@ public class ClassInfo extends TreeInfo { public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) { return this.findMethodInHierarchy(name, desc, includeThisClass, traversal, 0); } - + /** * Finds the specified public or protected method in this class's hierarchy - * + * * @param name Method name to search for * @param desc Method descriptor * @param includeThisClass True to return this class if the method exists @@ -1066,10 +1190,10 @@ public class ClassInfo extends TreeInfo { public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, int flags) { return this.findInHierarchy(name, desc, includeThisClass, traversal, flags, Type.METHOD); } - + /** * Finds the specified private or protected field in this class's hierarchy - * + * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses @@ -1078,10 +1202,10 @@ public class ClassInfo extends TreeInfo { public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE); } - + /** * Finds the specified private or protected field in this class's hierarchy - * + * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses @@ -1091,10 +1215,10 @@ public class ClassInfo extends TreeInfo { public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass, int flags) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, flags); } - + /** * Finds the specified public or protected field in this class's hierarchy - * + * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses @@ -1103,10 +1227,10 @@ public class ClassInfo extends TreeInfo { public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE); } - + /** * Finds the specified public or protected field in this class's hierarchy - * + * * @param field Field to search for * @param includeThisClass True to return this class if the field exists * here, or false to search only superclasses @@ -1116,10 +1240,10 @@ public class ClassInfo extends TreeInfo { public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass, int flags) { return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, flags); } - + /** * Finds the specified public or protected field in this class's hierarchy - * + * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists @@ -1132,7 +1256,7 @@ public class ClassInfo extends TreeInfo { /** * Finds the specified public or protected field in this class's hierarchy - * + * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists @@ -1143,10 +1267,10 @@ public class ClassInfo extends TreeInfo { public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) { return this.findFieldInHierarchy(name, desc, includeThisClass, traversal, 0); } - + /** * Finds the specified public or protected field in this class's hierarchy - * + * * @param name Field name to search for * @param desc Field descriptor * @param includeThisClass True to return this class if the field exists @@ -1158,11 +1282,11 @@ public class ClassInfo extends TreeInfo { public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, int flags) { return this.findInHierarchy(name, desc, includeThisClass, traversal, flags, Type.FIELD); } - + /** * Finds a public or protected member in the hierarchy of this class which - * matches the supplied details - * + * matches the supplied details + * * @param name Member name to search * @param desc Member descriptor * @param includeThisClass True to return this class if the field exists @@ -1172,23 +1296,24 @@ public class ClassInfo extends TreeInfo { * @param type Type of member to search for (field or method) * @return the discovered member or null if the member could not be resolved */ + @SuppressWarnings("unchecked") private M findInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, int flags, Type type) { if (includeThisClass) { M member = this.findMember(name, desc, flags, type); if (member != null) { return member; } - + if (traversal.canTraverse()) { for (MixinInfo mixin : this.mixins) { M mixinMember = mixin.getClassInfo().findMember(name, desc, flags, type); if (mixinMember != null) { return this.cloneMember(mixinMember); } - } + } } } - + ClassInfo superClassInfo = this.getSuperClass(); if (superClassInfo != null) { for (ClassInfo superTarget : superClassInfo.getTargets()) { @@ -1199,40 +1324,55 @@ public class ClassInfo extends TreeInfo { } } + if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces())) { + for (String implemented : this.interfaces) { + ClassInfo iface = ClassInfo.forName(implemented); + if (iface == null) { + ClassInfo.logger.debug("Failed to resolve declared interface {} on {}", implemented, this.name); + continue; +// throw new RuntimeException(new ClassNotFoundException(implemented)); + } + M member = iface.findInHierarchy(name, desc, true, traversal.next(), flags & ~ClassInfo.INCLUDE_PRIVATE, type); + if (member != null) { + return this.isInterface ? member : (M)new InterfaceMethod(member); + } + } + } + return null; } - + /** * Effectively a clone method for member, placed here so that the enclosing * instance for the inner class is this class and not the enclosing instance - * of the existing class. Basically creates a cloned member with this + * of the existing class. Basically creates a cloned member with this * ClassInfo as its parent. - * - * @param member - * @return + * + * @param member member to clone + * @return wrapper member */ @SuppressWarnings("unchecked") private M cloneMember(M member) { if (member instanceof Method) { return (M)new Method(member); } - + return (M)new Field(member); } - + /** * Finds the specified public or protected method in this class - * + * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodNode method) { return this.findMethod(method.name, method.desc, method.access); } - + /** * Finds the specified public or protected method in this class - * + * * @param method Method to search for * @param flags search flags * @return the method object or null if the method could not be resolved @@ -1240,20 +1380,20 @@ public class ClassInfo extends TreeInfo { public Method findMethod(MethodNode method, int flags) { return this.findMethod(method.name, method.desc, flags); } - + /** * Finds the specified public or protected method in this class - * + * * @param method Method to search for * @return the method object or null if the method could not be resolved */ public Method findMethod(MethodInsnNode method) { return this.findMethod(method.name, method.desc, 0); } - + /** * Finds the specified public or protected method in this class - * + * * @param method Method to search for * @param flags search flags * @return the method object or null if the method could not be resolved @@ -1261,10 +1401,10 @@ public class ClassInfo extends TreeInfo { public Method findMethod(MethodInsnNode method, int flags) { return this.findMethod(method.name, method.desc, flags); } - + /** * Finds the specified public or protected method in this class - * + * * @param name Method name to search for * @param desc Method signature to search for * @param flags search flags @@ -1273,20 +1413,20 @@ public class ClassInfo extends TreeInfo { public Method findMethod(String name, String desc, int flags) { return this.findMember(name, desc, flags, Type.METHOD); } - + /** * Finds the specified field in this class - * + * * @param field Field to search for * @return the field object or null if the field could not be resolved */ public Field findField(FieldNode field) { return this.findField(field.name, field.desc, field.access); } - + /** * Finds the specified public or protected method in this class - * + * * @param field Field to search for * @param flags search flags * @return the field object or null if the field could not be resolved @@ -1294,10 +1434,10 @@ public class ClassInfo extends TreeInfo { public Field findField(FieldInsnNode field, int flags) { return this.findField(field.name, field.desc, flags); } - + /** * Finds the specified field in this class - * + * * @param name Field name to search for * @param desc Field signature to search for * @param flags search flags @@ -1309,7 +1449,7 @@ public class ClassInfo extends TreeInfo { /** * Finds the specified member in this class - * + * * @param name Field name to search for * @param desc Field signature to search for * @param flags search flags @@ -1319,13 +1459,13 @@ public class ClassInfo extends TreeInfo { private M findMember(String name, String desc, int flags, Type memberType) { @SuppressWarnings("unchecked") Set members = (Set)(memberType == Type.METHOD ? this.methods : this.fields); - + for (M member : members) { if (member.equals(name, desc) && member.matchesFlags(flags)) { return member; } } - + return null; } @@ -1339,7 +1479,7 @@ public class ClassInfo extends TreeInfo { } return ((ClassInfo)other).name.equals(this.name); } - + /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @@ -1353,9 +1493,9 @@ public class ClassInfo extends TreeInfo { * the class was already defined, then the original ClassInfo is returned * from the internal cache. Otherwise a new ClassInfo is created and * returned. - * - * @param classNode - * @return + * + * @param classNode classNode to get info for + * @return ClassInfo instance for the supplied classNode */ static ClassInfo fromClassNode(ClassNode classNode) { ClassInfo info = ClassInfo.cache.get(classNode.name); @@ -1363,21 +1503,21 @@ public class ClassInfo extends TreeInfo { info = new ClassInfo(classNode); ClassInfo.cache.put(classNode.name, info); } - + return info; } /** * Return a ClassInfo for the specified class name, fetches the ClassInfo * from the cache where possible - * + * * @param className Binary name of the class to look up * @return ClassInfo for the specified class name or null if the specified * name cannot be resolved for some reason */ public static ClassInfo forName(String className) { className = className.replace('.', '/'); - + ClassInfo info = ClassInfo.cache.get(className); if (info == null) { try { @@ -1386,19 +1526,19 @@ public class ClassInfo extends TreeInfo { } catch (Exception ex) { ex.printStackTrace(); } - + // Put null in the cache if load failed ClassInfo.cache.put(className, info); ClassInfo.logger.trace("Added class metadata for {} to metadata cache", className); } - + return info; } /** * Return a ClassInfo for the specified class type, fetches the ClassInfo * from the cache where possible and generates the class meta if not. - * + * * @param type Type to look up * @return ClassInfo for the supplied type or null if the supplied type * cannot be found or is a primitive type diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/Config.java b/src/main/java/org/spongepowered/asm/mixin/transformer/Config.java new file mode 100644 index 00000000..d0c61983 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/Config.java @@ -0,0 +1,121 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.extensibility.IMixinConfig; + +/** + * Handle for marshalling mixin configs outside of the transformer package + */ +public class Config { + + /** + * Config name, used as identity for the purposes of {@link #equals} + */ + private final String name; + + /** + * Config + */ + private final MixinConfig config; + + public Config(MixinConfig config) { + this.name = config.getName(); + this.config = config; + } + + public String getName() { + return this.name; + } + + /** + * Access inner config + */ + MixinConfig get() { + return this.config; + } + + /** + * Get API-level config view + */ + public IMixinConfig getConfig() { + return this.config; + } + + /** + * Get environment for the config + */ + public MixinEnvironment getEnvironment() { + return this.config.getEnvironment(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return this.config.toString(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return obj instanceof Config && this.name.equals(((Config)obj).name); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return this.name.hashCode(); + } + + /** + * Factory method, create a config from the specified config file and fail + * over to the specified environment if no selector is present in the config + * + * @param configFile config resource + * @param outer failover environment + * @return new config or null if invalid config version + */ + @Deprecated + public static Config create(String configFile, MixinEnvironment outer) { + return MixinConfig.create(configFile, outer); + } + + /** + * Factory method, create a config from the specified config resource + * + * @param configFile config resource + * @return new config or null if invalid config version + */ + public static Config create(String configFile) { + return MixinConfig.create(configFile, MixinEnvironment.getDefaultEnvironment()); + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerModule.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerModule.java index dfc7764b..75919aaa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerModule.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformerModule.java @@ -24,11 +24,6 @@ */ package org.spongepowered.asm.mixin.transformer; -import java.util.SortedSet; - -import org.spongepowered.asm.lib.tree.ClassNode; - - /** * Mixin Transformer Module interface for pre- and post-processors */ @@ -37,19 +32,15 @@ public interface IMixinTransformerModule { /** * Called before the mixins are applied * - * @param transformedName Target class name - * @param targetClass Target class tree - * @param mixins Mixins to be applied + * @param context Target class context */ - public abstract void preApply(String transformedName, ClassNode targetClass, SortedSet mixins); + public abstract void preApply(TargetClassContext context); /** * Called after the mixins are applied * - * @param transformedName Target class name - * @param targetClass Target class tree - * @param mixins Mixins which were applied + * @param context Target class context */ - public abstract void postApply(String transformedName, ClassNode targetClass, SortedSet mixins); + public abstract void postApply(TargetClassContext context); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java index 1b3baaec..62e4746b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -27,11 +27,15 @@ package org.spongepowered.asm.mixin.transformer; import java.util.HashSet; import java.util.Set; +import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.Interface; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.ASMHelper; /** @@ -56,6 +60,12 @@ public class InterfaceInfo extends TreeInfo { */ private final Type iface; + /** + * True if all methods implementing this interface should be treated as + * unique + */ + private final boolean unique; + /** * Method signatures in the interface, lazy loaded */ @@ -68,7 +78,7 @@ public class InterfaceInfo extends TreeInfo { * @param prefix Method prefix * @param iface Interface to load */ - private InterfaceInfo(MixinInfo mixin, String prefix, Type iface) { + private InterfaceInfo(MixinInfo mixin, String prefix, Type iface, boolean unique) { if (prefix == null || prefix.length() < 2 || !prefix.endsWith("$")) { throw new InvalidMixinException(mixin, String.format("Prefix %s for iface %s is not valid", prefix, iface.toString())); } @@ -76,6 +86,7 @@ public class InterfaceInfo extends TreeInfo { this.mixin = mixin; this.prefix = prefix; this.iface = iface; + this.unique = unique; } /** @@ -121,6 +132,15 @@ public class InterfaceInfo extends TreeInfo { public Type getIface() { return this.iface; } + + /** + * Get the internal name of the interface + * + * @return the internal name for the interface + */ + public String getName() { + return this.iface.getClassName(); + } /** * Get the internal name of the interface @@ -130,6 +150,15 @@ public class InterfaceInfo extends TreeInfo { public String getInternalName() { return this.iface.getInternalName(); } + + /** + * Get whether all methods for this interface should be treated as unique + * + * @return true to treat all member methods as unique + */ + public boolean isUnique() { + return this.unique; + } /** * Processes a method node in the mixin and renames it if necessary. If the @@ -146,20 +175,46 @@ public class InterfaceInfo extends TreeInfo { } if (!method.name.startsWith(this.prefix)) { + if (this.methods.contains(method.name + method.desc)) { + this.decorateUniqueMethod(method); + } return false; } String realName = method.name.substring(this.prefix.length()); String signature = realName + method.desc; + if (!this.methods.contains(signature)) { - throw new InvalidMixinException(this.mixin, String.format("%s does not exist in target interface %s", realName, this.iface.toString())); + throw new InvalidMixinException(this.mixin, String.format("%s does not exist in target interface %s", realName, this.getName())); + } + + if ((method.access & Opcodes.ACC_PUBLIC) == 0) { + throw new InvalidMixinException(this.mixin, String.format("%s cannot implement %s because it is not visible", realName, this.getName())); } ASMHelper.setVisibleAnnotation(method, MixinRenamed.class, "originalName", method.name, "isInterfaceMember", true); + this.decorateUniqueMethod(method); method.name = realName; return true; } + /** + * Decorate the target method with {@link Unique} if the interface is marked + * as unique + * + * @param method method to decorate + */ + private void decorateUniqueMethod(MethodNode method) { + if (!this.unique) { + return; + } + + if (ASMHelper.getVisibleAnnotation(method, Unique.class) == null) { + ASMHelper.setVisibleAnnotation(method, Unique.class); + this.mixin.getClassInfo().findMethod(method).setUnique(true); + } + } + /** * Convert an {@link Interface} annotation node into an * {@link InterfaceInfo} @@ -171,11 +226,34 @@ public class InterfaceInfo extends TreeInfo { static InterfaceInfo fromAnnotation(MixinInfo mixin, AnnotationNode node) { String prefix = ASMHelper.getAnnotationValue(node, "prefix"); Type iface = ASMHelper.getAnnotationValue(node, "iface"); + Boolean unique = ASMHelper.getAnnotationValue(node, "unique"); if (prefix == null || iface == null) { - throw new InvalidMixinException(mixin, String.format("@Interface annotation on is missing a required parameter")); + throw new InvalidMixinException(mixin, String.format("@Interface annotation on %s is missing a required parameter", mixin)); } - return new InterfaceInfo(mixin, prefix, iface); + return new InterfaceInfo(mixin, prefix, iface, unique != null ? unique.booleanValue() : false); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + InterfaceInfo that = (InterfaceInfo) o; + + return this.mixin.equals(that.mixin) && this.prefix.equals(that.prefix) && this.iface.equals(that.iface); + } + + @Override + public int hashCode() { + int result = this.mixin.hashCode(); + result = 31 * result + this.prefix.hashCode(); + result = 31 * result + this.iface.hashCode(); + return result; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java new file mode 100644 index 00000000..dc438dde --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java @@ -0,0 +1,321 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.tree.FieldInsnNode; +import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Reference to a field or method that also includes invocation + * instructions. + * + * To instances are defined to be equal if they both refer to the same method + * and have the same invocation instructions. + */ +public abstract class MemberRef { + + /** + * A static reference to a method backed by an invoke instruction + */ + public static final class Method extends MemberRef { + + /** + * Method invocation instruction + */ + public final MethodInsnNode insn; + + /** + * ctor + * + * @param insn Method instruction of this member reference + */ + public Method(MethodInsnNode insn) { + this.insn = insn; + } + + @Override + public boolean isField() { + return false; + } + + @Override + public int getOpcode() { + return this.insn.getOpcode(); + } + + @Override + public String getOwner() { + return this.insn.owner; + } + + @Override + public void setOwner(String owner) { + this.insn.owner = owner; + } + + @Override + public String getName() { + return this.insn.name; + } + + @Override + public String getDesc() { + return this.insn.desc; + } + + @Override + public void setDesc(String desc) { + this.insn.desc = desc; + } + } + + /** + * A static reference to a field backed by field get/put instruction + */ + public static final class Field extends MemberRef { + + /** + * Field accessor instruction + */ + public final FieldInsnNode insn; + + /** + * ctor + * + * @param insn Field instruction this member reference + */ + public Field(FieldInsnNode insn) { + this.insn = insn; + } + + @Override + public boolean isField() { + return true; + } + + @Override + public int getOpcode() { + return this.insn.getOpcode(); + } + + @Override + public String getOwner() { + return this.insn.owner; + } + + @Override + public void setOwner(String owner) { + this.insn.owner = owner; + } + + @Override + public String getName() { + return this.insn.name; + } + + @Override + public String getDesc() { + return this.insn.desc; + } + + @Override + public void setDesc(String desc) { + this.insn.desc = desc; + } + } + + /** + * A reference to a field or method backed by a method handle + */ + public static final class Handle extends MemberRef { + + private org.spongepowered.asm.lib.Handle handle; + + /** + * Creates a member reference initially referring to the member referred + * to by the method handle and the invocation instruction of the method + * handle. + * + * @param handle Initial method handle. + */ + public Handle(org.spongepowered.asm.lib.Handle handle) { + this.handle = handle; + } + + /** + * Gets a method handle for the member this is object is referring to. + * + * @return Method handle representing this object + */ + public org.spongepowered.asm.lib.Handle getMethodHandle() { + return this.handle; + } + + @Override + public boolean isField() { + switch (this.handle.getTag()) { + case Opcodes.H_INVOKEVIRTUAL: + case Opcodes.H_INVOKESTATIC: + case Opcodes.H_INVOKEINTERFACE: + case Opcodes.H_INVOKESPECIAL: + case Opcodes.H_NEWINVOKESPECIAL: + return false; + case Opcodes.H_GETFIELD: + case Opcodes.H_GETSTATIC: + case Opcodes.H_PUTFIELD: + case Opcodes.H_PUTSTATIC: + return true; + default: + throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + "."); + } + } + + @Override + public int getOpcode() { + switch (this.handle.getTag()) { + case Opcodes.H_INVOKEVIRTUAL: + return Opcodes.INVOKEVIRTUAL; + case Opcodes.H_INVOKESTATIC: + return Opcodes.INVOKESTATIC; + case Opcodes.H_INVOKEINTERFACE: + return Opcodes.INVOKEINTERFACE; + case Opcodes.H_INVOKESPECIAL: + case Opcodes.H_NEWINVOKESPECIAL: + return Opcodes.INVOKESPECIAL; + case Opcodes.H_GETFIELD: + return Opcodes.GETFIELD; + case Opcodes.H_GETSTATIC: + return Opcodes.GETSTATIC; + case Opcodes.H_PUTFIELD: + return Opcodes.PUTFIELD; + case Opcodes.H_PUTSTATIC: + return Opcodes.PUTSTATIC; + default: + throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + "."); + } + } + + @Override + public String getOwner() { + return this.handle.getOwner(); + } + + @Override + public void setOwner(String owner) { + this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc()); + } + + @Override + public String getName() { + return this.handle.getName(); + } + + @Override + public String getDesc() { + return this.handle.getDesc(); + } + + @Override + public void setDesc(String desc) { + this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc); + } + } + + /** + * Whether this member is a field. + * + * @return If this member is a field, else it is a method + */ + public abstract boolean isField(); + + /** + * The opcode of the invocation. + * + * @return The opcode of the invocation + */ + public abstract int getOpcode(); + + /** + * The internal name for the owner of this member. + * + * @return The owners name + */ + public abstract String getOwner(); + + /** + * Changes the owner of this + * + * @param owner New owner + */ + public abstract void setOwner(String owner); + + /** + * Name of this member. + * + * @return Name of this member. + */ + public abstract String getName(); + + /** + * Descriptor of this member. + * + * @return Descriptor of this member + */ + public abstract String getDesc(); + + /** + * Changes the descriptor of this member + * + * @param desc New descriptor of this member + */ + public abstract void setDesc(String desc); + + @Override + public String toString() { + return ASMHelper.getOpcodeName(this.getOpcode()) + " for " + + this.getOwner() + "." + this.getName() + (this.isField() ? ":" : "") + this.getDesc(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof MemberRef)) { + return false; + } + + MemberRef other = (MemberRef)obj; + return this.getOpcode() == other.getOpcode() + && this.getOwner().equals(other.getOwner()) + && this.getName().equals(other.getName()) + && this.getDesc().equals(other.getDesc()); + } + + @Override + public int hashCode() { + return this.toString().hashCode(); + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java new file mode 100644 index 00000000..3f422627 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java @@ -0,0 +1,123 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.Map.Entry; + +import org.spongepowered.asm.lib.tree.FieldNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException; + +/** + * Applicator for interface mixins, mainly just disables things which aren't + * supported for interface mixins + */ +public class MixinApplicatorInterface extends MixinApplicatorStandard { + + /** + * ctor + * + * @param context applier context + */ + MixinApplicatorInterface(TargetClassContext context) { + super(context); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinApplicator + * #applyInterfaces( + * org.spongepowered.asm.mixin.transformer.MixinTargetContext) + */ + @Override + protected void applyInterfaces(MixinTargetContext mixin) { + for (String interfaceName : mixin.getInterfaces()) { + if (!this.targetClass.name.equals(interfaceName) && !this.targetClass.interfaces.contains(interfaceName)) { + this.targetClass.interfaces.add(interfaceName); + mixin.getTargetClassInfo().addInterface(interfaceName); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinApplicator + * #applyFields( + * org.spongepowered.asm.mixin.transformer.MixinTargetContext) + */ + @Override + protected void applyFields(MixinTargetContext mixin) { + // shadow fields have no meaning for interfaces, just spam the dev with messages + for (Entry entry : mixin.getShadowFields()) { + FieldNode shadow = entry.getKey(); + this.logger.error("Ignoring redundant @Shadow field {}:{} in {}", shadow.name, shadow.desc, mixin); + } + + this.mergeNewFields(mixin); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinApplicator + * #applyInitialisers( + * org.spongepowered.asm.mixin.transformer.MixinTargetContext) + */ + @Override + protected void applyInitialisers(MixinTargetContext mixin) { + // disabled for interface mixins + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinApplicator + * #prepareInjections( + * org.spongepowered.asm.mixin.transformer.MixinTargetContext) + */ + @Override + protected void prepareInjections(MixinTargetContext mixin) { + // disabled for interface mixins + for (MethodNode method : this.targetClass.methods) { + try { + InjectionInfo injectInfo = InjectionInfo.parse(mixin, method); + if (injectInfo != null) { + throw new InvalidInterfaceMixinException(mixin, injectInfo + " is not supported on interface mixin method " + method.name); + } + } catch (InvalidInjectionException ex) { + String description = ex.getInjectionInfo() != null ? ex.getInjectionInfo().toString() : "Injection"; + throw new InvalidInterfaceMixinException(mixin, description + " is not supported in interface mixin"); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinApplicator + * #applyInjections( + * org.spongepowered.asm.mixin.transformer.MixinTargetContext) + */ + @Override + protected void applyInjections(MixinTargetContext mixin) { + // Do nothing + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java similarity index 70% rename from src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java rename to src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 9ef1870b..4c39c19f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -24,12 +24,14 @@ */ package org.spongepowered.asm.mixin.transformer; +import java.lang.annotation.Annotation; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.SortedSet; import org.apache.logging.log4j.LogManager; @@ -46,25 +48,65 @@ import org.spongepowered.asm.lib.tree.LabelNode; import org.spongepowered.asm.lib.tree.LineNumberNode; import org.spongepowered.asm.lib.tree.MethodInsnNode; import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.MixinEnvironment.Option; -import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.ASMHelper; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.ConstraintParser; import org.spongepowered.asm.util.ConstraintParser.Constraint; -import org.spongepowered.asm.util.ConstraintViolationException; -import org.spongepowered.asm.util.InvalidConstraintException; +import org.spongepowered.asm.util.throwables.ConstraintViolationException; +import org.spongepowered.asm.util.throwables.InvalidConstraintException; +import com.google.common.collect.ImmutableList; /** * Applies mixins to a target class */ -public class MixinApplicator { +public class MixinApplicatorStandard { + + /** + * Annotations which can have constraints + */ + protected static final List> CONSTRAINED_ANNOTATIONS = ImmutableList.>of( + Overwrite.class, + Inject.class, + ModifyArg.class, + Redirect.class, + ModifyVariable.class, + ModifyConstant.class + ); + + /** + * Passes the mixin applicator applies to each mixin + */ + enum ApplicatorPass { + /** + * Main pass, mix in methods, fields, interfaces etc + */ + MAIN, + + /** + * Enumerate injectors and scan for injection points + */ + PREINJECT, + + /** + * Apply injectors from previous pass + */ + INJECT + } /** * Internal struct for representing a range @@ -145,7 +187,7 @@ public class MixinApplicator { * locals are shifted so that they don't interfere with locals in the * receiving constructor. */ - private static final int[] INITIALISER_OPCODE_BLACKLIST = { + protected static final int[] INITIALISER_OPCODE_BLACKLIST = { Opcodes.RETURN, Opcodes.ILOAD, Opcodes.LLOAD, Opcodes.FLOAD, Opcodes.DLOAD, Opcodes.IALOAD, Opcodes.LALOAD, Opcodes.FALOAD, Opcodes.DALOAD, Opcodes.AALOAD, Opcodes.BALOAD, Opcodes.CALOAD, Opcodes.SALOAD, Opcodes.ISTORE, Opcodes.LSTORE, Opcodes.FSTORE, Opcodes.DSTORE, Opcodes.ASTORE, Opcodes.IASTORE, Opcodes.LASTORE, Opcodes.FASTORE, Opcodes.DASTORE, Opcodes.AASTORE, Opcodes.BASTORE, Opcodes.CASTORE, @@ -155,39 +197,64 @@ public class MixinApplicator { /** * Log more things */ - private final Logger logger = LogManager.getLogger("mixin"); + protected final Logger logger = LogManager.getLogger("mixin"); /** - * Session ID, used as a check when parsing {@link MixinMerged} annotations - * to prevent them being applied at compile time by people trying to - * circumvent mixin application + * Target class context */ - private final String sessionId; + protected final TargetClassContext context; /** * Target class name */ - private final String targetName; + protected final String targetName; /** * Target class tree */ - private final ClassNode targetClass; + protected final ClassNode targetClass; - MixinApplicator(String sessionId, String transformedName, ClassNode targetClass) { - this.sessionId = sessionId; - this.targetName = transformedName; - this.targetClass = targetClass; + MixinApplicatorStandard(TargetClassContext context) { + this.context = context; + this.targetName = context.getClassName(); + this.targetClass = context.getClassNode(); } /** * Apply supplied mixins to the target class */ void apply(SortedSet mixins) { + List mixinContexts = new ArrayList(); + for (MixinInfo mixin : mixins) { this.logger.log(mixin.getLoggingLevel(), "Mixing {} from {} into {}", mixin.getName(), mixin.getParent(), this.targetName); - this.applyMixin(mixin.createContextFor(this.targetClass)); + mixinContexts.add(mixin.createContextFor(this.context)); } + + MixinTargetContext current = null; + + try { + for (MixinTargetContext context : mixinContexts) { + (current = context).preApply(this.targetName, this.targetClass); + } + + for (ApplicatorPass pass : ApplicatorPass.values()) { + for (MixinTargetContext context : mixinContexts) { + this.applyMixin(current = context, pass); + } + } + + for (MixinTargetContext context : mixinContexts) { + (current = context).postApply(this.targetName, this.targetClass); + } + } catch (InvalidMixinException ex) { + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(current, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst applying the mixin class: " + + ex.getMessage(), ex); + } + + this.context.processDebugTasks(); } /** @@ -195,23 +262,28 @@ public class MixinApplicator { * * @param mixin Mixin to apply */ - private void applyMixin(MixinTargetContext mixin) { - try { - mixin.preApply(this.targetName, this.targetClass); - - this.applyInterfaces(mixin); - this.applyAttributes(mixin); - this.applyAnnotations(mixin); - this.applyFields(mixin); - this.applyMethods(mixin); - this.applyInitialisers(mixin); - this.applyInjections(mixin); - - mixin.postApply(this.targetName, this.targetClass); - } catch (InvalidMixinException ex) { - throw ex; - } catch (Exception ex) { - throw new InvalidMixinException(mixin, "Unexpecteded error whilst applying the mixin class", ex); + protected final void applyMixin(MixinTargetContext mixin, ApplicatorPass pass) { + switch (pass) { + case MAIN: + this.applyInterfaces(mixin); + this.applyAttributes(mixin); + this.applyAnnotations(mixin); + this.applyFields(mixin); + this.applyMethods(mixin); + this.applyInitialisers(mixin); + break; + + case PREINJECT: + this.prepareInjections(mixin); + break; + + case INJECT: + this.applyInjections(mixin); + break; + + default: + // wat? + throw new IllegalStateException("Invalid pass specified " + pass); } } @@ -220,10 +292,11 @@ public class MixinApplicator { * * @param mixin */ - private void applyInterfaces(MixinTargetContext mixin) { + protected void applyInterfaces(MixinTargetContext mixin) { for (String interfaceName : mixin.getInterfaces()) { if (!this.targetClass.interfaces.contains(interfaceName)) { this.targetClass.interfaces.add(interfaceName); + mixin.getTargetClassInfo().addInterface(interfaceName); } } } @@ -233,10 +306,11 @@ public class MixinApplicator { * * @param mixin */ - private void applyAttributes(MixinTargetContext mixin) { + protected void applyAttributes(MixinTargetContext mixin) { if (mixin.shouldSetSourceFile()) { this.targetClass.sourceFile = mixin.getSourceFile(); } + this.targetClass.version = Math.max(this.targetClass.version, mixin.getMinRequiredClassVersion()); } /** @@ -244,7 +318,7 @@ public class MixinApplicator { * * @param mixin */ - private void applyAnnotations(MixinTargetContext mixin) { + protected void applyAnnotations(MixinTargetContext mixin) { ClassNode sourceClass = mixin.getClassNode(); this.mergeAnnotations(sourceClass, this.targetClass); } @@ -257,14 +331,27 @@ public class MixinApplicator { * * @param mixin */ - private void applyFields(MixinTargetContext mixin) { - for (FieldNode shadow : mixin.getShadowFields()) { + protected void applyFields(MixinTargetContext mixin) { + this.mergeShadowFields(mixin); + this.mergeNewFields(mixin); + } + + protected void mergeShadowFields(MixinTargetContext mixin) { + for (Entry entry : mixin.getShadowFields()) { + FieldNode shadow = entry.getKey(); FieldNode target = this.findTargetField(shadow); if (target != null) { this.mergeAnnotations(shadow, target); + + // Strip the FINAL flag from @Mutable non-private fields + if (entry.getValue().isDecoratedMutable() && !ASMHelper.hasFlag(target, Opcodes.ACC_PRIVATE)) { + target.access &= ~Opcodes.ACC_FINAL; + } } } - + } + + protected void mergeNewFields(MixinTargetContext mixin) { for (FieldNode field : mixin.getFields()) { FieldNode target = this.findTargetField(field); if (target == null) { @@ -279,7 +366,7 @@ public class MixinApplicator { * * @param mixin */ - private void applyMethods(MixinTargetContext mixin) { + protected void applyMethods(MixinTargetContext mixin) { for (MethodNode shadow : mixin.getShadowMethods()) { MethodNode target = this.findTargetMethod(shadow); if (target != null) { @@ -292,21 +379,9 @@ public class MixinApplicator { mixin.transformMethod(mixinMethod); if (!mixinMethod.name.startsWith("<")) { - AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class); - boolean isOverwrite = overwrite != null; - if (isOverwrite) { - this.checkConstraints(mixin, overwrite); - } - - if (MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_STATIC) - && !MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE) - && !MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC) - && !isOverwrite) { - throw new InvalidMixinException(mixin, - String.format("Mixin classes cannot contain visible static methods or fields, found %s", mixinMethod.name)); - } - - this.mergeMethod(mixin, mixinMethod, isOverwrite); + this.checkMethodVisibility(mixin, mixinMethod); + this.checkMethodConstraints(mixin, mixinMethod); + this.mergeMethod(mixin, mixinMethod); } else if (Constants.CLINIT.equals(mixinMethod.name)) { // Class initialiser insns get appended this.appendInsns(mixinMethod); @@ -319,14 +394,13 @@ public class MixinApplicator { * * @param mixin Mixin being applied * @param method Method to merge - * @param isOverwrite true if the method is annotated with an - * {@link Overwrite} annotation */ - private void mergeMethod(MixinTargetContext mixin, MethodNode method, boolean isOverwrite) { + protected void mergeMethod(MixinTargetContext mixin, MethodNode method) { + boolean isOverwrite = ASMHelper.getVisibleAnnotation(method, Overwrite.class) != null; MethodNode target = this.findTargetMethod(method); if (target != null) { - if (this.alreadyMerged(mixin, method, isOverwrite, target)) { + if (this.isAlreadyMerged(mixin, method, isOverwrite, target)) { return; } @@ -339,16 +413,12 @@ public class MixinApplicator { this.targetClass.methods.remove(target); } } else if (isOverwrite) { - throw new InvalidMixinException(mixin, String.format("Overwrite target %s was not located in the target class", method.name)); + throw new InvalidMixinException(mixin, String.format("Overwrite target \"%s\" was not located in target class %s", + method.name, mixin.getTargetClassRef())); } this.targetClass.methods.add(method); - mixin.getTargetClassInfo().addMethod(method); - - ASMHelper.setVisibleAnnotation(method, MixinMerged.class, - "mixin", mixin.getClassName(), - "priority", mixin.getPriority(), - "sessionId", this.sessionId); + mixin.addMergedMethod(method); } /** @@ -362,23 +432,40 @@ public class MixinApplicator { * @param target target method being checked * @return true if the target was already merged and should be skipped */ - private boolean alreadyMerged(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target) { + protected boolean isAlreadyMerged(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target) { AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class); if (merged == null) { + if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) { + this.logger.warn("Overwrite prohibited for @Final method {} in {}. Skipping method.", method.name, mixin); + return true; + } return false; } String sessionId = ASMHelper.getAnnotationValue(merged, "sessionId"); - if (!this.sessionId.equals(sessionId)) { + if (!this.context.getSessionId().equals(sessionId)) { throw new ClassFormatError("Invalid @MixinMerged annotation found in" + mixin + " at " + method.name + " in " + this.targetClass.name); } - + + if (ASMHelper.hasFlag(target, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE) + && ASMHelper.hasFlag(method, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE)) { + if (mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE)) { + this.logger.warn("Synthetic bridge method clash for {} in {}", method.name, mixin); + } + return true; + } + String owner = ASMHelper.getAnnotationValue(merged, "mixin"); int priority = ASMHelper.getAnnotationValue(merged, "priority"); if (priority >= mixin.getPriority() && !owner.equals(mixin.getClassName())) { - this.logger.warn("Method overwrite conflict for {}, previously written by {}. Skipping method.", method.name, owner); + this.logger.warn("Method overwrite conflict for {} in {}, previously written by {}. Skipping method.", method.name, mixin, owner); + return true; + } + + if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) { + this.logger.warn("Method overwrite conflict for @Final method {} in {} declared by {}. Skipping method.", method.name, mixin, owner); return true; } @@ -398,25 +485,27 @@ public class MixinApplicator { * @return true if the intrinsic method was skipped (short-circuit further * merge operations) */ - private boolean mergeIntrinsic(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, + protected boolean mergeIntrinsic(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target, AnnotationNode intrinsic) { if (isOverwrite) { throw new InvalidMixinException(mixin, "@Intrinsic is not compatible with @Overwrite, remove one of these annotations on " - + method.name); + + method.name + " in " + mixin); } - if (MixinApplicator.hasFlag(method, Opcodes.ACC_STATIC)) { - throw new InvalidMixinException(mixin, "@Intrinsic method cannot be static, found " + method.name); + String methodName = method.name + method.desc; + if (ASMHelper.hasFlag(method, Opcodes.ACC_STATIC)) { + throw new InvalidMixinException(mixin, "@Intrinsic method cannot be static, found " + methodName + " in " + mixin); } AnnotationNode renamed = ASMHelper.getVisibleAnnotation(method, MixinRenamed.class); if (renamed == null || !ASMHelper.getAnnotationValue(renamed, "isInterfaceMember", false)) { - throw new InvalidMixinException(mixin, "@Intrinsic method must be prefixed interface method, no rename encountered on " + method.name); + throw new InvalidMixinException(mixin, "@Intrinsic method must be prefixed interface method, no rename encountered on " + + methodName + " in " + mixin); } if (!ASMHelper.getAnnotationValue(intrinsic, "displace", false)) { - this.logger.log(mixin.getLoggingLevel(), "Skipping Intrinsic mixin method {}", method.name); + this.logger.log(mixin.getLoggingLevel(), "Skipping Intrinsic mixin method {} for {}", methodName, mixin.getTargetClassRef()); return true; } @@ -431,7 +520,7 @@ public class MixinApplicator { * @param method Method being merged * @param target target method being checked */ - private void displaceIntrinsic(MixinTargetContext mixin, MethodNode method, MethodNode target) { + protected void displaceIntrinsic(MixinTargetContext mixin, MethodNode method, MethodNode target) { // Deliberately include invalid character in the method name so that // we guarantee no hackiness String proxyName = "proxy+" + target.name; @@ -455,7 +544,7 @@ public class MixinApplicator { * * @param method */ - private void appendInsns(MethodNode method) { + protected final void appendInsns(MethodNode method) { if (Type.getReturnType(method.desc) != Type.VOID_TYPE) { throw new IllegalArgumentException("Attempted to merge insns from a method which does not return void"); } @@ -463,7 +552,7 @@ public class MixinApplicator { MethodNode target = this.findTargetMethod(method); if (target != null) { - AbstractInsnNode returnNode = MixinApplicator.findInsn(target, Opcodes.RETURN); + AbstractInsnNode returnNode = MixinApplicatorStandard.findInsn(target, Opcodes.RETURN); if (returnNode != null) { Iterator injectIter = method.instructions.iterator(); @@ -490,7 +579,7 @@ public class MixinApplicator { * * @param mixin */ - private void applyInitialisers(MixinTargetContext mixin) { + protected void applyInitialisers(MixinTargetContext mixin) { // Try to find a suitable constructor, we need a constructor with line numbers in order to extract the initialiser MethodNode ctor = this.getConstructor(mixin); if (ctor == null) { @@ -505,7 +594,7 @@ public class MixinApplicator { // Patch the initialiser into the target class ctors for (MethodNode method : this.targetClass.methods) { - if (Constants.INIT.equals(method.name)) { + if (Constants.CTOR.equals(method.name)) { method.maxStack = Math.max(method.maxStack, ctor.maxStack); this.injectInitialiser(mixin, method, initialiser); } @@ -516,20 +605,18 @@ public class MixinApplicator { * Finds a suitable ctor for reading the instance initialiser bytecode * * @param mixin mixin to search - * @return + * @return appropriate ctor or null if none found */ - private MethodNode getConstructor(MixinTargetContext mixin) { + protected MethodNode getConstructor(MixinTargetContext mixin) { MethodNode ctor = null; for (MethodNode mixinMethod : mixin.getMethods()) { - if (Constants.INIT.equals(mixinMethod.name)) { - if (MixinApplicator.hasLineNumbers(mixinMethod)) { - if (ctor == null) { - ctor = mixinMethod; - } else { - // Not an error condition, just weird - this.logger.warn(String.format("Mixin %s has multiple constructors, %s was selected\n", mixin, ctor.desc)); - } + if (Constants.CTOR.equals(mixinMethod.name) && MixinApplicatorStandard.hasLineNumbers(mixinMethod)) { + if (ctor == null) { + ctor = mixinMethod; + } else { + // Not an error condition, just weird + this.logger.warn(String.format("Mixin %s has multiple constructors, %s was selected\n", mixin, ctor.desc)); } } } @@ -556,7 +643,7 @@ public class MixinApplicator { line = ((LineNumberNode)insn).line; lineNumberIsValid = true; } else if (insn instanceof MethodInsnNode) { - if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.INIT.equals(((MethodInsnNode)insn).name) && superIndex == -1) { + if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.CTOR.equals(((MethodInsnNode)insn).name) && superIndex == -1) { superIndex = ctor.instructions.indexOf(insn); start = line; } @@ -592,7 +679,7 @@ public class MixinApplicator { * @return initialiser bytecode extracted from the supplied constructor, or * null if the constructor range could not be parsed */ - private Deque getInitialiser(MixinTargetContext mixin, MethodNode ctor) { + protected final Deque getInitialiser(MixinTargetContext mixin, MethodNode ctor) { // Find the range of line numbers which corresponds to the constructor body Range init = this.getConstructorRange(ctor); if (!init.isValid()) { @@ -631,7 +718,7 @@ public class MixinApplicator { trimAtOpcode = -1; continue; } - for (int ivalidOp : MixinApplicator.INITIALISER_OPCODE_BLACKLIST) { + for (int ivalidOp : MixinApplicatorStandard.INITIALISER_OPCODE_BLACKLIST) { if (opcode == ivalidOp) { // At the moment I don't handle any transient locals because I haven't seen any in the wild, but let's avoid writing // code which will likely break things and fix it if a real test case ever appears @@ -650,7 +737,7 @@ public class MixinApplicator { if (last != null) { if (last.getOpcode() != Opcodes.PUTFIELD) { throw new InvalidMixinException(mixin, "Could not parse initialiser, expected 0xB5, found 0x" - + Integer.toHexString(last.getOpcode())); + + Integer.toHexString(last.getOpcode()) + " in " + mixin); } } @@ -663,22 +750,22 @@ public class MixinApplicator { * @param ctor * @param initialiser */ - private void injectInitialiser(MixinTargetContext mixin, MethodNode ctor, Deque initialiser) { + protected final void injectInitialiser(MixinTargetContext mixin, MethodNode ctor, Deque initialiser) { Map labels = ASMHelper.cloneLabels(ctor.instructions); for (Iterator iter = ctor.instructions.iterator(0); iter.hasNext();) { AbstractInsnNode insn = iter.next(); - if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.INIT.equals(((MethodInsnNode)insn).name)) { + if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.CTOR.equals(((MethodInsnNode)insn).name)) { for (AbstractInsnNode node : initialiser) { if (node instanceof LabelNode) { continue; } if (node instanceof JumpInsnNode) { - throw new InvalidMixinException(mixin, "Unsupported opcode in initialiser"); + throw new InvalidMixinException(mixin, "Unsupported JUMP opcode in initialiser in " + mixin); } - AbstractInsnNode iThinkWereACloneNow = node.clone(labels); - ctor.instructions.insert(insn, iThinkWereACloneNow); - insn = iThinkWereACloneNow; + AbstractInsnNode imACloneNow = node.clone(labels); + ctor.instructions.insert(insn, imACloneNow); + insn = imACloneNow; } return; } @@ -688,50 +775,73 @@ public class MixinApplicator { } /** - * Process {@link Inject} annotations and inject callbacks to annotated - * methods - * @param mixin + * Scan for injector methods and injection points + * + * @param mixin Mixin being scanned */ - private void applyInjections(MixinTargetContext mixin) { - List injected = new ArrayList(); - - for (MethodNode method : this.targetClass.methods) { - InjectionInfo injectInfo = InjectionInfo.parse(mixin, method); - if (injectInfo == null) { - continue; - } - - if (injectInfo.isValid()) { - injectInfo.inject(); - injected.add(injectInfo); - } - - method.visibleAnnotations.remove(injectInfo.getAnnotation()); - } - - for (InjectionInfo injectInfo : injected) { - injectInfo.postInject(); + protected void prepareInjections(MixinTargetContext mixin) { + mixin.prepareInjections(); + } + + /** + * Apply all injectors discovered in the previous pass + * + * @param mixin Mixin being applied + */ + protected void applyInjections(MixinTargetContext mixin) { + mixin.applyInjections(); + } + + /** + * Check visibility before merging a mixin method + * + * @param mixin + * @param mixinMethod + */ + protected void checkMethodVisibility(MixinTargetContext mixin, MethodNode mixinMethod) { + if (ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_STATIC) + && !ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE) + && !ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC) + && !(ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class) != null)) { + throw new InvalidMixinException(mixin, + String.format("Mixin %s contains non-private static method %s", mixin, mixinMethod)); } } + /** + * Check constraints in annotations on the specified mixin method + * + * @param mixin Target context + * @param method Mixin method + */ + protected void checkMethodConstraints(MixinTargetContext mixin, MethodNode method) { + for (Class annotationType : MixinApplicatorStandard.CONSTRAINED_ANNOTATIONS) { + AnnotationNode annotation = ASMHelper.getVisibleAnnotation(method, annotationType); + if (annotation != null) { + this.checkConstraints(mixin, method, annotation); + } + } + } + /** * Check constraints for the specified annotation based on token values in * the current environment * * @param mixin Mixin being applied + * @param method annotated method * @param annotation Annotation node to check constraints */ - private void checkConstraints(MixinTargetContext mixin, AnnotationNode annotation) { + protected final void checkConstraints(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { try { Constraint constraint = ConstraintParser.parse(annotation); MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); try { constraint.check(environment); } catch (ConstraintViolationException ex) { - if (environment.getOption(Option.IGNORE_CONSTRAINTS)) { - this.logger.warn("Constraint violation: {}", ex.getMessage()); - } else { - throw new InvalidMixinException(mixin, ex.getMessage(), ex); + String message = String.format("Constraint violation: %s on %s in %s", ex.getMessage(), method, mixin); + this.logger.warn(message); + if (!environment.getOption(Option.IGNORE_CONSTRAINTS)) { + throw new InvalidMixinException(mixin, message, ex); } } } catch (InvalidConstraintException ex) { @@ -750,7 +860,7 @@ public class MixinApplicator { * @param from ClassNode to merge annotations from * @param to ClassNode to merge annotations to */ - private void mergeAnnotations(ClassNode from, ClassNode to) { + protected final void mergeAnnotations(ClassNode from, ClassNode to) { to.visibleAnnotations = this.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, from.name); to.invisibleAnnotations = this.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, from.name); } @@ -766,7 +876,7 @@ public class MixinApplicator { * @param from MethodNode to merge annotations from * @param to MethodNode to merge annotations to */ - private void mergeAnnotations(MethodNode from, MethodNode to) { + protected final void mergeAnnotations(MethodNode from, MethodNode to) { to.visibleAnnotations = this.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, from.name); to.invisibleAnnotations = this.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, from.name); } @@ -782,7 +892,7 @@ public class MixinApplicator { * @param from FieldNode to merge annotations from * @param to FieldNode to merge annotations to */ - private void mergeAnnotations(FieldNode from, FieldNode to) { + protected final void mergeAnnotations(FieldNode from, FieldNode to) { to.visibleAnnotations = this.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, from.name); to.invisibleAnnotations = this.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, from.name); } @@ -807,7 +917,7 @@ public class MixinApplicator { } for (AnnotationNode annotation : from) { - if (annotation.desc.startsWith("L" + Constants.MIXIN_PACKAGE_REF)) { + if (!this.isMergeableAnnotation(annotation)) { continue; } @@ -827,6 +937,13 @@ public class MixinApplicator { return to; } + private boolean isMergeableAnnotation(AnnotationNode annotation) { + if (annotation.desc.startsWith("L" + Constants.MIXIN_PACKAGE_REF)) { + return annotation.desc.endsWith("Debug;"); + } + return true; + } + /** * Find the first insn node with a matching opcode in the specified method * @@ -834,7 +951,7 @@ public class MixinApplicator { * @param opcode opcode to search for * @return found node or null if not found */ - private static AbstractInsnNode findInsn(MethodNode method, int opcode) { + protected static AbstractInsnNode findInsn(MethodNode method, int opcode) { Iterator findReturnIter = method.instructions.iterator(); while (findReturnIter.hasNext()) { AbstractInsnNode insn = findReturnIter.next(); @@ -866,7 +983,7 @@ public class MixinApplicator { * * @return Target method matching searchFor, or null if not found */ - private MethodNode findTargetMethod(MethodNode searchFor) { + protected final MethodNode findTargetMethod(MethodNode searchFor) { for (MethodNode target : this.targetClass.methods) { if (target.name.equals(searchFor.name) && target.desc.equals(searchFor.desc)) { return target; @@ -882,7 +999,7 @@ public class MixinApplicator { * * @return Target field matching searchFor, or null if not found */ - private FieldNode findTargetField(FieldNode searchFor) { + protected final FieldNode findTargetField(FieldNode searchFor) { for (FieldNode target : this.targetClass.fields) { if (target.name.equals(searchFor.name)) { return target; @@ -892,25 +1009,4 @@ public class MixinApplicator { return null; } - /** - * Check whether the specified flag is set on the specified method - * - * @param method - * @param flag - * @return True if the specified flag is set in this method's access flags - */ - static boolean hasFlag(MethodNode method, int flag) { - return (method.access & flag) == flag; - } - - /** - * Check whether the specified flag is set on the specified field - * - * @param field - * @param flag - * @return True if the specified flag is set in this field's access flags - */ - static boolean hasFlag(FieldNode field, int flag) { - return (field.access & flag) == flag; - } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index 1a0e9df5..9a7b6545 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.transformer; import java.io.InputStreamReader; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -33,29 +34,49 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; - -import net.minecraft.launchwrapper.Launch; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.launch.MixinInitialisationError; +import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; -import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.VersionNumber; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; +import net.minecraft.launchwrapper.Launch; + /** * Mixin configuration bundle */ class MixinConfig implements Comparable, IMixinConfig { + /** + * Wrapper for injection options + */ + static class InjectorOptions { + + @SerializedName("defaultRequire") + int defaultRequireValue = 0; + + @SerializedName("defaultGroup") + String defaultGroup = "default"; + + } + /** * Global order of mixin configs, used to determine ordering between configs * with equivalent priority @@ -66,7 +87,7 @@ class MixinConfig implements Comparable, IMixinConfig { * Global list of mixin classes, so we can skip any duplicates */ private static final Set globalMixinList = new HashSet(); - + /** * Log even more things */ @@ -91,13 +112,30 @@ class MixinConfig implements Comparable, IMixinConfig { * Synthetic inner classes for mixins in this set */ private final transient Set syntheticInnerClasses = new HashSet(); + + /** + * Marshal + */ + private transient Config handle; + + /** + * Target selector, eg. @env(DEFAULT) + */ + @SerializedName("target") + private String selector; /** * Minimum version of the mixin subsystem required to correctly apply mixins * in this configuration. */ @SerializedName("minVersion") - private String version; + private String version; + + /** + * Minimum compatibility level required for mixins in this set + */ + @SerializedName("compatibilityLevel") + private String compatibility; /** * Determines whether failures in this mixin config are considered terminal @@ -171,7 +209,17 @@ class MixinConfig implements Comparable, IMixinConfig { * Intrinsic order (for sorting configurations with identical priority) */ private final transient int order = MixinConfig.configOrder++; + +// /** +// * Phase selector +// */ +// private transient List selectors; + /** + * Parent environment + */ + private transient MixinEnvironment env; + /** * Name of the file this config was initialised from */ @@ -183,6 +231,12 @@ class MixinConfig implements Comparable, IMixinConfig { @SerializedName("plugin") private String pluginClassName; + /** + * Injector options + */ + @SerializedName("injectors") + private InjectorOptions injectorOptions = new InjectorOptions(); + /** * Config plugin, if supplied */ @@ -196,8 +250,8 @@ class MixinConfig implements Comparable, IMixinConfig { /** * Keep track of initialisation state */ - private transient boolean initialised = false; - + private transient boolean prepared = false; + /** * Spawn via GSON, no public ctor for you */ @@ -207,15 +261,73 @@ class MixinConfig implements Comparable, IMixinConfig { * Called immediately after deserialisation * * @param name Mixin config name + * @param fallbackEnvironment Fallback environment if not specified in + * config * @return true if the config was successfully initialised and should be * returned, or false if initialisation failed and the config should * be discarded */ - private boolean onLoad(String name) { + private boolean onLoad(String name, MixinEnvironment fallbackEnvironment) { this.name = name; + this.env = this.parseSelector(this.selector, fallbackEnvironment); + this.initCompatibilityLevel(); + return this.checkVersion(); + } + + @SuppressWarnings("deprecation") + private void initCompatibilityLevel() { + if (this.compatibility == null) { + return; + } + CompatibilityLevel level = CompatibilityLevel.valueOf(this.compatibility.trim().toUpperCase()); + CompatibilityLevel current = MixinEnvironment.getCompatibilityLevel(); + + if (level == current) { + return; + } + + // Current level is higher than required but too new to support it + if (current.isAtLeast(level)) { + if (!current.canSupport(level)) { + throw new MixinInitialisationError("Mixin config " + this.name + " requires compatibility level " + level + " which is too old"); + } + } + + // Current level is lower than required but current level prohibits elevation + if (!current.canElevateTo(level)) { + throw new MixinInitialisationError("Mixin config " + this.name + " requires compatibility level " + level + " which is prohibited by " + + current); + } + + MixinEnvironment.setCompatibilityLevel(level); + } + + // AMS - temp + private MixinEnvironment parseSelector(String target, MixinEnvironment fallbackEnvironment) { + if (target != null) { + String[] selectors = target.split("[&\\| ]"); + for (String selector : selectors) { + selector = selector.trim(); + Pattern environmentSelector = Pattern.compile("^@env(?:ironment)?\\(([A-Z]+)\\)$"); + Matcher environmentSelectorMatcher = environmentSelector.matcher(selector); + if (environmentSelectorMatcher.matches()) { + // only parse first env selector + return MixinEnvironment.getEnvironment(Phase.forName(environmentSelectorMatcher.group(1))); + } + } + + Phase phase = Phase.forName(target); + if (phase != null) { + return MixinEnvironment.getEnvironment(phase); + } + } + return fallbackEnvironment; + } + + private boolean checkVersion() throws MixinInitialisationError { VersionNumber minVersion = VersionNumber.parse(this.version); - VersionNumber curVersion = VersionNumber.parse(MixinEnvironment.getCurrentEnvironment().getVersion()); + VersionNumber curVersion = VersionNumber.parse(this.env.getVersion()); if (minVersion.compareTo(curVersion) > 0) { this.logger.warn("Mixin config {} requires mixin subsystem version {} but {} was found. The mixin config will not be applied.", this.name, minVersion, curVersion); @@ -227,6 +339,13 @@ class MixinConfig implements Comparable, IMixinConfig { return false; } + return true; + } + + /** + * Initialise the config once it's selected + */ + void onSelect() { if (this.pluginClassName != null) { try { Class pluginClass = Class.forName(this.pluginClassName, true, Launch.classLoader); @@ -256,9 +375,7 @@ class MixinConfig implements Comparable, IMixinConfig { } this.refMapper = ReferenceMapper.read(this.refMapperConfig); - this.verboseLogging |= MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERBOSE); - - return true; + this.verboseLogging |= this.env.getOption(Option.DEBUG_VERBOSE); } /** @@ -274,20 +391,20 @@ class MixinConfig implements Comparable, IMixinConfig { * either the hasMixinsFor() or getMixinsFor() methods. *

*/ - void initialise() { - if (this.initialised) { + void prepare(IHotSwap hotSwapper) { + if (this.prepared) { return; } - this.initialised = true; + this.prepared = true; - this.initialiseMixins(this.mixinClasses, false); + this.prepareMixins(this.mixinClasses, false, hotSwapper); - switch (MixinEnvironment.getCurrentEnvironment().getSide()) { + switch (this.env.getSide()) { case CLIENT: - this.initialiseMixins(this.mixinClassesClient, false); + this.prepareMixins(this.mixinClassesClient, false, hotSwapper); break; case SERVER: - this.initialiseMixins(this.mixinClassesServer, false); + this.prepareMixins(this.mixinClassesServer, false, hotSwapper); break; case UNKNOWN: //$FALL-THROUGH$ @@ -297,10 +414,10 @@ class MixinConfig implements Comparable, IMixinConfig { } } - void postInitialise() { + void postInitialise(IHotSwap hotSwapper) { if (this.plugin != null) { List pluginMixins = this.plugin.getMixins(); - this.initialiseMixins(pluginMixins, true); + this.prepareMixins(pluginMixins, true, hotSwapper); } for (Iterator iter = this.mixins.iterator(); iter.hasNext();) { @@ -310,6 +427,10 @@ class MixinConfig implements Comparable, IMixinConfig { for (String innerClass : mixin.getSyntheticInnerClasses()) { this.syntheticInnerClasses.add(innerClass.replace('/', '.')); } + } catch (InvalidMixinException ex) { + this.logger.error(ex.getMixin() + ": " + ex.getMessage(), ex); + this.removeMixin(mixin); + iter.remove(); } catch (Exception ex) { this.logger.error(ex.getMessage(), ex); this.removeMixin(mixin); @@ -328,7 +449,7 @@ class MixinConfig implements Comparable, IMixinConfig { } } - private void initialiseMixins(List mixinClasses, boolean suppressPlugin) { + private void prepareMixins(List mixinClasses, boolean suppressPlugin, IHotSwap hotSwapper) { if (mixinClasses == null) { return; } @@ -340,8 +461,10 @@ class MixinConfig implements Comparable, IMixinConfig { continue; } + MixinInfo mixin = null; + try { - MixinInfo mixin = new MixinInfo(this, mixinClass, true, this.plugin, suppressPlugin); + mixin = new MixinInfo(this, mixinClass, true, this.plugin, suppressPlugin); if (mixin.getTargetClasses().size() > 0) { MixinConfig.globalMixinList.add(fqMixinClass); for (String targetClass : mixin.getTargetClasses()) { @@ -349,9 +472,20 @@ class MixinConfig implements Comparable, IMixinConfig { this.mixinsFor(targetClassName).add(mixin); this.unhandledTargets.add(targetClassName); } + if (hotSwapper != null) { + hotSwapper.registerMixinClass(mixin.getClassName()); + } this.mixins.add(mixin); } + } catch (InvalidMixinException ex) { + if (this.required) { + throw ex; + } + this.logger.error(ex.getMessage(), ex); } catch (Exception ex) { + if (this.required) { + throw new InvalidMixinException(mixin, "Error initialising mixin " + mixin + " - " + ex.getClass() + ": " + ex.getMessage(), ex); + } this.logger.error(ex.getMessage(), ex); } } @@ -361,6 +495,16 @@ class MixinConfig implements Comparable, IMixinConfig { this.unhandledTargets.remove(transformedName); } + /** + * Get marshalling handle + */ + public Config getHandle() { + if (this.handle == null) { + this.handle = new Config(this); + } + return this.handle; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinConfig#isRequired() */ @@ -368,7 +512,16 @@ class MixinConfig implements Comparable, IMixinConfig { public boolean isRequired() { return this.required; } - + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.extensibility.IMixinConfig + * #getEnvironment() + */ + @Override + public MixinEnvironment getEnvironment() { + return this.env; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinConfig#getName() */ @@ -400,6 +553,49 @@ class MixinConfig implements Comparable, IMixinConfig { public int getDefaultMixinPriority() { return this.mixinPriority; } + + /** + * Get the defined value for the {@link Inject#require} parameter on + * injectors defined in mixins in this configuration. + * + * @return default require value + */ + public int getDefaultRequiredInjections() { + return this.injectorOptions.defaultRequireValue; + } + + /** + * Get the defined injector group for injectors + * + * @return default group name + */ + public String getDefaultInjectorGroup() { + String defaultGroup = this.injectorOptions.defaultGroup; + return defaultGroup != null && !defaultGroup.isEmpty() ? defaultGroup : "default"; + } + + // AMS - temp + public boolean select(MixinEnvironment environment) { + return this.env == environment; + } + + /** + * Get the number of mixins in this config, for debug logging + * + * @return total enumerated mixins in set + */ + int getDeclaredMixinCount() { + return MixinConfig.getCollectionSize(this.mixinClasses, this.mixinClassesClient, this.mixinClassesServer); + } + + /** + * Get the number of mixins actually initialised, for debug logging + * + * @return total enumerated mixins in set + */ + int getMixinCount() { + return this.mixins.size(); + } /** * Get the list of mixin classes we will be applying @@ -420,9 +616,21 @@ class MixinConfig implements Comparable, IMixinConfig { * Get the reference remapper for injectors */ public ReferenceMapper getReferenceMapper() { + if (this.env.getOption(Option.DISABLE_REFMAP)) { + return ReferenceMapper.DEFAULT_MAPPER; + } + this.refMapper.setContext(this.env.getRefmapObfuscationContext()); return this.refMapper; } + String remapClassName(String className, String reference) { +// String remapped = this.plugin != null ? this.plugin.remap(className, reference) : null; +// if (remapped != null) { +// return remapped; +// } + return this.getReferenceMapper().remap(className, reference); + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinConfig#getPlugin() */ @@ -480,7 +688,7 @@ class MixinConfig implements Comparable, IMixinConfig { * class * * @param targetClass - * @return + * @return true if this bundle contains any mixins for the specified target */ public boolean hasMixinsFor(String targetClass) { return this.mixinMapping.containsKey(targetClass); @@ -490,7 +698,7 @@ class MixinConfig implements Comparable, IMixinConfig { * Get mixins for the specified target class * * @param targetClass - * @return + * @return mixins for the specified target */ public List getMixinsFor(String targetClass) { return this.mixinsFor(targetClass); @@ -504,6 +712,24 @@ class MixinConfig implements Comparable, IMixinConfig { } return mixins; } + + /** + * Updates a mixin with new bytecode + * + * @param mixinClass Name of the mixin class + * @param bytes New bytecode + * @return List of classes that need to be updated + */ + public List reloadMixin(String mixinClass, byte[] bytes) { + for (Iterator iter = this.mixins.iterator(); iter.hasNext();) { + MixinInfo mixin = iter.next(); + if (mixin.getClassName().equals(mixinClass)) { + mixin.reloadMixin(bytes); + return mixin.getTargetClasses(); + } + } + return Collections.emptyList(); + } @Override public String toString() { @@ -529,18 +755,30 @@ class MixinConfig implements Comparable, IMixinConfig { * specified configFile, which must be accessible on the classpath * * @param configFile - * @return + * @param outer fallback environment + * @return new Config */ - static MixinConfig create(String configFile) { + static Config create(String configFile, MixinEnvironment outer) { try { MixinConfig config = new Gson().fromJson(new InputStreamReader(Launch.classLoader.getResourceAsStream(configFile)), MixinConfig.class); - if (config.onLoad(configFile)) { - return config; + if (config.onLoad(configFile, outer)) { + return config.getHandle(); } return null; } catch (Exception ex) { ex.printStackTrace(); - throw new IllegalArgumentException(String.format("The specified configuration file '%s' was invalid or could not be read", configFile)); + throw new IllegalArgumentException(String.format("The specified resource '%s' was invalid or could not be read", configFile), ex); } } + + private static int getCollectionSize(Collection... collections) { + int total = 0; + for (Collection collection : collections) { + if (collection != null) { + total += collection.size(); + } + } + return total; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index 58a62684..4c4a0877 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -25,22 +25,19 @@ package org.spongepowered.asm.mixin.transformer; import java.io.IOException; -import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; - import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.lib.ClassReader; +import org.spongepowered.asm.lib.MethodVisitor; import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldNode; @@ -49,31 +46,506 @@ import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException; import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.launchwrapper.LaunchClassLoaderUtil; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; +import net.minecraft.launchwrapper.Launch; + /** * Runtime information bundle about a mixin */ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { + /** + * A MethodNode in a mixin + */ + class MixinMethodNode extends MethodNode { + + private final String originalName; + + public MixinMethodNode(int access, String name, String desc, String signature, String[] exceptions) { + super(Opcodes.ASM5, access, name, desc, signature, exceptions); + this.originalName = name; + } + + @Override + public String toString() { + return String.format("%s%s", this.originalName, this.desc); + } + + public String getOriginalName() { + return this.originalName; + } + + } + + /** + * ClassNode for a MixinInfo + */ + class MixinClassNode extends ClassNode { + + public final List mixinMethods; + + public MixinClassNode(MixinInfo mixin) { + this(Opcodes.ASM5); + } + + @SuppressWarnings("unchecked") + public MixinClassNode(int api) { + super(api); + this.mixinMethods = (List)(Object)this.methods; + } + + public MixinInfo getMixin() { + return MixinInfo.this; + } + + @Override + public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { + MethodNode method = new MixinMethodNode(access, name, desc, signature, exceptions); + this.methods.add(method); + return method; + } + + } + + /** + * Mixin preparation/parse/validation state + */ + class State { + + /** + * Mixin bytes (read once, generate tree on demand) + */ + private byte[] mixinBytes; + + /** + * Mixin ClassInfo + */ + private final ClassInfo classInfo; + + /** + * True if the superclass of the mixin is not the direct + * superclass of one or more targets + */ + private boolean detachedSuper; + + /** + * True if this mixin is decorated with {@link Unique} + */ + private boolean unique; + + /** + * All interfaces implemented by this mixin, including soft + * implementations + */ + protected final Set interfaces = new HashSet(); + + /** + * Interfaces soft-implemented using {@link Implements} + */ + protected final List softImplements = new ArrayList(); + + /** + * Synthetic inner classes + */ + protected final Set syntheticInnerClasses = new HashSet(); + + /** + * Initial ClassNode created for mixin validation, not used for actual + * application + */ + protected MixinClassNode classNode; + + State(byte[] mixinBytes) { + this(mixinBytes, null); + } + + State(byte[] mixinBytes, ClassInfo classInfo) { + this.mixinBytes = mixinBytes; + this.connect(); + this.classInfo = classInfo != null ? classInfo : ClassInfo.fromClassNode(this.getClassNode()); + } + + private void connect() { + this.classNode = this.createClassNode(0); + } + + private void complete() { + this.classNode = null; + } + + ClassInfo getClassInfo() { + return this.classInfo; + } + + byte[] getClassBytes() { + return this.mixinBytes; + } + + ClassNode getClassNode() { + return this.classNode; + } + + boolean isDetachedSuper() { + return this.detachedSuper; + } + + boolean isUnique() { + return this.unique; + } + + List getSoftImplements() { + return this.softImplements; + } + + Set getSyntheticInnerClasses() { + return this.syntheticInnerClasses; + } + + Set getInterfaces() { + return this.interfaces; + } + + /** + * Gets a new tree from the bytecode + * + * @param flags Flags passed into classReader + * @return Tree representing the bytecode + */ + MixinClassNode createClassNode(int flags) { + MixinClassNode classNode = new MixinClassNode(MixinInfo.this); + ClassReader classReader = new ClassReader(this.mixinBytes); + classReader.accept(classNode, flags); + return classNode; + } + + /** + * Performs pre-flight checks on the mixin + * + * @param type Mixin Type + * @param targetClasses Mixin's target classes + */ + void validate(SubType type, List targetClasses) { + type.validate(this, targetClasses); + + this.detachedSuper = type.isDetachedSuper(); + this.unique = ASMHelper.getVisibleAnnotation(this.getClassNode(), Unique.class) != null; + + // Pre-flight checks + this.validateInner(); + this.validateClassVersion(); + this.validateRemappables(targetClasses); + + // Read information from the mixin + this.readImplementations(); + this.readInnerClasses(); + + // Takeoff validation + this.validateChanges(type, targetClasses); + + // Null out the validation classnode + this.complete(); + } + + private void validateInner() { + // isInner (shouldn't) return true for static inner classes + if (!this.classInfo.isProbablyStatic()) { + throw new InvalidMixinException(MixinInfo.this, "Inner class mixin must be declared static"); + } + } + + private void validateClassVersion() { + if (this.classNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) { + String helpText = "."; + for (CompatibilityLevel level : CompatibilityLevel.values()) { + if (level.classVersion() >= this.classNode.version) { + helpText = String.format(". Mixin requires compatibility level %s or above.", level.name()); + } + } + + throw new InvalidMixinException(MixinInfo.this, "Unsupported mixin class version " + this.classNode.version + helpText); + } + } + + private void validateRemappables(List targetClasses) { + // Can't have remappable fields or methods on a multi-target mixin, because after obfuscation the fields will remap to conflicting names + if (targetClasses.size() > 1) { + for (FieldNode field : this.classNode.fields) { + this.validateRemappable(Shadow.class, field.name, ASMHelper.getVisibleAnnotation(field, Shadow.class)); + } + + for (MethodNode method : this.classNode.methods) { + this.validateRemappable(Shadow.class, method.name, ASMHelper.getVisibleAnnotation(method, Shadow.class)); + AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(method, Overwrite.class); + if (overwrite != null && ((method.access & Opcodes.ACC_STATIC) == 0 || (method.access & Opcodes.ACC_PUBLIC) == 0)) { + throw new InvalidMixinException(MixinInfo.this, "Found @Overwrite annotation on " + method.name + " in " + this); + } + } + } + } + + private void validateRemappable(Class annotationClass, String name, AnnotationNode annotation) { + if (annotation != null && ASMHelper.getAnnotationValue(annotation, "remap", Boolean.TRUE)) { + throw new InvalidMixinException(MixinInfo.this, "Found a remappable @" + annotationClass.getSimpleName() + " annotation on " + name + + " in " + this); + } + } + + /** + * Read and process any {@link Implements} annotations on the mixin + */ + void readImplementations() { + this.interfaces.addAll(this.classNode.interfaces); + + AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(this.classNode, Implements.class); + if (implementsAnnotation == null) { + return; + } + + List interfaces = ASMHelper.getAnnotationValue(implementsAnnotation); + if (interfaces == null) { + return; + } + + for (AnnotationNode interfaceNode : interfaces) { + InterfaceInfo interfaceInfo = InterfaceInfo.fromAnnotation(MixinInfo.this, interfaceNode); + this.softImplements.add(interfaceInfo); + this.interfaces.add(interfaceInfo.getInternalName()); + // only add interface if its initial initialisation + if (!(this instanceof Reloaded)) { + this.classInfo.addInterface(interfaceInfo.getInternalName()); + } + } + } + + /** + * Read inner class definitions for the class and locate any synthetic + * inner classes so that we can add them to the passthrough set in our + * parent config. + */ + void readInnerClasses() { + for (InnerClassNode inner : this.classNode.innerClasses) { + ClassInfo innerClass = ClassInfo.forName(inner.name); + if (innerClass.isSynthetic() && innerClass.isProbablyStatic()) { + if ((inner.outerName != null && inner.outerName.equals(this.classInfo.getName())) + || inner.name.startsWith(this.classNode.name + "$")) { + this.syntheticInnerClasses.add(inner.name); + } else { + throw new InvalidMixinException(MixinInfo.this, "Unhandled synthetic inner class found: " + inner.name); + } + } + } + } + + protected void validateChanges(SubType type, List targetClasses) { + type.createPreProcessor(this.classNode).prepare(); + } + } + + /** + * State use when hotswap reloading a mixin + */ + class Reloaded extends State { + + /** + * The previous validation state to compare the changes to + */ + private final State previous; + + Reloaded(State previous, byte[] mixinBytes) { + super(mixinBytes, previous.getClassInfo()); + this.previous = previous; + } + + /** + * Validates that the changes are allowed to be made, these restrictions + * only exits while reloading mixins. + */ + @Override + protected void validateChanges(SubType type, List targetClasses) { + if (!this.syntheticInnerClasses.equals(this.previous.syntheticInnerClasses)) { + throw new MixinReloadException(MixinInfo.this, "Cannot change inner classes"); + } + if (!this.interfaces.equals(this.previous.interfaces)) { + throw new MixinReloadException(MixinInfo.this, "Cannot change interfaces"); + } + if (!new HashSet(this.softImplements).equals(new HashSet(this.previous.softImplements))) { + throw new MixinReloadException(MixinInfo.this, "Cannot change soft interfaces"); + } + List targets = MixinInfo.this.readTargetClasses(this.classNode, true); + if (!new HashSet(targets).equals(new HashSet(targetClasses))) { + throw new MixinReloadException(MixinInfo.this, "Cannot change target classes"); + } + int priority = MixinInfo.this.readPriority(this.classNode); + if (priority != MixinInfo.this.getPriority()) { + throw new MixinReloadException(MixinInfo.this, "Cannot change mixin priority"); + } + } + } + + /** + * Mixin sub-type, eg. standard mixin, interface mixin, accessor + */ + abstract static class SubType { + + /** + * Outer + */ + protected final MixinInfo mixin; + + /** + * String representation of annotation type, for use in messages + */ + protected final String annotationType; + + /** + * Target of this mixin subtype must be an interface, false for a class + */ + protected final boolean targetMustBeInterface; + + /** + * Detached super, parsed out during validation + */ + protected boolean detached; + + SubType(MixinInfo info, String annotationType, boolean targetMustBeInterface) { + this.mixin = info; + this.annotationType = annotationType; + this.targetMustBeInterface = targetMustBeInterface; + } + + /** + * Get whether this mixin is detached super, must call {@link #validate} + * first + * + * @return true if super is detached + */ + boolean isDetachedSuper() { + return this.detached; + } + + /** + * Validate a single target before adding + * + * @param targetName + * @param targetInfo + */ + void validateTarget(String targetName, ClassInfo targetInfo) { + boolean targetIsInterface = targetInfo.isInterface(); + if (targetIsInterface != this.targetMustBeInterface) { + String not = targetIsInterface ? "" : "not "; + throw new InvalidMixinException(this.mixin, this.annotationType + " target type mismatch: " + targetName + + " is " + not + "an interface in " + this); + } + } + + abstract void validate(State state, List targetClasses); + + abstract MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode); + + /** + * A standard mixin + */ + static class Standard extends SubType { + + Standard(MixinInfo info) { + super(info, "@Mixin", false); + } + + @Override + void validate(State state, List targetClasses) { + ClassNode classNode = state.getClassNode(); + + for (ClassInfo targetClass : targetClasses) { + if (classNode.superName.equals(targetClass.getSuperName())) { + continue; + } + + if (!targetClass.hasSuperClass(classNode.superName, ClassInfo.Traversal.SUPER)) { + ClassInfo superClass = ClassInfo.forName(classNode.superName); + if (superClass.isMixin()) { + // If superclass is a mixin, check for hierarchy derp + for (ClassInfo superTarget : superClass.getTargets()) { + if (targetClasses.contains(superTarget)) { + throw new InvalidMixinException(this.mixin, "Illegal hierarchy detected. Derived mixin " + this + + " targets the same class " + superTarget.getClassName() + " as its superclass " + + superClass.getClassName()); + } + } + } + + throw new InvalidMixinException(this.mixin, "Super class '" + classNode.superName.replace('/', '.') + "' of " + + this.mixin.getName() + " was not found in the hierarchy of target class '" + targetClass + "'"); + } + + this.detached = true; + } + } + + @Override + MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode) { + return new MixinPreProcessorStandard(this.mixin, classNode); + } + } + + /** + * An interface mixin + */ + static class Interface extends SubType { + + Interface(MixinInfo info) { + super(info, "@Mixin", true); + } + + @Override + void validate(State state, List targetClasses) { + if (!MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces()) { + throw new InvalidMixinException(this.mixin, "Interface mixin not supported in current enviromnment"); + } + + ClassNode classNode = state.getClassNode(); + + if (!"java/lang/Object".equals(classNode.superName)) { + throw new InvalidMixinException(this.mixin, "Super class of " + this + " is invalid, found " + + classNode.superName.replace('/', '.')); + } + } + + @Override + MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode) { + return new MixinPreProcessorInterface(this.mixin, classNode); + } + } + } + + /** + * Class loader utility + */ + private static final LaunchClassLoaderUtil classLoaderUtil = LaunchClassLoaderUtil.forClassLoader(Launch.classLoader); + /** * Global order of mixin infos, used to determine ordering between mixins * with equivalent priority */ static int mixinOrder = 0; - static final Set invalidClasses = MixinInfo.$getInvalidClassesSet(); - /** * Logger */ @@ -94,11 +566,6 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ private final String className; - /** - * Mixin ClassInfo - */ - private final transient ClassInfo classInfo; - /** * Mixin priority, read from the {@link Mixin} annotation on the mixin class */ @@ -118,49 +585,42 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * Intrinsic order (for sorting mixins with identical priority) */ private final transient int order = MixinInfo.mixinOrder++; - - /** - * Mixin bytes (read once, generate tree on demand) - */ - private final transient byte[] mixinBytes; /** * Configuration plugin */ private final transient IMixinConfigPlugin plugin; - - /** - * All interfaces implemented by this mixin, including soft implementations - */ - private final transient Set interfaces = new HashSet(); - /** - * Interfaces soft-implemented using {@link Implements} - */ - private final transient List softImplements = new ArrayList(); - - /** - * Synthetic inner classes - */ - private final transient Set syntheticInnerClasses = new HashSet(); - /** * The environment phase in which this mixin was initialised */ private final transient Phase phase; /** - * Initial ClassNode created for mixin validation, not used for actual - * application + * Cached class info */ - private transient ClassNode validationClassNode; + private final transient ClassInfo info; /** - * True if the superclass of the mixin is not the direct superclass - * of one or more targets + * Mixin type */ - private boolean detachedSuper; + private final transient SubType type; + + /** + * Strict target checks enabled + */ + private final transient boolean strict; + /** + * Holds state that currently is not fully initialised or validated + */ + private transient State pendingState; + + /** + * Holds the current validated state + */ + private transient State state; + /** * Internal ctor, called by {@link MixinConfig} * @@ -169,34 +629,65 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * @param runTransformers * @param plugin * @param suppressPlugin - * @throws ClassNotFoundException */ - MixinInfo(MixinConfig parent, String mixinName, boolean runTransformers, IMixinConfigPlugin plugin, boolean suppressPlugin) - throws ClassNotFoundException { + MixinInfo(MixinConfig parent, String mixinName, boolean runTransformers, IMixinConfigPlugin plugin, boolean suppressPlugin) { this.parent = parent; this.name = mixinName; this.className = parent.getMixinPackage() + mixinName; this.plugin = plugin; - this.phase = MixinEnvironment.getCurrentEnvironment().getPhase(); + this.phase = parent.getEnvironment().getPhase(); + this.strict = parent.getEnvironment().getOption(Option.DEBUG_TARGETS); // Read the class bytes and transform - this.mixinBytes = this.loadMixinClass(this.className, runTransformers); + try { + byte[] mixinBytes = this.loadMixinClass(this.className, runTransformers); + this.pendingState = new State(mixinBytes); + this.info = this.pendingState.getClassInfo(); + this.type = this.initType(); + } catch (InvalidMixinException ex) { + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, ex); + } - ClassNode classNode = this.getClassNode(0); - this.priority = this.readPriority(classNode); - this.targetClasses = this.readTargetClasses(classNode, suppressPlugin); - this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction())); - this.validationClassNode = classNode; - this.classInfo = ClassInfo.fromClassNode(classNode); + // Read the class bytes and transform + try { + this.priority = this.readPriority(this.pendingState.getClassNode()); + this.targetClasses = this.readTargetClasses(this.pendingState.getClassNode(), suppressPlugin); + this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction())); + } catch (InvalidMixinException ex) { + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, ex); + } } + /** + * Initialise the mixin subtype handler + * + * @return subtype + */ + private SubType initType() { + if (this.info.isInterface()) { + return new SubType.Interface(this); + } + return new SubType.Standard(this); + } + + /** + * Run validation pass + */ void validate() { - this.detachedSuper = this.validateTargetClasses(this.validationClassNode); - this.validateMixin(this.validationClassNode); - this.readImplementations(this.validationClassNode); - this.readInnerClasses(this.validationClassNode); - new MixinPreProcessor(this, this.validationClassNode).prepare(); - this.validationClassNode = null; + if (this.pendingState == null) { + throw new IllegalStateException("No pending validation state for " + this); + } + + try { + this.pendingState.validate(this.type, this.targetClasses); + this.state = this.pendingState; + } finally { + this.pendingState = null; + } } /** @@ -204,29 +695,38 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * * @param classNode * @param suppressPlugin - * @return + * @return target class list read from classNode */ - private List readTargetClasses(ClassNode classNode, boolean suppressPlugin) { + protected List readTargetClasses(ClassNode classNode, boolean suppressPlugin) { + if (classNode == null) { + return Collections.emptyList(); + } + AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class); if (mixin == null) { throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className)); } List targets = new ArrayList(); - List publicTargets = ASMHelper.getAnnotationValue(mixin, "value"); + List publicTargets = ASMHelper.getAnnotationValue(mixin, "value"); List privateTargets = ASMHelper.getAnnotationValue(mixin, "targets"); if (publicTargets != null) { - this.readTargets(targets, Lists.transform(publicTargets, new Function() { + this.readTargets(targets, Lists.transform(publicTargets, new Function() { @Override - public String apply(Type input) { + public String apply(org.spongepowered.asm.lib.Type input) { return input.getClassName(); - }; + } }), suppressPlugin, false); } if (privateTargets != null) { - this.readTargets(targets, privateTargets, suppressPlugin, true); + this.readTargets(targets, Lists.transform(privateTargets, new Function() { + @Override + public String apply(String input) { + return MixinInfo.this.getParent().remapClassName(MixinInfo.this.getClassRef(), input); + } + }), suppressPlugin, true); } return targets; @@ -235,22 +735,20 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Reads a target list into the outTargets list */ - private void readTargets(List outTargets, List inTargets, boolean suppressPlugin, boolean checkPublic) { - for (String targetClassName : inTargets) { - targetClassName = targetClassName.replace('/', '.'); - if (this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetClassName, this.className)) { - ClassInfo targetInfo = ClassInfo.forName(targetClassName); - if (targetInfo == null) { - throw new RuntimeException("@Mixin target " + targetClassName + " was not found " + this); + private void readTargets(Collection outTargets, Collection inTargets, boolean suppressPlugin, boolean checkPublic) { + for (String targetRef : inTargets) { + String targetName = targetRef.replace('/', '.'); + if (MixinInfo.classLoaderUtil.isClassLoaded(targetName)) { + String message = String.format("Critical problem: %s target %s was already transformed.", this, targetName); + if (this.parent.isRequired()) { + throw new MixinTargetAlreadyLoadedException(this, message, targetName); } - if (targetInfo.isInterface()) { - throw new InvalidMixinException(this, "@Mixin target " + targetClassName + " is an interface in " + this); - } - if (checkPublic && targetInfo.isPublic()) { - throw new InvalidMixinException(this, "@Mixin target " + targetClassName + " is public in " + this - + " and must be specified in value"); - } - if (!outTargets.contains(targetInfo)) { + this.logger.error(message); + } + + if (this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className)) { + ClassInfo targetInfo = this.getTarget(targetName, checkPublic); + if (targetInfo != null && !outTargets.contains(targetInfo)) { outTargets.add(targetInfo); targetInfo.addMixin(this); } @@ -258,13 +756,38 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { } } + private ClassInfo getTarget(String targetName, boolean checkPublic) throws InvalidMixinException { + ClassInfo targetInfo = ClassInfo.forName(targetName); + if (targetInfo == null) { + this.handleTargetError(String.format("@Mixin target %s was not found %s", targetName, this)); + return null; + } + this.type.validateTarget(targetName, targetInfo); + if (checkPublic && targetInfo.isPublic()) { + this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", targetName, this)); + } + return targetInfo; + } + + private void handleTargetError(String message) { + if (this.strict) { + this.logger.error(message); + throw new InvalidMixinException(this, message); + } + this.logger.warn(message); + } + /** * Read the priority from the {@link Mixin} annotation * * @param classNode - * @return + * @return priority read from classNode */ - private int readPriority(ClassNode classNode) { + protected int readPriority(ClassNode classNode) { + if (classNode == null) { + return this.parent.getDefaultMixinPriority(); + } + AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class); if (mixin == null) { throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className)); @@ -274,103 +797,19 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { return priority == null ? this.parent.getDefaultMixinPriority() : priority.intValue(); } - private boolean validateTargetClasses(ClassNode classNode) { - boolean detached = false; - - for (ClassInfo targetClass : this.targetClasses) { - if (classNode.superName.equals(targetClass.getSuperName())) { - continue; - } - - if (!targetClass.hasSuperClass(classNode.superName, ClassInfo.Traversal.IMMEDIATE)) { - throw new InvalidMixinException(this, "Super class '" + classNode.superName.replace('/', '.') + "' of " + this.name - + " was not found in the hierarchy of target class '" + targetClass + "'"); - } - - detached = true; - } - - return detached; + /** + * Current state, either the validated state or the uninitialised state if + * the mixin is initialising for the first time. Should never return null. + */ + private State getState() { + return this.state != null ? this.state : this.pendingState; } /** - * Performs pre-flight checks on the mixin - * - * @param classNode + * Get the ClassInfo for the mixin class */ - private void validateMixin(ClassNode classNode) { - // isInner (shouldn't) return true for static inner classes - if (!this.classInfo.isProbablyStatic()) { - throw new InvalidMixinException(this, "Inner class mixin must be declared static"); - } - - // Can't have remappable fields or methods on a multi-target mixin, because after obfuscation the fields will remap to conflicting names - if (this.targetClasses.size() > 1) { - for (FieldNode field : classNode.fields) { - this.checkRemappable(Shadow.class, field.name, ASMHelper.getVisibleAnnotation(field, Shadow.class)); - } - - for (MethodNode method : classNode.methods) { - this.checkRemappable(Shadow.class, method.name, ASMHelper.getVisibleAnnotation(method, Shadow.class)); - AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(method, Overwrite.class); - if (overwrite != null && ((method.access & Opcodes.ACC_STATIC) == 0 || (method.access & Opcodes.ACC_PUBLIC) == 0)) { - throw new InvalidMixinException(this, "Found @Overwrite annotation on " + method.name + " in " + this); - } - } - } - } - - private void checkRemappable(Class annotationClass, String name, AnnotationNode annotation) { - if (annotation != null && ASMHelper.getAnnotationValue(annotation, "remap", Boolean.TRUE)) { - throw new InvalidMixinException(this, "Found a remappable @" + annotationClass.getSimpleName() + " annotation on " + name - + " in " + this); - } - } - - /** - * Read and process any {@link Implements} annotations on the mixin - */ - private void readImplementations(ClassNode classNode) { - this.interfaces.addAll(classNode.interfaces); - - AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(classNode, Implements.class); - if (implementsAnnotation == null) { - return; - } - - List interfaces = ASMHelper.getAnnotationValue(implementsAnnotation); - if (interfaces == null) { - return; - } - - for (AnnotationNode interfaceNode : interfaces) { - InterfaceInfo interfaceInfo = InterfaceInfo.fromAnnotation(this, interfaceNode); - this.softImplements.add(interfaceInfo); - this.interfaces.add(interfaceInfo.getInternalName()); - this.classInfo.addInterface(interfaceInfo.getInternalName()); - } - } - - /** - * Read inner class definitions for the class and locate any synthetic inner - * classes so that we can add them to the passthrough set in our parent - * config. - */ - private void readInnerClasses(ClassNode classNode) { - for (InnerClassNode inner : classNode.innerClasses) { - ClassInfo innerClass = ClassInfo.forName(inner.name); - if (innerClass.isSynthetic() && innerClass.isProbablyStatic()) { - if ((inner.outerName != null && inner.outerName.equals(this.classInfo.getName())) || inner.name.startsWith(classNode.name + "$")) { - this.syntheticInnerClasses.add(inner.name); - } else { - throw new InvalidMixinException(this, "Unhandled synthetic inner class found: " + inner.name); - } - } - } - } - ClassInfo getClassInfo() { - return this.classInfo; + return this.info; } /** @@ -384,10 +823,18 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Get the parent config which declares this mixin */ - public MixinConfig getParent() { + MixinConfig getParent() { return this.parent; } + /** + * Get the mixin priority + */ + @Override + public int getPriority() { + return this.priority; + } + /** * Get the simple name of the mixin */ @@ -409,7 +856,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public String getClassRef() { - return this.classInfo.getName(); + return this.getClassInfo().getName(); } /** @@ -417,7 +864,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public byte[] getClassBytes() { - return this.mixinBytes; + return this.getState().getClassBytes(); } /** @@ -426,7 +873,14 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public boolean isDetachedSuper() { - return this.detachedSuper; + return this.getState().isDetachedSuper(); + } + + /** + * True if this mixin is decorated with {@link Unique} + */ + public boolean isUnique() { + return this.getState().isUnique(); } /** @@ -448,11 +902,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * Get a new tree for the class bytecode */ @Override - public ClassNode getClassNode(int flags) { - MixinClassNode classNode = new MixinClassNode(this); - ClassReader classReader = new ClassReader(this.mixinBytes); - classReader.accept(classNode, flags); - return classNode; + public MixinClassNode getClassNode(int flags) { + return this.getState().createClassNode(flags); } /** @@ -467,48 +918,41 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * Get the soft implementations for this mixin */ List getSoftImplements() { - return Collections.unmodifiableList(this.softImplements); + return Collections.unmodifiableList(this.getState().getSoftImplements()); } /** * Get the synthetic inner classes for this mixin */ - public Set getSyntheticInnerClasses() { - return Collections.unmodifiableSet(this.syntheticInnerClasses); + Set getSyntheticInnerClasses() { + return Collections.unmodifiableSet(this.getState().getSyntheticInnerClasses()); } /** * Get the target class list for this mixin */ - public List getTargets() { + List getTargets() { return Collections.unmodifiableList(this.targetClasses); } - - /** - * Get the mixin priority - */ - @Override - public int getPriority() { - return this.priority; - } /** * Get all interfaces for this mixin * * @return mixin interfaces */ - public Set getInterfaces() { - return this.interfaces; + Set getInterfaces() { + return this.getState().getInterfaces(); } /** * Get a new mixin target context object for the specified target * * @param target - * @return + * @return new context */ - public MixinTargetContext createContextFor(ClassNode target) { - return new MixinPreProcessor(this, this.getClassNode(ClassReader.EXPAND_FRAMES)).createContextFor(target); + MixinTargetContext createContextFor(TargetClassContext target) { + MixinClassNode classNode = this.getClassNode(ClassReader.EXPAND_FRAMES); + return this.type.createPreProcessor(classNode).prepare().createContextFor(target); } /** @@ -532,13 +976,24 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { // Inject the mixin class name into the LaunchClassLoader's invalid // classes set so that any classes referencing the mixin directly will // cause the game to crash - if (MixinInfo.invalidClasses != null) { - MixinInfo.invalidClasses.add(mixinClassName); - } + MixinInfo.classLoaderUtil.registerInvalidClass(mixinClassName); return mixinBytes; } + /** + * Updates this mixin with new bytecode + * + * @param mixinBytes New bytecode + */ + void reloadMixin(byte[] mixinBytes) { + if (this.pendingState != null) { + throw new IllegalStateException("Cannot reload mixin while it is initialising"); + } + this.pendingState = new Reloaded(this.state, mixinBytes); + this.validate(); + } + /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @@ -580,16 +1035,5 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { public String toString() { return String.format("%s:%s", this.parent.getName(), this.name); } - - @SuppressWarnings("unchecked") - private static Set $getInvalidClassesSet() { - try { - Field invalidClasses = LaunchClassLoader.class.getDeclaredField("invalidClasses"); - invalidClasses.setAccessible(true); - return (Set)invalidClasses.get(Launch.classLoader); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java deleted file mode 100644 index 769da82d..00000000 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * This file is part of Mixin, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * Copyright (c) contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package org.spongepowered.asm.mixin.transformer; - -import java.lang.annotation.Annotation; -import java.util.Deque; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; -import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; -import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; -import org.spongepowered.asm.util.ASMHelper; -import org.spongepowered.asm.util.Constants; - - -/** - *

Mixin bytecode pre-processor. This class is responsible for bytecode pre- - * processing tasks required to be performed on mixin bytecode before the mixin - * can be applied. In previous versions the duties performed by this class were - * performed by {@link MixinInfo}.

- * - *

Before a mixin can be applied to the target class, it is necessary to - * convert certain aspects of the mixin bytecode into the intended final form of - * the mixin, this involves for example stripping the prefix from shadow and - * soft-implemented methods. This preparation is done in two stages: first the - * target-context-insensitive transformations are applied (this also acts as a - * validation pass when the mixin is first loaded) and then transformations - * which depend on the target class are applied in a second stage.

- * - *

The validation pass propagates method renames into the metadata tree and - * thus changes made during this phase are visible to all other mixins. The - * target-context-sensitive pass on the other hand can only operate on private - * class members for obvious reasons.

- */ -class MixinPreProcessor { - - /** - * The mixin - */ - private final MixinInfo mixin; - - /** - * Mixin class node - */ - private final ClassNode classNode; - - private boolean prepared, attached; - - MixinPreProcessor(MixinInfo mixin, ClassNode classNode) { - this.mixin = mixin; - this.classNode = classNode; - } - - /** - * Run the first pass. Propagates changes into the metadata tree. - * - * @return Prepared classnode - */ - ClassNode prepare() { - if (!this.prepared) { - this.prepared = true; - - for (MethodNode mixinMethod : this.classNode.methods) { - Method method = this.mixin.getClassInfo().findMethod(mixinMethod); - this.prepareShadow(mixinMethod, method); - this.prepareSoftImplements(mixinMethod, method); - } - } - - return this.classNode; - } - - private void prepareShadow(MethodNode mixinMethod, Method method) { - AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class); - if (shadowAnnotation == null) { - return; - } - - String prefix = ASMHelper.getAnnotationValue(shadowAnnotation, "prefix", Shadow.class); - if (mixinMethod.name.startsWith(prefix)) { - ASMHelper.setVisibleAnnotation(mixinMethod, MixinRenamed.class, "originalName", mixinMethod.name); - String newName = mixinMethod.name.substring(prefix.length()); - method.renameTo(newName); - mixinMethod.name = newName; - } - } - - private void prepareSoftImplements(MethodNode mixinMethod, Method method) { - for (InterfaceInfo iface : this.mixin.getSoftImplements()) { - if (iface.renameMethod(mixinMethod)) { - method.renameTo(mixinMethod.name); - } - } - } - - MixinTargetContext createContextFor(ClassNode target) { - this.prepare(); - MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target); - this.attach(context); - return context; - } - - /** - * Run the second pass, attach to the specified context - * - * @param context - */ - void attach(MixinTargetContext context) { - if (this.attached) { - throw new IllegalStateException("Preprocessor was already attached"); - } - - this.attached = true; - - // Perform context-sensitive attachment phase - this.attachMethods(context); - this.attachFields(context); - - // Apply transformations to the mixin bytecode - this.transform(context); - } - - private void attachMethods(MixinTargetContext context) { - for (Iterator iter = this.classNode.methods.iterator(); iter.hasNext();) { - MethodNode mixinMethod = iter.next(); - - if (this.processMethod(context, mixinMethod, Shadow.class, true, true)) { - iter.remove(); - context.addShadowMethod(mixinMethod); - continue; - } - - this.processMethod(context, mixinMethod, Overwrite.class, false, false); - } - } - - private boolean processMethod(MixinTargetContext context, MethodNode mixinMethod, Class annotationType, - boolean mustExist, boolean mustBePrivate) { - AnnotationNode annotation = ASMHelper.getVisibleAnnotation(mixinMethod, annotationType); - if (annotation == null) { - return false; - } - - Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_PRIVATE); - MethodNode target = MixinPreProcessor.findMethod(context.getTargetClass(), mixinMethod, annotation); - - if (target == null) { - if (!mustExist) { - return false; - } - - throw new InvalidMixinException(this.mixin, annotationType.getSimpleName() + " method " + mixinMethod.name - + " was not located in the target class"); - } - - if (Constants.INIT.equals(target.name)) { - throw new InvalidMixinException(this.mixin, "Nice try! Cannot alias a constructor!"); - } - - if (!target.name.equals(mixinMethod.name)) { - if (mustBePrivate && (target.access & Opcodes.ACC_PRIVATE) == 0) { - throw new InvalidMixinException(this.mixin, "Non-private method cannot be aliased. Found " + target.name); - } - - mixinMethod.name = target.name; - method.renameTo(target.name); - } - - return true; - } - - private void attachFields(MixinTargetContext context) { - for (Iterator iter = this.classNode.fields.iterator(); iter.hasNext();) { - FieldNode mixinField = iter.next(); - AnnotationNode shadow = ASMHelper.getVisibleAnnotation(mixinField, Shadow.class); - if (!this.validateField(context, mixinField, shadow)) { - iter.remove(); - continue; - } - - context.transformDescriptor(mixinField); - - Field field = this.mixin.getClassInfo().findField(mixinField); - FieldNode target = this.findField(context.getTargetClass(), mixinField, shadow); - if (target == null) { - // If this field is a shadow field but is NOT found in the target class, that's bad, mmkay - if (shadow != null) { - throw new InvalidMixinException(this.mixin, "Shadow field " + mixinField.name + " was not located in the target class"); - } - } else { - // Check that the shadow field has a matching descriptor - if (!target.desc.equals(mixinField.desc)) { - throw new InvalidMixinException(this.mixin, "The field " + mixinField.name + " in the target class has a conflicting signature"); - } - - if (!target.name.equals(mixinField.name)) { - if ((target.access & Opcodes.ACC_PRIVATE) == 0 && (target.access & Opcodes.ACC_SYNTHETIC) == 0) { - throw new InvalidMixinException(this.mixin, "Non-private field cannot be aliased. Found " + target.name); - } - - mixinField.name = target.name; - field.renameTo(target.name); - } - - // Shadow fields get stripped from the mixin class - iter.remove(); - - if (shadow != null) { - context.addShadowField(mixinField); - } - } - } - } - - private boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { - // Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition - if (MixinApplicator.hasFlag(field, Opcodes.ACC_STATIC) - && !MixinApplicator.hasFlag(field, Opcodes.ACC_PRIVATE) - && !MixinApplicator.hasFlag(field, Opcodes.ACC_SYNTHETIC)) { - throw new InvalidMixinException(context, String.format("Mixin classes cannot contain visible static methods or fields, found %s", - field.name)); - } - - // Shadow fields can't have prefixes, it's meaningless for them anyway - String prefix = ASMHelper.getAnnotationValue(shadow, "prefix", Shadow.class); - if (field.name.startsWith(prefix)) { - throw new InvalidMixinException(context, String.format("Shadow field %s in %s has a shadow prefix. This is not allowed.", - field.name, context)); - } - - // Imaginary super fields get stripped from the class, but first we validate them - if (Constants.IMAGINARY_SUPER.equals(field.name)) { - if (field.access != Opcodes.ACC_PRIVATE) { - throw new InvalidMixinException(this.mixin, "Imaginary super field " + field.name + " must be private and non-final"); - } - if (!field.desc.equals("L" + this.mixin.getClassRef() + ";")) { - throw new InvalidMixinException(this.mixin, "Imaginary super field " + field.name + " must have the same type as the parent mixin"); - } - return false; - } - - return true; - } - - /** - * Apply discovered method and field renames to method invocations and field - * accesses in the mixin - */ - private void transform(MixinTargetContext context) { - for (MethodNode mixinMethod : this.classNode.methods) { - for (Iterator iter = mixinMethod.instructions.iterator(); iter.hasNext();) { - AbstractInsnNode insn = iter.next(); - if (insn instanceof MethodInsnNode) { - MethodInsnNode methodNode = (MethodInsnNode)insn; - Method method = this.mixin.getClassInfo().findMethodInHierarchy(methodNode, true, ClassInfo.INCLUDE_PRIVATE); - if (method != null && method.isRenamed()) { - methodNode.name = method.getName(); - } - } else if (insn instanceof FieldInsnNode) { - FieldInsnNode fieldNode = (FieldInsnNode)insn; - Field field = this.mixin.getClassInfo().findField(fieldNode, ClassInfo.INCLUDE_PRIVATE); - if (field != null && field.isRenamed()) { - fieldNode.name = field.getName(); - } - } - } - } - } - - private static MethodNode findMethod(ClassNode classNode, MethodNode method, AnnotationNode annotation) { - Deque aliases = new LinkedList(); - aliases.add(method.name); - if (annotation != null) { - List aka = ASMHelper.>getAnnotationValue(annotation, "aliases"); - if (aka != null) { - aliases.addAll(aka); - } - } - - return MixinPreProcessor.findMethod(classNode, aliases, method.desc); - } - - private static MethodNode findMethod(ClassNode classNode, Deque aliases, String desc) { - String alias = aliases.poll(); - if (alias == null) { - return null; - } - - for (MethodNode target : classNode.methods) { - if (target.name.equals(alias) && target.desc.equals(desc)) { - return target; - } - } - - return MixinPreProcessor.findMethod(classNode, aliases, desc); - } - - private FieldNode findField(ClassNode classNode, FieldNode field, AnnotationNode shadow) { - Deque aliases = new LinkedList(); - aliases.add(field.name); - if (shadow != null) { - List aka = ASMHelper.>getAnnotationValue(shadow, "aliases"); - if (aka != null) { - aliases.addAll(aka); - } - } - - return this.findField(classNode, aliases, field.desc); - } - - /** - * Finds a field in the target class - * - * @param aliases - * @param desc - * @return Target field or null if not found - */ - private FieldNode findField(ClassNode classNode, Deque aliases, String desc) { - String alias = aliases.poll(); - if (alias == null) { - return null; - } - - for (FieldNode target : classNode.fields) { - if (target.name.equals(alias) && target.desc.equals(desc)) { - return target; - } - } - - return this.findField(classNode, aliases, desc); - } -} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java new file mode 100644 index 00000000..d9fbf4e2 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java @@ -0,0 +1,85 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.FieldNode; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; +import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; +import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Bytecode preprocessor for interface mixins, simply performs some additional + * verification for things which are unsupported in interfaces + */ +class MixinPreProcessorInterface extends MixinPreProcessorStandard { + + /** + * Ctor + * + * @param mixin Mixin info + * @param classNode Mixin classnode + */ + MixinPreProcessorInterface(MixinInfo mixin, MixinClassNode classNode) { + super(mixin, classNode); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinPreProcessor + * #prepareMethod(org.spongepowered.asm.lib.tree.MethodNode, + * org.spongepowered.asm.mixin.transformer.ClassInfo.Method) + */ + @Override + protected void prepareMethod(MixinMethodNode mixinMethod, Method method) { + // I have no idea how the hell you'd compile this, but we make sure anyway! + if (!ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_PUBLIC)) { + throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains a non-public method! Found " + method + " in " + + this.mixin); + } + + super.prepareMethod(mixinMethod, method); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.MixinPreProcessor + * #validateField( + * org.spongepowered.asm.mixin.transformer.MixinTargetContext, + * org.spongepowered.asm.lib.tree.FieldNode, + * org.spongepowered.asm.lib.tree.AnnotationNode) + */ + @Override + protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { + if (!ASMHelper.hasFlag(field, Opcodes.ACC_STATIC)) { + throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains an instance field! Found " + field.name + " in " + + this.mixin); + } + + return super.validateField(context, field, shadow); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java new file mode 100644 index 00000000..2bcffcbf --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -0,0 +1,481 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.lang.annotation.Annotation; +import java.util.Iterator; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.FieldInsnNode; +import org.spongepowered.asm.lib.tree.FieldNode; +import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.Surrogate; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; +import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; +import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; +import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.Constants; + +/** + *

Mixin bytecode pre-processor. This class is responsible for bytecode pre- + * processing tasks required to be performed on mixin bytecode before the mixin + * can be applied. In previous versions the duties performed by this class were + * performed by {@link MixinInfo}.

+ * + *

Before a mixin can be applied to the target class, it is necessary to + * convert certain aspects of the mixin bytecode into the intended final form of + * the mixin, this involves for example stripping the prefix from shadow and + * soft-implemented methods. This preparation is done in two stages: first the + * target-context-insensitive transformations are applied (this also acts as a + * validation pass when the mixin is first loaded) and then transformations + * which depend on the target class are applied in a second stage.

+ * + *

The validation pass propagates method renames into the metadata tree and + * thus changes made during this phase are visible to all other mixins. The + * target-context-sensitive pass on the other hand can only operate on private + * class members for obvious reasons.

+ */ +class MixinPreProcessorStandard { + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * The mixin + */ + protected final MixinInfo mixin; + + /** + * Mixin class node + */ + protected final MixinClassNode classNode; + + private final boolean verboseLogging, strictUnique; + + private boolean prepared, attached; + + MixinPreProcessorStandard(MixinInfo mixin, MixinClassNode classNode) { + this.mixin = mixin; + this.classNode = classNode; + MixinEnvironment env = mixin.getParent().getEnvironment(); + this.verboseLogging = env.getOption(Option.DEBUG_VERBOSE); + this.strictUnique = env.getOption(Option.DEBUG_UNIQUE); + } + + /** + * Run the first pass. Propagates changes into the metadata tree. + * + * @return Prepared classnode + */ + MixinPreProcessorStandard prepare() { + if (!this.prepared) { + this.prepared = true; + + for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { + Method method = this.mixin.getClassInfo().findMethod(mixinMethod); + this.prepareMethod(mixinMethod, method); + } + + for (FieldNode mixinField : this.classNode.fields) { + this.prepareField(mixinField); + } + } + + return this; + } + + protected void prepareMethod(MixinMethodNode mixinMethod, Method method) { + this.prepareShadow(mixinMethod, method); + this.prepareSoftImplements(mixinMethod, method); + } + + protected void prepareShadow(MixinMethodNode mixinMethod, Method method) { + AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class); + if (shadowAnnotation == null) { + return; + } + + String prefix = ASMHelper.getAnnotationValue(shadowAnnotation, "prefix", Shadow.class); + if (mixinMethod.name.startsWith(prefix)) { + ASMHelper.setVisibleAnnotation(mixinMethod, MixinRenamed.class, "originalName", mixinMethod.name); + String newName = mixinMethod.name.substring(prefix.length()); + method.renameTo(newName); + mixinMethod.name = newName; + } + } + + protected void prepareSoftImplements(MixinMethodNode mixinMethod, Method method) { + for (InterfaceInfo iface : this.mixin.getSoftImplements()) { + if (iface.renameMethod(mixinMethod)) { + method.renameTo(mixinMethod.name); + } + } + } + + protected void prepareField(FieldNode mixinField) { + // stub + } + + MixinTargetContext createContextFor(TargetClassContext target) { + MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target); + this.attach(context); + return context; + } + + /** + * Run the second pass, attach to the specified context + * + * @param context + */ + void attach(MixinTargetContext context) { + if (this.attached) { + throw new IllegalStateException("Preprocessor was already attached"); + } + + this.attached = true; + + // Perform context-sensitive attachment phase + this.attachMethods(context); + this.attachFields(context); + + // Apply transformations to the mixin bytecode + this.transform(context); + } + + protected void attachMethods(MixinTargetContext context) { + for (Iterator iter = this.classNode.mixinMethods.iterator(); iter.hasNext();) { + MixinMethodNode mixinMethod = iter.next(); + + if (!this.validateMethod(context, mixinMethod)) { + iter.remove(); + continue; + } + + if (this.processInjectorMethod(context, mixinMethod)) { + continue; + } + + if (this.processShadowMethod(context, mixinMethod)) { + iter.remove(); + context.addShadowMethod(mixinMethod); + continue; + } + + if (this.processOverwriteMethod(context, mixinMethod)) { + continue; + } + + if (this.processUniqueMethod(context, mixinMethod)) { + iter.remove(); + continue; + } + + this.processMethod(mixinMethod); + } + } + + protected boolean validateMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + return true; + } + + protected boolean processInjectorMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + AnnotationNode annotation = InjectionInfo.getInjectorAnnotation(context, mixinMethod); + boolean surrogate = ASMHelper.getVisibleAnnotation(mixinMethod, Surrogate.class) != null; + if (annotation == null && !surrogate) { + return false; + } + + String handlerName = context.getHandlerName(annotation, mixinMethod, surrogate); + Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); + + if (method.isUnique()) { + MixinPreProcessorStandard.logger.warn("Redundant @Unique on injector method {} in {}. Injectors are implicitly unique", method, context); + } + + method.renameTo(handlerName); + mixinMethod.name = handlerName; + + return true; + } + + protected boolean processShadowMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + return this.processSpecialMethod(context, mixinMethod, Shadow.class, false); + } + + protected boolean processOverwriteMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + return this.processSpecialMethod(context, mixinMethod, Overwrite.class, true); + } + + protected boolean processSpecialMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class type, + boolean overwrite) { + + AnnotationNode annotation = ASMHelper.getVisibleAnnotation(mixinMethod, type); + if (annotation == null) { + return false; + } + + if (this.mixin.isUnique() && overwrite) { + throw new InvalidMixinException(this.mixin, "@Overwrite method " + mixinMethod.name + " found in a @Unique mixin"); + } + + Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); + MethodNode target = context.findMethod(mixinMethod, annotation); + + if (method.isUnique()) { + throw new InvalidMixinException(this.mixin, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be @Unique"); + } + + if (target == null) { + if (overwrite) { + return false; + } + target = context.findRemappedMethod(mixinMethod); + if (target == null) { + throw new InvalidMixinException(this.mixin, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + + " was not located in the target class"); + } + mixinMethod.name = target.name; + method.renameTo(target.name); + } + + if (Constants.CTOR.equals(target.name)) { + throw new InvalidMixinException(this.mixin, "Nice try! Cannot alias a constructor!"); + } + + if (!target.name.equals(mixinMethod.name)) { + if (!overwrite && (target.access & Opcodes.ACC_PRIVATE) == 0) { + throw new InvalidMixinException(this.mixin, "Non-private method cannot be aliased. Found " + target.name); + } + + mixinMethod.name = target.name; + method.renameTo(target.name); + } + + return true; + } + + protected boolean processUniqueMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { + Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); + if (method == null || (!method.isUnique() && !this.mixin.isUnique())) { + return false; + } + + MethodNode target = context.findMethod(mixinMethod, null); + if (target == null) { + return false; + } + + if ((mixinMethod.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) != 0) { + String uniqueName = context.getUniqueName(mixinMethod); + MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique method {}{} to {} in {}", + mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); + mixinMethod.name = uniqueName; + method.renameTo(uniqueName); + return false; + } + + if (this.strictUnique) { + throw new InvalidMixinException(this.mixin, "Method conflict, @Unique method " + mixinMethod.name + " in " + this.mixin + + " cannot overwrite " + target.name + target.desc + " in " + context.getTarget()); + } + + MixinPreProcessorStandard.logger.warn("Discarding @Unique public method {} in {} because it already exists in {}", mixinMethod.name, + this.mixin, context.getTarget()); + + return true; + } + + protected void processMethod(MixinMethodNode mixinMethod) { + Method method = this.mixin.getClassInfo().findMethod(mixinMethod); + if (method == null) { + return; + } + + Method parentMethod = this.mixin.getClassInfo().findMethodInHierarchy(mixinMethod, false); + if (parentMethod != null && parentMethod.isRenamed()) { + mixinMethod.name = parentMethod.getName(); + method.renameTo(parentMethod.getName()); + } + } + + protected void attachFields(MixinTargetContext context) { + for (Iterator iter = this.classNode.fields.iterator(); iter.hasNext();) { + FieldNode mixinField = iter.next(); + AnnotationNode shadow = ASMHelper.getVisibleAnnotation(mixinField, Shadow.class); + boolean isShadow = shadow != null; + + if (!this.validateField(context, mixinField, shadow)) { + iter.remove(); + continue; + } + + context.transformDescriptor(mixinField); + + Field field = this.mixin.getClassInfo().findField(mixinField); + if (field.isUnique() && isShadow) { + throw new InvalidMixinException(this.mixin, "@Shadow field " + mixinField.name + " cannot be @Unique"); + } + + FieldNode target = context.findField(mixinField, shadow); + if (target == null) { + if (shadow == null) { + continue; + } + target = context.findRemappedField(mixinField); + if (target == null) { + // If this field is a shadow field but is NOT found in the target class, that's bad, mmkay + throw new InvalidMixinException(this.mixin, "Shadow field " + mixinField.name + " was not located in the target class"); + } + mixinField.name = target.name; + field.renameTo(target.name); + } + + if (field.isUnique()) { + if ((mixinField.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) != 0) { + String uniqueName = context.getUniqueName(mixinField); + MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique field {}{} to {} in {}", + mixinField.name, mixinField.desc, uniqueName, this.mixin); + mixinField.name = uniqueName; + field.renameTo(uniqueName); + continue; + } + + if (this.strictUnique) { + throw new InvalidMixinException(this.mixin, "Field conflict, @Unique field " + mixinField.name + " in " + this.mixin + + " cannot overwrite " + target.name + target.desc + " in " + context.getTarget()); + } + + MixinPreProcessorStandard.logger.warn("Discarding @Unique public field {} in {} because it already exists in {}. " + + "Note that declared FIELD INITIALISERS will NOT be removed!", mixinField.name, this.mixin, context.getTarget()); + + iter.remove(); + continue; + } + + // Check that the shadow field has a matching descriptor + if (!target.desc.equals(mixinField.desc)) { + throw new InvalidMixinException(this.mixin, "The field " + mixinField.name + " in the target class has a conflicting signature"); + } + + if (!target.name.equals(mixinField.name)) { + if ((target.access & Opcodes.ACC_PRIVATE) == 0 && (target.access & Opcodes.ACC_SYNTHETIC) == 0) { + throw new InvalidMixinException(this.mixin, "Non-private field cannot be aliased. Found " + target.name); + } + + mixinField.name = target.name; + field.renameTo(target.name); + } + + // Shadow fields get stripped from the mixin class + iter.remove(); + + if (isShadow) { + boolean isFinal = field.isDecoratedFinal(); + if (this.verboseLogging && ASMHelper.hasFlag(target, Opcodes.ACC_FINAL) != isFinal) { + String message = isFinal + ? "@Shadow field {}::{} is decorated with @Final but target is not final" + : "@Shadow target {}::{} is final but shadow is not decorated with @Final"; + MixinPreProcessorStandard.logger.warn(message, this.mixin, mixinField.name); + } + + context.addShadowField(mixinField, field); + } + } + } + + protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { + // Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition + if (ASMHelper.hasFlag(field, Opcodes.ACC_STATIC) + && !ASMHelper.hasFlag(field, Opcodes.ACC_PRIVATE) + && !ASMHelper.hasFlag(field, Opcodes.ACC_SYNTHETIC) + && shadow == null) { + throw new InvalidMixinException(context, String.format("Mixin %s contains non-private static field %s:%s", + context, field.name, field.desc)); + } + + // Shadow fields can't have prefixes, it's meaningless for them anyway + String prefix = ASMHelper.getAnnotationValue(shadow, "prefix", Shadow.class); + if (field.name.startsWith(prefix)) { + throw new InvalidMixinException(context, String.format("@Shadow field %s.%s has a shadow prefix. This is not allowed.", + context, field.name)); + } + + // Imaginary super fields get stripped from the class, but first we validate them + if (Constants.IMAGINARY_SUPER.equals(field.name)) { + if (field.access != Opcodes.ACC_PRIVATE) { + throw new InvalidMixinException(this.mixin, "Imaginary super field " + context + "." + field.name + + " must be private and non-final"); + } + if (!field.desc.equals("L" + this.mixin.getClassRef() + ";")) { + throw new InvalidMixinException(this.mixin, "Imaginary super field " + context + "." + field.name + + " must have the same type as the parent mixin"); + } + return false; + } + + return true; + } + + /** + * Apply discovered method and field renames to method invocations and field + * accesses in the mixin + */ + protected void transform(MixinTargetContext context) { + for (MethodNode mixinMethod : this.classNode.methods) { + for (Iterator iter = mixinMethod.instructions.iterator(); iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + if (insn instanceof MethodInsnNode) { + MethodInsnNode methodNode = (MethodInsnNode)insn; + Method method = ClassInfo.forName(methodNode.owner).findMethodInHierarchy(methodNode, true, ClassInfo.INCLUDE_PRIVATE); + if (method != null && method.isRenamed()) { + methodNode.name = method.getName(); + } + } else if (insn instanceof FieldInsnNode) { + FieldInsnNode fieldNode = (FieldInsnNode)insn; + Field field = ClassInfo.forName(fieldNode.owner).findField(fieldNode, ClassInfo.INCLUDE_PRIVATE); + if (field != null && field.isRenamed()) { + fieldNode.name = field.getName(); + } + } + } + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index a5316fa5..ff89ce28 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -25,32 +25,45 @@ package org.spongepowered.asm.mixin.transformer; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Collection; +import java.util.Deque; import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.lib.Handle; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.LdcInsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.TypeInsnNode; +import org.spongepowered.asm.lib.tree.*; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.SoftOverride; -import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.InjectorGroupInfo; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; -import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal; +import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; +import org.spongepowered.asm.obfuscation.RemapperChain; import org.spongepowered.asm.util.ASMHelper; import org.spongepowered.asm.util.Constants; - /** * This object keeps track of data for applying a mixin to a specific target * class during a mixin application. This is a single-use object which @@ -60,6 +73,11 @@ import org.spongepowered.asm.util.Constants; * in the mixin to the appropriate members in the target class hierarchy. */ public class MixinTargetContext implements IReferenceMapperContext { + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); /** * Mixin info @@ -74,7 +92,12 @@ public class MixinTargetContext implements IReferenceMapperContext { /** * */ - private final ClassNode targetClass; + private final TargetClassContext targetClass; + + /** + * Session ID from context + */ + private final String sessionId; /** * Target ClassInfo @@ -89,13 +112,22 @@ public class MixinTargetContext implements IReferenceMapperContext { /** * Shadow field list */ - private final List shadowFields = new ArrayList(); + private final Map shadowFields = new LinkedHashMap(); /** - * Information about methods in the target class, used to keep track of - * transformations we apply + * List of methods successfully merged from this mixin */ - private final Map targetMethods = new HashMap(); + private final List mergedMethods = new ArrayList(); + + /** + * Injector groups + */ + private final InjectorGroupInfo.Map injectorGroups = new InjectorGroupInfo.Map(); + + /** + * Injectors for this target + */ + private final List injectors = new ArrayList(); /** * True if this mixin inherits from a mixin at any point in its hierarchy @@ -106,21 +138,30 @@ public class MixinTargetContext implements IReferenceMapperContext { * True if this mixin's superclass is detached from the target superclass */ private final boolean detachedSuper; + + /** + * Minimum class version required to apply this mixin, target class will be + * upgraded if the version is below this value + */ + private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion(); + /** * ctor * * @param mixin Mixin information * @param classNode Mixin classnode - * @param target target class + * @param context target class */ - MixinTargetContext(MixinInfo mixin, ClassNode classNode, ClassNode target) { + MixinTargetContext(MixinInfo mixin, ClassNode classNode, TargetClassContext context) { this.mixin = mixin; this.classNode = classNode; - this.targetClass = target; - this.targetClassInfo = ClassInfo.forName(target.name); + this.targetClass = context; + this.targetClassInfo = ClassInfo.forName(this.targetClass.getName()); this.inheritsFromMixin = mixin.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy(); - this.detachedSuper = !this.classNode.superName.equals(this.targetClass.superName); + this.detachedSuper = !this.classNode.superName.equals(this.targetClass.getClassNode().superName); + this.sessionId = context.getSessionId(); + this.requireVersion(classNode.version); } /** @@ -131,10 +172,25 @@ public class MixinTargetContext implements IReferenceMapperContext { } /** - * @param field + * @param fieldNode */ - void addShadowField(FieldNode field) { - this.shadowFields.add(field); + void addShadowField(FieldNode fieldNode, Field fieldInfo) { + this.shadowFields.put(fieldNode, fieldInfo); + } + + /** + * Callback from the applicator which notifies us that a method was merged + * + * @param method + */ + void addMergedMethod(MethodNode method) { + this.mergedMethods.add(method); + this.targetClassInfo.addMethod(method); + + ASMHelper.setVisibleAnnotation(method, MixinMerged.class, + "mixin", this.getClassName(), + "priority", this.getPriority(), + "sessionId", this.sessionId); } /* (non-Javadoc) @@ -144,6 +200,15 @@ public class MixinTargetContext implements IReferenceMapperContext { public String toString() { return this.mixin.toString(); } + + /** + * Get the environment of the owning mixin config + * + * @return mixin parent environment + */ + public MixinEnvironment getEnvironment() { + return this.mixin.getParent().getEnvironment(); + } /** * Get the mixin tree @@ -171,6 +236,15 @@ public class MixinTargetContext implements IReferenceMapperContext { public String getClassRef() { return this.mixin.getClassRef(); } + + /** + * Get the target class context + * + * @return the target class context + */ + public TargetClassContext getTarget() { + return this.targetClass; + } /** * Get the target class reference @@ -179,7 +253,7 @@ public class MixinTargetContext implements IReferenceMapperContext { * mixins) */ public String getTargetClassRef() { - return this.targetClass.name; + return this.targetClass.getName(); } /** @@ -187,8 +261,8 @@ public class MixinTargetContext implements IReferenceMapperContext { * * @return the target class */ - public ClassNode getTargetClass() { - return this.targetClass; + public ClassNode getTargetClassNode() { + return this.targetClass.getClassNode(); } /** @@ -199,6 +273,41 @@ public class MixinTargetContext implements IReferenceMapperContext { public ClassInfo getTargetClassInfo() { return this.targetClassInfo; } + + /** + * Get the minimum required class version for this mixin + */ + public int getMinRequiredClassVersion() { + return this.minRequiredClassVersion; + } + + /** + * Get the defined value for the {@link Inject#require} parameter on + * injectors defined in mixins in this configuration. + * + * @return default require value + */ + public int getDefaultRequiredInjections() { + return this.mixin.getParent().getDefaultRequiredInjections(); + } + + /** + * Get the defined injector group for injectors + * + * @return default group name + */ + public String getDefaultInjectorGroup() { + return this.mixin.getParent().getDefaultInjectorGroup(); + } + + /** + * Get the injector groups for this target + * + * @return injector groups + */ + public InjectorGroupInfo.Map getInjectorGroups() { + return this.injectorGroups; + } /** * Find the corresponding class type for the supplied mixin class in this @@ -224,7 +333,7 @@ public class MixinTargetContext implements IReferenceMapperContext { /** * Handles "re-parenting" the method supplied, changes all references to the * mixin class to refer to the target class (for field accesses and method - * invokations) and also handles fixing up the targets of INVOKESPECIAL + * invocations) and also handles fixing up the targets of INVOKESPECIAL * opcodes for mixins with detached targets. * * @param method Method to transform @@ -233,18 +342,24 @@ public class MixinTargetContext implements IReferenceMapperContext { this.validateMethod(method); this.transformDescriptor(method); + AbstractInsnNode lastInsn = null; for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (insn instanceof MethodInsnNode) { - this.transformMethodNode(method, iter, (MethodInsnNode)insn); + this.transformMethodRef(method, iter, new MemberRef.Method((MethodInsnNode)insn)); } else if (insn instanceof FieldInsnNode) { - this.transformFieldNode(method, iter, (FieldInsnNode)insn); + this.transformFieldRef(method, iter, new MemberRef.Field((FieldInsnNode)insn)); + this.checkFinal(method, iter, (FieldInsnNode)insn); } else if (insn instanceof TypeInsnNode) { - this.transformTypeNode(method, iter, (TypeInsnNode)insn); + this.transformTypeNode(method, iter, (TypeInsnNode)insn, lastInsn); } else if (insn instanceof LdcInsnNode) { this.transformConstantNode(method, iter, (LdcInsnNode)insn); + } else if (insn instanceof InvokeDynamicInsnNode) { + this.transformInvokeDynamicNode(method, iter, (InvokeDynamicInsnNode)insn); } + + lastInsn = insn; } } @@ -257,64 +372,106 @@ public class MixinTargetContext implements IReferenceMapperContext { private void validateMethod(MethodNode method) { // Any method tagged with @SoftOverride must have an implementation visible from if (ASMHelper.getInvisibleAnnotation(method, SoftOverride.class) != null) { - Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER); + ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER); if (superMethod == null || !superMethod.isInjected()) { throw new InvalidMixinException(this, "Mixin method " + method.name + method.desc + " is tagged with @SoftOverride but no " - + "valid method was found in superclasses of " + this.targetClass.name); + + "valid method was found in superclasses of " + this.targetClass.getName()); } } } /** - * Transforms method invocations in the method. Updates static and dynamic - * bindings. + * Transforms a method invocation/reference in the method. Updates static + * and dynamic bindings. * * @param method Method being processed * @param iter Insn interator - * @param methodInsn Insn to transform + * @param methodRef Method reference to transform */ - private void transformMethodNode(MethodNode method, Iterator iter, MethodInsnNode methodInsn) { - this.transformDescriptor(methodInsn); + private void transformMethodRef(MethodNode method, Iterator iter, MemberRef methodRef) { + this.transformDescriptor(methodRef); - if (methodInsn.owner.equals(this.getClassRef())) { - methodInsn.owner = this.targetClass.name; + if (methodRef.getOwner().equals(this.getClassRef())) { + methodRef.setOwner(this.targetClass.getName()); } else if ((this.detachedSuper || this.inheritsFromMixin)) { - if (methodInsn.getOpcode() == Opcodes.INVOKESPECIAL) { - this.updateStaticBinding(method, methodInsn); - } else if (methodInsn.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodInsn.owner).isMixin()) { - this.updateDynamicBinding(method, methodInsn); + if (methodRef.getOpcode() == Opcodes.INVOKESPECIAL) { + this.updateStaticBinding(method, methodRef); + } else if (methodRef.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodRef.getOwner()).isMixin()) { + this.updateDynamicBinding(method, methodRef); } } } /** - * Transforms field accesses in the method. Handles imaginary super accesses - * and converts them to real super-invocations and rewrites field accesses - * which refer to mixin or supermixin classes to their relevant targets. + * Transforms field access/reference in the method. Handles imaginary super + * accesses and converts them to real super-invocations and rewrites field + * accesses which refer to mixin or supermixin classes to their relevant + * targets. * * @param method Method being processed * @param iter Insn interator - * @param fieldInsn Insn to transform + * @param fieldRef Field Reference to transform */ - private void transformFieldNode(MethodNode method, Iterator iter, FieldInsnNode fieldInsn) { - if (Constants.IMAGINARY_SUPER.equals(fieldInsn.name)) { - this.processImaginarySuper(method, fieldInsn); - iter.remove(); + private void transformFieldRef(MethodNode method, Iterator iter, MemberRef fieldRef) { + if (Constants.IMAGINARY_SUPER.equals(fieldRef.getName())) { + if (fieldRef instanceof MemberRef.Field) { + this.processImaginarySuper(method, ((MemberRef.Field) fieldRef).insn); + iter.remove(); + } else { + throw new InvalidMixinException(this.mixin, "Cannot call imaginary super from method handle."); + } } - this.transformDescriptor(fieldInsn); + this.transformDescriptor(fieldRef); - if (fieldInsn.owner.equals(this.getClassRef())) { - fieldInsn.owner = this.targetClass.name; + if (fieldRef.getOwner().equals(this.getClassRef())) { + fieldRef.setOwner(this.targetClass.getName()); } else { - ClassInfo fieldOwner = ClassInfo.forName(fieldInsn.owner); + ClassInfo fieldOwner = ClassInfo.forName(fieldRef.getOwner()); if (fieldOwner.isMixin()) { ClassInfo actualOwner = this.targetClassInfo.findCorrespondingType(fieldOwner); - fieldInsn.owner = actualOwner != null ? actualOwner.getName() : this.targetClass.name; + fieldRef.setOwner(actualOwner != null ? actualOwner.getName() : this.targetClass.getName()); } } } + private void checkFinal(MethodNode method, Iterator iter, FieldInsnNode fieldNode) { + if (!fieldNode.owner.equals(this.targetClass.getName())) { + return; + } + + int opcode = fieldNode.getOpcode(); + if (opcode == Opcodes.GETFIELD || opcode == Opcodes.GETSTATIC) { + return; + } + + for (Entry shadow : this.shadowFields.entrySet()) { + FieldNode shadowFieldNode = shadow.getKey(); + if (!shadowFieldNode.desc.equals(fieldNode.desc) || !shadowFieldNode.name.equals(fieldNode.name)) { + continue; + } + Field shadowField = shadow.getValue(); + if (shadowField.isDecoratedFinal()) { + if (shadowField.isDecoratedMutable()) { + if (this.mixin.getParent().getEnvironment().getOption(Option.DEBUG_VERBOSE)) { + MixinTargetContext.logger.warn("Write access to @Mutable @Final field {} in {}::{}", shadowField, this.mixin, method.name); + } + } else { + if (Constants.CTOR.equals(method.name) || Constants.CLINIT.equals(method.name)) { + MixinTargetContext.logger.warn("@Final field {} in {} should be final", shadowField, this.mixin); + } else { + MixinTargetContext.logger.error("Write access detected to @Final field {} in {}::{}", shadowField, this.mixin, method.name); + if (this.mixin.getParent().getEnvironment().getOption(Option.DEBUG_VERIFY)) { + throw new InvalidMixinException(this.mixin, "Write access detected to @Final field " + shadowField + " in " + this.mixin + + "::" + method.name); + } + } + } + } + return; + } + } + /** * Transforms type operations (eg. cast, instanceof) in the method being * processed. Changes references to mixin classes to that of the appropriate @@ -323,34 +480,94 @@ public class MixinTargetContext implements IReferenceMapperContext { * @param method Method being processed * @param iter Insn interator * @param typeInsn Insn to transform + * @param lastNode Last insn in the method */ - private void transformTypeNode(MethodNode method, Iterator iter, TypeInsnNode typeInsn) { + private void transformTypeNode(MethodNode method, Iterator iter, TypeInsnNode typeInsn, AbstractInsnNode lastNode) { + if (typeInsn.getOpcode() == Opcodes.CHECKCAST + && typeInsn.desc.equals(this.targetClass.getName()) + && lastNode.getOpcode() == Opcodes.ALOAD + && ((VarInsnNode)lastNode).var == 0) { + iter.remove(); + return; + } + if (typeInsn.desc.equals(this.getClassRef())) { - typeInsn.desc = this.targetClass.name; + typeInsn.desc = this.targetClass.getName(); } this.transformDescriptor(typeInsn); } /** - * Transforms class literals in the method being processed. + * Transforms class literals and method handle loads in the method being + * processed. * * @param method Method being processed * @param iter Insn interator * @param ldcInsn Insn to transform */ private void transformConstantNode(MethodNode method, Iterator iter, LdcInsnNode ldcInsn) { - if (ldcInsn.cst instanceof Type) { - Type type = (Type)ldcInsn.cst; - String desc = this.transformSingleDescriptor(type); - if (!type.toString().equals(desc)) { - ldcInsn.cst = Type.getType(desc); - } + ldcInsn.cst = this.transformConstant(method, iter, ldcInsn.cst); + } + + /** + * Transforms a invoke dynamic instruction in the method being processed. + * + * @param method Method being processed + * @param iter Insn interator + * @param dynInsn Insn to transform + */ + private void transformInvokeDynamicNode(MethodNode method, Iterator iter, InvokeDynamicInsnNode dynInsn) { + this.requireVersion(Opcodes.V1_7); + dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc); + dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm); + for (int i = 0; i < dynInsn.bsmArgs.length; i++) { + dynInsn.bsmArgs[i] = this.transformConstant(method, iter, dynInsn.bsmArgs[i]); } } /** - * Handle "imaginary super" invokations, these are invokations in + * Transforms a constant in the constant pool. + * + * @param method Method being processed + * @param iter Insn interator + * @param constant Consatnt pool entry + * @return Transformed constant + */ + private Object transformConstant(MethodNode method, Iterator iter, Object constant) { + if (constant instanceof Type) { + Type type = (Type)constant; + String desc = this.transformDescriptor(type); + if (!type.toString().equals(desc)) { + return Type.getType(desc); + } + return constant; + } else if (constant instanceof Handle) { + return this.transformHandle(method, iter, (Handle)constant); + } + return constant; + } + + /** + * Transforms a method handle that is referenced from the method being + * processed. + * + * @param method Method being processed + * @param iter Insn interator + * @param handle Handle to transform + */ + private Handle transformHandle(MethodNode method, Iterator iter, Handle handle) { + MemberRef.Handle memberRef = new MemberRef.Handle(handle); + if (memberRef.isField()) { + this.transformFieldRef(method, iter, memberRef); + } else { + this.transformMethodRef(method, iter, memberRef); + } + return memberRef.getMethodHandle(); + } + + /** + * Handle "imaginary super" invocations, these are invocations in * non-derived mixins for accessing methods known to exist in a supermixin * which is not directly inherited by this mixix. The method can only call * its own super-implmentation and the methd must also be tagged with @@ -363,7 +580,7 @@ public class MixinTargetContext implements IReferenceMapperContext { */ private void processImaginarySuper(MethodNode method, FieldInsnNode fieldInsn) { if (fieldInsn.getOpcode() != Opcodes.GETFIELD) { - if (Constants.INIT.equals(method.name)) { + if (Constants.CTOR.equals(method.name)) { throw new InvalidMixinException(this, "Illegal imaginary super declaration: field " + fieldInsn.name + " must not specify an initialiser"); } @@ -388,7 +605,7 @@ public class MixinTargetContext implements IReferenceMapperContext { MethodInsnNode methodNode = (MethodInsnNode)insn; if (methodNode.owner.equals(this.getClassRef()) && methodNode.name.equals(method.name) && methodNode.desc.equals(method.desc)) { methodNode.setOpcode(Opcodes.INVOKESPECIAL); - this.updateStaticBinding(method, methodNode); + this.updateStaticBinding(method, new MemberRef.Method(methodNode)); return; } } @@ -402,10 +619,10 @@ public class MixinTargetContext implements IReferenceMapperContext { * which contains the specified method. * * @param method Method containing the instruction - * @param insn INVOKE instruction node + * @param methodRef Unbound reference to the method */ - private void updateStaticBinding(MethodNode method, MethodInsnNode insn) { - this.updateBinding(method, insn, Traversal.SUPER); + private void updateStaticBinding(MethodNode method, MemberRef methodRef) { + this.updateBinding(method, methodRef, Traversal.SUPER); } /** @@ -413,27 +630,29 @@ public class MixinTargetContext implements IReferenceMapperContext { * which contains the specified method. * * @param method Method containing the instruction - * @param insn INVOKE instruction node + * @param methodRef Unbound reference to the method */ - private void updateDynamicBinding(MethodNode method, MethodInsnNode insn) { - this.updateBinding(method, insn, Traversal.ALL); + private void updateDynamicBinding(MethodNode method, MemberRef methodRef) { + this.updateBinding(method, methodRef, Traversal.ALL); } - private void updateBinding(MethodNode method, MethodInsnNode insn, Traversal traversal) { - if (Constants.INIT.equals(method.name) || insn.owner.equals(this.targetClass.name) || this.targetClass.name.startsWith("<")) { + private void updateBinding(MethodNode method, MemberRef methodRef, Traversal traversal) { + if (Constants.CTOR.equals(method.name) + || methodRef.getOwner().equals(this.targetClass.getName()) + || this.targetClass.getName().startsWith("<")) { return; } - Method superMethod = this.targetClassInfo.findMethodInHierarchy(insn.name, insn.desc, traversal == Traversal.ALL, traversal); + ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(methodRef.getName(), methodRef.getDesc(), + traversal == Traversal.ALL, traversal); if (superMethod != null) { if (superMethod.getOwner().isMixin()) { - throw new InvalidMixinException(this, "Invalid " + ASMHelper.getOpcodeName(insn) + " in " + this + " resolved " + insn.owner - + " -> " + superMethod.getOwner() + " for " + insn.name + insn.desc); + throw new InvalidMixinException(this, "Invalid " + methodRef + " in " + this + " resolved " + superMethod.getOwner() + + " but is mixin."); } - insn.owner = superMethod.getOwner().getName(); - } else if (ClassInfo.forName(insn.owner).isMixin()) { - throw new MixinTransformerError("Error resolving " + ASMHelper.getOpcodeName(insn) + " target for " + insn.owner + "." + insn.name - + " in " + this); + methodRef.setOwner(superMethod.getImplementor().getName()); + } else if (ClassInfo.forName(methodRef.getOwner()).isMixin()) { + throw new MixinTransformerError("Error resolving " + methodRef + " in " + this); } } @@ -449,18 +668,6 @@ public class MixinTargetContext implements IReferenceMapperContext { field.desc = this.transformSingleDescriptor(field.desc, false); } - /** - * Transforms a field insn descriptor in the context of this mixin target - * - * @param field Field instruction node to transform - */ - public void transformDescriptor(FieldInsnNode field) { - if (!this.inheritsFromMixin) { - return; - } - field.desc = this.transformSingleDescriptor(field.desc, false); - } - /** * Transforms a method descriptor in the context of this mixin target * @@ -474,15 +681,20 @@ public class MixinTargetContext implements IReferenceMapperContext { } /** - * Transforms a method insn descriptor in the context of this mixin target + * Transforms a method or field reference descriptor in the context of this + * mixin target * - * @param method Method instruction node to transform + * @param member Reference to the method or field */ - public void transformDescriptor(MethodInsnNode method) { + public void transformDescriptor(MemberRef member) { if (!this.inheritsFromMixin) { return; } - method.desc = this.transformMethodDescriptor(method.desc); + if (member.isField()) { + member.setDesc(this.transformSingleDescriptor(member.getDesc(), false)); + } else { + member.setDesc(this.transformMethodDescriptor(member.getDesc())); + } } /** @@ -496,6 +708,13 @@ public class MixinTargetContext implements IReferenceMapperContext { } typeInsn.desc = this.transformSingleDescriptor(typeInsn.desc, true); } + + private String transformDescriptor(Type type) { + if (type.getSort() == Type.METHOD) { + return this.transformMethodDescriptor(type.getDescriptor()); + } + return this.transformSingleDescriptor(type); + } private String transformSingleDescriptor(Type type) { if (type.getSort() < Type.ARRAY) { @@ -545,19 +764,86 @@ public class MixinTargetContext implements IReferenceMapperContext { * @return new or existing target handle for the supplied method */ public Target getTargetMethod(MethodNode method) { - if (!this.targetClass.methods.contains(method)) { - throw new IllegalArgumentException("Invalid target method supplied to getTargetMethod()"); - } - - String targetName = method.name + method.desc; - Target target = this.targetMethods.get(targetName); - if (target == null) { - target = new Target(method); - this.targetMethods.put(targetName, target); - } - return target; + return this.targetClass.getTargetMethod(method); } + MethodNode findMethod(MethodNode method, AnnotationNode annotation) { + Deque aliases = new LinkedList(); + aliases.add(method.name); + if (annotation != null) { + List aka = ASMHelper.>getAnnotationValue(annotation, "aliases"); + if (aka != null) { + aliases.addAll(aka); + } + } + + return this.targetClass.findAliasedMethod(aliases, method.desc); + } + + MethodNode findRemappedMethod(MethodNode method) { + RemapperChain remapperChain = MixinEnvironment.getCurrentEnvironment().getRemappers(); + String remappedName = remapperChain.mapMethodName(this.targetClass.getName(), method.name, method.desc); + if (remappedName.equals(method.name)) { + return null; + } + + Deque aliases = new LinkedList(); + aliases.add(remappedName); + + return this.targetClass.findAliasedMethod(aliases, method.desc); + } + + FieldNode findField(FieldNode field, AnnotationNode shadow) { + Deque aliases = new LinkedList(); + aliases.add(field.name); + if (shadow != null) { + List aka = ASMHelper.>getAnnotationValue(shadow, "aliases"); + if (aka != null) { + aliases.addAll(aka); + } + } + + return this.targetClass.findAliasedField(aliases, field.desc); + } + + FieldNode findRemappedField(FieldNode field) { + RemapperChain remapperChain = MixinEnvironment.getCurrentEnvironment().getRemappers(); + String remappedName = remapperChain.mapFieldName(this.targetClass.getName(), field.name, field.desc); + if (remappedName.equals(field.name)) { + return null; + } + + Deque aliases = new LinkedList(); + aliases.add(remappedName); + return this.targetClass.findAliasedField( aliases, field.desc); + } + + /** + * Mark this mixin as requiring the specified class version in the context + * of the current target + * + * @param version version to require + */ + protected void requireVersion(int version) { + this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version); + + // This validation is done on the mixin beforehand, however it's still + // possible that an upstream transformer can inject java 7 instructions + // without updating the class version. + if (version > MixinEnvironment.getCompatibilityLevel().classVersion()) { + throw new InvalidMixinException(this, "Unsupported mixin class version " + version); + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.refmap.IReferenceMapperContext + * #getMixin() + */ + @Override + public IMixinInfo getMixin() { + return this.mixin; + } + /** * Get the mixin info for this mixin */ @@ -588,7 +874,7 @@ public class MixinTargetContext implements IReferenceMapperContext { * * @return shadow methods in the mixin */ - public List getShadowMethods() { + public Collection getShadowMethods() { return this.shadowMethods; } @@ -606,8 +892,8 @@ public class MixinTargetContext implements IReferenceMapperContext { * * @return shadow fields in the mixin */ - public List getShadowFields() { - return this.shadowFields; + public Set> getShadowFields() { + return this.shadowFields.entrySet(); } /** @@ -673,6 +959,65 @@ public class MixinTargetContext implements IReferenceMapperContext { * @param targetClass Target class */ public void postApply(String transformedName, ClassNode targetClass) { + try { + this.injectorGroups.validateAll(); + } catch (InjectionValidationException ex) { + InjectorGroupInfo group = ex.getGroup(); + throw new InjectionError( + String.format("Critical injection failure: Callback group %s in %s failed injection check: %s", + group, this.mixin, ex.getMessage())); + } + this.mixin.postApply(transformedName, targetClass); } + + public String getHandlerName(AnnotationNode annotation, MethodNode method, boolean surrogate) { + return this.targetClass.getHandlerName(annotation, method, surrogate); + } + + public String getUniqueName(MethodNode method) { + return this.targetClass.getUniqueName(method); + } + + public String getUniqueName(FieldNode field) { + return this.targetClass.getUniqueName(field); + } + + /** + * Scans the target class for injector methods and prepares discovered + * injectors + */ + public void prepareInjections() { + this.injectors.clear(); + + for (MethodNode method : this.mergedMethods) { + InjectionInfo injectInfo = InjectionInfo.parse(this, method); + if (injectInfo == null) { + continue; + } + + if (injectInfo.isValid()) { + injectInfo.prepare(); + this.injectors.add(injectInfo); + } + + method.visibleAnnotations.remove(injectInfo.getAnnotation()); + } + } + + /** + * Apply injectors discovered in the {@link #prepareInjections()} pass + */ + public void applyInjections() { + for (InjectionInfo injectInfo : this.injectors) { + injectInfo.inject(); + } + + for (InjectionInfo injectInfo : this.injectors) { + injectInfo.postInject(); + } + + this.injectors.clear(); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index adcc3004..c2849c4f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -27,9 +27,11 @@ package org.spongepowered.asm.mixin.transformer; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; +import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; @@ -37,9 +39,6 @@ import java.util.TreeSet; import java.util.UUID; import java.util.regex.Pattern; -import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraft.launchwrapper.Launch; - import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; @@ -48,22 +47,104 @@ import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.FieldNode; import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.mixin.MixinApplyError; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.mixin.Mixins; +import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; +import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; +import org.spongepowered.asm.mixin.throwables.MixinApplyError; +import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.throwables.MixinPrepareError; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.transformer.MixinTransformerModuleCheckClass.ValidationFailedException; import org.spongepowered.asm.mixin.transformer.debug.IDecompiler; +import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; +import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.transformers.TreeTransformer; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.PrettyPrinter; + +import net.minecraft.launchwrapper.IClassTransformer; +import net.minecraft.launchwrapper.Launch; /** * Transformer which manages the mixin configuration and application process */ public class MixinTransformer extends TreeTransformer { + /** + * Phase during which an error occurred, delegates to functionality in + * available handler + */ + static enum ErrorPhase { + /** + * Error during initialisation of a MixinConfig + */ + PREPARE { + @Override + ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) { + try { + return handler.onPrepareError(mixin.getConfig(), ex, mixin, action); + } catch (AbstractMethodError ame) { + // Catch if error handler is pre-0.5.4 + return action; + } + } + + @Override + protected String getContext(IMixinInfo mixin, String context) { + return String.format("preparing %s in %s", mixin.getName(), context); + } + }, + /** + * Error during application of a mixin to a target class + */ + APPLY { + @Override + ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) { + try { + return handler.onApplyError(context, ex, mixin, action); + } catch (AbstractMethodError ame) { + // Catch if error handler is pre-0.5.4 + return action; + } + } + + @Override + protected String getContext(IMixinInfo mixin, String context) { + return String.format("%s -> %s", mixin, context); + } + }; + + /** + * Human-readable name + */ + private final String text; + + private ErrorPhase() { + this.text = this.name().toLowerCase(); + } + + abstract ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action); + + protected abstract String getContext(IMixinInfo mixin, String context); + + public String getLogMessage(String context, InvalidMixinException ex, IMixinInfo mixin) { + return String.format("Mixin %s failed %s: %s %s", this.text, this.getContext(mixin, context), ex.getClass().getName(), ex.getMessage()); + } + + public String getErrorMessage(IMixinInfo mixin, IMixinConfig config, Phase phase) { + return String.format("Mixin [%s] from phase [%s] in config [%s] FAILED during %s", mixin, phase, config, this.name()); + } + + } + /** * Proxy transformer for the mixin transformer. These transformers are used * to allow the mixin transformer to be re-registered in the transformer @@ -277,6 +358,11 @@ public class MixinTransformer extends TreeTransformer { */ private final IDecompiler decompiler; + /** + * Hot-Swap agent + */ + private final IHotSwap hotSwapper; + /** * ctor */ @@ -285,7 +371,7 @@ public class MixinTransformer extends TreeTransformer { Object globalMixinTransformer = environment.getActiveTransformer(); if (globalMixinTransformer instanceof IClassTransformer) { - throw new RuntimeException("Terminating MixinTransformer instance " + this); + throw new MixinException("Terminating MixinTransformer instance " + this); } // I am a leaf on the wind @@ -294,7 +380,8 @@ public class MixinTransformer extends TreeTransformer { TreeInfo.setLock(this.lock); this.decompiler = this.initDecompiler(new File(MixinTransformer.DEBUG_OUTPUT, "java")); - + this.hotSwapper = this.initHotSwapper(); + try { FileUtils.deleteDirectory(this.classExportDir); } catch (IOException ex) { @@ -303,7 +390,7 @@ public class MixinTransformer extends TreeTransformer { } private IDecompiler initDecompiler(File outputPath) { - if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT)) { + if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT_DECOMPILE)) { return null; } @@ -313,7 +400,9 @@ public class MixinTransformer extends TreeTransformer { Class clazz = (Class)Class.forName("org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler"); Constructor ctor = clazz.getDeclaredConstructor(File.class); - return ctor.newInstance(outputPath); + IDecompiler decompiler = ctor.newInstance(outputPath); + this.logger.info("Fernflower decompiler was successfully initialised, exported classes will be decompiled"); + return decompiler; } catch (Throwable th) { this.logger.info("Fernflower could not be loaded, exported classes will not be decompiled. {}: {}", th.getClass().getSimpleName(), th.getMessage()); @@ -321,6 +410,26 @@ public class MixinTransformer extends TreeTransformer { return null; } + private IHotSwap initHotSwapper() { + if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.HOT_SWAP)) { + return null; + } + + try { + this.logger.info("Attempting to load Hot-Swap agent"); + @SuppressWarnings("unchecked") + Class clazz = + (Class)Class.forName("org.spongepowered.tools.agent.MixinAgent"); + Constructor ctor = clazz.getDeclaredConstructor(MixinTransformer.class); + return ctor.newInstance(this); + } catch (Throwable th) { + this.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}", + th.getClass().getSimpleName(), th.getMessage()); + } + + return null; + } + /** * Force-load all classes targetted by mixins but not yet applied */ @@ -330,13 +439,22 @@ public class MixinTransformer extends TreeTransformer { for (MixinConfig config : this.configs) { unhandled.addAll(config.getUnhandledTargets()); } - - for (String nextClass : unhandled) { + + Logger auditLogger = LogManager.getLogger("mixin/audit"); + + for (String target : unhandled) { try { - this.logger.info("Force-loading class {}", nextClass); - Class.forName(nextClass, true, Launch.classLoader); + auditLogger.info("Force-loading class {}", target); + Class.forName(target, true, Launch.classLoader); } catch (ClassNotFoundException ex) { - throw new Error("Could not force-load " + nextClass); + auditLogger.error("Could not force-load " + target, ex); + } + } + + for (MixinConfig config : this.configs) { + for (String target : config.getUnhandledTargets()) { + ClassAlreadyLoadedException ex = new ClassAlreadyLoadedException(target + " was already classloaded"); + auditLogger.error("Could not force-load " + target, ex); } } } @@ -346,7 +464,7 @@ public class MixinTransformer extends TreeTransformer { * #transform(java.lang.String, java.lang.String, byte[]) */ @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) { + public synchronized byte[] transform(String name, String transformedName, byte[] basicClass) { if (basicClass == null || transformedName == null || this.errorState) { return basicClass; } @@ -357,10 +475,10 @@ public class MixinTransformer extends TreeTransformer { if (this.currentEnvironment != environment && !locked) { try { - this.init(environment); + this.select(environment); } catch (Exception ex) { this.lock.pop(); - throw new RuntimeException(ex); + throw new MixinException(ex); } } @@ -394,41 +512,69 @@ public class MixinTransformer extends TreeTransformer { if (mixins != null) { // Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now if (locked) { - this.logger.warn("Re-entrance detected, this will cause serious problems.", new RuntimeException()); + this.logger.warn("Re-entrance detected, this will cause serious problems.", new MixinException()); throw new MixinApplyError("Re-entrance error."); } - + + if (this.hotSwapper != null) { + this.hotSwapper.registerTargetClass(transformedName, basicClass); + } + try { - basicClass = this.applyMixins(transformedName, basicClass, mixins); + // Tree for target class + ClassNode targetClassNode = this.readClass(basicClass, true); + TargetClassContext context = new TargetClassContext(this.sessionId, transformedName, targetClassNode, mixins); + basicClass = this.applyMixins(context); } catch (InvalidMixinException th) { - if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) { - this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass); - } - - this.handleMixinErrorState(transformedName, th); + this.dumpClassOnFailure(transformedName, basicClass, environment); + this.handleMixinApplyError(transformedName, th, environment); } } return basicClass; - } catch (Exception ex) { - if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) { - this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass); - } - - throw new MixinTransformerError("An unexpected critical error was encountered", ex); + } catch (Throwable th) { + th.printStackTrace(); + this.dumpClassOnFailure(transformedName, basicClass, environment); + throw new MixinTransformerError("An unexpected critical error was encountered", th); } finally { this.lock.pop(); } } - private void init(MixinEnvironment environment) { + /** + * Update a mixin class with new bytecode. + * + * @param mixinClass Name of the mixin + * @param bytes New bytecode + * @return List of classes that need to be updated + */ + public List reload(String mixinClass, byte[] bytes) { + if (this.lock.getDepth() > 0) { + throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered"); + } + List targets = new ArrayList(); + for (MixinConfig config : this.configs) { + targets.addAll(config.reloadMixin(mixinClass, bytes)); + } + return targets; + } + + private void select(MixinEnvironment environment) { this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG; this.logger.log(this.verboseLoggingLevel, "Preparing mixins for {}", environment); + long startTime = System.currentTimeMillis(); - this.addConfigs(environment); - this.addModules(environment); - this.initConfigs(); + this.selectConfigs(environment); + this.selectModules(environment); + int totalMixins = this.prepareConfigs(environment); this.currentEnvironment = environment; + + double elapsedTime = (System.currentTimeMillis() - startTime) * 0.001D; + if (elapsedTime > 0.25D) { + String elapsed = new DecimalFormat("###0.000").format(elapsedTime); + String perMixinTime = new DecimalFormat("###0.0").format((elapsedTime / totalMixins) * 1000.0); + this.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({} msec avg.)", totalMixins, elapsed, perMixinTime); + } } /** @@ -436,20 +582,19 @@ public class MixinTransformer extends TreeTransformer { * * @param environment Environment to query */ - private void addConfigs(MixinEnvironment environment) { - List configs = environment.getMixinConfigs(); - - if (configs != null) { - for (String configFile : configs) { - try { - MixinConfig config = MixinConfig.create(configFile); - if (config != null) { - this.logger.log(this.verboseLoggingLevel, "Adding mixin config {}", config); - this.pendingConfigs.add(config); - } - } catch (Exception ex) { - this.logger.warn(String.format("Failed to load mixin config: %s", configFile), ex); + private void selectConfigs(MixinEnvironment environment) { + for (Iterator iter = Mixins.getConfigs().iterator(); iter.hasNext();) { + Config handle = iter.next(); + try { + MixinConfig config = handle.get(); + if (config.select(environment)) { + iter.remove(); + this.logger.log(this.verboseLoggingLevel, "Selecting config {}", config); + config.onSelect(); + this.pendingConfigs.add(config); } + } catch (Exception ex) { + this.logger.warn(String.format("Failed to select mixin config: %s", handle), ex); } } @@ -461,7 +606,7 @@ public class MixinTransformer extends TreeTransformer { * * @param environment Environment to query */ - private void addModules(MixinEnvironment environment) { + private void selectModules(MixinEnvironment environment) { this.modules.clear(); // Run CheckClassAdapter on the mixin bytecode if debug option is enabled @@ -476,12 +621,21 @@ public class MixinTransformer extends TreeTransformer { } /** - * Initialise mixin configs + * Prepare mixin configs + * + * @param environment Environment + * @return total number of mixins initialised */ - private void initConfigs() { + private int prepareConfigs(MixinEnvironment environment) { + int totalMixins = 0; + for (MixinConfig config : this.pendingConfigs) { try { - config.initialise(); + this.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount()); + config.prepare(this.hotSwapper); + totalMixins += config.getMixinCount(); + } catch (InvalidMixinException ex) { + this.handleMixinPrepareError(config, ex, environment); } catch (Exception ex) { this.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + ex.getMessage(), ex); } @@ -505,15 +659,19 @@ public class MixinTransformer extends TreeTransformer { for (MixinConfig config : this.pendingConfigs) { try { - config.postInitialise(); + config.postInitialise(this.hotSwapper); + } catch (InvalidMixinException ex) { + this.handleMixinPrepareError(config, ex, environment); } catch (Exception ex) { - this.logger.error("Error encountered during mixin config postInit setp'" + config.getName() + "': " + ex.getMessage(), ex); + this.logger.error("Error encountered during mixin config postInit step'" + config.getName() + "': " + ex.getMessage(), ex); } } this.configs.addAll(this.pendingConfigs); Collections.sort(this.configs); this.pendingConfigs.clear(); + + return totalMixins; } /** @@ -546,100 +704,122 @@ public class MixinTransformer extends TreeTransformer { } } - return this.writeClass(transformedName, passThroughClass); + return this.writeClass(transformedName, passThroughClass, false); } /** * Apply mixins for specified target class to the class described by the * supplied byte array. * - * @param transformedName - * @param basicClass - * @param mixins + * @param context * @return class bytecode after application of mixins */ - private byte[] applyMixins(String transformedName, byte[] basicClass, SortedSet mixins) { - // Tree for target class - ClassNode targetClass = this.readClass(basicClass, true); - - this.preApply(transformedName, targetClass, mixins); - this.apply(transformedName, targetClass, mixins); - this.postApply(transformedName, targetClass, mixins); - - return this.writeClass(transformedName, targetClass); + private byte[] applyMixins(TargetClassContext context) { + this.preApply(context); + this.apply(context); + try { + this.postApply(context); + } catch (ValidationFailedException ex) { + this.logger.info(ex.getMessage()); + // If verify is enabled and failed, write out the bytecode to allow us to inspect it + if (context.isExportForced() || MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT)) { + this.writeClass(context); + } + } + return this.writeClass(context); } /** * Process tasks before mixin application * - * @param transformedName Target class transformed name - * @param targetClass Target class - * @param mixins Mixin which were just applied + * @param context Target class context */ - private void preApply(String transformedName, ClassNode targetClass, SortedSet mixins) { + private void preApply(TargetClassContext context) { for (IMixinTransformerModule module : this.modules) { - module.preApply(transformedName, targetClass, mixins); + module.preApply(context); } } /** * Apply the mixins to the target class * - * @param transformedName Target class transformed name - * @param targetClass Target class - * @param mixins Mixin which were just applied + * @param context Target class context */ - private void apply(String transformedName, ClassNode targetClass, SortedSet mixins) { - MixinApplicator applicator = new MixinApplicator(this.sessionId, transformedName, targetClass); - applicator.apply(mixins); + private void apply(TargetClassContext context) { + context.applyMixins(); } /** * Process tasks after mixin application * - * @param transformedName Target class transformed name - * @param targetClass Target class - * @param mixins Mixin which were just applied + * @param context Target class context */ - private void postApply(String transformedName, ClassNode targetClass, SortedSet mixins) { + private void postApply(TargetClassContext context) { for (IMixinTransformerModule module : this.modules) { - module.postApply(transformedName, targetClass, mixins); + module.postApply(context); } } - private void handleMixinErrorState(String targetClassName, InvalidMixinException th) throws MixinApplyError { + private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError { + this.handleMixinError(config.getName(), ex, environment, ErrorPhase.PREPARE); + } + + private void handleMixinApplyError(String targetClass, InvalidMixinException ex, MixinEnvironment environment) throws MixinApplyError { + this.handleMixinError(targetClass, ex, environment, ErrorPhase.APPLY); + } + + private void handleMixinError(String context, InvalidMixinException ex, MixinEnvironment environment, ErrorPhase errorPhase) throws Error { this.errorState = true; - MixinInfo mixin = th.getMixin(); - MixinConfig config = mixin.getParent(); - ErrorAction action = config.isRequired() ? ErrorAction.ERROR : ErrorAction.WARN; + IMixinInfo mixin = ex.getMixin(); - if (MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERBOSE)) { - th.printStackTrace(); + if (mixin == null) { + this.logger.error("InvalidMixinException has no mixin!", ex); + throw ex; } + IMixinConfig config = mixin.getConfig(); + Phase phase = mixin.getPhase(); + ErrorAction action = config.isRequired() ? ErrorAction.ERROR : ErrorAction.WARN; + + if (environment.getOption(Option.DEBUG_VERBOSE)) { + new PrettyPrinter() + .add("Invalid Mixin").centre() + .hr('-') + .kvWidth(10) + .kv("Action", errorPhase.name()) + .kv("Mixin", mixin.getClassName()) + .kv("Config", config.getName()) + .kv("Phase", phase) + .hr('-') + .add(" %s", ex.getClass().getName()) + .hr('-') + .addWrapped(" %s", ex.getMessage()) + .hr('-') + .add(ex.getStackTrace(), 8) + .trace(action.logLevel); + } + for (IMixinErrorHandler handler : this.getErrorHandlers(mixin.getPhase())) { - ErrorAction newAction = handler.onError(targetClassName, th, mixin, action); + ErrorAction newAction = errorPhase.onError(handler, context, ex, mixin, action); if (newAction != null) { action = newAction; } } - this.logger.log(action.logLevel, String.format("Mixin failed applying %s -> %s: %s %s", mixin, targetClassName, - th.getClass().getName(), th.getMessage()), th); + this.logger.log(action.logLevel, errorPhase.getLogMessage(context, ex, mixin), ex); this.errorState = false; if (action == ErrorAction.ERROR) { - throw new MixinApplyError(String.format("Mixin [%s] from phase [%s] in config [%s] FAILED", mixin, mixin.getPhase(), - config), th); + throw new MixinApplyError(errorPhase.getErrorMessage(mixin, config, phase), ex); } } private List getErrorHandlers(Phase phase) { List handlers = new ArrayList(); - for (String handlerClassName : MixinEnvironment.getEnvironment(phase).getErrorHandlerClasses()) { + for (String handlerClassName : Mixins.getErrorHandlerClasses()) { try { this.logger.info("Instancing error handler class {}", handlerClassName); Class handlerClass = Class.forName(handlerClassName, true, Launch.classLoader); @@ -664,15 +844,19 @@ public class MixinTransformer extends TreeTransformer { return Pattern.compile(this.prepareFilter(filter), Pattern.CASE_INSENSITIVE).matcher(subject).matches(); } - private byte[] writeClass(String transformedName, ClassNode targetClass) { + private byte[] writeClass(TargetClassContext context) { + return this.writeClass(context.getClassName(), context.getClassNode(), context.isExportForced()); + } + + private byte[] writeClass(String transformedName, ClassNode targetClass, boolean forceExport) { // Collapse tree to bytes byte[] bytes = this.writeClass(targetClass); // Export transformed class for debugging purposes MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); - if (environment.getOption(Option.DEBUG_EXPORT)) { + if (forceExport || environment.getOption(Option.DEBUG_EXPORT)) { String filter = environment.getOptionValue(Option.DEBUG_EXPORT_FILTER); - if (filter == null || this.applyFilter(filter, transformedName)) { + if (forceExport || filter == null || this.applyFilter(filter, transformedName)) { File outputFile = this.dumpClass(transformedName.replace('.', '/'), bytes); if (this.decompiler != null) { this.decompiler.decompile(outputFile); @@ -683,6 +867,12 @@ public class MixinTransformer extends TreeTransformer { return bytes; } + private void dumpClassOnFailure(String className, byte[] bytes, MixinEnvironment env) { + if (env.getOption(Option.DUMP_TARGET_ON_FAILURE)) { + this.dumpClass(className.replace('.', '/') + ".target", bytes); + } + } + private File dumpClass(String fileName, byte[] bytes) { File outputFile = new File(this.classExportDir, fileName + ".class"); try { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleCheckClass.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleCheckClass.java index 8aefa0b1..73cb870b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleCheckClass.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleCheckClass.java @@ -24,36 +24,56 @@ */ package org.spongepowered.asm.mixin.transformer; -import java.util.SortedSet; - import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.util.CheckClassAdapter; - +import org.spongepowered.asm.mixin.throwables.MixinException; /** * Mixin transformer module which runs CheckClassAdapter on the post-mixin * bytecode */ public class MixinTransformerModuleCheckClass implements IMixinTransformerModule { - - /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule - * #preTransform(java.lang.String, org.objectweb.asm.tree.ClassNode, - * java.util.SortedSet) + + /** + * Exception thrown when checkclass fails */ - @Override - public void preApply(String transformedName, ClassNode targetClass, SortedSet mixins) { + public static class ValidationFailedException extends MixinException { + + private static final long serialVersionUID = 1L; + + public ValidationFailedException(String message, Throwable cause) { + super(message, cause); + } + + public ValidationFailedException(String message) { + super(message); + } + + public ValidationFailedException(Throwable cause) { + super(cause); + } + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule - * #postTransform(java.lang.String, org.objectweb.asm.tree.ClassNode, - * java.util.SortedSet) + * #preApply(org.spongepowered.asm.mixin.transformer.TargetClassContext) */ @Override - public void postApply(String transformedName, ClassNode targetClass, SortedSet mixins) { - targetClass.accept(new CheckClassAdapter(new MixinClassWriter(ClassWriter.COMPUTE_FRAMES))); + public void preApply(TargetClassContext context) { + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule + * #postApply(org.spongepowered.asm.mixin.transformer.TargetClassContext) + */ + @Override + public void postApply(TargetClassContext context) { + try { + context.getClassNode().accept(new CheckClassAdapter(new MixinClassWriter(ClassWriter.COMPUTE_FRAMES))); + } catch (RuntimeException ex) { + throw new ValidationFailedException(ex.getMessage(), ex); + } } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java index 3a0f6e17..89c88f0b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java @@ -32,10 +32,8 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; -import java.util.SortedSet; import org.apache.commons.io.IOUtils; -import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal; import org.spongepowered.asm.util.PrettyPrinter; @@ -46,41 +44,40 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.io.Files; - /** * Checks whether interfaces declared on mixin target classes are actually fully * implemented and generates reports to the console and to files on disk */ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformerModule { - + /** * CSV Report file */ private final File csv; - + /** * Text Report file */ private final File report; - + /** * Methods from interfaces that are already in the class before mixins are * applied. */ private final Multimap interfaceMethods = HashMultimap.create(); - + public MixinTransformerModuleInterfaceChecker() { File debugOutputFolder = new File(MixinTransformer.DEBUG_OUTPUT, "audit"); debugOutputFolder.mkdirs(); this.csv = new File(debugOutputFolder, "mixin_implementation_report.csv"); this.report = new File(debugOutputFolder, "mixin_implementation_report.txt"); - + try { Files.write("Class,Method,Signature,Interface\n", this.csv, Charsets.ISO_8859_1); } catch (IOException ex) { // well this sucks } - + try { String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); Files.write("Mixin Implementation Report generated on " + dateTime + "\n", this.report, Charsets.ISO_8859_1); @@ -91,49 +88,48 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule - * #preTransform(java.lang.String, org.objectweb.asm.tree.ClassNode, - * java.util.SortedSet) + * #preApply(org.spongepowered.asm.mixin.transformer.TargetClassContext) */ @Override - public void preApply(String transformedName, ClassNode targetClass, SortedSet mixins) { - ClassInfo targetClassInfo = ClassInfo.forName(targetClass.name); - for (Method m : targetClassInfo.getInterfaceMethods()) { + public void preApply(TargetClassContext context) { + ClassInfo targetClassInfo = context.getClassInfo(); + for (Method m : targetClassInfo.getInterfaceMethods(false)) { this.interfaceMethods.put(targetClassInfo, m); } } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule - * #postTransform(java.lang.String, org.objectweb.asm.tree.ClassNode, - * java.util.SortedSet) + * #postApply(org.spongepowered.asm.mixin.transformer.TargetClassContext) */ @Override - public void postApply(String transformedName, ClassNode targetClass, SortedSet mixins) { - ClassInfo targetClassInfo = ClassInfo.forName(targetClass.name); + public void postApply(TargetClassContext context) { + ClassInfo targetClassInfo = context.getClassInfo(); String className = targetClassInfo.getName().replace('/', '.'); int missingMethodCount = 0; PrettyPrinter printer = new PrettyPrinter(); - + printer.add("Class: %s", className).hr(); printer.add("%-32s %-47s %s", "Return Type", "Missing Method", "From Interface").hr(); - Set interfaceMethods = targetClassInfo.getInterfaceMethods(); - Set implementedMethods = new HashSet(targetClassInfo.getSuperClass().getInterfaceMethods()); + Set interfaceMethods = targetClassInfo.getInterfaceMethods(true); + Set implementedMethods = new HashSet(targetClassInfo.getSuperClass().getInterfaceMethods(true)); implementedMethods.addAll(this.interfaceMethods.removeAll(targetClassInfo)); - + for (Method method : interfaceMethods) { Method found = targetClassInfo.findMethodInHierarchy(method.getName(), method.getDesc(), true, Traversal.ALL); - if (found != null) { + // If method IS found and IS implemented, then do nothing (don't print an error) + if (found != null && !found.isAbstract()) { continue; } - + // Don't blame the subclass for not implementing methods that it does not need to implement. if (implementedMethods.contains(method)) { continue; } - + if (missingMethodCount > 0) { printer.add(); } @@ -143,7 +139,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer missingMethodCount++; printer.add("%-32s%s", signaturePrinter.getReturnType(), signaturePrinter); printer.add("%-80s %s", "", iface); - + this.appendToCSVReport(className, method, iface); } @@ -164,7 +160,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer private void appendToTextReport(PrettyPrinter printer) { FileOutputStream fos = null; - + try { fos = new FileOutputStream(this.report, true); PrintStream stream = new PrintStream(fos); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java new file mode 100644 index 00000000..2ba06fb5 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java @@ -0,0 +1,316 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.Deque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedSet; + +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.lib.tree.FieldNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.Debug; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.util.ASMHelper; + +/** + * Struct for containing target class information during mixin application + */ +class TargetClassContext { + + /** + * Mutable integer + */ + static class Counter { + public int value; + } + + /** + * Transformer session ID + */ + private final String sessionId; + + /** + * Target class name + */ + private final String className; + + /** + * Target class as tree + */ + private final ClassNode classNode; + + /** + * Target class metadata + */ + private final ClassInfo classInfo; + + /** + * Mixins to apply + */ + private final SortedSet mixins; + + /** + * Injector Method descriptor to ID map + */ + private final Map injectorMethodIndices = new HashMap(); + + /** + * Information about methods in the target class, used to keep track of + * transformations we apply + */ + private final Map targetMethods = new HashMap(); + + /** + * Do not remap injector handler methods (debug option) + */ + private final boolean disableHandlerRemap; + + /** + * Unique method and field indices + */ + private int nextUniqueMethodIndex, nextUniqueFieldIndex; + + /** + * True once mixins have been applied to this class + */ + private boolean applied; + + /** + * True if this class is decorated with an {@link Debug} annotation which + * instructs an export + */ + private boolean forceExport; + + TargetClassContext(String sessionId, String name, ClassNode classNode, SortedSet mixins) { + this.sessionId = sessionId; + this.className = name; + this.classNode = classNode; + this.classInfo = ClassInfo.fromClassNode(classNode); + this.mixins = mixins; + this.disableHandlerRemap = MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_DISABLE_HANDLER_REMAP); + } + + @Override + public String toString() { + return this.className; + } + + public boolean isApplied() { + return this.applied; + } + + public boolean isExportForced() { + return this.forceExport; + } + + /** + * Get the transformer session ID + */ + public String getSessionId() { + return this.sessionId; + } + + /** + * Get the internal class name + */ + public String getName() { + return this.classNode.name; + } + + /** + * Get the class name + */ + public String getClassName() { + return this.className; + } + + /** + * Get the class tree + */ + public ClassNode getClassNode() { + return this.classNode; + } + + /** + * Get the class methods (from the tree) + */ + public List getMethods() { + return this.classNode.methods; + } + + /** + * Get the class fields (from the tree) + */ + public List getFields() { + return this.classNode.fields; + } + + /** + * Get the target class metadata + */ + public ClassInfo getClassInfo() { + return this.classInfo; + } + + /** + * Get the mixins for this target class + */ + public SortedSet getMixins() { + return this.mixins; + } + + MethodNode findAliasedMethod(Deque aliases, String desc) { + String alias = aliases.poll(); + if (alias == null) { + return null; + } + + for (MethodNode target : this.classNode.methods) { + if (target.name.equals(alias) && target.desc.equals(desc)) { + return target; + } + } + + return this.findAliasedMethod(aliases, desc); + } + + /** + * Finds a field in the target class + * + * @param aliases + * @param desc + * @return Target field or null if not found + */ + FieldNode findAliasedField(Deque aliases, String desc) { + String alias = aliases.poll(); + if (alias == null) { + return null; + } + + for (FieldNode target : this.classNode.fields) { + if (target.name.equals(alias) && target.desc.equals(desc)) { + return target; + } + } + + return this.findAliasedField(aliases, desc); + } + + /** + * Get a target method handle from the target class + * + * @param method method to get a target handle for + * @return new or existing target handle for the supplied method + */ + public Target getTargetMethod(MethodNode method) { + if (!this.classNode.methods.contains(method)) { + throw new IllegalArgumentException("Invalid target method supplied to getTargetMethod()"); + } + + String targetName = method.name + method.desc; + Target target = this.targetMethods.get(targetName); + if (target == null) { + target = new Target(this.classNode, method); + this.targetMethods.put(targetName, target); + } + return target; + } + + public String getHandlerName(AnnotationNode annotation, MethodNode method, boolean surrogate) { + if (this.disableHandlerRemap) { + return method.name; + } + + String descriptor = String.format("%s%s", method.name, method.desc); + Counter id = this.injectorMethodIndices.get(descriptor); + if (id == null) { + id = new Counter(); + this.injectorMethodIndices.put(descriptor, id); + } else if (!surrogate) { + id.value++; + } + return String.format("%s$%s$%d", InjectionInfo.getInjectorPrefix(annotation), method.name, id.value); + } + + public String getUniqueName(MethodNode method) { + return String.format("md%s$%s$%d", this.sessionId.substring(30), method.name, this.nextUniqueMethodIndex++); + } + + public String getUniqueName(FieldNode field) { + return String.format("fd%s$%s$%d", this.sessionId.substring(30), field.name, this.nextUniqueFieldIndex++); + } + + /** + * Apply mixins to this class + */ + public void applyMixins() { + if (this.applied) { + throw new IllegalStateException("Mixins already applied to target class " + this.className); + } + this.applied = true; + MixinApplicatorStandard applicator = this.createApplicator(); + applicator.apply(this.mixins); + } + + private MixinApplicatorStandard createApplicator() { + if (this.classInfo.isInterface()) { + return new MixinApplicatorInterface(this); + } + return new MixinApplicatorStandard(this); + } + + + /** + * Process {@link Debug} annotations on the class after application + */ + public void processDebugTasks() { + if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERBOSE)) { + return; + } + + AnnotationNode classDebugAnnotation = ASMHelper.getVisibleAnnotation(this.classNode, Debug.class); + if (classDebugAnnotation != null) { + this.forceExport = Boolean.TRUE.equals(ASMHelper.getAnnotationValue(classDebugAnnotation, "export")); + if (Boolean.TRUE.equals(ASMHelper.getAnnotationValue(classDebugAnnotation, "print"))) { + ASMHelper.textify(this.classNode, System.err); + } + } + + for (MethodNode method : this.classNode.methods) { + AnnotationNode methodDebugAnnotation = ASMHelper.getVisibleAnnotation(method, Debug.class); + if (methodDebugAnnotation != null && Boolean.TRUE.equals(ASMHelper.getAnnotationValue(methodDebugAnnotation, "print"))) { + ASMHelper.textify(method, System.err); + } + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java index 9c9dfeb4..91a8b032 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java @@ -28,9 +28,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URLClassLoader; -import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraft.launchwrapper.Launch; - import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -38,6 +35,10 @@ import org.spongepowered.asm.lib.ClassReader; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.MixinTransformer.ReEntranceState; +import org.spongepowered.asm.util.launchwrapper.LaunchClassLoaderUtil; + +import net.minecraft.launchwrapper.IClassTransformer; +import net.minecraft.launchwrapper.Launch; /** * Base class for "info" objects which use ASM tree API to do stuff, with things @@ -86,16 +87,16 @@ abstract class TreeInfo { protected static byte[] loadClass(String className, boolean runTransformers) throws ClassNotFoundException, IOException { String transformedName = className.replace('/', '.'); String name = MixinEnvironment.getCurrentEnvironment().unmap(transformedName); - byte[] classBytes = null; - - if ((classBytes = TreeInfo.getClassBytes(name, transformedName)) == null) { - throw new ClassNotFoundException(String.format("The specified class '%s' was not found", transformedName)); - } + byte[] classBytes = TreeInfo.getClassBytes(name, transformedName); if (runTransformers) { classBytes = TreeInfo.applyTransformers(name, transformedName, classBytes); } + if (classBytes == null) { + throw new ClassNotFoundException(String.format("The specified class '%s' was not found", transformedName)); + } + return classBytes; } @@ -136,6 +137,10 @@ abstract class TreeInfo { * except the excluded transformers */ private static byte[] applyTransformers(String name, String transformedName, byte[] basicClass) { + if (LaunchClassLoaderUtil.forClassLoader(Launch.classLoader).isClassExcluded(name, transformedName)) { + return basicClass; + } + MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); for (IClassTransformer transformer : environment.getTransformers()) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java b/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java new file mode 100644 index 00000000..cca77c9a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java @@ -0,0 +1,51 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.debug; + +/** + * Interface to allow the hot-swap agent to be loaded on-demand + */ +public interface IHotSwap { + + /** + * Registers a mixin class with the agent. + * + * This is needed as the mixin needs to be loaded to be redefined. + * + * @param name Fully qualified name of the mixin class + */ + public abstract void registerMixinClass(String name); + + /** + * Registers a class targeted by at least one mixin. + * + * This is used to rollback the target class to a state before the mixin's + * where applied. + * + * @param name Name of the class + * @param bytecode Bytecode of the class before mixin's have been applied + */ + public abstract void registerTargetClass(String name, byte[] bytecode); +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java index 28e9922f..9af19373 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java @@ -29,14 +29,14 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.spongepowered.asm.mixin.transformer.MixinApplicator; +import org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard; /** *

For internal use only! Contains small parts. Keep out of reach of * children.

* - *

Decoration annotation used by the {@link MixinApplicator} to mark methods - * in a class which have been added or overwritten by a mixin.

+ *

Decoration annotation used by the {@link MixinApplicatorStandard} to mark + * methods in a class which have been added or overwritten by a mixin.

*/ @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java index 23322b28..7a5634cf 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java @@ -29,7 +29,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** *

Internal use only.

* diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidInterfaceMixinException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidInterfaceMixinException.java new file mode 100644 index 00000000..e7467064 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidInterfaceMixinException.java @@ -0,0 +1,61 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.throwables; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; + +/** + * Exception thrown for bad states when parsing/loading interface mixins + */ +public class InvalidInterfaceMixinException extends InvalidMixinException { + + private static final long serialVersionUID = 2L; + + public InvalidInterfaceMixinException(IMixinInfo mixin, String message) { + super(mixin, message); + } + + public InvalidInterfaceMixinException(IReferenceMapperContext context, String message) { + super(context, message); + } + + public InvalidInterfaceMixinException(IMixinInfo mixin, Throwable cause) { + super(mixin, cause); + } + + public InvalidInterfaceMixinException(IReferenceMapperContext context, Throwable cause) { + super(context, cause); + } + + public InvalidInterfaceMixinException(IMixinInfo mixin, String message, Throwable cause) { + super(mixin, message, cause); + } + + public InvalidInterfaceMixinException(IReferenceMapperContext context, String message, Throwable cause) { + super(context, message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InvalidMixinException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java similarity index 57% rename from src/main/java/org/spongepowered/asm/mixin/transformer/InvalidMixinException.java rename to src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java index 27a51454..2d87c77a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InvalidMixinException.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java @@ -22,45 +22,50 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; +package org.spongepowered.asm.mixin.transformer.throwables; -public class InvalidMixinException extends RuntimeException { +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext; +import org.spongepowered.asm.mixin.throwables.MixinException; - private static final long serialVersionUID = 1L; +/** + * Thrown by the mixin validator when a mixin fails a pre-flight check + */ +public class InvalidMixinException extends MixinException { + + private static final long serialVersionUID = 2L; - private final MixinInfo mixin; + private final IMixinInfo mixin; - public InvalidMixinException(MixinInfo mixin, String message) { + public InvalidMixinException(IMixinInfo mixin, String message) { super(message); this.mixin = mixin; } - public InvalidMixinException(MixinTargetContext mixin, String message) { - super(message); - this.mixin = mixin.getInfo(); + public InvalidMixinException(IReferenceMapperContext context, String message) { + this(context.getMixin(), message); } - public InvalidMixinException(MixinInfo mixin, Throwable message) { - super(message); + public InvalidMixinException(IMixinInfo mixin, Throwable cause) { + super(cause); this.mixin = mixin; } - public InvalidMixinException(MixinTargetContext mixin, Throwable message) { - super(message); - this.mixin = mixin.getInfo(); + public InvalidMixinException(IReferenceMapperContext context, Throwable cause) { + this(context.getMixin(), cause); } - public InvalidMixinException(MixinInfo mixin, String message, Throwable cause) { + public InvalidMixinException(IMixinInfo mixin, String message, Throwable cause) { super(message, cause); this.mixin = mixin; } - public InvalidMixinException(MixinTargetContext mixin, String message, Throwable cause) { + public InvalidMixinException(IReferenceMapperContext context, String message, Throwable cause) { super(message, cause); - this.mixin = mixin.getInfo(); + this.mixin = context.getMixin(); } - public MixinInfo getMixin() { + public IMixinInfo getMixin() { return this.mixin; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinReloadException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinReloadException.java new file mode 100644 index 00000000..f35e3118 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinReloadException.java @@ -0,0 +1,49 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.throwables; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * An exception that occurs when a mixin reloads and does something it is + * normally allowed to do but isn't due to reloading restrictions. + */ +public class MixinReloadException extends MixinException { + + private static final long serialVersionUID = 2L; + + private final IMixinInfo mixinInfo; + + public MixinReloadException(IMixinInfo mixinInfo, String message) { + super(message); + this.mixinInfo = mixinInfo; + } + + public IMixinInfo getMixinInfo() { + return this.mixinInfo; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTargetAlreadyLoadedException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTargetAlreadyLoadedException.java new file mode 100644 index 00000000..613ad74c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTargetAlreadyLoadedException.java @@ -0,0 +1,52 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.throwables; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +/** + * Exception thrown when a specified mixin target was already classloaded. + */ +public class MixinTargetAlreadyLoadedException extends InvalidMixinException { + + private static final long serialVersionUID = 1L; + + private final String target; + + public MixinTargetAlreadyLoadedException(IMixinInfo mixin, String message, String target) { + super(mixin, message); + this.target = target; + } + + public MixinTargetAlreadyLoadedException(IMixinInfo mixin, String message, String target, Throwable cause) { + super(mixin, message, cause); + this.target = target; + } + + public String getTarget() { + return this.target; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerError.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java similarity index 96% rename from src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerError.java rename to src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java index 6b0f9978..103e6660 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerError.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java @@ -22,8 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; - +package org.spongepowered.asm.mixin.transformer.throwables; /** * Error to throw for things which really shouldn't happen diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java b/src/main/java/org/spongepowered/asm/mixin/transformer/verify/MixinVerifier.java similarity index 95% rename from src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java rename to src/main/java/org/spongepowered/asm/mixin/transformer/verify/MixinVerifier.java index c7869a82..3e0a93e8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/verify/MixinVerifier.java @@ -22,13 +22,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.mixin.transformer; +package org.spongepowered.asm.mixin.transformer.verify; import java.util.List; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.analysis.SimpleVerifier; - +import org.spongepowered.asm.mixin.transformer.ClassInfo; /** * Verifier which handles class info lookups via {@link ClassInfo} @@ -94,6 +94,9 @@ public class MixinVerifier extends SimpleVerifier { return false; } ClassInfo typeInfo = ClassInfo.forType(type); + if (typeInfo == null) { + return false; + } if (typeInfo.isInterface()) { typeInfo = ClassInfo.forName("java/lang/Object"); } diff --git a/src/main/java/org/spongepowered/asm/obfuscation/RemapperChain.java b/src/main/java/org/spongepowered/asm/obfuscation/RemapperChain.java new file mode 100644 index 00000000..926c0358 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/RemapperChain.java @@ -0,0 +1,115 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.obfuscation; + +import java.util.ArrayList; +import java.util.List; + +import org.spongepowered.asm.mixin.extensibility.IRemapper; + +/** + * Mixin environment remapper chain. Contains all remappers for the current + * environment to facilitate remapping via all registered remappers. + */ +public class RemapperChain implements IRemapper { + + private final List remappers = new ArrayList(); + + @Override + public String toString() { + return String.format("RemapperChain[%d]", this.remappers.size()); + } + + public RemapperChain add(IRemapper remapper) { + this.remappers.add(remapper); + return this; + } + + @Override + public String mapMethodName(String owner, String name, String desc) { + for (IRemapper remapper : this.remappers) { + String newName = remapper.mapMethodName(owner, name, desc); + if (newName != null && !newName.equals(name)) { + name = newName; + } + } + return name; + } + + @Override + public String mapFieldName(String owner, String name, String desc) { + for (IRemapper remapper : this.remappers) { + String newName = remapper.mapFieldName(owner, name, desc); + if (newName != null && !newName.equals(name)) { + name = newName; + } + } + return name; + } + + @Override + public String map(String typeName) { + for (IRemapper remapper : this.remappers) { + String newName = remapper.map(typeName); + if (newName != null && !newName.equals(typeName)) { + typeName = newName; + } + } + return typeName; + } + + @Override + public String unmap(String typeName) { + for (IRemapper remapper : this.remappers) { + String newName = remapper.unmap(typeName); + if (newName != null && !newName.equals(typeName)) { + typeName = newName; + } + } + return typeName; + } + + @Override + public String mapDesc(String desc) { + for (IRemapper remapper : this.remappers) { + String newDesc = remapper.mapDesc(desc); + if (newDesc != null && !newDesc.equals(desc)) { + desc = newDesc; + } + } + return desc; + } + + @Override + public String unmapDesc(String desc) { + for (IRemapper remapper : this.remappers) { + String newDesc = remapper.unmapDesc(desc); + if (newDesc != null && !newDesc.equals(desc)) { + desc = newDesc; + } + } + return desc; + } +} diff --git a/src/main/java/org/spongepowered/asm/obfuscation/SrgContainer.java b/src/main/java/org/spongepowered/asm/obfuscation/SrgContainer.java new file mode 100644 index 00000000..86891539 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/SrgContainer.java @@ -0,0 +1,90 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.obfuscation; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; + +import org.spongepowered.asm.mixin.throwables.MixinException; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.io.Files; + +import joptsimple.internal.Strings; + +/** + * Ported from Srg2Source ( + * + * github.com/MinecraftForge/Srg2Source). + */ +public class SrgContainer { + + private final BiMap packageMap = HashBiMap.create(); + private final BiMap classMap = HashBiMap.create(); + private final BiMap fieldMap = HashBiMap.create(); + private final BiMap methodMap = HashBiMap.create(); + + public void readSrg(File srg) throws IOException { + for (String line : Files.readLines(srg, Charset.defaultCharset())) { + if (Strings.isNullOrEmpty(line) || line.startsWith("#")) { + continue; + } + + String type = line.substring(0, 2); + String[] args = line.substring(4).split(" "); + + if (type.equals("PK")) { + this.packageMap.forcePut(args[0], args[1]); + } else if (type.equals("CL")) { + this.classMap.forcePut(args[0], args[1]); + } else if (type.equals("FD")) { + this.fieldMap.forcePut(new SrgField(args[0]), new SrgField(args[1])); + } else if (type.equals("MD")) { + this.methodMap.forcePut(new SrgMethod(args[0], args[1]), new SrgMethod(args[2], args[3])); + } else { + throw new MixinException("Invalid SRG file: " + srg); + } + } + } + + public SrgMethod getMethodMapping(SrgMethod methodName) { + return this.methodMap.get(methodName); + } + + public SrgField getFieldMapping(SrgField fieldName) { + return this.fieldMap.get(fieldName); + } + + public String getClassMapping(String className) { + return this.classMap.get(className); + } + + public String getPackageMapping(String packageName) { + return this.packageMap.get(packageName); + } + +} diff --git a/src/main/java/org/spongepowered/asm/obfuscation/SrgField.java b/src/main/java/org/spongepowered/asm/obfuscation/SrgField.java new file mode 100644 index 00000000..30f25b4f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/SrgField.java @@ -0,0 +1,89 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.obfuscation; + +import com.google.common.base.Objects; + +/** + * Stores information about an SRG field mapping during AP runs + */ +public final class SrgField { + + private final String mapping; + + public SrgField(String mapping) { + this.mapping = mapping; + } + + public String getName() { + if (this.mapping == null) { + return null; + } + int pos = this.mapping.lastIndexOf('/'); + return pos > -1 ? this.mapping.substring(pos + 1) : this.mapping; + } + + public String getOwner() { + if (this.mapping == null) { + return null; + } + int pos = this.mapping.lastIndexOf('/'); + return pos > -1 ? this.mapping.substring(0, pos) : null; + } + + public String getMapping() { + return this.mapping; + } + + public SrgField move(String newOwner) { + return new SrgField((newOwner != null ? newOwner + "/" : "") + this.getName()); + } + + public SrgField copy() { + return new SrgField(this.mapping); + } + + @Override + public int hashCode() { + return Objects.hashCode(this.mapping); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof SrgField) { + return Objects.equal(this.mapping, ((SrgField)obj).mapping); + } + return false; + } + + @Override + public String toString() { + return this.mapping; + } + +} \ No newline at end of file diff --git a/src/main/java/org/spongepowered/asm/obfuscation/SrgMethod.java b/src/main/java/org/spongepowered/asm/obfuscation/SrgMethod.java new file mode 100644 index 00000000..f0a9d8f6 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/obfuscation/SrgMethod.java @@ -0,0 +1,104 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.obfuscation; + +import com.google.common.base.Objects; + +/** + * Stores information about an SRG method mapping during AP runs + */ +public final class SrgMethod { + + private final String name; + private final String desc; + + public SrgMethod(String name, String desc) { + this.name = name; + this.desc = desc; + } + + public SrgMethod(String owner, String simpleName, String desc) { + this.name = SrgMethod.createName(owner, simpleName); + this.desc = desc; + } + + public String getName() { + return this.name; + } + + public String getSimpleName() { + if (this.name == null) { + return null; + } + int pos = this.name.lastIndexOf('/'); + return pos > -1 ? this.name.substring(pos + 1) : this.name; + } + + public String getOwner() { + if (this.name == null) { + return null; + } + int pos = this.name.lastIndexOf('/'); + return pos > -1 ? this.name.substring(0, pos) : null; + } + + public String getDesc() { + return this.desc; + } + + public SrgMethod move(String newOwner) { + return new SrgMethod(newOwner, this.getSimpleName(), this.desc); + } + + public SrgMethod copy() { + return new SrgMethod(this.name, this.desc); + } + + @Override + public int hashCode() { + return Objects.hashCode(this.name, this.desc); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof SrgMethod) { + return Objects.equal(this.name, ((SrgMethod)obj).name) && Objects.equal(this.desc, ((SrgMethod)obj).desc); + } + return false; + } + + @Override + public String toString() { + return String.format("%s %s", this.name, this.desc); + } + + private static String createName(String owner, String simpleName) { + return (owner != null ? owner + "/" : "") + simpleName; + } + +} diff --git a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java index cefca54d..ed2174db 100644 --- a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java +++ b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java @@ -24,13 +24,13 @@ */ package org.spongepowered.asm.transformers; -import net.minecraft.launchwrapper.IClassTransformer; - import org.spongepowered.asm.lib.ClassReader; import org.spongepowered.asm.lib.ClassWriter; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.transformer.MixinClassWriter; +import net.minecraft.launchwrapper.IClassTransformer; + /** * Base class for transformers which work with ASM tree model */ diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java index b22d18b3..ae21c867 100644 --- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java +++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java @@ -24,8 +24,10 @@ */ package org.spongepowered.asm.util; +import static com.google.common.base.Preconditions.*; import static org.spongepowered.asm.lib.ClassWriter.*; +import java.io.OutputStream; import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.util.ArrayList; @@ -36,16 +38,68 @@ import java.util.Map; import org.spongepowered.asm.lib.ClassReader; import org.spongepowered.asm.lib.ClassWriter; +import org.spongepowered.asm.lib.MethodVisitor; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.*; import org.spongepowered.asm.lib.util.CheckClassAdapter; +import org.spongepowered.asm.lib.util.TraceClassVisitor; +import com.google.common.primitives.Ints; + +/** + * Utility methods for working with ASM + */ public class ASMHelper { - private static final int[] intConstants = new int[] - {Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5}; + public static final int[] CONSTANTS_INT = { + Opcodes.ICONST_M1, Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5 + }; + public static final int[] CONSTANTS_FLOAT = { + Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2 + }; + + public static final int[] CONSTANTS_DOUBLE = { + Opcodes.DCONST_0, Opcodes.DCONST_1 + }; + + public static final int[] CONSTANTS_LONG = { + Opcodes.LCONST_0, Opcodes.LCONST_1 + }; + + public static final int[] CONSTANTS_ALL = { + Opcodes.ACONST_NULL, + Opcodes.ICONST_M1, + Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5, + Opcodes.LCONST_0, Opcodes.LCONST_1, + Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2, + Opcodes.DCONST_0, Opcodes.DCONST_1, + Opcodes.BIPUSH, // 15 + Opcodes.SIPUSH, // 16 + Opcodes.LDC, // 17 + }; + + private static final Object[] CONSTANTS_VALUES = { + null, + Integer.valueOf(-1), + Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), + Long.valueOf(0L), Long.valueOf(1L), + Float.valueOf(0.0F), Float.valueOf(1.0F), Float.valueOf(2.0F), + Double.valueOf(0.0), Double.valueOf(1.0) + }; + + private static final String[] CONSTANTS_TYPES = { + null, + "I", + "I", "I", "I", "I", "I", "I", + "J", "J", + "F", "F", "F", + "D", "D", + "I", //"B", + "I", //"S" + }; + /** * Generate a new method "boolean name()", which returns a constant value. * @@ -279,7 +333,7 @@ public class ASMHelper { if (c == -1) { return new InsnNode(Opcodes.ICONST_M1); } else if (c >= 0 && c <= 5) { - return new InsnNode(intConstants[c]); + return new InsnNode(ASMHelper.CONSTANTS_INT[c + 1]); } else if (c >= Byte.MIN_VALUE && c <= Byte.MAX_VALUE) { return new IntInsnNode(Opcodes.BIPUSH, c); } else if (c >= Short.MIN_VALUE && c <= Short.MAX_VALUE) { @@ -322,6 +376,32 @@ public class ASMHelper { clazz.methods.add(method); } + /** + * Runs textifier on the specified class node and dumps the output to the + * specified output stream + * + * @param classNode class to textify + * @param out output stream + */ + public static void textify(ClassNode classNode, OutputStream out) { + classNode.accept(new TraceClassVisitor(new PrintWriter(out))); + } + + /** + * Runs textifier on the specified method node and dumps the output to the + * specified output stream + * + * @param methodNode method to textify + * @param out output stream + */ + public static void textify(MethodNode methodNode, OutputStream out) { + TraceClassVisitor trace = new TraceClassVisitor(new PrintWriter(out)); + MethodVisitor mv = trace.visitMethod(methodNode.access, methodNode.name, methodNode.desc, methodNode.signature, + methodNode.exceptions.toArray(new String[0])); + methodNode.accept(mv); + trace.visitEnd(); + } + /** * Dumps the output of CheckClassAdapter.verify to System.out * @@ -342,6 +422,19 @@ public class ASMHelper { ClassReader cr = new ClassReader(bytes); CheckClassAdapter.verify(cr, true, new PrintWriter(System.out)); } + + /** + * Prints a representation of a method's instructions to stderr + * + * @param method Method to print + */ + public static void printMethodWithOpcodeIndices(MethodNode method) { + System.err.printf("%s%s\n", method.name, method.desc); + int i = 0; + for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { + System.err.printf("[%4d] %s\n", i++, ASMHelper.getNodeDescriptionForDebug(iter.next())); + } + } /** * Prints a representation of a method's instructions to stderr @@ -362,32 +455,36 @@ public class ASMHelper { * @param node Node to print */ public static void printNode(AbstractInsnNode node) { - System.err.printf("%-14s ", node.getClass().getSimpleName().replace("Node", "")); - if (node instanceof LabelNode) { - System.err.printf("[%s]", ((LabelNode)node).getLabel()); - } else if (node instanceof JumpInsnNode) { - System.err.printf("[%s] [%s]", ASMHelper.getOpcodeName(node), ((JumpInsnNode)node).label.getLabel()); - } else if (node instanceof VarInsnNode) { - System.err.printf("[%s] %d", ASMHelper.getOpcodeName(node), ((VarInsnNode)node).var); - } else if (node instanceof MethodInsnNode) { - MethodInsnNode mth = (MethodInsnNode)node; - System.err.printf("[%s] %s %s %s", ASMHelper.getOpcodeName(node), mth.owner, mth.name, mth.desc); - } else if (node instanceof FieldInsnNode) { - FieldInsnNode fld = (FieldInsnNode)node; - System.err.printf("[%s] %s %s %s", ASMHelper.getOpcodeName(node), fld.owner, fld.name, fld.desc); - } else if (node instanceof LineNumberNode) { - LineNumberNode ln = (LineNumberNode)node; - System.err.printf("LINE=%d LABEL=[%s]", ln.line, ln.start.getLabel()); - } else if (node instanceof LdcInsnNode) { - System.err.print(((LdcInsnNode)node).cst); - } else if (node instanceof IntInsnNode) { - System.err.print(((IntInsnNode)node).operand); - } else { - System.err.printf("[%s] ", ASMHelper.getOpcodeName(node)); - } - System.err.print("\n"); + System.err.printf("%s\n", ASMHelper.getNodeDescriptionForDebug(node)); } + public static String getNodeDescriptionForDebug(AbstractInsnNode node) { + String out = String.format("%-14s ", node.getClass().getSimpleName().replace("Node", "")); + if (node instanceof LabelNode) { + out += String.format("[%s]", ((LabelNode)node).getLabel()); + } else if (node instanceof JumpInsnNode) { + out += String.format("[%s] [%s]", ASMHelper.getOpcodeName(node), ((JumpInsnNode)node).label.getLabel()); + } else if (node instanceof VarInsnNode) { + out += String.format("[%s] %d", ASMHelper.getOpcodeName(node), ((VarInsnNode)node).var); + } else if (node instanceof MethodInsnNode) { + MethodInsnNode mth = (MethodInsnNode)node; + out += String.format("[%s] %s %s %s", ASMHelper.getOpcodeName(node), mth.owner, mth.name, mth.desc); + } else if (node instanceof FieldInsnNode) { + FieldInsnNode fld = (FieldInsnNode)node; + out += String.format("[%s] %s %s %s", ASMHelper.getOpcodeName(node), fld.owner, fld.name, fld.desc); + } else if (node instanceof LineNumberNode) { + LineNumberNode ln = (LineNumberNode)node; + out += String.format("LINE=%d LABEL=[%s]", ln.line, ln.start.getLabel()); + } else if (node instanceof LdcInsnNode) { + out += (((LdcInsnNode)node).cst); + } else if (node instanceof IntInsnNode) { + out += (((IntInsnNode)node).operand); + } else { + out += String.format("[%s] ", ASMHelper.getOpcodeName(node)); + } + return out; + } + /** * Uses reflection to find an approximate constant name match for the * supplied node's opcode @@ -734,6 +831,7 @@ public class ASMHelper { */ @SuppressWarnings("unchecked") public static T getAnnotationValue(AnnotationNode annotation, String key, Class annotationClass) { + checkNotNull(annotationClass, "annotationClass cannot be null"); T value = ASMHelper.getAnnotationValue(annotation, key); if (value == null) { try { @@ -898,4 +996,127 @@ public class ASMHelper { return labels; } + + /** + * @param returnType + * @param args + */ + public static String generateDescriptor(Object returnType, Object... args) { + StringBuilder sb = new StringBuilder().append('('); + + for (Object arg : args) { + sb.append(ASMHelper.toDescriptor(arg)); + } + + return sb.append(')').append(returnType != null ? ASMHelper.toDescriptor(returnType) : "V").toString(); + } + + /** + * @param arg + */ + private static String toDescriptor(Object arg) { + if (arg instanceof String) { + return (String)arg; + } else if (arg instanceof Type) { + return arg.toString(); + } else if (arg instanceof Class) { + return Type.getDescriptor((Class)arg).toString(); + } + return arg == null ? "" : arg.toString(); + } + + public static String getSimpleName(Class annotationType) { + return annotationType.getSimpleName(); + } + + public static String getSimpleName(AnnotationNode annotation) { + return ASMHelper.getSimpleName(annotation.desc); + } + + public static String getSimpleName(String desc) { + return desc.substring(desc.lastIndexOf('/') + 1).replace(";", ""); + } + + public static boolean isConstant(AbstractInsnNode insn) { + if (insn == null) { + return false; + } + return Ints.contains(ASMHelper.CONSTANTS_ALL, insn.getOpcode()); + } + + public static Object getConstant(AbstractInsnNode insn) { + if (insn == null) { + return null; + } else if (insn instanceof LdcInsnNode) { + return ((LdcInsnNode)insn).cst; + } else if (insn instanceof IntInsnNode) { + int value = ((IntInsnNode)insn).operand; + if (insn.getOpcode() == Opcodes.BIPUSH || insn.getOpcode() == Opcodes.SIPUSH) { + return Integer.valueOf(value); + } + throw new IllegalArgumentException("IntInsnNode with invalid opcode " + insn.getOpcode() + " in getConstant"); + } + + int index = Ints.indexOf(ASMHelper.CONSTANTS_ALL, insn.getOpcode()); + return index < 0 ? null : ASMHelper.CONSTANTS_VALUES[index]; + } + + public static Type getConstantType(AbstractInsnNode insn) { + if (insn == null) { + return null; + } else if (insn instanceof LdcInsnNode) { + Object cst = ((LdcInsnNode)insn).cst; + if (cst instanceof Integer) { + return Type.getType("I"); + } else if (cst instanceof Float) { + return Type.getType("F"); + } else if (cst instanceof Long) { + return Type.getType("J"); + } else if (cst instanceof Double) { + return Type.getType("D"); + } else if (cst instanceof String) { + return Type.getType(Constants.STRING); + } else if (cst instanceof Type) { + return Type.getType(Constants.CLASS); + } + throw new IllegalArgumentException("LdcInsnNode with invalid payload type " + cst.getClass() + " in getConstant"); + } + + int index = Ints.indexOf(ASMHelper.CONSTANTS_ALL, insn.getOpcode()); + return index < 0 ? null : Type.getType(ASMHelper.CONSTANTS_TYPES[index]); + } + + /** + * Check whether the specified flag is set on the specified class + * + * @param classNode + * @param flag + * @return True if the specified flag is set in this method's access flags + */ + public static boolean hasFlag(ClassNode classNode, int flag) { + return (classNode.access & flag) == flag; + } + + /** + * Check whether the specified flag is set on the specified method + * + * @param method + * @param flag + * @return True if the specified flag is set in this method's access flags + */ + public static boolean hasFlag(MethodNode method, int flag) { + return (method.access & flag) == flag; + } + + /** + * Check whether the specified flag is set on the specified field + * + * @param field + * @param flag + * @return True if the specified flag is set in this field's access flags + */ + public static boolean hasFlag(FieldNode field, int flag) { + return (field.access & flag) == flag; + } + } diff --git a/src/main/java/org/spongepowered/asm/util/Constants.java b/src/main/java/org/spongepowered/asm/util/Constants.java index ce791d4b..e3cb559d 100644 --- a/src/main/java/org/spongepowered/asm/util/Constants.java +++ b/src/main/java/org/spongepowered/asm/util/Constants.java @@ -26,18 +26,37 @@ package org.spongepowered.asm.util; import org.spongepowered.asm.mixin.Mixin; - /** * Miscellaneous shared constants */ public abstract class Constants { - public static final String INIT = ""; + public static final String CTOR = ""; public static final String CLINIT = ""; public static final String IMAGINARY_SUPER = "super$"; public static final String DEBUG_OUTPUT_PATH = ".mixin.out"; public static final String MIXIN_PACKAGE = Mixin.class.getPackage().getName(); public static final String MIXIN_PACKAGE_REF = Constants.MIXIN_PACKAGE.replace('.', '/'); + public static final String STRING = "Ljava/lang/String;"; + public static final String OBJECT = "Ljava/lang/Object;"; + public static final String CLASS = "Ljava/lang/Class;"; + private Constants() {} + + /** + * Shared Jar Manifest Attributes + */ + public abstract static class ManifestAttributes { + + public static final String TWEAKER = "TweakClass"; + public static final String MAINCLASS = "Main-Class"; + public static final String MIXINCONFIGS = "MixinConfigs"; + public static final String TOKENPROVIDERS = "MixinTokenProviders"; + + @Deprecated + public static final String COMPATIBILITY = "MixinCompatibilityLevel"; + + private ManifestAttributes() {} + } } diff --git a/src/main/java/org/spongepowered/asm/util/ConstraintParser.java b/src/main/java/org/spongepowered/asm/util/ConstraintParser.java index fdabbc76..4ef7af17 100644 --- a/src/main/java/org/spongepowered/asm/util/ConstraintParser.java +++ b/src/main/java/org/spongepowered/asm/util/ConstraintParser.java @@ -28,7 +28,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.spongepowered.asm.lib.tree.AnnotationNode; - +import org.spongepowered.asm.util.throwables.ConstraintViolationException; +import org.spongepowered.asm.util.throwables.InvalidConstraintException; /** * Parser for constraints diff --git a/src/main/java/org/spongepowered/asm/util/ITokenProvider.java b/src/main/java/org/spongepowered/asm/util/ITokenProvider.java index c86decc9..b63c2ef4 100644 --- a/src/main/java/org/spongepowered/asm/util/ITokenProvider.java +++ b/src/main/java/org/spongepowered/asm/util/ITokenProvider.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.util; - /** * Agent which can supply token values to a * {@link org.spongepowered.asm.util.ConstraintParser.Constraint}. diff --git a/src/main/java/org/spongepowered/asm/util/JavaVersion.java b/src/main/java/org/spongepowered/asm/util/JavaVersion.java new file mode 100644 index 00000000..342d6dfc --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/JavaVersion.java @@ -0,0 +1,55 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Small helper to resolve the current java version + */ +public abstract class JavaVersion { + + private static double current = 0.0; + + private JavaVersion() {} + + public static double current() { + if (JavaVersion.current == 0.0) { + JavaVersion.current = JavaVersion.resolveCurrentVersion(); + } + return JavaVersion.current; + } + + private static double resolveCurrentVersion() { + String version = System.getProperty("java.version"); + Matcher matcher = Pattern.compile("[0-9]+\\.[0-9]+").matcher(version); + if (matcher.find()) { + return Double.parseDouble(matcher.group()); + } + return 1.6; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index d1cf5feb..81603529 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -47,8 +47,9 @@ import org.spongepowered.asm.lib.tree.analysis.BasicValue; import org.spongepowered.asm.lib.tree.analysis.Frame; import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.ClassInfo.FrameData; -import org.spongepowered.asm.mixin.transformer.MixinVerifier; - +import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; +import org.spongepowered.asm.mixin.transformer.verify.MixinVerifier; +import org.spongepowered.asm.util.throwables.LVTGeneratorException; /** * Utility methods for working with local variables using ASM @@ -71,10 +72,10 @@ public class Locals { * @param pos Start position */ public static void loadLocals(Type[] locals, InsnList insns, int pos, int limit) { - limit += pos; - for (; pos < locals.length && pos < limit; pos++) { + for (; pos < locals.length && limit > 0; pos++) { if (locals[pos] != null) { insns.add(new VarInsnNode(locals[pos].getOpcode(Opcodes.ILOAD), pos)); + limit--; } } } @@ -126,7 +127,15 @@ public class Locals { node = Locals.nextNode(method.instructions, node); } - List frames = ClassInfo.forName(classNode.name).findMethod(method).getFrames(); + ClassInfo classInfo = ClassInfo.forName(classNode.name); + if (classInfo == null) { + throw new LVTGeneratorException("Could not load class metadata for " + classNode.name + " generating LVT for " + method.name); + } + Method methodInfo = classInfo.findMethod(method); + if (methodInfo == null) { + throw new LVTGeneratorException("Could not locate method metadata for " + method.name + " generating LVT in " + classNode.name); + } + List frames = methodInfo.getFrames(); LocalVariableNode[] frame = new LocalVariableNode[method.maxLocals]; int local = 0, index = 0; @@ -177,7 +186,7 @@ public class Locals { frame[framePos] = null; // TOP } } else { - throw new RuntimeException("Unrecognised locals opcode " + localType + " in locals array at position " + localPos + throw new LVTGeneratorException("Unrecognised locals opcode " + localType + " in locals array at position " + localPos + " in " + classNode.name + "." + method.name + method.desc); } } else if (localType == null) { @@ -185,7 +194,7 @@ public class Locals { frame[framePos] = null; } } else { - throw new RuntimeException("Invalid value " + localType + " in locals array at position " + localPos + throw new LVTGeneratorException("Invalid value " + localType + " in locals array at position " + localPos + " in " + classNode.name + "." + method.name + method.desc); } } @@ -220,23 +229,48 @@ public class Locals { * variable at the specified location in the specified local slot */ public static LocalVariableNode getLocalVariableAt(ClassNode classNode, MethodNode method, AbstractInsnNode node, int var) { + return Locals.getLocalVariableAt(classNode, method, method.instructions.indexOf(node), var); + } + + /** + * Attempts to locate the appropriate entry in the local variable table for + * the specified local variable index at the location specified by pos. + * + * @param classNode Containing class + * @param method Method + * @param var Local variable index + * @param pos The opcode index to get the local variable table at + * @return a LocalVariableNode containing information about the local + * variable at the specified location in the specified local slot + */ + private static LocalVariableNode getLocalVariableAt(ClassNode classNode, MethodNode method, int pos, int var) { LocalVariableNode localVariableNode = null; + LocalVariableNode fallbackNode = null; - int pos = method.instructions.indexOf(node); - - List localVariables = Locals.getLocalVariableTable(classNode, method); - for (LocalVariableNode local : localVariables) { + for (LocalVariableNode local : Locals.getLocalVariableTable(classNode, method)) { if (local.index != var) { continue; } - int start = method.instructions.indexOf(local.start); - int end = method.instructions.indexOf(local.end); - if (localVariableNode == null || start < pos && end > pos) { + if (Locals.isOpcodeInRange(method.instructions, local, pos)) { localVariableNode = local; + } else if (localVariableNode == null) { + fallbackNode = local; } } + + if (localVariableNode == null && !method.localVariables.isEmpty()) { + for (LocalVariableNode local : Locals.getGeneratedLocalVariableTable(classNode, method)) { + if (local.index == var && Locals.isOpcodeInRange(method.instructions, local, pos)) { + localVariableNode = local; + } + } + } + + return localVariableNode != null ? localVariableNode : fallbackNode; + } - return localVariableNode; + private static boolean isOpcodeInRange(InsnList insns, LocalVariableNode local, int pos) { + return insns.indexOf(local.start) < pos && insns.indexOf(local.end) > pos; } /** @@ -248,23 +282,32 @@ public class Locals { * * @param classNode Containing class * @param method Method - * @return generated local variable table + * @return local variable table */ public static List getLocalVariableTable(ClassNode classNode, MethodNode method) { if (method.localVariables.isEmpty()) { - String signature = String.format("%s.%s%s", classNode.name, method.name, method.desc); - - List localVars = Locals.calculatedLocalVariables.get(signature); - if (localVars != null) { - return localVars; - } - - localVars = Locals.generateLocalVariableTable(classNode, method); - Locals.calculatedLocalVariables.put(signature, localVars); + return Locals.getGeneratedLocalVariableTable(classNode, method); + } + return method.localVariables; + } + + /** + * Gets the generated the local variable table for the specified method. + * + * @param classNode Containing class + * @param method Method + * @return generated local variable table + */ + public static List getGeneratedLocalVariableTable(ClassNode classNode, MethodNode method) { + String methodId = String.format("%s.%s%s", classNode.name, method.name, method.desc); + List localVars = Locals.calculatedLocalVariables.get(methodId); + if (localVars != null) { return localVars; } - return method.localVariables; + localVars = Locals.generateLocalVariableTable(classNode, method); + Locals.calculatedLocalVariables.put(methodId, localVars); + return localVars; } /** diff --git a/src/main/java/org/spongepowered/asm/util/ObfuscationUtil.java b/src/main/java/org/spongepowered/asm/util/ObfuscationUtil.java new file mode 100644 index 00000000..5dc69656 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/ObfuscationUtil.java @@ -0,0 +1,99 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +/** + * Utility methods for obfuscation tasks + */ +public abstract class ObfuscationUtil { + + /** + * Interface for remapper proxies + */ + public interface IClassRemapper { + + /** + * Map type name to the new name. Subclasses can override. + * + * @param typeName Class name to convert + * @return new name for the class + */ + public abstract String map(String typeName); + + /** + * Convert a mapped type name back to the original obfuscated name + * + * @param typeName Class name to convert + * @return old name for the class + */ + public abstract String unmap(String typeName); + + } + + private ObfuscationUtil() {} + + public static String mapDescriptor(String desc, IClassRemapper remapper) { + return ObfuscationUtil.remapDescriptor(desc, remapper, false); + } + + public static String unmapDescriptor(String desc, IClassRemapper remapper) { + return ObfuscationUtil.remapDescriptor(desc, remapper, true); + } + + private static String remapDescriptor(String desc, IClassRemapper remapper, boolean unmap) { + StringBuilder sb = new StringBuilder(); + StringBuilder token = null; + + for (int pos = 0; pos < desc.length(); pos++) { + char c = desc.charAt(pos); + if (token != null) { + if (c == ';') { + sb.append('L').append(ObfuscationUtil.remap(token.toString(), remapper, unmap)).append(';'); + token = null; + } else { + token.append(c); + } + continue; + } + if (c == 'L') { + token = new StringBuilder(); + } else { + sb.append(c); + } + } + + if (token != null) { + throw new IllegalArgumentException("Invalid descriptor '" + desc + "', missing ';'"); + } + + return sb.toString(); + } + + private static Object remap(String typeName, IClassRemapper remapper, boolean unmap) { + String result = unmap ? remapper.unmap(typeName) : remapper.map(typeName); + return result != null ? result : typeName; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java index 2c39b880..064dc7a5 100644 --- a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java +++ b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java @@ -26,45 +26,395 @@ package org.spongepowered.asm.util; import java.io.PrintStream; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.base.Strings; - /** * Prints information in a pretty box */ public class PrettyPrinter { /** - * "Horizontal rule" marker + * Interface for object which supports printing to pretty printer */ - private static final char HR = '\253'; + public interface IPrettyPrintable { + + /** + * Append this objec to specified pretty printer + * + * @param printer printer to append to + */ + public abstract void print(PrettyPrinter printer); + + } + + /** + * Interface for objects which need their width calculated prior to printing + */ + interface IVariableWidthEntry { + + public abstract int getWidth(); + + } + + /** + * Interface for objects which control their own output format + */ + interface ISpecialEntry { + + } + + /** + * A key/value pair for convenient printing + */ + class KeyValue implements PrettyPrinter.IVariableWidthEntry { + + private final String key; + + private final Object value; + + public KeyValue(String key, Object value) { + this.key = key; + this.value = value; + } + + @Override + public String toString() { + return String.format(PrettyPrinter.this.kvFormat, this.key, this.value); + } + + @Override + public int getWidth() { + return this.toString().length(); + } + + } + + /** + * Horizontal rule + */ + class HorizontalRule implements PrettyPrinter.ISpecialEntry { + + private final char[] hrChars; + + public HorizontalRule(char... hrChars) { + this.hrChars = hrChars; + } + + @Override + public String toString() { + return Strings.repeat(new String(this.hrChars), PrettyPrinter.this.width + 2); + } + + } + + /** + * Centred text + */ + class CentredText { + + private final Object centred; + + public CentredText(Object centred) { + this.centred = centred; + } + + @Override + public String toString() { + String text = this.centred.toString(); + return String.format("%" + (((PrettyPrinter.this.width - (text.length())) / 2) + text.length()) + "s", text); + } + + } + + /** + * Table column alignment + */ + public static enum Alignment { + LEFT, + RIGHT + } + + /** + * Table information, added to output in order to print header + */ + static class Table implements PrettyPrinter.IVariableWidthEntry { + + final List columns = new ArrayList(); + + final List rows = new ArrayList(); + + String format = "%s"; + + int colSpacing = 2; + + boolean addHeader = true; + + void headerAdded() { + this.addHeader = false; + } + + void setColSpacing(int spacing) { + this.colSpacing = Math.max(0, spacing); + this.updateFormat(); + } + + Table grow(int size) { + while (this.columns.size() < size) { + this.columns.add(new Column(this)); + } + this.updateFormat(); + return this; + } + + Column add(Column column) { + this.columns.add(column); + return column; + } + + Row add(Row row) { + this.rows.add(row); + return row; + } + + Column addColumn(String title) { + return this.add(new Column(this, title)); + } + + Column addColumn(Alignment align, int size, String title) { + return this.add(new Column(this, align, size, title)); + } + + Row addRow(Object... args) { + return this.add(new Row(this, args)); + } + + void updateFormat() { + String spacing = Strings.repeat(" ", this.colSpacing); + StringBuilder format = new StringBuilder(); + boolean addSpacing = false; + for (Column column : this.columns) { + if (addSpacing) { + format.append(spacing); + } + addSpacing = true; + format.append(column.getFormat()); + } + this.format = format.toString(); + } + + String getFormat() { + return this.format; + } + + Object[] getTitles() { + List titles = new ArrayList(); + for (Column column : this.columns) { + titles.add(column.getTitle()); + } + return titles.toArray(); + } + + @Override + public String toString() { + boolean nonEmpty = false; + String[] titles = new String[this.columns.size()]; + for (int col = 0; col < this.columns.size(); col++) { + titles[col] = this.columns.get(col).toString(); + nonEmpty |= !titles[col].isEmpty(); + } + return nonEmpty ? String.format(this.format, (Object[])titles) : null; + } + + @Override + public int getWidth() { + String str = this.toString(); + return str != null ? str.length() : 0; + } + + } + + /** + * Table column, internal + */ + static class Column { + + private final Table table; + + private Alignment align = Alignment.LEFT; + + private int minWidth = 1; + + private int maxWidth = Integer.MAX_VALUE; + + private int size = 0; + + private String title = ""; + + private String format = "%s"; + + Column(Table table) { + this.table = table; + } + + Column(Table table, String title) { + this(table); + this.title = title; + this.minWidth = title.length(); + this.updateFormat(); + } + + Column(Table table, Alignment align, int size, String title) { + this(table, title); + this.align = align; + this.size = size; + } + + void setAlignment(Alignment align) { + this.align = align; + this.updateFormat(); + } + + void setWidth(int width) { + if (width > this.size) { + this.size = width; + this.updateFormat(); + } + } + + void setMinWidth(int width) { + if (width > this.minWidth) { + this.minWidth = width; + this.updateFormat(); + } + } + + void setMaxWidth(int width) { + this.size = Math.min(this.size, this.maxWidth); + this.maxWidth = Math.max(1, width); + this.updateFormat(); + } + + void setTitle(String title) { + this.title = title; + this.setWidth(title.length()); + } + + private void updateFormat() { + int width = Math.min(this.maxWidth, this.size == 0 ? this.minWidth : this.size); + this.format = "%" + (this.align == Alignment.RIGHT ? "" : "-") + width + "s"; + this.table.updateFormat(); + } + + int getMaxWidth() { + return this.maxWidth; + } + + String getTitle() { + return this.title; + } + + String getFormat() { + return this.format; + } + + @Override + public String toString() { + if (this.title.length() > this.maxWidth) { + return this.title.substring(0, this.maxWidth); + } + + return this.title; + } + + } + + /** + * Table row, internal + */ + static class Row implements PrettyPrinter.IVariableWidthEntry { + + final Table table; + + final String[] args; + + public Row(Table table, Object... args) { + this.table = table.grow(args.length); + this.args = new String[args.length]; + for (int i = 0; i < args.length; i++) { + this.args[i] = args[i].toString(); + this.table.columns.get(i).setMinWidth(this.args[i].length()); + } + } + + @Override + public String toString() { + Object[] args = new Object[this.table.columns.size()]; + for (int col = 0; col < args.length; col++) { + Column column = this.table.columns.get(col); + if (col >= this.args.length) { + args[col] = ""; + } else { + args[col] = (this.args[col].length() > column.getMaxWidth()) ? this.args[col].substring(0, column.getMaxWidth()) : this.args[col]; + } + } + + return String.format(this.table.format, args); + } + + @Override + public int getWidth() { + return this.toString().length(); + } + + } + + /** + * Horizontal rule + */ + private final HorizontalRule horizontalRule = new HorizontalRule('*'); /** - * If specified as the first character on a line, centres the line + * Content lines */ - private static final char CENTRE = '\252'; + private final List lines = new ArrayList(); + + /** + * Table + */ + private Table table; + + /** + * True when a variable-width entry is added whose width must be calculated + * on print + */ + private boolean recalcWidth = false; /** * Box with (adapts to contents) */ - private int width = 100; + protected int width = 100; /** * Wrap width used when an explicit wrap width is not specified */ - private int wrapWidth = 80; + protected int wrapWidth = 80; /** - * Content lines + * Key/value key width */ - private final List lines = new ArrayList(); + protected int kvKeyWidth = 10; + + protected String kvFormat = PrettyPrinter.makeKvFormat(this.kvKeyWidth); public PrettyPrinter() { this(100); @@ -74,22 +424,162 @@ public class PrettyPrinter { this.width = width; } + /** + * Set the wrap width (default 80 columns) + * + * @param wrapWidth new width (in characters) to wrap to + * @return fluent interface + */ public PrettyPrinter wrapTo(int wrapWidth) { this.wrapWidth = wrapWidth; return this; } + /** + * Get the current wrap width + * + * @return the current wrap width + */ public int wrapTo() { return this.wrapWidth; } + + /** + * Begin a new table with no header and adaptive column widths + * + * @return fluent interface + */ + public PrettyPrinter table() { + this.table = new Table(); + return this; + } + + /** + * Begin a new table with the specified headers and adaptive column widths + * + * @param titles Column titles + * @return fluent interface + */ + public PrettyPrinter table(String... titles) { + this.table = new Table(); + for (String title : titles) { + this.table.addColumn(title); + } + return this; + } + /** + * Begin a new table with the specified format. The format is specified as a + * sequence of values with {@link String}s defining column titles, + * {@link Integer}s defining column widths, and {@link Alignment}s defining + * column alignments. Widths and alignment specifiers should follow the + * relevant column title. Specify a negative value to specify the + * maximum width for a column (values will be truncated). + * + *

For example, to specify a table with two columns of width 10:

+ * + * printer.table("Column 1", 10, "Column 2", 10); + * + *

A table with a column 30 characters wide and a right-aligned column 20 + * characters wide:

+ * + * printer.table("Column 1", 30, "Column 2", 20, Alignment.RIGHT); + * + * + * @param format + * @return fluent interface + */ + public PrettyPrinter table(Object... format) { + this.table = new Table(); + Column column = null; + for (Object entry : format) { + if (entry instanceof String) { + column = this.table.addColumn((String)entry); + } else if (entry instanceof Integer && column != null) { + int width = ((Integer)entry).intValue(); + if (width > 0) { + column.setWidth(width); + } else if (width < 0) { + column.setMaxWidth(-width); + } + } else if (entry instanceof Alignment && column != null) { + column.setAlignment((Alignment)entry); + } else if (entry != null) { + column = this.table.addColumn(entry.toString()); + } + } + return this; + } + + /** + * Set the column spacing for the current table. Default = 2 + * + * @param spacing Column spacing in characters + * @return fluent interface + */ + public PrettyPrinter spacing(int spacing) { + if (this.table == null) { + this.table = new Table(); + } + this.table.setColSpacing(spacing); + return this; + } + + /** + * Print the current table header. The table header is automatically printed + * before the first row if not explicitly specified by calling this method. + * + * @return fluent interface + */ + public PrettyPrinter th() { + return this.th(false); + } + + private PrettyPrinter th(boolean onlyIfNeeded) { + if (this.table == null) { + this.table = new Table(); + } + if (!onlyIfNeeded || this.table.addHeader) { + this.table.headerAdded(); + this.addLine(this.table); + } + return this; + } + + /** + * Print a table row with the specified values. If more columns are + * specified than exist in the table, then the table is automatically + * expanded. + * + * @param args column values + * @return fluent interface + */ + public PrettyPrinter tr(Object... args) { + this.th(true); + this.addLine(this.table.addRow(args)); + this.recalcWidth = true; + return this; + } + /** * Adds a blank line to the output * * @return fluent interface */ public PrettyPrinter add() { - this.lines.add(""); + this.addLine(""); + return this; + } + + /** + * Adds a string line to the output + * + * @param string format string + * @return fluent interface + */ + public PrettyPrinter add(String string) { + this.addLine(string); + this.width = Math.max(this.width, string.length()); return this; } @@ -103,7 +593,7 @@ public class PrettyPrinter { */ public PrettyPrinter add(String format, Object... args) { String line = String.format(format, args); - this.lines.add(line); + this.addLine(line); this.width = Math.max(this.width, line.length()); return this; } @@ -132,7 +622,139 @@ public class PrettyPrinter { return this; } - + + /** + * Add elements of the array to the output, one per line, with array indices + * + * @param array Array of objects to print + * @return fluent interface + */ + public PrettyPrinter addIndexed(Object[] array) { + int indexWidth = String.valueOf(array.length - 1).length(); + String format = "[%" + indexWidth + "d] %s"; + for (int index = 0; index < array.length; index++) { + this.add(format, index, array[index]); + } + + return this; + } + + /** + * Add elements of the collection to the output, one per line, with indices + * + * @param c Collection of objects to print + * @return fluent interface + */ + public PrettyPrinter addWithIndices(Collection c) { + return this.addIndexed(c.toArray()); + } + + /** + * Adds a pretty-printable object to the output, the object is responsible + * for adding its own representation to this printer + * + * @param printable object to add + * @return fluent interface + */ + public PrettyPrinter add(IPrettyPrintable printable) { + if (printable != null) { + printable.print(this); + } + return this; + } + + /** + * Print a formatted representation of the specified throwable with the + * default indent (4) + * + * @param th Throwable to print + * @return fluent interface + */ + public PrettyPrinter add(Throwable th) { + return this.add(th, 4); + } + + /** + * Print a formatted representation of the specified throwable with the + * specified indent + * + * @param th Throwable to print + * @param indent Indent size for stacktrace lines + * @return fluent interface + */ + public PrettyPrinter add(Throwable th, int indent) { + this.add("%s: %s", th.getClass().getName(), th.getMessage()); + return this.add(th.getStackTrace(), indent); + } + + /** + * Print a formatted representation of the specified stack trace with the + * specified indent + * + * @param stackTrace stack trace to print + * @param indent Indent size for stacktrace lines + * @return fluent interface + */ + public PrettyPrinter add(StackTraceElement[] stackTrace, int indent) { + String margin = Strings.repeat(" ", indent); + for (StackTraceElement st : stackTrace) { + this.add("%s%s", margin, st); + } + return this; + } + + /** + * Adds the specified object to the output + * + * @param object object to add + * @return fluent interface + */ + public PrettyPrinter add(Object object) { + return this.add(object, 0); + } + + /** + * Adds the specified object to the output + * + * @param object object to add + * @param indent indent amount + * @return fluent interface + */ + public PrettyPrinter add(Object object, int indent) { + String margin = Strings.repeat(" ", indent); + return this.append(object, indent, margin); + } + + private PrettyPrinter append(Object object, int indent, String margin) { + if (object instanceof String) { + return this.add("%s%s", margin, object); + } else if (object instanceof Iterable) { + for (Object entry : (Iterable)object) { + this.append(entry, indent, margin); + } + return this; + } else if (object instanceof Map) { + this.kvWidth(indent); + return this.add((Map)object); + } else if (object instanceof IPrettyPrintable) { + return this.add((IPrettyPrintable)object); + } else if (object instanceof Throwable) { + return this.add((Throwable)object, indent); + } else if (object.getClass().isArray()) { + return this.add((Object[])object, indent + "%s"); + } + return this.add("%s%s", margin, object); + } + + /** + * Adds a formatted line to the output, and attempts to wrap the line + * content to the current wrap width + * + * @param format format string + * @param args arguments + * + * @return fluent interface + */ public PrettyPrinter addWrapped(String format, Object... args) { return this.addWrapped(this.wrapWidth, format, args); } @@ -157,7 +779,7 @@ public class PrettyPrinter { try { for (String wrappedLine : this.getWrapped(width, line, indent)) { - this.lines.add(wrappedLine); + this.addLine(wrappedLine); } } catch (Exception ex) { this.add(line); @@ -185,6 +807,59 @@ public class PrettyPrinter { return lines; } + /** + * Add a formatted key/value pair to the output + * + * @param key Key + * @param format Value format + * @param args Value args + * @return fluent interface + */ + public PrettyPrinter kv(String key, String format, Object... args) { + return this.kv(key, String.format(format, args)); + } + + /** + * Add a key/value pair to the output + * + * @param key Key + * @param value Value + * @return fluent interface + */ + public PrettyPrinter kv(String key, Object value) { + this.addLine(new KeyValue(key, value)); + return this.kvWidth(key.length()); + } + + /** + * Set the minimum key display width + * + * @param width width to set + * @return fluent + */ + public PrettyPrinter kvWidth(int width) { + if (width > this.kvKeyWidth) { + this.kvKeyWidth = width; + this.kvFormat = PrettyPrinter.makeKvFormat(width); + } + this.recalcWidth = true; + return this; + } + + /** + * Add all values of the specified map to this printer as key/value pairs + * + * @param map Map with entries to add + * @return fluent + */ + public PrettyPrinter add(Map map) { + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey() == null ? "null" : entry.getKey().toString(); + this.kv(key, entry.getValue()); + } + return this; + } + /** * Adds a horizontal rule to the output * @@ -202,7 +877,7 @@ public class PrettyPrinter { * @return fluent interface */ public PrettyPrinter hr(char ruleChar) { - this.lines.add("" + PrettyPrinter.HR + ruleChar); + this.addLine(new HorizontalRule(ruleChar)); return this; } @@ -213,39 +888,211 @@ public class PrettyPrinter { */ public PrettyPrinter centre() { if (!this.lines.isEmpty()) { - this.lines.add(PrettyPrinter.CENTRE + this.lines.remove(this.lines.size() - 1)); + Object lastLine = this.lines.get(this.lines.size() - 1); + if (lastLine instanceof String) { + this.addLine(new CentredText(this.lines.remove(this.lines.size() - 1))); + } } return this; } + + private void addLine(Object line) { + if (line == null) { + return; + } + this.lines.add(line); + this.recalcWidth |= line instanceof PrettyPrinter.IVariableWidthEntry; + } + + /** + * Outputs this printer to stderr and to a logger decorated with the calling + * class name with level {@link Level#DEBUG} + * + * @return fluent interface + */ + public PrettyPrinter trace() { + return this.trace(PrettyPrinter.getDefaultLoggerName()); + } + /** + * Outputs this printer to stderr and to a logger decorated with the calling + * class name at the specified level + * + * @param level Log level to write messages + * @return fluent interface + */ + public PrettyPrinter trace(Level level) { + return this.trace(PrettyPrinter.getDefaultLoggerName(), level); + } + + /** + * Outputs this printer to stderr and to a logger decorated with specified + * name with level {@link Level#DEBUG} + * + * @param logger Logger name to write to + * @return fluent interface + */ + public PrettyPrinter trace(String logger) { + return this.trace(System.err, LogManager.getLogger(logger)); + } + + /** + * Outputs this printer to stderr and to a logger decorated with specified + * name with the specified level + * + * @param logger Logger name to write to + * @param level Log level to write messages + * @return fluent interface + */ + public PrettyPrinter trace(String logger, Level level) { + return this.trace(System.err, LogManager.getLogger(logger), level); + } + + /** + * Outputs this printer to stderr and to the supplied logger with level + * {@link Level#DEBUG} + * + * @param logger Logger to write to + * @return fluent interface + */ + public PrettyPrinter trace(Logger logger) { + return this.trace(System.err, logger); + } + + /** + * Outputs this printer to stderr and to the supplied logger with the + * specified level + * + * @param logger Logger to write to + * @param level Log level to write messages + * @return fluent interface + */ + public PrettyPrinter trace(Logger logger, Level level) { + return this.trace(System.err, logger, level); + } + + /** + * Outputs this printer to the specified stream and to a logger decorated + * with the calling class name with level {@link Level#DEBUG} + * + * @param stream Output stream to print to + * @return fluent interface + */ + public PrettyPrinter trace(PrintStream stream) { + return this.trace(stream, PrettyPrinter.getDefaultLoggerName()); + } + + /** + * Outputs this printer to the specified stream and to a logger decorated + * with the calling class name with the specified level + * + * @param stream Output stream to print to + * @param level Log level to write messages + * @return fluent interface + */ + public PrettyPrinter trace(PrintStream stream, Level level) { + return this.trace(stream, PrettyPrinter.getDefaultLoggerName(), level); + } + + /** + * Outputs this printer to the specified stream and to a logger with the + * specified name with level {@link Level#DEBUG} + * + * @param stream Output stream to print to + * @param logger Logger name to write to + * @return fluent interface + */ + public PrettyPrinter trace(PrintStream stream, String logger) { + return this.trace(stream, LogManager.getLogger(logger)); + } + + /** + * Outputs this printer to the specified stream and to a logger with the + * specified name at the specified level + * + * @param stream Output stream to print to + * @param logger Logger name to write to + * @param level Log level to write messages + * @return fluent interface + */ + public PrettyPrinter trace(PrintStream stream, String logger, Level level) { + return this.trace(stream, LogManager.getLogger(logger), level); + } + + /** + * Outputs this printer to the specified stream and to the supplied logger + * with level {@link Level#DEBUG} + * + * @param stream Output stream to print to + * @param logger Logger to write to + * @return fluent interface + */ + public PrettyPrinter trace(PrintStream stream, Logger logger) { + return this.trace(stream, logger, Level.DEBUG); + } + + /** + * Outputs this printer to the specified stream and to the supplied logger + * with at the specified level + * + * @param stream Output stream to print to + * @param logger Logger to write to + * @param level Log level to write messages + * @return fluent interface + */ + public PrettyPrinter trace(PrintStream stream, Logger logger, Level level) { + this.log(logger, level); + this.print(stream); + return this; + } + + /** + * Print this printer to stderr + * + * @return fluent interface + */ + public PrettyPrinter print() { + return this.print(System.err); + } + /** * Print this printer to the specified output * * @param stream stream to print to + * @return fluent interface */ - public void print(PrintStream stream) { - this.printHr(stream, '*'); - for (String line : this.lines) { - int len = line.length(); - if (len > 1 && line.charAt(0) == PrettyPrinter.HR) { - this.printHr(stream, line.charAt(1)); + public PrettyPrinter print(PrintStream stream) { + this.updateWidth(); + this.printSpecial(stream, this.horizontalRule); + for (Object line : this.lines) { + if (line instanceof ISpecialEntry) { + this.printSpecial(stream, (ISpecialEntry)line); } else { - if (len > 0 && line.charAt(0) == PrettyPrinter.CENTRE) { - String text = line.substring(1); - line = String.format("%" + (((this.width - (text.length())) / 2) + text.length()) + "s", text); - } - stream.printf("/* %-" + this.width + "s */\n", line); + this.printString(stream, line.toString()); } } - this.printHr(stream, '*'); + this.printSpecial(stream, this.horizontalRule); + return this; } - private void printHr(PrintStream stream, char... hrChars) { - stream.printf("/*%s*/\n", Strings.repeat(new String(hrChars), this.width + 2)); + private void printSpecial(PrintStream stream, ISpecialEntry line) { + stream.printf("/*%s*/\n", line.toString()); } - - public void log(Logger logger) { - this.log(logger, Level.INFO); + + private void printString(PrintStream stream, String string) { + if (string != null) { + stream.printf("/* %-" + this.width + "s */\n", string); + } + } + + /** + * Write this printer to the specified logger at {@link Level#INFO} + * + * @param logger logger to log to + * @return fluent interface + */ + public PrettyPrinter log(Logger logger) { + return this.log(logger, Level.INFO); } /** @@ -253,25 +1100,68 @@ public class PrettyPrinter { * * @param logger logger to log to * @param level log level + * @return fluent interface */ - public void log(Logger logger, Level level) { - this.logHr(logger, level, '*'); - for (String line : this.lines) { - int len = line.length(); - if (len > 1 && line.charAt(0) == PrettyPrinter.HR) { - this.logHr(logger, level, line.charAt(1)); + public PrettyPrinter log(Logger logger, Level level) { + this.updateWidth(); + this.logSpecial(logger, level, this.horizontalRule); + for (Object line : this.lines) { + if (line instanceof ISpecialEntry) { + this.logSpecial(logger, level, (ISpecialEntry)line); } else { - if (len > 0 && line.charAt(0) == PrettyPrinter.CENTRE) { - String text = line.substring(1); - line = String.format("%" + (((this.width - (text.length())) / 2) + text.length()) + "s", text); - } - logger.log(level, String.format("/* %-" + this.width + "s */", line)); + this.logString(logger, level, line.toString()); } } - this.logHr(logger, level, '*'); + this.logSpecial(logger, level, this.horizontalRule); + return this; + } + + private void logSpecial(Logger logger, Level level, ISpecialEntry line) { + logger.log(level, "/*{}*/", line.toString()); + } + + private void logString(Logger logger, Level level, String line) { + if (line != null) { + logger.log(level, String.format("/* %-" + this.width + "s */", line)); + } } - private void logHr(Logger logger, Level level, char... hrChars) { - logger.log(level, String.format("/*%s*/", Strings.repeat(new String(hrChars), this.width + 2))); + private void updateWidth() { + if (this.recalcWidth) { + this.recalcWidth = false; + for (Object line : this.lines) { + if (line instanceof IVariableWidthEntry) { + this.width = Math.min(4096, Math.max(this.width, ((IVariableWidthEntry)line).getWidth())); + } + } + } } + + private static String makeKvFormat(int keyWidth) { + return String.format("%%%ds : %%s", keyWidth); + } + + private static String getDefaultLoggerName() { + String name = new Throwable().getStackTrace()[2].getClassName(); + int pos = name.lastIndexOf('.'); + return pos == -1 ? name : name.substring(pos + 1); + } + + /** + * Convenience method, alternative to using Thread.dumpStack which + * prints to stderr in pretty-printed format. + */ + public static void dumpStack() { + new PrettyPrinter().add(new Exception("Stack trace")).print(System.err); + } + + /** + * Convenience methods, pretty-prints the specified throwable to stderr + * + * @param th Throwable to log + */ + public static void print(Throwable th) { + new PrettyPrinter().add(th).print(System.err); + } + } diff --git a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java index f5784843..9d610785 100644 --- a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java +++ b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java @@ -32,7 +32,6 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import com.google.common.base.Strings; - /** * Generates callback signature for callback pretty-print */ diff --git a/src/main/java/org/spongepowered/asm/util/VersionNumber.java b/src/main/java/org/spongepowered/asm/util/VersionNumber.java index a95e3068..50625e93 100644 --- a/src/main/java/org/spongepowered/asm/util/VersionNumber.java +++ b/src/main/java/org/spongepowered/asm/util/VersionNumber.java @@ -28,7 +28,6 @@ import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; - /** * Represents a software version number in major.minor.revision.build * format as a sequence of four shorts packed into a long. This is to diff --git a/src/main/java/org/spongepowered/asm/util/launchwrapper/LaunchClassLoaderUtil.java b/src/main/java/org/spongepowered/asm/util/launchwrapper/LaunchClassLoaderUtil.java new file mode 100644 index 00000000..8e916132 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/launchwrapper/LaunchClassLoaderUtil.java @@ -0,0 +1,196 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.launchwrapper; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import net.minecraft.launchwrapper.LaunchClassLoader; + +/** + * Utility class for reflecting into {@link LaunchClassLoader}. We do not + * write anything of the classloader fields, but we need to be able to read + * them to perform some validation tasks, and insert entries for mixin "classes" + * into the invalid classes set. + */ +public final class LaunchClassLoaderUtil { + + /** + * ClassLoader -> util mapping + */ + private static final Map utils = new HashMap(); + + /** + * ClassLoader for this util + */ + private final LaunchClassLoader classLoader; + + // Reflected fields + private Map> cachedClasses; + private final Set invalidClasses; + private final Set classLoaderExceptions; + private final Set transformerExceptions; + + /** + * Singleton, use factory to get an instance + * + * @param classLoader class loader + */ + private LaunchClassLoaderUtil(LaunchClassLoader classLoader) { + this.classLoader = classLoader; + this.cachedClasses = LaunchClassLoaderUtil.>>getField(classLoader, "cachedClasses"); + this.invalidClasses = LaunchClassLoaderUtil.>getField(classLoader, "invalidClasses"); + this.classLoaderExceptions = LaunchClassLoaderUtil.>getField(classLoader, "classLoaderExceptions"); + this.transformerExceptions = LaunchClassLoaderUtil.>getField(classLoader, "transformerExceptions"); + } + + /** + * Get the classloader + */ + public LaunchClassLoader getClassLoader() { + return this.classLoader; + } + + /** + * Get all loaded class names from the cache + */ + public Set getLoadedClasses() { + return this.getLoadedClasses(null); + } + + /** + * Get the names of loaded classes from the cache, filter using the supplied + * filter string + * + * @param filter filter string or null + * @return set of class names + */ + public Set getLoadedClasses(String filter) { + Set loadedClasses = new HashSet(); + for (String className : this.cachedClasses.keySet()) { + if (filter == null || className.startsWith(filter)) { + loadedClasses.add(className); + } + } + return loadedClasses; + } + + /** + * Get whether a class name exists in the cache (indicating it was loaded + * via the inner loader + * + * @param name class name + * @return true if the class name exists in the cache + */ + public boolean isClassLoaded(String name) { + if (this.cachedClasses != null && this.cachedClasses.containsKey(name)) { + return true; + } + + return false; + } + + /** + * Get whether the specified name or transformedName exist in either of the + * exclusion lists + * + * @param name class name + * @param transformedName transformed class name + * @return true if either exclusion list contains either of the names + */ + public boolean isClassExcluded(String name, String transformedName) { + for (final String exception : this.getClassLoaderExceptions()) { + if (transformedName.startsWith(exception) || name.startsWith(exception)) { + return true; + } + } + + for (final String exception : this.getTransformerExceptions()) { + if (transformedName.startsWith(exception) || name.startsWith(exception)) { + return true; + } + } + + return false; + } + + /** + * Stuff a class name directly into the invalidClasses set, this prevents + * the loader from classloading the named class. This is used by the mixin + * processor to prevent classloading of mixin classes + * + * @param name class name + */ + public void registerInvalidClass(String name) { + if (this.invalidClasses != null) { + this.invalidClasses.add(name); + } + } + + public Set getClassLoaderExceptions() { + if (this.classLoaderExceptions != null) { + return this.classLoaderExceptions; + } + return Collections.emptySet(); + } + + public Set getTransformerExceptions() { + if (this.transformerExceptions != null) { + return this.transformerExceptions; + } + return Collections.emptySet(); + } + + @SuppressWarnings("unchecked") + private static T getField(LaunchClassLoader classLoader, String fieldName) { + try { + Field field = LaunchClassLoader.class.getDeclaredField(fieldName); + field.setAccessible(true); + return (T)field.get(classLoader); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + /** + * Get the utility class for the supplied classloader + * + * @param classLoader classLoader to fetch utility wrapper for + * @return utility wrapper + */ + public static LaunchClassLoaderUtil forClassLoader(LaunchClassLoader classLoader) { + LaunchClassLoaderUtil util = LaunchClassLoaderUtil.utils.get(classLoader); + if (util == null) { + util = new LaunchClassLoaderUtil(classLoader); + LaunchClassLoaderUtil.utils.put(classLoader, util); + } + return util; + } +} diff --git a/src/main/java/org/spongepowered/asm/util/ConstraintViolationException.java b/src/main/java/org/spongepowered/asm/util/throwables/ConstraintViolationException.java similarity index 98% rename from src/main/java/org/spongepowered/asm/util/ConstraintViolationException.java rename to src/main/java/org/spongepowered/asm/util/throwables/ConstraintViolationException.java index 8165d805..581b9a0b 100644 --- a/src/main/java/org/spongepowered/asm/util/ConstraintViolationException.java +++ b/src/main/java/org/spongepowered/asm/util/throwables/ConstraintViolationException.java @@ -22,11 +22,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.util; +package org.spongepowered.asm.util.throwables; import org.spongepowered.asm.util.ConstraintParser.Constraint; - /** * Exception thrown when a constraint violation is encountered */ diff --git a/src/main/java/org/spongepowered/asm/util/InvalidConstraintException.java b/src/main/java/org/spongepowered/asm/util/throwables/InvalidConstraintException.java similarity index 97% rename from src/main/java/org/spongepowered/asm/util/InvalidConstraintException.java rename to src/main/java/org/spongepowered/asm/util/throwables/InvalidConstraintException.java index 984ca28f..9e821648 100644 --- a/src/main/java/org/spongepowered/asm/util/InvalidConstraintException.java +++ b/src/main/java/org/spongepowered/asm/util/throwables/InvalidConstraintException.java @@ -22,8 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.util; - +package org.spongepowered.asm.util.throwables; /** * Exception thrown when a constraint declaration is invalid diff --git a/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorException.java b/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorException.java new file mode 100644 index 00000000..012bac11 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorException.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.throwables; + +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Exception thrown when something goes horribly wrong whilst summoning the + * antichrist generating the LVT for a target method. + */ +public class LVTGeneratorException extends MixinException { + + private static final long serialVersionUID = 1L; + + public LVTGeneratorException(String message) { + super(message); + } + + public LVTGeneratorException(String message, Throwable cause) { + super(message, cause); + } + +}