diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java index 10baa013..6248eb55 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java @@ -38,6 +38,7 @@ 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.ModifyArgs; import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; @@ -51,6 +52,7 @@ import org.spongepowered.tools.obfuscation.mirror.TypeUtils; @SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.injection.Inject", "org.spongepowered.asm.mixin.injection.ModifyArg", + "org.spongepowered.asm.mixin.injection.ModifyArgs", "org.spongepowered.asm.mixin.injection.Redirect", "org.spongepowered.asm.mixin.injection.At" }) @@ -70,6 +72,7 @@ public class MixinObfuscationProcessorInjection extends MixinObfuscationProcesso this.processMixins(roundEnv); this.processInjectors(roundEnv, Inject.class); this.processInjectors(roundEnv, ModifyArg.class); + this.processInjectors(roundEnv, ModifyArgs.class); this.processInjectors(roundEnv, Redirect.class); this.processInjectors(roundEnv, ModifyVariable.class); this.processInjectors(roundEnv, ModifyConstant.class); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java new file mode 100644 index 00000000..533be5d1 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java @@ -0,0 +1,166 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.invoke.arg.Args; +import org.spongepowered.asm.mixin.injection.throwables.InjectionError; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.ConstraintParser.Constraint; + +/** + * Specifies that this mixin method should inject an multi-argument modifier + * callback to itself in the target method(s) identified by {@link #method}. + * This type of injector provides a powerful but inefficient method for + * modifying multiple arguments of a method at once without making use of a + * {@link Redirect} injector. In general it is better to use redirectors where + * possible, however this type of injector can also function where {@link + * Redirect} cannot, such as modifying arguments of a super-constructor call. To + * modify a single method argument, use {@link ModifyArg} instead. + * + *

This injector works by creating an argument bundle in the form of + * {@link Args} which is passed to your handler method. You can manipulate the + * method arguments via the bundle in your handler method. The bundle is then + * unpacked and the original method is called with the modified arguments.

+ * + *

Since the argument bundle is created for every invocation of the target + * method, and primitive types must undergo boxing and unboxing, this injector + * is intrinsically less efficient than other methods. However for certain uses + * this injector is more powerful:

+ * + * + * + *

Methods decorated with this injector should return void and + * return either:

+ * + * + */ +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ModifyArgs { + + /** + * String representation of a + * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo + * MemberInfo} which identifies the target method. + * + * @return target method + */ + public String method(); + + /** + * A {@link Slice} annotation which describes the method bisection used in + * the {@link #at} query for this injector. + * + * @return slice + */ + public Slice slice() default @Slice; + + /** + * An {@link At} annotation which describes the {@link InjectionPoint} in + * the target method. The specified {@link InjectionPoint} must only + * return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances + * and an exception will be thrown if this is not the case. + * + * @return {@link At} which identifies the target method invocation + */ + public At at(); + + /** + * By default, the annotation processor will attempt to locate an + * obfuscation mapping for all {@link ModifyArgs} methods since it is + * anticipated that in general the target of a {@link ModifyArgs} annotation + * will be an obfuscated method in the target class. However since it is + * possible to also apply mixins to non-obfuscated targets (or non- + * obfuscated methods in obfuscated targets, such as methods added by Forge) + * it may be necessary to suppress the compiler error which would otherwise + * be generated. Setting this value to false will cause the + * annotation processor to skip this annotation when attempting to build the + * obfuscation table for the mixin. + * + * @return True to instruct the annotation processor to search for + * obfuscation mappings for this annotation + */ + public boolean remap() default true; + + /** + * In general, injectors are intended to "fail soft" in that a failure to + * locate the injection point in the target method is not considered an + * error condition. Another transformer may have changed the method + * structure or any number of reasons may cause an injection to fail. This + * also makes it possible to define several injections to achieve the same + * task given expected mutation of the target class and the + * injectors which fail are simply ignored. + * + *

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

+ * + * @return Minimum required number of injected callbacks, default specified + * by the containing config + */ + public int require() default -1; + + /** + * Like {@link #require()} but only enabled if the + * {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set + * to true and defaults to 1. Use this option during debugging to + * perform simple checking of your injectors. Causes the injector to throw + * a {@link InvalidInjectionException} if the expected number of injections + * is not realised. + * + * @return Minimum number of expected callbacks, default 1 + */ + public int expect() default 1; + + /** + * Returns constraints which must be validated for this injector to + * succeed. See {@link Constraint} for details of constraint formats. + * + * @return Constraints for this annotation + */ + public String constraints() default ""; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 2da99583..b85d03fe 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -52,8 +52,6 @@ import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.Bytecode; -import com.google.common.base.Joiner; - /** * Base class for bytecode injectors */ @@ -272,10 +270,6 @@ public abstract class Injector { insns.add(new InsnNode(Opcodes.ATHROW)); } - protected static String printArgs(Type[] args) { - return "(" + Joiner.on("").join(args) + ")"; - } - /** * Returns whether the from type can be coerced to the to * type. diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java index cb093bae..8480851d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java @@ -30,12 +30,12 @@ import java.util.List; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; -import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.Bytecode; /** * A bytecode injector which allows a single argument of a chosen method call to @@ -132,7 +132,7 @@ public class ModifyArgInjector extends InvokeInjector { private int injectMultiArgHandler(Target target, Type[] args, int argIndex, InsnList insns) { if (!Arrays.equals(args, this.methodArgs)) { throw new InvalidInjectionException(this.info, "@ModifyArg method " + this + " targets a method with an invalid signature " - + Injector.printArgs(args) + ", expected " + Injector.printArgs(this.methodArgs)); + + Bytecode.getDescriptor(args) + ", expected " + Bytecode.getDescriptor(this.methodArgs)); } int[] argMap = this.storeArgs(target, args, insns, 0); @@ -146,7 +146,7 @@ public class ModifyArgInjector extends InvokeInjector { if (this.index > -1) { if (this.index >= args.length || !args[this.index].equals(this.returnType)) { throw new InvalidInjectionException(this.info, "Specified index " + this.index + " for @ModifyArg is invalid for args " - + Injector.printArgs(args) + ", expected " + this.returnType + " on " + this); + + Bytecode.getDescriptor(args) + ", expected " + this.returnType + " on " + this); } return this.index; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java new file mode 100644 index 00000000..aa938647 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java @@ -0,0 +1,129 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.invoke; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.InsnNode; +import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.Bytecode; + +/** + * A bytecode injector which allows a single argument of a chosen method call to + * be altered. + */ +public class ModifyArgsInjector extends InvokeInjector { + + /** + * @param info Injection info + * @param index target arg index + */ + public ModifyArgsInjector(InjectionInfo info) { + super(info, "@ModifyArgs"); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.invoke.InvokeInjector + * #checkTarget(org.spongepowered.asm.mixin.injection.struct.Target) + */ + @Override + protected void checkTarget(Target target) { + if (!this.isStatic && target.isStatic) { + throw new InvalidInjectionException(this.info, "non-static callback method " + this + " targets a static method which is not supported"); + } + } + + /** + * Do the injection + */ + @Override + protected void injectAtInvoke(Target target, InjectionNode node) { + MethodInsnNode targetMethod = (MethodInsnNode)node.getCurrentTarget(); + + Type[] args = Type.getArgumentTypes(targetMethod.desc); + if (args.length == 0) { + throw new InvalidInjectionException(this.info, "@ModifyArgs injector " + this + " targets a method invocation " + + targetMethod.name + targetMethod.desc + " with no arguments!"); + } + + String argClass = ArgsClassGenerator.getInstance().getClassRef(targetMethod.desc); + + boolean withArgs = false; + String shortDesc = String.format("(L%s;)V", ArgsClassGenerator.CREF_ARGS); + if (!this.methodNode.desc.equals(shortDesc)) { + String targetDesc = Bytecode.changeDescriptorReturnType(target.method.desc, "V"); + String longDesc = String.format("(L%s;%s", ArgsClassGenerator.CREF_ARGS, targetDesc.substring(1)); + if (this.methodNode.desc.equals(longDesc)) { + withArgs = true; + } else { + throw new InvalidInjectionException(this.info, "@ModifyArgs injector " + this + " has an invalid signature " + + this.methodNode.desc + ", expected " + shortDesc + " or " + longDesc); + } + } + + InsnList insns = new InsnList(); + target.addToStack(1); + + String factoryDesc = Bytecode.changeDescriptorReturnType(targetMethod.desc, "L" + argClass + ";"); + insns.add(new MethodInsnNode(Opcodes.INVOKESTATIC, argClass, "of", factoryDesc, false)); + insns.add(new InsnNode(Opcodes.DUP)); + + if (!this.isStatic) { + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + insns.add(new InsnNode(Opcodes.SWAP)); + } + + if (withArgs) { + target.addToStack(Bytecode.getArgsSize(target.arguments)); + Bytecode.loadArgs(target.arguments, insns, target.isStatic ? 0 : 1); + } + + this.invokeHandler(insns); + + for (int i = 0; i < args.length; i++) { + if (i < args.length - 1) { + insns.add(new InsnNode(Opcodes.DUP)); + } + insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, argClass, ArgsClassGenerator.GETTER + i, "()" + args[i].getDescriptor(), false)); + if (i < args.length - 1) { + if (args[i].getSize() == 1) { + insns.add(new InsnNode(Opcodes.SWAP)); + } else { + insns.add(new InsnNode(Opcodes.DUP2_X1)); + insns.add(new InsnNode(Opcodes.POP2)); + } + } + } + + target.insns.insertBefore(targetMethod, insns); + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index 9e4f779b..b184aa75 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -309,9 +309,9 @@ public class RedirectInjector extends InvokeInjector { final Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args); boolean injectTargetParams = false; - String desc = Injector.printArgs(stackVars) + returnType; + String desc = Bytecode.getDescriptor(stackVars, returnType); if (!desc.equals(this.methodNode.desc)) { - String alternateDesc = Injector.printArgs(ObjectArrays.concat(stackVars, target.arguments, Type.class)) + returnType; + String alternateDesc = Bytecode.getDescriptor(ObjectArrays.concat(stackVars, target.arguments, Type.class), returnType); if (alternateDesc.equals(this.methodNode.desc)) { injectTargetParams = true; } else { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/Args.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/Args.java new file mode 100644 index 00000000..578076e3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/Args.java @@ -0,0 +1,102 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.invoke.arg; + +import org.spongepowered.asm.mixin.injection.ModifyArgs; + +/** + * Argument bundle class used in {@link ModifyArgs} callbacks. See the + * documentation for {@link ModifyArgs} for details. Synthetic subclasses are + * generated at runtime for specific injectors. + */ +public abstract class Args { + + /** + * Argument values + */ + protected final Object[] values; + + /** + * Ctor. + * + * @param values argument values + */ + protected Args(Object[] values) { + this.values = values; + } + + /** + * Return the argument list size. + * + * @return number of arguments available + */ + public int size() { + return this.values.length; + } + + /** + * Retrieve the argument value at the specified index + * + * @param index argument index to retrieve + * @param the argument type + * @return the argument value + * @throws ArrayIndexOutOfBoundsException if a value outside the range of + * available arguments is accessed + */ + @SuppressWarnings("unchecked") + public T get(int index) { + return (T)this.values[index]; + } + + /** + * Set (modify) the specified argument value. Internal verification is + * performed upon supplied values and the following requirements are + * enforced: + * + *
    + *
  • Reference types must be assignable to the object type, or can be + * null. + *
  • Primitive types must match the target types exactly and cannot + * be null. + *
+ * + * @param index Argument index to set + * @param value Argument value + * @param Argument type + * @throws ArgumentIndexOutOfBoundsException if the specified argument index + * is outside the range of available arguments + */ + public abstract void set(int index, T value); + + /** + * Set (modify) all argument values. The number and type of arguments + * supplied to this method must precisely match the argument types in the + * bundle. See {@link #set(int, Object)} for details. + * + * @param values Argument values to set + */ + public abstract void setAll(Object... values); + +} \ No newline at end of file diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java new file mode 100644 index 00000000..1a70fd30 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java @@ -0,0 +1,515 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.invoke.arg; + +import java.util.HashMap; +import java.util.Map; + +import org.spongepowered.asm.lib.ClassVisitor; +import org.spongepowered.asm.lib.ClassWriter; +import org.spongepowered.asm.lib.Label; +import org.spongepowered.asm.lib.MethodVisitor; +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.util.CheckClassAdapter; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.ModifyArgs; +import org.spongepowered.asm.mixin.transformer.IClassGenerator; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.SignaturePrinter; +import org.spongepowered.asm.util.visitor.MethodVisitorEx; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; + +/** + * Class generator which creates subclasses of {@link Args} to be used by the + * {@link ModifyArgs} injector. The subclasses contain getter and setter logic + * to provide access to a particular configuration of arguments and classes are + * only generated for each unique argument combination. + */ +public final class ArgsClassGenerator implements IClassGenerator { + + public static final String CLASS_NAME_BASE = "org.spongepowered.asm.synthetic.Args$"; + public static final String GETTER = "$"; + + private static final String OBJECT = "java/lang/Object"; + private static final String OBJECT_ARRAY = "[L" + ArgsClassGenerator.OBJECT + ";"; + + public static final String CNAME_ARGS = Args.class.getName(); + public static final String CREF_ARGS = ArgsClassGenerator.CNAME_ARGS.replace('.', '/'); + private static final String CTOR_DESC = "(" + ArgsClassGenerator.OBJECT_ARRAY + ")V"; + + private static final String VALUES_FIELD = "values"; + + private static final String NPE = "java/lang/NullPointerException"; + private static final String AIOOBE = "org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentIndexOutOfBoundsException"; + private static final String ACE = "org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentCountException"; + + /** + * Singleton instance + */ + private static ArgsClassGenerator instance; + + /** + * The next subclass number, classes generated in sequence eg. + * Args$1, Args$2, etc. + */ + private int nextIndex = 1; + + /** + * Map of descriptors to generated class names + */ + private final BiMap classNames = HashBiMap.create(); + + /** + * Generated bytes. Technically a generator shouldn't have to return class + * bytes for a class more than once, but this saves the class being + * regenerated if anything causes a second invocation of {@link #generate} + * for the same class + */ + private final Map classBytes = new HashMap(); + + private ArgsClassGenerator() { + // singleton (for now) + } + + /** + * Get (or generate) the class name for the specified descriptor. The class + * will not be generated until it is used. Calling this method simply + * allocates a name for the specified descriptor. + * + * @param desc Descriptor of the target method, with the return + * type changed to void (V) + * @return name of the Args subclass to use + */ + public String getClassName(String desc) { + if (!desc.endsWith(")V")) { + throw new IllegalArgumentException("Invalid @ModifyArgs method descriptor"); + } + + String name = this.classNames.get(desc); + if (name == null) { + name = String.format("%s%d", ArgsClassGenerator.CLASS_NAME_BASE, this.nextIndex++); + this.classNames.put(desc, name); + } + return name; + } + + /** + * Get (or generate) the class name for the specified descriptor in internal + * format (reference). The class will not be generated until it is used. + * Calling this method simply allocates a name for the specified descriptor. + * + * @param desc Descriptor of the target method, with the return + * type changed to void (V) + * @return reference of the Args subclass to use + */ + public String getClassRef(String desc) { + return this.getClassName(desc).replace('.', '/'); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.IClassGenerator#generate + * (java.lang.String) + */ + @Override + public byte[] generate(String name) { + return this.getBytes(name); + } + + /** + * Fetch or generate class bytes for the specified class name. Returns null + * if this generator does not have bytes for the specified class. + * + * @param name Class name + * @return class bytes or null + */ + public byte[] getBytes(String name) { + byte[] bytes = this.classBytes.get(name); + if (bytes == null) { + String desc = this.classNames.inverse().get(name); + if (desc == null) { + return null; + } + bytes = this.generateClass(name, desc); + this.classBytes.put(name, bytes); + } + return bytes; + } + + /** + * Generate an {@link Args} subclass + * + * @param name Class name to generate + * @param desc Argument descriptor (return type ignored) + * @return generated class + */ + private byte[] generateClass(String name, String desc) { + String ref = name.replace('.', '/'); + Type[] args = Type.getArgumentTypes(desc); + + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + ClassVisitor visitor = writer; + if (MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERIFY)) { + visitor = new CheckClassAdapter(writer); + } + + visitor.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, ref, null, ArgsClassGenerator.CREF_ARGS, null); + visitor.visitSource(name.substring(name.lastIndexOf('.') + 1) + ".java", null); + + this.generateCtor(ref, desc, args, visitor); + this.generateFactory(ref, desc, args, visitor); + this.generateSetters(ref, desc, args, visitor); + this.generateGetters(ref, desc, args, visitor); + + visitor.visitEnd(); + + return writer.toByteArray(); + } + + /** + * Generate the constructor for the subclass, the ctor simply calls the + * superclass ctor and does nothing else besides + * + * @param ref Class ref being generated + * @param desc Argument descriptor + * @param args Parsed argument list from descriptor + * @param writer Class writer + */ + private void generateCtor(String ref, String desc, Type[] args, ClassVisitor writer) { + MethodVisitor ctor = writer.visitMethod(Opcodes.ACC_PRIVATE, Constants.CTOR, ArgsClassGenerator.CTOR_DESC, null, null); + ctor.visitCode(); + ctor.visitVarInsn(Opcodes.ALOAD, 0); + ctor.visitVarInsn(Opcodes.ALOAD, 1); + ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, ArgsClassGenerator.CREF_ARGS, Constants.CTOR, ArgsClassGenerator.CTOR_DESC, false); + ctor.visitInsn(Opcodes.RETURN); + ctor.visitMaxs(2, 2); + ctor.visitEnd(); + } + + /** + * Generate the factory method (of) for the subclass, the factory + * method takes the arguments which would have been passed to the target + * method, marshals them into an Object[] array, and then calls the + * constructor. + * + * @param ref Class ref being generated + * @param desc Argument descriptor + * @param args Parsed argument list from descriptor + * @param writer Class writer + */ + private void generateFactory(String ref, String desc, Type[] args, ClassVisitor writer) { + String factoryDesc = Bytecode.changeDescriptorReturnType(desc, "L" + ref + ";"); + MethodVisitorEx of = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "of", factoryDesc, null, null)); + of.visitCode(); + + // Create args subclass + of.visitTypeInsn(Opcodes.NEW, ref); + of.visitInsn(Opcodes.DUP); + + // Create Object[] array to contain args + of.visitConstant((byte)args.length); + of.visitTypeInsn(Opcodes.ANEWARRAY, ArgsClassGenerator.OBJECT); + + // Iterate over args and stuff them into the array + byte argIndex = 0; + for (Type arg : args) { + of.visitInsn(Opcodes.DUP); + of.visitConstant(argIndex); + of.visitVarInsn(arg.getOpcode(Opcodes.ILOAD), argIndex++); + ArgsClassGenerator.box(of, arg); + of.visitInsn(Opcodes.AASTORE); + } + + // Call the constructor passing in the generated array + of.visitMethodInsn(Opcodes.INVOKESPECIAL, ref, Constants.CTOR, ArgsClassGenerator.CTOR_DESC, false); + + // Return the new object + of.visitInsn(Opcodes.ARETURN); + + of.visitMaxs(6, Bytecode.getArgsSize(args)); + of.visitEnd(); + } + + /** + * Generate the getter method for each arguments. These getters are not + * available from consumer code, but instead are called by the injector to + * retrieve each argument in turn for passing to the method invocation being + * modified. + * + * @param ref Class ref being generated + * @param desc Argument descriptor + * @param args Parsed argument list from descriptor + * @param writer Class writer + */ + private void generateGetters(String ref, String desc, Type[] args, ClassVisitor writer) { + byte argIndex = 0; + for (Type arg : args) { + String name = ArgsClassGenerator.GETTER + argIndex; + String sig = "()" + arg.getDescriptor(); + MethodVisitorEx get = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC, name, sig, null, null)); + get.visitCode(); + + // Read the value from the values field + get.visitVarInsn(Opcodes.ALOAD, 0); + get.visitFieldInsn(Opcodes.GETFIELD, ref, ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); + get.visitConstant(argIndex); + get.visitInsn(Opcodes.AALOAD); + + // Unbox (if primitive) or cast down the value + ArgsClassGenerator.unbox(get, arg); + + // Return the value + get.visitInsn(arg.getOpcode(Opcodes.IRETURN)); + + + get.visitMaxs(2, 1); + get.visitEnd(); + argIndex++; + } + } + + /** + * Generate the set method body. The set method performs a + * CHECKCAST on all incoming arguments, checks that the argument + * index is not out of bounds, and also ensures that primitive types are not + * assigned null by the consumer code. + * + * @param ref Class ref being generated + * @param desc Argument descriptor + * @param args Parsed argument list from descriptor + * @param writer Class writer + */ + private void generateSetters(String ref, String desc, Type[] args, ClassVisitor writer) { + this.generateIndexedSetter(ref, desc, args, writer); + this.generateMultiSetter(ref, desc, args, writer); + } + + /** + * Generate the set method body. The set method performs a + * CHECKCAST on all incoming arguments, checks that the argument + * index is not out of bounds, and also ensures that primitive types are not + * assigned null by the consumer code. + * + * @param ref Class ref being generated + * @param desc Argument descriptor + * @param args Parsed argument list from descriptor + * @param writer Class writer + */ + private void generateIndexedSetter(String ref, String desc, Type[] args, ClassVisitor writer) { + MethodVisitorEx set = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC, "set", "(ILjava/lang/Object;)V", null, null)); + set.visitCode(); + + Label store = new Label(), checkNull = new Label(); + Label[] labels = new Label[args.length]; + for (int label = 0; label < labels.length; label++) { + labels[label] = new Label(); + } + + // Put the values array on the stack to begin with + set.visitVarInsn(Opcodes.ALOAD, 0); + set.visitFieldInsn(Opcodes.GETFIELD, ref, ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); + + // Each argument index will jump to its own label + for (byte index = 0; index < args.length; index++) { + set.visitVarInsn(Opcodes.ILOAD, 1); + set.visitConstant(index); + set.visitJumpInsn(Opcodes.IF_ICMPEQ, labels[index]); + } + + // No argument was matched, so we throw an out of bounds exception + ArgsClassGenerator.throwAIOOBE(set, 1); + + // For each arg we do a CHECKCAST to ensure the supplied type is + // assignable to the arg type, we leave the index and value on the stack + // and jump to the next stage + for (int index = 0; index < args.length; index++) { + String boxingType = Bytecode.getBoxingType(args[index]); + set.visitLabel(labels[index]); + set.visitVarInsn(Opcodes.ILOAD, 1); + set.visitVarInsn(Opcodes.ALOAD, 2); + set.visitTypeInsn(Opcodes.CHECKCAST, boxingType != null ? boxingType : args[index].getInternalName()); + set.visitJumpInsn(Opcodes.GOTO, boxingType != null ? checkNull : store); + } + + // For primitive types, we check that the supplied value is not null + set.visitLabel(checkNull); + set.visitInsn(Opcodes.DUP); + set.visitJumpInsn(Opcodes.IFNONNULL, store); + + // If the arg type is primitive but the user supplied NULL, throw an exception + ArgsClassGenerator.throwNPE(set, "Argument with primitive type cannot be set to NULL"); + + // Everything above succeeded, so we just assign the value into the array + set.visitLabel(store); + set.visitInsn(Opcodes.AASTORE); + set.visitInsn(Opcodes.RETURN); + set.visitMaxs(6, 3); + set.visitEnd(); + } + + /** + * Generate the varargs set method body. The set method + * performs a CHECKCAST on all incoming arguments, and also ensures + * that primitive types are not assigned null by the consumer code. + * + * @param ref Class ref being generated + * @param desc Argument descriptor + * @param args Parsed argument list from descriptor + * @param writer Class writer + */ + private void generateMultiSetter(String ref, String desc, Type[] args, ClassVisitor writer) { + MethodVisitorEx set = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC, "setAll", "([Ljava/lang/Object;)V", null, null)); + set.visitCode(); + + Label lengthOk = new Label(), nullPrimitive = new Label(); + int maxStack = 6; + + // Compare the length of the varargs array to the expected argument count + set.visitVarInsn(Opcodes.ALOAD, 1); + set.visitInsn(Opcodes.ARRAYLENGTH); + set.visitInsn(Opcodes.DUP); + set.visitConstant((byte)args.length); + + // If the lengths are the same, proceed with assignment + set.visitJumpInsn(Opcodes.IF_ICMPEQ, lengthOk); + + set.visitTypeInsn(Opcodes.NEW, ArgsClassGenerator.ACE); + set.visitInsn(Opcodes.DUP); + set.visitInsn(Opcodes.DUP2_X1); + set.visitInsn(Opcodes.POP2); + set.visitConstant((byte)args.length); + set.visitLdcInsn(new SignaturePrinter("", null, args).setFullyQualified(true).getFormattedArgs()); + + set.visitMethodInsn(Opcodes.INVOKESPECIAL, ArgsClassGenerator.ACE, Constants.CTOR, "(IILjava/lang/String;)V", false); + set.visitInsn(Opcodes.ATHROW); + + set.visitLabel(lengthOk); + set.visitInsn(Opcodes.POP); // Pop the remaining length value + + // Put the values array on the stack to begin with + set.visitVarInsn(Opcodes.ALOAD, 0); + set.visitFieldInsn(Opcodes.GETFIELD, ref, ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); + + for (byte index = 0; index < args.length; index++) { + // Dup the member array reference and target index + set.visitInsn(Opcodes.DUP); + set.visitConstant(index); + + // Read the value from the varargs array + set.visitVarInsn(Opcodes.ALOAD, 1); + set.visitConstant(index); + set.visitInsn(Opcodes.AALOAD); + + // Check the argument type + String boxingType = Bytecode.getBoxingType(args[index]); + set.visitTypeInsn(Opcodes.CHECKCAST, boxingType != null ? boxingType : args[index].getInternalName()); + + // For primitives, check the value is not null + if (boxingType != null) { + set.visitInsn(Opcodes.DUP); + set.visitJumpInsn(Opcodes.IFNULL, nullPrimitive); + maxStack = 7; + } + + // Everything succeeded, assign the value + set.visitInsn(Opcodes.AASTORE); + } + + set.visitInsn(Opcodes.RETURN); + + set.visitLabel(nullPrimitive); + ArgsClassGenerator.throwNPE(set, "Argument with primitive type cannot be set to NULL"); + set.visitInsn(Opcodes.RETURN); + + set.visitMaxs(maxStack, 2); + set.visitEnd(); + } + + private static void throwNPE(MethodVisitorEx method, String message) { + method.visitTypeInsn(Opcodes.NEW, ArgsClassGenerator.NPE); + method.visitInsn(Opcodes.DUP); + method.visitLdcInsn(message); + method.visitMethodInsn(Opcodes.INVOKESPECIAL, ArgsClassGenerator.NPE, Constants.CTOR, "(Ljava/lang/String;)V", false); + method.visitInsn(Opcodes.ATHROW); + } + + private static void throwAIOOBE(MethodVisitorEx method, int arg) { + method.visitTypeInsn(Opcodes.NEW, ArgsClassGenerator.AIOOBE); + method.visitInsn(Opcodes.DUP); + method.visitVarInsn(Opcodes.ILOAD, arg); + method.visitMethodInsn(Opcodes.INVOKESPECIAL, ArgsClassGenerator.AIOOBE, Constants.CTOR, "(I)V", false); + method.visitInsn(Opcodes.ATHROW); + } + + /** + * Box (if necessary) the supplied primitive type. Does not affect + * reference types. + * + * @param method method visitor + * @param var type to box + */ + private static void box(MethodVisitor method, Type var) { + String boxingType = Bytecode.getBoxingType(var); + if (boxingType != null) { + String desc = String.format("(%s)L%s;", var.getDescriptor(), boxingType); + method.visitMethodInsn(Opcodes.INVOKESTATIC, boxingType, "valueOf", desc, false); + } + } + + /** + * Unbox (if necessary, otherwise just CHECKCAST) the supplied type + * + * @param method method visitor + * @param var type to unbox + */ + private static void unbox(MethodVisitor method, Type var) { + String boxingType = Bytecode.getBoxingType(var); + if (boxingType != null) { + String unboxingMethod = Bytecode.getUnboxingMethod(var); + String desc = "()" + var.getDescriptor(); + method.visitTypeInsn(Opcodes.CHECKCAST, boxingType); + method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, boxingType, unboxingMethod, desc, false); + } else { + method.visitTypeInsn(Opcodes.CHECKCAST, var.getInternalName()); + } + } + + /** + * Get the singleton instance + * + * @return the singleton instance + */ + public static ArgsClassGenerator getInstance() { + if (ArgsClassGenerator.instance == null) { + ArgsClassGenerator.instance = new ArgsClassGenerator(); + } + return ArgsClassGenerator.instance; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentCountException.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentCountException.java new file mode 100644 index 00000000..6808ba0f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentCountException.java @@ -0,0 +1,39 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.invoke.arg; + +/** + * Exception thrown when varargs array passed into {@link Args#setAll} + * is of a different length than the args + */ +public class ArgumentCountException extends IllegalArgumentException { + + private static final long serialVersionUID = 1L; + + public ArgumentCountException(int received, int expected, String desc) { + super("Invalid number of arguments for setAll, received " + received + " but expected " + expected + ": " + desc); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentIndexOutOfBoundsException.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentIndexOutOfBoundsException.java new file mode 100644 index 00000000..b775072a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentIndexOutOfBoundsException.java @@ -0,0 +1,39 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.invoke.arg; + +/** + * Exception thrown when attempting to set an argument (via) {@link Args} which + * is out of bounds + */ +public class ArgumentIndexOutOfBoundsException extends IndexOutOfBoundsException { + + private static final long serialVersionUID = 1L; + + public ArgumentIndexOutOfBoundsException(int index) { + super("Argument index is out of bounds: " + index); + } + +} 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 26e2ef34..c2f2701d 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 @@ -45,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; @@ -60,8 +61,8 @@ import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; /** * Contructs information about an injection from an {@link Inject} annotation @@ -408,6 +409,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC 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(ModifyArgs.class.getSimpleName() + ";")) { + return new ModifyArgsInjectionInfo(mixin, method, annotation); } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { return new RedirectInjectionInfo(mixin, method, annotation); } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { @@ -435,6 +438,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC annotation = Annotations.getSingleVisible(method, Inject.class, ModifyArg.class, + ModifyArgs.class, Redirect.class, ModifyVariable.class, ModifyConstant.class @@ -456,6 +460,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC if (annotation != null) { if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) { return "modify"; + } else if (annotation.desc.endsWith(ModifyArgs.class.getSimpleName() + ";")) { + return "args"; } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { return "redirect"; } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java new file mode 100644 index 00000000..ca1104be --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java @@ -0,0 +1,53 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.ModifyArgs; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.invoke.ModifyArgsInjector; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + * Information about a {@link ModifyArgs} injector + */ +public class ModifyArgsInjectionInfo extends InjectionInfo { + + public ModifyArgsInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected Injector parseInjector(AnnotationNode injectAnnotation) { + return new ModifyArgsInjector(this); + } + + @Override + protected String getDescription() { + return "Multi-argument modifier method"; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IClassGenerator.java new file mode 100644 index 00000000..aef95f61 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IClassGenerator.java @@ -0,0 +1,43 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +/** + * Base interface for class generators + */ +public interface IClassGenerator { + + /** + * Generate (if possible) the specified class name. The generator should + * return null if it cannot generate the specified class, in order + * that the next generator in the chain can process the request. The first + * generator to return a value will halt further processing of the request. + * + * @param name Class name to generate + * @return Class bytecode or null + */ + public abstract byte[] generate(String name); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 8a607ff8..fbb2e9bf 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -51,6 +51,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; @@ -58,8 +59,8 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.ConstraintParser; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -80,6 +81,7 @@ class MixinApplicatorStandard { Overwrite.class, Inject.class, ModifyArg.class, + ModifyArgs.class, Redirect.class, ModifyVariable.class, ModifyConstant.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 02d125d1..9b946ea6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -53,6 +53,7 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator; import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; import org.spongepowered.asm.mixin.throwables.MixinApplyError; import org.spongepowered.asm.mixin.throwables.MixinException; @@ -403,6 +404,11 @@ public class MixinTransformer extends TreeTransformer { */ private final List modules = new ArrayList(); + /** + * Modules which generate synthetic classes required by mixins + */ + private final List generators = new ArrayList(); + /** * Re-entrance detector */ @@ -469,6 +475,8 @@ public class MixinTransformer extends TreeTransformer { this.exporter = new Exporter(); this.hotSwapper = this.initHotSwapper(); this.postProcessor = new MixinPostProcessor(); + + this.generators.add(ArgsClassGenerator.getInstance()); } private IHotSwap initHotSwapper() { @@ -526,7 +534,17 @@ public class MixinTransformer extends TreeTransformer { */ @Override public synchronized byte[] transform(String name, String transformedName, byte[] basicClass) { - if (basicClass == null || transformedName == null || this.errorState) { + if (transformedName == null || this.errorState) { + return basicClass; + } + + if (basicClass == null) { + for (IClassGenerator generator : this.generators) { + if ((basicClass = generator.generate(transformedName)) != null) { + this.exporter.export(transformedName.replace('.', '/'), true, basicClass); + return basicClass; + } + } return basicClass; } diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index a29ec4bd..2221ba75 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -42,6 +42,7 @@ import org.spongepowered.asm.lib.tree.*; import org.spongepowered.asm.lib.util.CheckClassAdapter; import org.spongepowered.asm.lib.util.TraceClassVisitor; +import com.google.common.base.Joiner; import com.google.common.primitives.Ints; /** @@ -144,6 +145,42 @@ public final class Bytecode { "I", //"S" }; + /** + * Mapping of {@link Type#getSort()} return values to boxing types + */ + private static final String[] BOXING_TYPES = { + null, + "java/lang/Boolean", + "java/lang/Character", + "java/lang/Byte", + "java/lang/Short", + "java/lang/Integer", + "java/lang/Float", + "java/lang/Long", + "java/lang/Double", + null, + null, + null + }; + + /** + * Mapping of {@link Type#getSort()} return values to boxing types + */ + private static final String[] UNBOXING_METHODS = { + null, + "booleanValue", + "charValue", + "byteValue", + "shortValue", + "intValue", + "floatValue", + "longValue", + "doubleValue", + null, + null, + null + }; + private Bytecode() { // utility class } @@ -541,6 +578,44 @@ public final class Bytecode { } return arg == null ? "" : arg.toString(); } + + /** + * Generate a method descriptor without return type for the supplied args + * array + * + * @param args argument types + * @return method descriptor without return type + */ + public static String getDescriptor(Type[] args) { + return "(" + Joiner.on("").join(args) + ")"; + } + + /** + * Generate a method descriptor with the specified types + * + * @param args argument types + * @param returnType return type + * @return generated method descriptor + */ + public static String getDescriptor(Type[] args, Type returnType) { + return Bytecode.getDescriptor(args) + returnType.toString(); + } + + /** + * Changes the return type of a method descriptor to the specified symbol + * + * @param desc descriptor to modify + * @param returnType new return type + * @return modified descriptor; + */ + public static String changeDescriptorReturnType(String desc, String returnType) { + if (desc == null) { + return null; + } else if (returnType == null) { + return desc; + } + return desc.substring(0, desc.lastIndexOf(')') + 1) + returnType; + } /** * Returns the simple name of an annotation, mainly used for printing @@ -787,4 +862,28 @@ public final class Bytecode { return Math.max(min, max + pad); } + /** + * Get the boxing type name for the specified type, if it is a primitive. + * For non-primitive types, null is returned + * + * @param type type to box + * @return boxing type or null + */ + public static String getBoxingType(Type type) { + return type == null ? null : Bytecode.BOXING_TYPES[type.getSort()]; + } + + /** + * Get the unboxing method name for the specified primitive type's + * corresponding reference type. For example, if the type passed in is + * int, then the return value will be intValue. Returns + * null for non-primitive types. + * + * @param type primitive type to get unboxing method for + * @return unboxing method name or null + */ + public static String getUnboxingMethod(Type type) { + return type == null ? null : Bytecode.UNBOXING_METHODS[type.getSort()]; + } + } diff --git a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java index e417d78d..1417cbfb 100644 --- a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java +++ b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java @@ -127,7 +127,7 @@ public class SignaturePrinter { * Return only the arguments portion of this signature as a Java-style block */ public String getFormattedArgs() { - return this.appendArgs(new StringBuilder(), true).toString(); + return this.appendArgs(new StringBuilder(), true, true).toString(); } /** @@ -193,25 +193,25 @@ public class SignaturePrinter { */ @Override public String toString() { - return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(this.name), false).toString(); + return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(this.name), false, true).toString(); } /** * Return this signature in descriptor format (return type after args) */ public String toDescriptor() { - StringBuilder args = this.appendArgs(new StringBuilder(), true); + StringBuilder args = this.appendArgs(new StringBuilder(), true, false); return args.append(SignaturePrinter.getTypeName(this.returnType, false, this.fullyQualified)).toString(); } - private StringBuilder appendArgs(StringBuilder sb, boolean typesOnly) { + private StringBuilder appendArgs(StringBuilder sb, boolean typesOnly, boolean pretty) { sb.append('('); for (int var = 0; var < this.argTypes.length; var++) { if (this.argTypes[var] == null) { continue; } else if (var > 0) { sb.append(','); - if (!typesOnly) { + if (pretty) { sb.append(' '); } } diff --git a/src/main/java/org/spongepowered/asm/util/visitor/MethodVisitorEx.java b/src/main/java/org/spongepowered/asm/util/visitor/MethodVisitorEx.java new file mode 100644 index 00000000..4e530a59 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/visitor/MethodVisitorEx.java @@ -0,0 +1,54 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.visitor; + +import org.spongepowered.asm.lib.MethodVisitor; +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.util.Bytecode; + +/** + * MethodVisitor with some extra convenience functionality + */ +public class MethodVisitorEx extends MethodVisitor { + + public MethodVisitorEx(MethodVisitor mv) { + super(Opcodes.ASM5, mv); + } + + /** + * Visit a byte constant instruction. The most specific constant instruction + * will be used where possible + * + * @param constant constant value to visit + */ + public void visitConstant(byte constant) { + if (constant > -2 && constant < 6) { + this.visitInsn(Bytecode.CONSTANTS_INT[constant + 1]); + return; + } + this.visitIntInsn(Opcodes.BIPUSH, constant); + } + +}