diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java index 9ad10654..c38d961d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.extensibility; import java.util.List; +import java.util.Set; import org.objectweb.asm.tree.ClassNode; @@ -65,6 +66,16 @@ public interface IMixinConfigPlugin { */ public abstract boolean shouldApplyMixin(String targetClassName, String mixinClassName); + /** + * Called after all configurations are initialised, this allows this plugin to observe classes targetted by other mixin configs and optionally + * remove targets from its own set. The set myTargets is a direct view of the targets collection in this companion config and keys may be removed + * from this set to suppress mixins in this config which target the specified class. Adding keys to the set will have no effect. + * + * @param myTargets Target class set from the companion config + * @param otherTargets Target class set incorporating targets from all other configs, read-only + */ + public abstract void acceptTargets(Set myTargets, Set otherTargets); + /** * After mixins specified in the configuration have been processed, this method is called to allow the plugin to add any additional mixins to * load. It should return a list of mixin class names or return null if the plugin does not wish to append any mixins of its own. 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 556f3b9c..895fa538 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -46,8 +46,13 @@ import com.google.gson.annotations.SerializedName; /** * Mixin configuration bundle */ -class MixinConfig { +class MixinConfig implements Comparable { + /** + * Global order of mixin configs, used to determine ordering between configs with equivalent priority + */ + private static int configOrder = 0; + /** * Global list of mixin classes, so we can skip any duplicates */ @@ -63,6 +68,12 @@ class MixinConfig { */ private final transient Map> mixinMapping = new HashMap>(); + /** + * Configuration priority + */ + @SerializedName("priority") + private final int priority = 1000; + /** * Package containing all mixins. This package will be monitored by the transformer so that we can explode if some dummy tries to reference a * mixin class directly. @@ -100,6 +111,11 @@ class MixinConfig { @SerializedName("referenceMap") private String refMapperConfig; + /** + * Intrinsic order (for sorting configurations with identical priority) + */ + private final transient int order = MixinConfig.configOrder++; + /** * Name of the file this config was initialised from */ @@ -179,7 +195,10 @@ class MixinConfig { *

For this reason we will invoke the initialisation on the first call to either the hasMixinsFor() or getMixinsFor() * methods.

*/ - private void initialise() { + void initialise() { + if (this.initialised) { + return; + } this.initialised = true; this.initialiseMixins(this.mixinClasses, false); @@ -195,7 +214,9 @@ class MixinConfig { this.logger.warn("Mixin environment was unable to detect the current side, sided mixins will not be applied"); break; } - + } + + void postInitialise() { if (this.plugin != null) { List pluginMixins = this.plugin.getMixins(); this.initialiseMixins(pluginMixins, true); @@ -261,6 +282,20 @@ class MixinConfig { return this.refMapper; } + /** + * Get the companion plugin, if available + */ + public IMixinConfigPlugin getPlugin() { + return this.plugin; + } + + /** + * Get targets for this configuration + */ + public Set getTargets() { + return this.mixinMapping.keySet(); + } + /** * Check whether this configuration bundle has a mixin for the specified class * @@ -268,10 +303,6 @@ class MixinConfig { * @return */ public boolean hasMixinsFor(String targetClass) { - if (!this.initialised) { - this.initialise(); - } - return this.mixinMapping.containsKey(targetClass); } @@ -282,10 +313,6 @@ class MixinConfig { * @return */ public List getMixinsFor(String targetClass) { - if (!this.initialised) { - this.initialise(); - } - return this.mixinsFor(targetClass); } @@ -297,6 +324,20 @@ class MixinConfig { } return mixins; } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(MixinConfig other) { + if (other == null) { + return 0; + } + if (other.priority == this.priority) { + return this.order - other.order; + } + return (this.priority - other.priority); + } /** * Factory method, creates a new mixin configuration bundle from the specified configFile, which must be accessible on the classpath diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java index 5d7bd60b..744899a5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java @@ -163,6 +163,13 @@ public class MixinData { return target; } + /** + * Get the mixin priority + */ + public int getPriority() { + return this.info.getPriority(); + } + /** * Get all interfaces for this mixin */ diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinMerged.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinMerged.java new file mode 100644 index 00000000..24db89cd --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinMerged.java @@ -0,0 +1,50 @@ +/* + * This file is part of Sponge, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered.org + * 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.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + *

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

+ * + *

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

+ */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface MixinMerged { + /** + * Mixin which merged this method + */ + public String mixin(); + + /** + * Prioriy of the mixin which merged this method, used to allow mixins with higher priority to overwrite methods already overwritten by those + * with a lower priority. + */ + public int priority(); +} 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 98ae4566..37c5c3cc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -32,6 +32,9 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.UUID; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.Launch; @@ -43,6 +46,7 @@ import org.apache.logging.log4j.core.helpers.Booleans; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FieldNode; @@ -55,6 +59,8 @@ import org.spongepowered.asm.mixin.InvalidMixinException; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.transformers.TreeTransformer; import org.spongepowered.asm.util.ASMHelper; @@ -130,11 +136,24 @@ public class MixinTransformer extends TreeTransformer { */ private final List configs = new ArrayList(); + /** + * True once initialisation is done. All mixin configs needs to be initialised as late as possible in startup (so that other transformers have + * had time to register) but before any game classes are transformed. To do this we initialise the configs on the first call to {@link #transform} + * and this flag keeps track of when we've done this. + */ + private boolean initDone; + /** * Sanity check for this transformer. The transformer should never be re-entrant by design so we need to detect and warn when it happens. */ private int reEntranceCheck = 0; + /** + * 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 + */ + private final String sessionId = UUID.randomUUID().toString(); + /** * ctor */ @@ -159,6 +178,8 @@ public class MixinTransformer extends TreeTransformer { } } } + + Collections.sort(this.configs); } /* (non-Javadoc) @@ -172,19 +193,35 @@ public class MixinTransformer extends TreeTransformer { this.detectReEntrance(); } + if (!this.initDone) { + this.initConfigs(); + this.initDone = true; + } + try { + SortedSet mixins = null; + for (MixinConfig config : this.configs) { if (transformedName != null && transformedName.startsWith(config.getMixinPackage())) { throw new RuntimeException(String.format("%s is a mixin class and cannot be referenced directly", transformedName)); } if (config.hasMixinsFor(transformedName)) { - try { - basicClass = this.applyMixins(config, transformedName, basicClass); - } catch (InvalidMixinException th) { - this.logger.warn(String.format("Class mixin failed: %s %s", th.getClass().getName(), th.getMessage()), th); - th.printStackTrace(); + if (mixins == null) { + mixins = new TreeSet(); } + + // Get and sort mixins for the class + mixins.addAll(config.getMixinsFor(transformedName)); + } + } + + if (mixins != null) { + try { + basicClass = this.applyMixins(transformedName, basicClass, mixins); + } catch (InvalidMixinException th) { + this.logger.warn(String.format("Class mixin failed: %s %s", th.getClass().getName(), th.getMessage()), th); + th.printStackTrace(); } } @@ -194,6 +231,43 @@ public class MixinTransformer extends TreeTransformer { } } + /** + * Initialise mixin configs + */ + private void initConfigs() { + for (MixinConfig config : this.configs) { + try { + config.initialise(); + } catch (Exception ex) { + this.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + ex.getMessage(), ex); + } + } + + for (MixinConfig config : this.configs) { + IMixinConfigPlugin plugin = config.getPlugin(); + if (plugin == null) { + continue; + } + + Set otherTargets = new HashSet(); + for (MixinConfig otherConfig : this.configs) { + if (!otherConfig.equals(config)) { + otherTargets.addAll(otherConfig.getTargets()); + } + } + + plugin.acceptTargets(config.getTargets(), Collections.unmodifiableSet(otherTargets)); + } + + for (MixinConfig config : this.configs) { + try { + config.postInitialise(); + } catch (Exception ex) { + this.logger.error("Error encountered during mixin config postInit setp'" + config.getName() + "': " + ex.getMessage(), ex); + } + } + } + /** * If re-entrance is detected, attempt to find the source and log a warning */ @@ -218,19 +292,15 @@ public class MixinTransformer extends TreeTransformer { /** * Apply mixins for specified target class to the class described by the supplied byte array * - * @param config * @param transformedName * @param basicClass + * @param mixins * @return */ - private byte[] applyMixins(MixinConfig config, String transformedName, byte[] basicClass) { + private byte[] applyMixins(String transformedName, byte[] basicClass, SortedSet mixins) { // Tree for target class ClassNode targetClass = this.readClass(basicClass, true); - // Get and sort mixins for the class - List mixins = config.getMixinsFor(transformedName); - Collections.sort(mixins); - for (MixinInfo mixin : mixins) { this.logger.info("Mixing {} into {}", mixin.getName(), transformedName); this.applyMixin(transformedName, targetClass, mixin.createData(targetClass)); @@ -259,7 +329,7 @@ public class MixinTransformer extends TreeTransformer { * @param targetClass * @param mixins */ - protected void postTransform(String transformedName, ClassNode targetClass, List mixins) { + protected void postTransform(String transformedName, ClassNode targetClass, SortedSet mixins) { // Stub for subclasses } @@ -374,13 +444,7 @@ public class MixinTransformer extends TreeTransformer { String.format("Mixin classes cannot contain visible static methods or fields, found %s", mixinMethod.name)); } - MethodNode target = this.findTargetMethod(targetClass, mixinMethod); - if (target != null) { - targetClass.methods.remove(target); - } else if (isOverwrite) { - throw new InvalidMixinException(String.format("Overwrite target %s was not located in the target class", mixinMethod.name)); - } - targetClass.methods.add(mixinMethod); + this.mergeMethod(targetClass, mixin, mixinMethod, isOverwrite); } else if (MixinTransformer.CLINIT.equals(mixinMethod.name)) { // Class initialiser insns get appended this.appendInsns(targetClass, mixinMethod.name, mixinMethod); @@ -441,6 +505,48 @@ public class MixinTransformer extends TreeTransformer { } } + /** + * Attempts to merge the supplied method into the target class + * + * @param targetClass Target class to merge into + * @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(ClassNode targetClass, MixinData mixin, MethodNode method, boolean isOverwrite) { + MethodNode target = this.findTargetMethod(targetClass, method); + + if (target != null) { + AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class); + if (merged != null) { + String sessionId = ASMHelper.getAnnotationValue(merged, "sessionId"); + + if (!this.sessionId.equals(sessionId)) { + throw new ClassFormatError("Invalid @MixinMerged annotation found in" + mixin + " at " + method.name + " in " + targetClass.name); + } + + 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); + return; + } + } + + targetClass.methods.remove(target); + } else if (isOverwrite) { + throw new InvalidMixinException(String.format("Overwrite target %s was not located in the target class", method.name)); + } + + targetClass.methods.add(method); + + ASMHelper.setVisibleAnnotation(method, MixinMerged.class, + "mixin", mixin.getClassName(), + "priority", mixin.getPriority(), + "sessionId", this.sessionId); + } + /** * Handles appending instructions from the source method to the target method * diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java index 7a662f1c..7458b0a6 100644 --- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java +++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java @@ -24,8 +24,13 @@ */ package org.spongepowered.asm.util; -import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; -import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS; +import static org.objectweb.asm.ClassWriter.*; + +import java.io.PrintWriter; +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; @@ -44,12 +49,6 @@ import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import org.objectweb.asm.util.CheckClassAdapter; -import java.io.PrintWriter; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class ASMHelper { private static final int[] intConstants = new int[] @@ -345,6 +344,82 @@ public class ASMHelper { CheckClassAdapter.verify(cr, true, new PrintWriter(System.out)); } + /** + * Set a runtime-visible annotation of the specified class on the supplied field node + * + * @param field Target field + * @param annotationClass Type of annotation to search for + * @param value Values (interleaved key/value pairs) to set + */ + public static void setVisibleAnnotation(FieldNode field, Class annotationClass, Object... value) { + AnnotationNode node = ASMHelper.makeAnnotationNode(Type.getDescriptor(annotationClass), value); + field.visibleAnnotations = ASMHelper.addAnnotation(field.visibleAnnotations, node); + } + + /** + * Set an invisible annotation of the specified class on the supplied field node + * + * @param field Target field + * @param annotationClass Type of annotation to search for + * @param value Values (interleaved key/value pairs) to set + */ + public static void setInvisibleAnnotation(FieldNode field, Class annotationClass, Object... value) { + AnnotationNode node = ASMHelper.makeAnnotationNode(Type.getDescriptor(annotationClass), value); + field.invisibleAnnotations = ASMHelper.addAnnotation(field.invisibleAnnotations, node); + } + + /** + * Set a runtime-visible annotation of the specified class on the supplied method node + * + * @param method Target method + * @param annotationClass Type of annotation to search for + * @param value Values (interleaved key/value pairs) to set + */ + public static void setVisibleAnnotation(MethodNode method, Class annotationClass, Object... value) { + AnnotationNode node = ASMHelper.makeAnnotationNode(Type.getDescriptor(annotationClass), value); + method.visibleAnnotations = ASMHelper.addAnnotation(method.visibleAnnotations, node); + } + + /** + * Set a invisible annotation of the specified class on the supplied method node + * + * @param method Target method + * @param annotationClass Type of annotation to search for + * @param value Values (interleaved key/value pairs) to set + */ + public static void setInvisibleAnnotation(MethodNode method, Class annotationClass, Object... value) { + AnnotationNode node = ASMHelper.makeAnnotationNode(Type.getDescriptor(annotationClass), value); + method.invisibleAnnotations = ASMHelper.addAnnotation(method.invisibleAnnotations, node); + } + + private static AnnotationNode makeAnnotationNode(String annotationType, Object... value) { + AnnotationNode node = new AnnotationNode(annotationType); + for (int pos = 0; pos < value.length - 1; pos += 2) { + node.visit((String)value[pos], value[pos + 1]); + } + return node; + } + + private static List addAnnotation(List annotations, AnnotationNode node) { + if (annotations == null) { + annotations = new ArrayList(1); + } else { + annotations.remove(ASMHelper.getAnnotation(annotations, node.desc)); + } + annotations.add(node); + return annotations; + } + + /** + * Get an invisible annotation of the specified class from the supplied field node + * + * @param field Source field + * @param annotationClass Type of annotation to search for + * @return the annotation, or null if not present + */ + public static void setInvisibleAnnotation(FieldNode field, Class annotationClass) { + } + /** * Get a runtime-visible annotation of the specified class from the supplied field node *