From adfeb072978bb0eaae6b39076808a1f5bed32bbb Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sun, 11 Jan 2015 22:44:45 +0000 Subject: [PATCH] Adding @ModifyArg and @Redirect annotations, example code to follow --- .../tools/obfuscation/AnnotatedMixins.java | 13 +- .../InjectionObfuscationProcessor.java | 26 +- .../asm/launch/MixinTweaker.java | 1 + .../asm/mixin/injection/InjectionPoint.java | 3 +- .../asm/mixin/injection/ModifyArg.java | 67 ++++++ .../asm/mixin/injection/Redirect.java | 58 +++++ .../injection/callback/CallbackInfo.java | 2 +- .../injection/callback/CallbackInjector.java | 224 +++++------------- .../asm/mixin/injection/code/Injector.java | 121 ++++++++++ .../{callback => code}/ReadOnlyInsnList.java | 4 +- .../injection/invoke/InvokeInjector.java | 149 ++++++++++++ .../injection/invoke/ModifyArgInjector.java | 161 +++++++++++++ .../injection/invoke/RedirectInjector.java | 96 ++++++++ .../struct/CallbackInjectionInfo.java | 47 ++++ .../mixin/injection/struct/InjectionInfo.java | 147 ++++++------ .../injection/struct/InjectionPointData.java | 3 +- .../struct/ModifyArgInjectionInfo.java | 46 ++++ .../struct/RedirectInjectionInfo.java | 43 ++++ .../asm/mixin/injection/struct/Target.java | 108 +++++++++ .../asm/mixin/transformer/MixinData.java | 40 +++- .../asm/mixin/transformer/MixinInfo.java | 5 +- .../mixin/transformer/MixinTransformer.java | 11 +- .../org/spongepowered/asm/util/ASMHelper.java | 40 ++++ 23 files changed, 1158 insertions(+), 257 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java rename src/main/java/org/spongepowered/asm/mixin/injection/{callback => code}/ReadOnlyInsnList.java (98%) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index ef463cfc..a794f862 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -325,9 +325,16 @@ class AnnotatedMixins { if (this.shouldRemap(mixinClass, inject)) { mixinClass.registerInjector(method, inject); - List annotationValue = MirrorUtils.>getAnnotationValue(inject, "at"); - for (AnnotationMirror at : annotationValue) { - mixinClass.registerInjectionPoint(at); + Object ats = MirrorUtils.getAnnotationValue(inject, "at"); + + if (ats instanceof List) { + @SuppressWarnings("unchecked") + List annotationValue = (List)ats; + for (AnnotationMirror at : annotationValue) { + mixinClass.registerInjectionPoint(at); + } + } else if (ats instanceof AnnotationMirror) { + mixinClass.registerInjectionPoint((AnnotationMirror)ats); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java index 4994eb3c..23973e53 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java @@ -24,6 +24,7 @@ */ package org.spongepowered.tools.obfuscation; +import java.lang.annotation.Annotation; import java.util.Set; import javax.annotation.processing.RoundEnvironment; @@ -38,15 +39,21 @@ 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.Redirect; 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.At" }) +@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" }) public class InjectionObfuscationProcessor extends MixinProcessor { @@ -60,7 +67,9 @@ public class InjectionObfuscationProcessor extends MixinProcessor { } this.processMixins(roundEnv); - this.processInjectors(roundEnv); + this.processInjectors(roundEnv, Inject.class); + this.processInjectors(roundEnv, ModifyArg.class); + this.processInjectors(roundEnv, Redirect.class); try { this.mixins.writeRefs(); @@ -74,20 +83,21 @@ public class InjectionObfuscationProcessor extends MixinProcessor { /** * Searches for {@link Inject} annotations and registers them with their parent mixins */ - private void processInjectors(RoundEnvironment roundEnv) { - for (Element elem : roundEnv.getElementsAnnotatedWith(Inject.class)) { + private void processInjectors(RoundEnvironment roundEnv, Class injectorClass) { + for (Element elem : roundEnv.getElementsAnnotatedWith(injectorClass)) { Element parent = elem.getEnclosingElement(); if (!(parent instanceof TypeElement)) { - throw new IllegalStateException("@Shadow element has unexpected parent with type " + MirrorUtils.getElementType(parent)); + throw new IllegalStateException("@" + injectorClass.getSimpleName() + " element has unexpected parent with type " + + MirrorUtils.getElementType(parent)); } - AnnotationMirror inject = MirrorUtils.getAnnotation(elem, Inject.class); + AnnotationMirror inject = MirrorUtils.getAnnotation(elem, injectorClass); if (elem.getKind() == ElementKind.METHOD) { this.mixins.registerInjector((TypeElement)parent, (ExecutableElement)elem, inject); } else { this.processingEnv.getMessager().printMessage(Kind.WARNING, - "Found an @Inject annotation on an element which is not a method: " + elem.toString()); + "Found an @" + injectorClass.getSimpleName() + " annotation on an element which is not a method: " + elem.toString()); } } } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java b/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java index 601c1dd6..25578e0f 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java @@ -176,6 +176,7 @@ public class MixinTweaker implements ITweaker { Attributes manifestAttributes = jarFile.getManifest().getMainAttributes(); return manifestAttributes.getValue(key); } catch (IOException ex) { + // be quiet checkstyle } finally { if (jarFile != null) { try { 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 1dc3ca49..2e264aed 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -290,7 +290,8 @@ public abstract class InjectionPoint { /** * Parse and instantiate an InjectionPoint from the supplied information. Returns null if an InjectionPoint could not be created. */ - public static InjectionPoint parse(MixinData mixin, String at, At.Shift shift, int by, List args, String target, int ordinal, int opcode) { + public static InjectionPoint parse(MixinData mixin, String at, At.Shift shift, int by, + List args, String target, int ordinal, int opcode) { InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode); InjectionPoint point = null; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java new file mode 100644 index 00000000..f48f4d0f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -0,0 +1,67 @@ +/* + * 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.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Specifies that this mixin method should inject an argument modifier to itself in the target method(s) identified by {@link #method}. + */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ModifyArg { + + /** + * String representation of a {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} which identifies the 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 nodes of type {@link org.objectweb.asm.tree.MethodInsnNode} and an exception will be thrown if this is not the case. + */ + public At at(); + + /** + *

Gets the argument index on the target to set. It is not necessary to set this value if there is only one argument of the modifier type in + * the hooked method's signature. For example if the target method accepts a boolean, an integer and a String, and the modifier method accepts + * and returns an integer, then the integer parameter will be automatically selected.

+ * + *

The index is zero-based.

+ */ + public int index() default -1; + + /** + * By default, the annotation processor will attempt to locate an obfuscation mapping for all {@link ModifyArg} methods since it is anticipated + * that in general the target of a {@link ModifyArg} 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. + */ + public boolean remap() default true; +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java new file mode 100644 index 00000000..3cbe9e1e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -0,0 +1,58 @@ +/* + * 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.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Specifies that this mixin method should redirect the specified {@link #method} call to the method decorated with this annotation. + */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Redirect { + + /** + * String representation of a {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} which identifies the 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 nodes of type {@link org.objectweb.asm.tree.MethodInsnNode} and an exception will be thrown if this is not the case. + */ + public At at(); + + /** + * By default, the annotation processor will attempt to locate an obfuscation mapping for all {@link ModifyArg} methods since it is anticipated + * that in general the target of a {@link ModifyArg} 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. + */ + public boolean remap() default true; +} 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 26d6466a..0efbc99c 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 @@ -107,7 +107,7 @@ public class CallbackInfo implements Cancellable { return CallbackInfo.class.getName(); } - static String getCallInfoClassName(Type returnType) { + public static String getCallInfoClassName(Type returnType) { return (returnType.equals(Type.VOID_TYPE) ? CallbackInfo.class.getName() : CallbackInfoReturnable.class.getName()).replace('.', '/'); } 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 c5ef2d0d..712844a7 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 @@ -24,112 +24,33 @@ */ package org.spongepowered.asm.mixin.injection.callback; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; import java.util.List; -import java.util.Set; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import org.objectweb.asm.tree.*; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; 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.points.BeforeReturn; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.util.ASMHelper; import org.spongepowered.asm.util.Locals; /** * This class is responsible for generating the bytecode for injected callbacks */ -public class CallbackInjector { - - private static final String CTOR = ""; - - /** - * Information about the current injection target, mainly just convenience rather than passing a bunch of values around - */ - class Target { - - /** - * Target method - */ - final MethodNode method; - - /** - * Method arguments - */ - final Type[] arguments; - - /** - * Return type computed from the method descriptor - */ - final Type returnType; - - /** - * Method's (original) MAXS - */ - // CHECKSTYLE:OFF - final int MAXS; - // CHECKSTYLE:ON - - /** - * Callback method descriptor based on this target - */ - final String callbackDescriptor; - - /** - * Callback info class - */ - final String callbackInfoClass; - - /** - * Make a new Target for the supplied method - */ - Target(MethodNode method) { - this.method = method; - this.arguments = Type.getArgumentTypes(method.desc); - - this.returnType = Type.getReturnType(method.desc); - this.MAXS = method.maxStack; - this.callbackInfoClass = CallbackInfo.getCallInfoClassName(this.returnType); - this.callbackDescriptor = String.format("(%sL%s;)V", method.desc.substring(1, method.desc.indexOf(')')), this.callbackInfoClass); - } - - /** - * Get the callback descriptor - */ - String getCallbackDescriptor(final boolean captureLocals, final Type[] locals, Type[] argumentTypes, int startIndex) { - if (!captureLocals) { - return this.callbackDescriptor; - } - - String descriptor = this.callbackDescriptor.substring(0, this.callbackDescriptor.indexOf(')')); - for (int l = startIndex; l < locals.length; l++) { - if (locals[l] != null) { - descriptor += locals[l].getDescriptor(); - } - } - - return descriptor + ")V"; - } - } - - /** - * True if the callback method is static - */ - private final boolean isStatic; - - /** - * Class node - */ - private final ClassNode classNode; - - /** - * Callback method - */ - private final MethodNode methodNode; +public class CallbackInjector extends Injector { /** * True if cancellable @@ -141,75 +62,26 @@ public class CallbackInjector { */ private final boolean captureLocals; - /** - * Make a new CallbackInjector for the supplied InjectionInfo - */ - public CallbackInjector(InjectionInfo info) { - this(info.getClassNode(), info.getMethod(), info.getCancellable(), info.getCaptureLocals()); - } - /** * Make a new CallbackInjector with the supplied args */ - public CallbackInjector(ClassNode classNode, MethodNode methodNode, boolean cancellable, boolean captureLocals) { - this.classNode = classNode; - this.methodNode = methodNode; + public CallbackInjector(InjectionInfo info, boolean cancellable, boolean captureLocals) { + super(info); this.cancellable = cancellable; this.captureLocals = captureLocals; - this.isStatic = ASMHelper.methodIsStatic(methodNode); } - /** - * Inject into the specified method at the specified injection points + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector#sanityCheck(org.spongepowered.asm.mixin.injection.callback.Target, + * java.util.List) */ - public void injectInto(MethodNode into, List injectionPoints) { - this.sanityCheck(into, injectionPoints); - - for (AbstractInsnNode targetNode : this.findTargetNodes(into, injectionPoints)) { - Type[] localTypes = null; - - if (this.captureLocals) { - LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, into, targetNode); - - if (locals != null) { - localTypes = new Type[locals.length]; - for (int l = 0; l < locals.length; l++) { - if (locals[l] != null) { - localTypes[l] = Type.getType(locals[l].desc); - } - } - } - } - - Target target = new Target(into); - this.inject(target, targetNode, localTypes); - } - } - - private Set findTargetNodes(MethodNode into, List injectionPoints) { - Set targetNodes = new HashSet(); - - // Defensive objects, so that injectionPoint instances can't modify our working copies - ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions); - Collection nodes = new ArrayList(32); - - for (InjectionPoint injectionPoint : injectionPoints) { - nodes.clear(); - if (injectionPoint.find(into.desc, insns, nodes)) { - targetNodes.addAll(nodes); - } - } - - insns.dispose(); - return targetNodes; - } - - private void sanityCheck(MethodNode target, List injectionPoints) { - if (ASMHelper.methodIsStatic(target) != this.isStatic) { + @Override + protected void sanityCheck(Target target, List injectionPoints) { + if (ASMHelper.methodIsStatic(target.method) != this.isStatic) { throw new InvalidInjectionException("'static' modifier of callback method does not match target in " + this.methodNode.name); } - if (CallbackInjector.CTOR.equals(target.name)) { + if (Injector.CTOR.equals(target.method.name)) { for (InjectionPoint injectionPoint : injectionPoints) { if (!injectionPoint.getClass().equals(BeforeReturn.class)) { throw new InvalidInjectionException("Found injection point type " + injectionPoint.getClass().getSimpleName() @@ -219,10 +91,34 @@ public class CallbackInjector { } } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector#inject(org.spongepowered.asm.mixin.injection.callback.Target, + * org.objectweb.asm.tree.AbstractInsnNode) + */ + @Override + protected void inject(Target target, AbstractInsnNode node) { + Type[] localTypes = null; + + if (this.captureLocals) { + LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, target.method, node); + + if (locals != null) { + localTypes = new Type[locals.length]; + for (int l = 0; l < locals.length; l++) { + if (locals[l] != null) { + localTypes[l] = Type.getType(locals[l].desc); + } + } + } + } + + this.inject(target, node, localTypes); + } + /** * Generate the actual bytecode */ - private void inject(Target target, final AbstractInsnNode targetNode, final Type[] locals) { + private void inject(Target target, final AbstractInsnNode node, final Type[] locals) { // Calculate the initial frame size based on the target method's arguments int initialFrameSize = ASMHelper.getFirstNonArgLocalIndex(target.arguments, !this.isStatic); @@ -234,7 +130,7 @@ public class CallbackInjector { // If it doesn't match, then cry if (!callbackDescriptor.equals(this.methodNode.desc)) { - throw new InvalidInjectionException("Invalid descriptor on callback method, expected " + callbackDescriptor); + throw new InvalidInjectionException("Invalid descriptor on callback: expected " + callbackDescriptor + " found " + this.methodNode.desc); } // These two variables keep track of the (additional) stack size required for the two actions we're going to be injecting insns to perform, @@ -256,7 +152,7 @@ public class CallbackInjector { // If this is a ReturnEventInfo AND we are right before a RETURN opcode (so we can expect the *original* return value to be on the stack, // then we dup the return value into a local var so we can push it later when we invoke the ReturnEventInfo ctor - if (targetNode instanceof InsnNode && targetNode.getOpcode() >= Opcodes.IRETURN && targetNode.getOpcode() < Opcodes.RETURN) { + if (node instanceof InsnNode && node.getOpcode() >= Opcodes.IRETURN && node.getOpcode() < Opcodes.RETURN) { pushReturnValue = true; insns.add(new InsnNode(Opcodes.DUP)); insns.add(new VarInsnNode(target.returnType.getOpcode(Opcodes.ISTORE), marshallVar)); @@ -292,12 +188,12 @@ public class CallbackInjector { if (this.cancellable) { // Inject the if (e.isCancelled()) return e.getReturnValue(); - this.injectCancellationCode(target, insns, targetNode, marshallVar); + this.injectCancellationCode(target, insns, node, marshallVar); } // Inject our generated code into the method - target.method.instructions.insertBefore(targetNode, insns); - target.method.maxStack = Math.max(target.method.maxStack, Math.max(target.MAXS + ctorMAXS, target.MAXS + invokeMAXS)); + target.method.instructions.insertBefore(node, insns); + target.method.maxStack = Math.max(target.method.maxStack, Math.max(target.maxStack + ctorMAXS, target.maxStack + invokeMAXS)); } protected int invokeCallbackInfoCtor(Target target, InsnList insns, boolean cancellable, boolean pushReturnValue, int marshallVar) { @@ -311,10 +207,10 @@ public class CallbackInjector { if (pushReturnValue) { insns.add(new VarInsnNode(target.returnType.getOpcode(Opcodes.ILOAD), marshallVar)); insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, - target.callbackInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(target.returnType), false)); + target.callbackInfoClass, Injector.CTOR, CallbackInfo.getConstructorDescriptor(target.returnType), false)); } else { insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, - target.callbackInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(), false)); + target.callbackInfoClass, Injector.CTOR, CallbackInfo.getConstructorDescriptor(), false)); } return ctorMAXS; @@ -323,11 +219,12 @@ public class CallbackInjector { /** * if (e.isCancelled()) return e.getReturnValue(); * + * @param target * @param insns - * @param targetNode + * @param node * @param marshallVar */ - protected void injectCancellationCode(Target target, final InsnList insns, final AbstractInsnNode targetNode, int marshallVar) { + protected void injectCancellationCode(Target target, final InsnList insns, final AbstractInsnNode node, int marshallVar) { insns.add(new VarInsnNode(Opcodes.ALOAD, marshallVar)); insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, target.callbackInfoClass, CallbackInfo.getIsCancelledMethodName(), CallbackInfo.getIsCancelledMethodSig(), false)); @@ -336,7 +233,7 @@ public class CallbackInjector { insns.add(new JumpInsnNode(Opcodes.IFEQ, notCancelled)); // If this is a void method, just injects a RETURN opcode, otherwise we need to get the return value from the EventInfo - this.injectReturnCode(target, insns, targetNode, marshallVar); + this.injectReturnCode(target, insns, node, marshallVar); insns.add(notCancelled); } @@ -344,11 +241,12 @@ public class CallbackInjector { /** * Inject the appropriate return code for the method type * + * @param target * @param insns - * @param targetNode + * @param node * @param marshallVar */ - protected void injectReturnCode(Target target, final InsnList insns, final AbstractInsnNode targetNode, int marshallVar) { + protected void injectReturnCode(Target target, final InsnList insns, final AbstractInsnNode node, int marshallVar) { if (target.returnType.equals(Type.VOID_TYPE)) { // Void method, so just return void insns.add(new InsnNode(Opcodes.RETURN)); 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 new file mode 100644 index 00000000..89beb049 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -0,0 +1,121 @@ +/* + * 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.injection.code; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +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.util.ASMHelper; + +import com.google.common.base.Joiner; + + +/** + * Base class for bytecode injectors + */ +public abstract class Injector { + + protected static final String CTOR = ""; + + /** + * Class node + */ + protected final ClassNode classNode; + + /** + * Callback method + */ + protected final MethodNode methodNode; + + /** + * True if the callback method is static + */ + protected final boolean isStatic; + + /** + * Make a new CallbackInjector for the supplied InjectionInfo + */ + public Injector(InjectionInfo info) { + this(info.getClassNode(), info.getMethod()); + } + + /** + * Make a new CallbackInjector with the supplied args + */ + private Injector(ClassNode classNode, MethodNode methodNode) { + this.classNode = classNode; + this.methodNode = methodNode; + this.isStatic = ASMHelper.methodIsStatic(this.methodNode); + } + + /** + * Inject into the specified method at the specified injection points + */ + public final void injectInto(Target target, List injectionPoints) { + this.sanityCheck(target, injectionPoints); + + for (AbstractInsnNode node : this.findTargetNodes(target.method, injectionPoints)) { + this.inject(target, node); + } + } + + protected Set findTargetNodes(MethodNode into, List injectionPoints) { + Set targetNodes = new HashSet(); + + // Defensive objects, so that injectionPoint instances can't modify our working copies + ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions); + Collection nodes = new ArrayList(32); + + for (InjectionPoint injectionPoint : injectionPoints) { + nodes.clear(); + if (injectionPoint.find(into.desc, insns, nodes)) { + targetNodes.addAll(nodes); + } + } + + insns.dispose(); + return targetNodes; + } + + protected void sanityCheck(Target target, List injectionPoints) { + // stub for subclasses + } + + protected abstract void inject(Target target, AbstractInsnNode node); + + protected static String printArgs(Type[] args) { + return "(" + Joiner.on("").join(args) + ")"; + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java similarity index 98% rename from src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java rename to src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java index 5bec4f62..91f5dcf2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.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.mixin.injection.callback; +package org.spongepowered.asm.mixin.injection.code; import java.util.ListIterator; @@ -33,7 +33,7 @@ import org.objectweb.asm.tree.InsnList; * Read-only wrapper for InsnList, defensively passed to InjectionPoint instances so that custom InjectionPoint implementations cannot modify the insn * list whilst inspecting it. */ -public class ReadOnlyInsnList extends InsnList { +class ReadOnlyInsnList extends InsnList { private InsnList insnList; 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 new file mode 100644 index 00000000..5d20be88 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java @@ -0,0 +1,149 @@ +/* + * 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.injection.invoke; + +import java.util.List; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.VarInsnNode; +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.util.ASMHelper; + + +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; + + 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; + } + + /* (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) { + if (ASMHelper.methodIsStatic(target.method) != this.isStatic) { + throw new InvalidInjectionException("'static' modifier of callback method does not match target in " + this.methodNode.name); + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector#inject(org.spongepowered.asm.mixin.injection.callback.Target, + * org.objectweb.asm.tree.AbstractInsnNode) + */ + @Override + protected void inject(Target target, AbstractInsnNode node) { + if (!(node instanceof MethodInsnNode)) { + throw new InvalidInjectionException(this.annotationType + " annotation is targetting a non-method insn in " + target + + " in " + this.classNode.name); + } + + this.inject(target, (MethodInsnNode)node); + } + + /** + * Do the injection + */ + protected abstract void inject(Target target, MethodInsnNode node); + + /** + * @param args + * @param insns + * @param argMap + * @param startArg + * @param endArg + */ + protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) { + if (!this.isStatic) { + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + } + this.pushArgs(insns, args, argMap, startArg, endArg); + insns.add(new MethodInsnNode(this.isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, + this.classNode.name, this.methodNode.name, this.methodNode.desc, false)); + } + + /** + * Generate an array containing local indexes for the specified args, returns an array of identical size to the supplied array with an + * allocated local index in each corresponding position + */ + protected int[] generateArgMap(Type[] args, int start, int local) { + int[] argMap = new int[args.length]; + for (int arg = start; arg < args.length; arg++) { + argMap[arg] = local; + local += args[arg].getSize(); + } + return argMap; + } + + /** + * Store args on the stack starting at the end and working back to position specified by start, return the generated argMap + */ + protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) { + int[] argMap = this.generateArgMap(args, start, target.method.maxLocals); + this.storeArgs(args, insns, argMap, start, args.length); + return argMap; + } + + /** + * Store args on the stack to their positions allocated based on argMap + */ + protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { + for (int arg = end - 1; arg >= start; arg--) { + insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg])); + } + } + + /** + * Load args onto the stack from their positions allocated in argMap + */ + protected void pushArgs(InsnList insns, Type[] args, int[] argMap, int start, int end) { + for (int arg = start; arg < end; arg++) { + insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg])); + } + } +} 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 new file mode 100644 index 00000000..0e81a4aa --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java @@ -0,0 +1,161 @@ +/* + * 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.injection.invoke; + +import java.util.Arrays; +import java.util.List; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; +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; + +/** + * A bytecode injector which allows a single argument of a chosen method call to be altered + */ +public class ModifyArgInjector extends InvokeInjector { + + /** + * Index of the target arg or -1 to find the arg automatically (only works where there is only one arg of specified type on the element) + */ + private final int index; + + /** + * True if processing in single arg mode, the callback only accepts a single arg of the same type as the return. Otherwise the handler method is + * expected to have matching args to the target invocation + */ + private final boolean singleArgMode; + + /** + * @param info Injection info + * @param index target arg index + */ + public ModifyArgInjector(InjectionInfo info, int index) { + super(info, "@ModifyArg"); + this.index = index; + this.singleArgMode = this.methodArgs.length == 1; + } + + /* (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 (this.singleArgMode) { + if (!this.methodArgs[0].equals(this.returnType)) { + throw new InvalidInjectionException("@ModifyArg return type must match the parameter type." + + " ARG=" + this.methodArgs[0] + " RETURN=" + this.returnType); + } + } + } + + /** + * Do the injection + */ + @Override + protected void inject(Target target, MethodInsnNode node) { + Type[] args = Type.getArgumentTypes(node.desc); + int argIndex = this.findArgIndex(target, args); + + InsnList insns = new InsnList(); + int extraLocals = 0; + + if (this.singleArgMode) { + extraLocals = this.injectSingleArgHandler(target, args, argIndex, insns); + } else { + extraLocals = this.injectMultiArgHandler(target, args, argIndex, insns); + } + + target.method.instructions.insertBefore(node, insns); + target.method.maxLocals = Math.max(target.method.maxLocals, target.maxLocals + extraLocals); + target.method.maxStack = Math.max(target.method.maxStack, target.maxStack + 2 - extraLocals); + } + + /** + * Inject handler opcodes for a single arg handler + */ + private int injectSingleArgHandler(Target target, Type[] args, int argIndex, InsnList insns) { + int[] argMap = this.storeArgs(target, args, insns, argIndex); + this.invokeHandlerWithArgs(args, insns, argMap, argIndex, argIndex + 1); + this.pushArgs(insns, args, argMap, argIndex + 1, args.length); + return target.method.maxLocals - argMap[argMap.length - 1] - 1 + args[args.length - 1].getSize(); + } + + /** + * Inject handler opcodes for a multi arg handler + */ + private int injectMultiArgHandler(Target target, Type[] args, int argIndex, InsnList insns) { + if (!Arrays.equals(args, this.methodArgs)) { + throw new InvalidInjectionException("@ModifyArg method targets a method with an invalid signature " + + Injector.printArgs(args) + ", expected " + Injector.printArgs(this.methodArgs)); + } + + int[] argMap = this.storeArgs(target, args, insns, 0); + this.pushArgs(insns, args, argMap, 0, argIndex); + this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length); + this.pushArgs(insns, args, argMap, argIndex + 1, args.length); + return target.method.maxLocals - argMap[argMap.length - 1] - 1 + 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("Specified index " + this.index + " for @ModifyArg is invalid for args " + + Injector.printArgs(args) + ", expected " + this.returnType); + } + return this.index; + } + + int argIndex = -1; + + for (int arg = 0; arg < args.length; arg++) { + if (!args[arg].equals(this.returnType)) { + continue; + } + + if (argIndex != -1) { + throw new InvalidInjectionException("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."); + } + + argIndex = arg; + } + + if (argIndex == -1) { + throw new InvalidInjectionException("Could not find arg matching type " + this.returnType + " for @ModifyArg target " + + target + " in " + this.classNode.name); + } + + return argIndex; + } +} 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 new file mode 100644 index 00000000..d119ab98 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -0,0 +1,96 @@ +/* + * 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.injection.invoke; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; +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.util.ASMHelper; + +import com.google.common.collect.ObjectArrays; + +/** + *

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:

+ * + *
+ *   int abc = 0;
+ *   int def = 1;
+ *   Foo someObject = new Foo();
+ *   
+ *   // Hooking this method
+ *   boolean xyz = someObject.bar(abc, def);
+ *
+ * + *

The signature of the redirected method should be:

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

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

+ */ +public class RedirectInjector extends InvokeInjector { + + /** + * @param info Injection info + */ + public RedirectInjector(InjectionInfo info) { + super(info, "@Redirect"); + } + + /** + * Do the injection + */ + @Override + protected void inject(Target target, MethodInsnNode node) { + 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)) { + throw new InvalidInjectionException("@Redirect handler method has an invalid signature " + + ", expected " + desc + " found " + this.methodNode.desc); + } + + InsnList insns = new InsnList(); + int extraLocals = ASMHelper.getArgsSize(stackVars) + 1; + int[] argMap = this.storeArgs(target, stackVars, insns, 0); + this.invokeHandlerWithArgs(stackVars, insns, argMap, 0, stackVars.length); + + target.method.instructions.insertBefore(node, insns); + target.method.instructions.remove(node); + target.method.maxLocals = Math.max(target.method.maxLocals, target.maxLocals + extraLocals); + target.method.maxStack = Math.max(target.method.maxStack, target.maxStack + 1); + } +} 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 new file mode 100644 index 00000000..48850e51 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java @@ -0,0 +1,47 @@ +/* + * 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.injection.struct; + +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.transformer.MixinData; +import org.spongepowered.asm.util.ASMHelper; + +public class CallbackInjectionInfo extends InjectionInfo { + + protected CallbackInjectionInfo(MixinData mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected Injector initInjector(AnnotationNode injectAnnotation) { + boolean cancellable = ASMHelper.getAnnotationValue(injectAnnotation, "cancellable", false); + boolean captureLocals = ASMHelper.getAnnotationValue(injectAnnotation, "captureLocals", false); + + return new CallbackInjector(this, cancellable, captureLocals); + } +} 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 f8f424a9..af220f8f 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 @@ -33,11 +33,13 @@ import java.util.List; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.InvalidMixinException; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InvalidInjectionException; -import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; +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.MixinData; import org.spongepowered.asm.util.ASMHelper; @@ -45,103 +47,113 @@ import org.spongepowered.asm.util.ASMHelper; /** * Contructs information about an injection from an {@link Inject} annotation and allows the injection to be processed */ -public class InjectionInfo { +public abstract class InjectionInfo { + + protected final AnnotationNode annotation; /** * Class */ - private final ClassNode classNode; + protected final ClassNode classNode; /** * Annotated method */ - private final MethodNode method; + protected final MethodNode method; + + /** + * Mixin data + */ + protected final MixinData mixin; + /** * Annotated method is static */ - private final boolean isStatic; - - /** - * True if the injection should be cancellable - */ - private boolean cancellable; - - /** - * True if the injection should capture local variables - */ - private boolean captureLocals; + protected final boolean isStatic; /** * Target method(s) */ - private final Deque targets = new ArrayDeque(); + protected final Deque targets = new ArrayDeque(); /** - * Injection points parsed from {@link At} annotations + * Injection points parsed from {@link org.spongepowered.asm.mixin.injection.At} annotations */ - private final List injectionPoints = new ArrayList(); + protected final List injectionPoints = new ArrayList(); /** * Bytecode injector */ - private CallbackInjector injector; + protected Injector injector; /** * ctor * - * @param classNode Class + * @param mixin * @param method Method - * @param injectAnnotation Annotation to parse + * @param annotation Annotation to parse */ - public InjectionInfo(ClassNode classNode, MethodNode method, MixinData mixin, AnnotationNode injectAnnotation) { - this.classNode = classNode; + protected InjectionInfo(MixinData mixin, MethodNode method, AnnotationNode annotation) { + this.annotation = annotation; this.method = method; + this.mixin = mixin; + this.classNode = mixin.getTargetClass(); this.isStatic = ASMHelper.methodIsStatic(method); - this.parse(mixin, injectAnnotation); + this.readAnnotation(); } /** * Parse the info from the supplied annotation */ - private void parse(MixinData mixin, AnnotationNode injectAnnotation) { - if (injectAnnotation == null) { + @SuppressWarnings("unchecked") + protected void readAnnotation() { + if (this.annotation == null) { return; } - String method = ASMHelper.getAnnotationValue(injectAnnotation, "method"); + String type = "@" + this.annotation.desc.substring(this.annotation.desc.lastIndexOf('/') + 1, this.annotation.desc.length() - 1); + + String method = ASMHelper.getAnnotationValue(this.annotation, "method"); if (method == null) { - throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " is missing method name"); + throw new InvalidInjectionException(type + " annotation on " + this.method.name + " is missing method name"); } - List ats = ASMHelper.>getAnnotationValue(injectAnnotation, "at"); - if (ats == null) { - throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " is missing 'at' value(s)"); + List ats = null; + Object atValue = ASMHelper.getAnnotationValue(this.annotation, "at"); + if (atValue instanceof List) { + ats = (List)atValue; + } else if (atValue instanceof AnnotationNode) { + ats = new ArrayList(); + ats.add((AnnotationNode)atValue); + } else { + throw new InvalidInjectionException(type + " annotation on " + this.method.name + " is missing 'at' value(s)"); } - MemberInfo targetMember = MemberInfo.parse(method, mixin); + MemberInfo targetMember = MemberInfo.parse(method, this.mixin); - if (targetMember.owner != null && targetMember.owner.equals(mixin.getTargetClassRef())) { - throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " specifies a target class '" + targetMember.owner - + "', which is not supported"); + if (targetMember.owner != null && targetMember.owner.equals(this.mixin.getTargetClassRef())) { + throw new InvalidInjectionException(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("@Inject annotation on " + this.method.name + " could not find '" + targetMember.name + "'"); + throw new InvalidInjectionException(type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'"); } - this.cancellable = ASMHelper.getAnnotationValue(injectAnnotation, "cancellable", false); - this.captureLocals = ASMHelper.getAnnotationValue(injectAnnotation, "captureLocals", false); - for (AnnotationNode at : ats) { - InjectionPoint injectionPoint = InjectionPoint.parse(mixin, at); + InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, at); if (injectionPoint != null) { this.injectionPoints.add(injectionPoint); } } + + this.injector = this.initInjector(this.annotation); } + + protected abstract Injector initInjector(AnnotationNode injectAnnotation); /** * Get whether there is enough valid information in this info to actually perform an injection @@ -154,21 +166,14 @@ public class InjectionInfo { * Perform the injection */ public void inject() { - CallbackInjector injector = this.getInjector(); while (this.targets.size() > 0) { - injector.injectInto(this.targets.removeFirst(), this.injectionPoints); + Target target = this.mixin.getTargetMethod(this.targets.removeFirst()); + this.injector.injectInto(target, this.injectionPoints); } } - /** - * Performs a full-body massage with scented oils - */ - private CallbackInjector getInjector() { - if (this.injector == null) { - this.injector = new CallbackInjector(this); - } - - return this.injector; + public AnnotationNode getAnnotation() { + return this.annotation; } /** @@ -192,20 +197,6 @@ public class InjectionInfo { return this.targets; } - /** - * Get whether cancellable or not - */ - public boolean getCancellable() { - return this.cancellable; - } - - /** - * Get whether injection should capture locals - */ - public boolean getCaptureLocals() { - return this.captureLocals; - } - /** * Finds methods in the target class which match searchFor * @@ -226,4 +217,28 @@ public class InjectionInfo { } } } + + @SuppressWarnings("unchecked") + public static InjectionInfo parse(MixinData mixin, MethodNode method) { + AnnotationNode annotation = null; + try { + annotation = ASMHelper.getSingleVisibleAnnotation(method, Inject.class, ModifyArg.class, Redirect.class); + } catch (IllegalArgumentException ex) { + throw new InvalidMixinException("Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": " + ex.getMessage()); + } + + if (annotation == null) { + return null; + } + + if (annotation.desc.endsWith(Inject.class.getSimpleName() + ";")) { + return new CallbackInjectionInfo(mixin, method, annotation); + } else if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) { + return new ModifyArgInjectionInfo(mixin, method, annotation); + } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { + return new RedirectInjectionInfo(mixin, method, annotation); + } + + return null; + } } 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 b855f632..fe892129 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,12 +28,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.transformer.MixinData; /** - * Data read from an {@link At} annotation and passed into an InjectionPoint ctor + * Data read from an {@link org.spongepowered.asm.mixin.injection.At} annotation and passed into an InjectionPoint ctor */ public class InjectionPointData { 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 new file mode 100644 index 00000000..85378c98 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.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.injection.struct; + +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.invoke.ModifyArgInjector; +import org.spongepowered.asm.mixin.transformer.MixinData; +import org.spongepowered.asm.util.ASMHelper; + +public class ModifyArgInjectionInfo extends InjectionInfo { + + public ModifyArgInjectionInfo(MixinData mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected Injector initInjector(AnnotationNode injectAnnotation) { + int index = ASMHelper.getAnnotationValue(injectAnnotation, "index", -1); + + return new ModifyArgInjector(this, index); + } +} 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 new file mode 100644 index 00000000..b39948ed --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java @@ -0,0 +1,43 @@ +/* + * 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.injection.struct; + +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector; +import org.spongepowered.asm.mixin.transformer.MixinData; + +public class RedirectInjectionInfo extends InjectionInfo { + + public RedirectInjectionInfo(MixinData mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected Injector initInjector(AnnotationNode injectAnnotation) { + return new RedirectInjector(this); + } +} 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 new file mode 100644 index 00000000..4e4595e8 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java @@ -0,0 +1,108 @@ +/* + * 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.injection.struct; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + + +/** + * Information about the current injection target, mainly just convenience rather than passing a bunch of values around + */ +public class Target { + + /** + * Target method + */ + public final MethodNode method; + + /** + * Method arguments + */ + public final Type[] arguments; + + /** + * Return type computed from the method descriptor + */ + public final Type returnType; + + /** + * Method's (original) MAXS + */ + public final int maxStack; + + /** + * Method's original max locals + */ + public final int maxLocals; + + /** + * Callback method descriptor based on this target + */ + public final String callbackDescriptor; + + /** + * Callback info class + */ + public final String callbackInfoClass; + + /** + * Make a new Target for the supplied method + */ + public Target(MethodNode method) { + this.method = method; + this.arguments = Type.getArgumentTypes(method.desc); + + this.returnType = Type.getReturnType(method.desc); + this.maxStack = method.maxStack; + this.maxLocals = method.maxLocals; + this.callbackInfoClass = CallbackInfo.getCallInfoClassName(this.returnType); + this.callbackDescriptor = String.format("(%sL%s;)V", method.desc.substring(1, method.desc.indexOf(')')), this.callbackInfoClass); + } + + /** + * Get the callback descriptor + */ + public String getCallbackDescriptor(final boolean captureLocals, final Type[] locals, Type[] argumentTypes, int startIndex) { + if (!captureLocals) { + return this.callbackDescriptor; + } + + String descriptor = this.callbackDescriptor.substring(0, this.callbackDescriptor.indexOf(')')); + for (int l = startIndex; l < locals.length; l++) { + if (locals[l] != null) { + descriptor += locals[l].getDescriptor(); + } + } + + return descriptor + ")V"; + } + + @Override + public String toString() { + return this.method.name + this.method.desc; + } +} 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 206a8220..b091c924 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinData.java @@ -42,6 +42,7 @@ import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.InvalidMixinException; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper; +import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.util.ASMHelper; @@ -61,6 +62,11 @@ public class MixinData { */ private final ClassNode classNode; + /** + * + */ + private final ClassNode targetClass; + /** * Methods we need to rename */ @@ -75,15 +81,21 @@ public class MixinData { * All interfaces implemented by this mixin, including soft implementations */ private final Set interfaces = new HashSet(); + + /** + * Information about methods in the target class, used to keep track of transformations we apply + */ + private final Map targetMethods = new HashMap(); /** * ctor * * @param info */ - MixinData(MixinInfo info) { + MixinData(MixinInfo info, ClassNode target) { this.info = info; this.classNode = info.getClassNode(ClassReader.EXPAND_FRAMES); + this.targetClass = target; this.prepare(); } @@ -118,6 +130,30 @@ public class MixinData { } return targetClasses.get(0); } + + /** + * Get the target class + */ + public ClassNode getTargetClass() { + return this.targetClass; + } + + /** + * Get a method from the target class + */ + 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; + } /** * Get all interfaces for this mixin @@ -139,7 +175,7 @@ public class MixinData { public ReferenceMapper getReferenceMapper() { return this.info.getParent().getReferenceMapper(); } - + /** * Prepare the mixin, applies any pre-processing transformations */ 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 525ad055..f323b97d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -230,10 +230,11 @@ class MixinInfo extends TreeInfo implements Comparable { /** * Get a new mixin data container for this info * + * @param target * @return */ - public MixinData getData() { - return new MixinData(this); + public MixinData createData(ClassNode target) { + return new MixinData(this, target); } /** 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 212ee23e..58f25019 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -40,7 +40,6 @@ 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; @@ -51,7 +50,6 @@ 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.injection.Inject; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.transformers.TreeTransformer; import org.spongepowered.asm.util.ASMHelper; @@ -143,7 +141,7 @@ public class MixinTransformer extends TreeTransformer { for (MixinInfo mixin : mixins) { this.logger.info("Mixing {} into {}", mixin.getName(), transformedName); - this.applyMixin(targetClass, mixin.getData()); + this.applyMixin(targetClass, mixin.createData(targetClass)); } // Extension point @@ -394,17 +392,16 @@ public class MixinTransformer extends TreeTransformer { */ private void applyInjections(ClassNode targetClass, MixinData mixin) { for (MethodNode method : targetClass.methods) { - AnnotationNode injectAnnotation = ASMHelper.getVisibleAnnotation(method, Inject.class); - if (injectAnnotation == null) { + InjectionInfo injectInfo = InjectionInfo.parse(mixin, method); + if (injectInfo == null) { continue; } - InjectionInfo injectInfo = new InjectionInfo(targetClass, method, mixin, injectAnnotation); if (injectInfo.isValid()) { injectInfo.inject(); } - method.visibleAnnotations.remove(injectAnnotation); + method.visibleAnnotations.remove(injectInfo.getAnnotation()); } } diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java index 15159650..7a662f1c 100644 --- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java +++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java @@ -46,6 +46,7 @@ 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; @@ -388,6 +389,28 @@ public class ASMHelper { return ASMHelper.getAnnotation(method.invisibleAnnotations, Type.getDescriptor(annotationClass)); } + /** + * Get a runtime-visible annotation of the specified class from the supplied method node + * + * @param method Source method + * @param annotationClasses Types of annotation to search for + * @return the annotation, or null if not present + */ + public static AnnotationNode getSingleVisibleAnnotation(MethodNode method, Class... annotationClasses) { + return ASMHelper.getSingleAnnotation(method.visibleAnnotations, annotationClasses); + } + + /** + * Get an invisible annotation of the specified class from the supplied method node + * + * @param method Source method + * @param annotationClasses Types of annotation to search for + * @return the annotation, or null if not present + */ + public static AnnotationNode getSingleInvisibleAnnotation(MethodNode method, Class... annotationClasses) { + return ASMHelper.getSingleAnnotation(method.invisibleAnnotations, annotationClasses); + } + /** * Get a runtime-visible annotation of the specified class from the supplied class node * @@ -432,6 +455,23 @@ public class ASMHelper { return null; } + private static AnnotationNode getSingleAnnotation(List annotations, Class... annotationClasses) { + List nodes = new ArrayList(); + for (Class annotationClass : annotationClasses) { + AnnotationNode annotation = ASMHelper.getAnnotation(annotations, Type.getDescriptor(annotationClass)); + if (annotation != null) { + nodes.add(annotation); + } + } + + int foundNodes = nodes.size(); + if (foundNodes > 1) { + throw new IllegalArgumentException("Conflicting annotations found: " + annotationClasses); + } + + return foundNodes == 0 ? null : nodes.get(0); + } + /** * Duck type the "value" entry (if any) of the specified annotation node *