From ecb23a9cc0c0a05346af7115de57dcdc3a873ce4 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Tue, 3 Mar 2015 18:05:47 +0000 Subject: [PATCH] Add Intrinsic method support, should fix issue with re-entrant accessors --- .../spongepowered/asm/mixin/Intrinsic.java | 134 ++++++++++++++++++ .../mixin/injection/struct/InjectionInfo.java | 6 + .../asm/mixin/transformer/InterfaceInfo.java | 1 + .../asm/mixin/transformer/MixinInfo.java | 1 + .../asm/mixin/transformer/MixinRenamed.java | 46 ++++++ .../mixin/transformer/MixinTargetContext.java | 10 ++ .../mixin/transformer/MixinTransformer.java | 127 +++++++++++++++-- 7 files changed, 310 insertions(+), 15 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/Intrinsic.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/MixinRenamed.java diff --git a/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java new file mode 100644 index 00000000..8fe993ba --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/Intrinsic.java @@ -0,0 +1,134 @@ +/* + * 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; + +import java.lang.annotation.ElementType; +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. + * + *

By default, all members within a mixin will overwrite (completely replace) + * matching methods in the target class without prejudice. However this can be + * a problem when soft-implementing an interface to deal with a method conflict + * because it may be desirable to only override the method if it does not + * already exist in the target, for example when running in a development + * environment.

+ * + *

This annotation introduces two new behaviours for dealing with target + * methods which implement a soft interface intrinsically.

+ * + *

Consider the following code:

+ * + *
@Shadow public int getSomething();
+ * 
+ * public int soft$getSomething() {
+ *     return this.getSomething();
+ * }
+ * + *

This type of accessor is common when an interface conflict occurs, but has + * the problem that the injected accessor will be effectively self-referential + * in development, because the prefix will be removed and the accessor will thus + * cause a stack overflow.

+ * + *

The only way to address this issue is to replace the shadow with a copy of + * the original accessor, like so: + * + *

@Shadow private int something;
+ * 
+ * public int soft$getSomething() {
+ *     return this.something;
+ * }
+ * + *

But this has the drawback of forcing the mixin to re-implement the target + * method, and thus forces ongoing maintenance of the mixin to include updating + * the contents of the accessor.

+ * + *

Intrinsic allows this problem to be circumvented in one of + * two ways. The first way essentially declares "don't merge this method if it + * already exists in the target". To use this behaviour, we simply tag our + * accessor with {@link Intrinsic @Intrinsic}:

+ * + *
@Shadow public int getSomething();
+ * 
+ * @Intrinsic // don't merge the method if the target already exists
+ * public int soft$getSomething() {
+ *     return this.getSomething();
+ * }
+ * + *

This is ideal if the accessor is simply providing a proxy through to an + * underlying obfuscated method, as in the example above. However, if the new + * method contains additional code, such as in this example:

+ * + *
@Shadow public int getSomething();
+ * 
+ * public int soft$getSomething() {
+ *     return this.someCondition ? this.someOtherValue : this.getSomething();
+ * }
+ * + *

Then we still have the original problem that the method becomes re-entrant + * without specifying the additional Overwrite. We can solve this with the + * second {@link Intrinsic} behaviour, and set the {@link #displace} argument to + * true. Setting displace instructs the mixin + * transformer to proxy the method call if the target already + * exists, but merge the method normally if it does not. This allows our new + * accessor to call the original method in all circumstances.

+ * + *

When displace is enabled, if the target method exists then + * instead of being overwritten it is instead renamed with a temporary + * name and all references to the original method within the Intrinsic + * method are updated to call the renamed method. This means that all + * external code will still reference the Intrinsic accessor (just as it would + * have done with a regular overwrite) but code within the Intrinsic + * accessor will call the overwritten method.

+ * + *
@Shadow public int getSomething();
+ * 
+ * @Intrinsic(displace = true) // if the target already exists, displace it
+ * public int soft$getSomething() {
+ *     return this.someCondition ? this.someOtherValue : this.getSomething();
+ * }
+ * + */ +@Target({ ElementType.METHOD}) +@Retention(RetentionPolicy.CLASS) +public @interface Intrinsic { + + /** + * If set to true, this intrinsic method will replace any existing method in + * the target class by renaming it and updating internal references inside + * the method to reference the displaced method. If false or omitted, + * instructs this intrinsic method to not overwrite the target method + * if it exists, contrary to the normal behaviour for mixins + * + * @return true if this intrinsic method should displace matching targets + */ + public boolean displace() default false; + +} 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 bb58dddf..c1d18624 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 @@ -40,6 +40,7 @@ import org.spongepowered.asm.mixin.injection.ModifyArg; 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.transformer.MixinMerged; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; @@ -238,6 +239,11 @@ public abstract class InjectionInfo { continue; } + AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class); + if (merged != null) { + throw new InvalidInjectionException(this, "Cannot inject into a mixin method"); + } + this.targets.add(target); ordinal++; } 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 b78452ae..9798868e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -165,6 +165,7 @@ public class InterfaceInfo extends TreeInfo { throw new InvalidMixinException(this.mixin, String.format("%s does not exist in target interface %s", realName, this.iface.toString())); } + ASMHelper.setVisibleAnnotation(method, MixinRenamed.class, "originalName", method.name, "isInterfaceMember", true); method.name = realName; return true; } 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 507a5c9e..77f4c727 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -356,6 +356,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { if (shadowAnnotation != null) { 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinRenamed.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinRenamed.java new file mode 100644 index 00000000..301c3d14 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinRenamed.java @@ -0,0 +1,46 @@ +/* + * 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; + + +/** + *

Internal use only.

+ * + *

Decoration annotation used by the {@link MixinInfo} to mark methods + * in a mixin which have been renamed prior to being merged.

+ */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface MixinRenamed { + + public String originalName(); + + public boolean isInterfaceMember(); +} 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 70bb9be1..bf6a313d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -29,6 +29,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; +import org.apache.logging.log4j.Level; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; @@ -507,6 +508,15 @@ public class MixinTargetContext implements IReferenceMapperContext { return this.mixin.getInterfaces(); } + /** + * Get the logging level for this mixin + * + * @return the logging level + */ + public Level getLoggingLevel() { + return this.mixin.getLoggingLevel(); + } + /** * Get whether to propogate the source file attribute from a mixin onto the * target class 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 555b3655..82547492 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -57,6 +57,7 @@ import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.util.CheckClassAdapter; +import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.MixinApplyError; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Overwrite; @@ -557,24 +558,18 @@ public class MixinTransformer extends TreeTransformer { 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); + if (this.alreadyMerged(targetClass, mixin, method, isOverwrite, target)) { + return; + } + + AnnotationNode intrinsic = ASMHelper.getInvisibleAnnotation(method, Intrinsic.class); + if (intrinsic != null) { + if (this.mergeIntrinsic(targetClass, mixin, method, isOverwrite, target, intrinsic)) { return; } + } else { + targetClass.methods.remove(target); } - - 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)); } @@ -588,6 +583,107 @@ public class MixinTransformer extends TreeTransformer { "sessionId", this.sessionId); } + /** + * Check whether this method was already merged into the target, returns + * false if the method was not already merged or if the incoming + * method has a higher priority than the already merged method. + * + * @param targetClass Target classnode + * @param mixin Mixin context + * @param method Method being merged + * @param isOverwrite True if the incoming method is tagged with Override + * @param target target method being checked + * @return true if the target was already merged and should be skipped + */ + private boolean alreadyMerged(ClassNode targetClass, MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target) { + AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class); + if (merged == null) { + return false; + } + + 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 true; + } + + return false; + } + + /** + * Validates and prepares an intrinsic merge, returns true if the intrinsic + * check results in a "skip" action, indicating that no further merge action + * should be undertaken + * + * @param targetClass Target classnode + * @param mixin Mixin context + * @param method Method being merged + * @param isOverwrite True if the incoming method is tagged with Override + * @param target target method being checked + * @param intrinsic {@link Intrinsic} annotation + * @return true if the intrinsic method was skipped (short-circuit further + * merge operations) + */ + private boolean mergeIntrinsic(ClassNode targetClass, 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); + } + + if (MixinTransformer.hasFlag(method, Opcodes.ACC_STATIC)) { + throw new InvalidMixinException(mixin, "@Intrinsic method cannot be static, found " + method.name); + } + + 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); + } + + if (!ASMHelper.getAnnotationValue(intrinsic, "displace", false)) { + this.logger.log(mixin.getLoggingLevel(), "Skipping Intrinsic mixin method {}", method.name); + return true; + } + + this.displaceIntrinsic(targetClass, mixin, method, target); + return false; + } + + /** + * Handles intrinsic displacement + * + * @param targetClass Target classnode + * @param mixin Mixin context + * @param method Method being merged + * @param target target method being checked + */ + private void displaceIntrinsic(ClassNode targetClass, 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; + + for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + if (insn instanceof MethodInsnNode && insn.getOpcode() != Opcodes.INVOKESTATIC) { + MethodInsnNode methodNode = (MethodInsnNode)insn; + if (methodNode.owner.equals(targetClass.name) && methodNode.name.equals(target.name) && methodNode.desc.equals(target.desc)) { + methodNode.name = proxyName; + } + } + } + + target.name = proxyName; + } + /** * Handles appending instructions from the source method to the target * method @@ -629,6 +725,7 @@ public class MixinTransformer extends TreeTransformer { } } } + if (!found) { sourceMethod.name = targetMethodName; targetClass.methods.add(sourceMethod);