diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index ff135a4a..ef5ffcb6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -31,9 +31,14 @@ import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; +import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; +import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.points.AfterInvoke; import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; import org.spongepowered.asm.mixin.injection.points.BeforeInvoke; @@ -308,12 +313,15 @@ public abstract class InjectionPoint { * * @param mixin Data for the mixin containing the annotation, used to obtain * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation * @param at {@link At} annotation to parse information from * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ - public static InjectionPoint parse(MixinTargetContext mixin, At at) { - return InjectionPoint.parse(mixin, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode()); + public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, At at) { + List args = Arrays.asList(at.args()); + return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), args, at.target(), at.ordinal(), at.opcode()); } /** @@ -322,11 +330,13 @@ public abstract class InjectionPoint { * * @param mixin Data for the mixin containing the annotation, used to obtain * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation * @param node {@link At} annotation to parse information from * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ - public static InjectionPoint parse(MixinTargetContext mixin, AnnotationNode node) { + public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, AnnotationNode node) { String at = ASMHelper.getAnnotationValue(node, "value"); List args = ASMHelper.>getAnnotationValue(node, "args"); String target = ASMHelper.getAnnotationValue(node, "target", ""); @@ -339,7 +349,7 @@ public abstract class InjectionPoint { args = ImmutableList.of(); } - return InjectionPoint.parse(mixin, at, shift, by, args, target, ordinal, opcode); + return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, ordinal, opcode); } /** @@ -348,6 +358,8 @@ public abstract class InjectionPoint { * * @param mixin Data for the mixin containing the annotation, used to obtain * the refmap, amongst other things + * @param method The annotated handler method + * @param parent The parent annotation which owns this {@link At} annotation * @param at Injection point specifier * @param shift Shift type to apply * @param by Amount of shift to apply for the BY shift type @@ -358,7 +370,7 @@ public abstract class InjectionPoint { * @return InjectionPoint parsed from the supplied data or null if parsing * failed */ - public static InjectionPoint parse(MixinTargetContext mixin, String at, At.Shift shift, int by, + public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, At.Shift shift, int by, List args, String target, int ordinal, int opcode) { InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode); InjectionPoint point = null; @@ -379,6 +391,12 @@ public abstract class InjectionPoint { point = new MethodHead(data); } else if (AfterInvoke.CODE.equals(at)) { point = new AfterInvoke(data); + } else if (BeforeLoadLocal.CODE.equals(at)) { + LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent); + point = new BeforeLoadLocal(mixin, Type.getReturnType(method.desc), discriminator, data); + } else if (AfterStoreLocal.CODE.equals(at)) { + LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent); + point = new AfterStoreLocal(mixin, Type.getReturnType(method.desc), discriminator, data); } else if (at.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { try { @SuppressWarnings("unchecked") Class cls = (Class) Class.forName(at); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java index 03d551e3..3b896892 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java @@ -28,7 +28,6 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.transformer.InvalidMixinException; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; - public class InvalidInjectionException extends InvalidMixinException { private static final long serialVersionUID = 1L; 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 fafe0188..304f8d5c 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 @@ -147,7 +147,7 @@ public abstract class Injector { return targetNodes; } - protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, ReadOnlyInsnList insns, Collection nodes) { + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { return injectionPoint.find(into.desc, insns, nodes); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java new file mode 100644 index 00000000..2ed1e3e0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java @@ -0,0 +1,81 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; + +/** + *

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

+ * + *

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

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

Example:

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

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

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

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

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

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

+ * + *

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

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

Example:

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

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

+ *
+ *   @At("LOAD")
+ *
+ */ +public class BeforeLoadLocal extends ContextualInjectionPoint { + + static class SearchState { + + private final int targetOrdinal; + private int ordinal = 0; + private boolean pendingCheck = false; + private boolean found = false; + private VarInsnNode varNode; + + SearchState(int targetOrdinal) { + this.targetOrdinal = targetOrdinal; + } + + boolean success() { + return this.found; + } + + boolean isPendingCheck() { + return this.pendingCheck; + } + + void setPendingCheck() { + this.pendingCheck = true; + } + + void register(VarInsnNode node) { + this.varNode = node; + } + + void check(Collection nodes, AbstractInsnNode insn, int local) { + this.pendingCheck = false; + if (local != this.varNode.var) { + return; + } + + if (this.targetOrdinal == -1 || this.targetOrdinal == this.ordinal) { + nodes.add(insn); + this.found = true; + } + + this.ordinal++; + this.varNode = null; + } + + } + + public static final String CODE = "LOAD"; + + private final Type returnType; + + private final LocalVariableDiscriminator discriminator; + + private final int opcode; + + private final int ordinal; + + private boolean opcodeAfter; + + public BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data) { + this(mixin, returnType, discriminator, data, Opcodes.ILOAD, false); + } + + protected BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data, + int opcode, boolean opcodeAfter) { + super(mixin); + this.returnType = returnType; + this.discriminator = discriminator; + this.opcode = data.getOpcode(returnType.getOpcode(opcode)); + this.ordinal = data.getOrdinal(); + this.opcodeAfter = opcodeAfter; + } + + @Override + boolean find(Target target, Collection nodes) { + SearchState state = new SearchState(this.ordinal); + + ListIterator iter = target.method.instructions.iterator(); + while (iter.hasNext()) { + AbstractInsnNode insn = iter.next(); + if (state.isPendingCheck()) { + int local = this.discriminator.findLocal(this.mixin, this.returnType, this.discriminator.isArgsOnly(), target, insn); + state.check(nodes, insn, local); + } else if (insn instanceof VarInsnNode && insn.getOpcode() == this.opcode && (this.ordinal == -1 || !state.success())) { + state.register((VarInsnNode)insn); + if (this.opcodeAfter) { + state.setPendingCheck(); + } else { + int local = this.discriminator.findLocal(this.mixin, this.returnType, this.discriminator.isArgsOnly(), target, insn); + state.check(nodes, insn, local); + } + } + } + + return state.success(); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/InvalidImplicitDiscriminatorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/InvalidImplicitDiscriminatorException.java new file mode 100644 index 00000000..0504cb56 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/InvalidImplicitDiscriminatorException.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.modify; + +public class InvalidImplicitDiscriminatorException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public InvalidImplicitDiscriminatorException(String message) { + super(message); + } + + public InvalidImplicitDiscriminatorException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java new file mode 100644 index 00000000..f54bb9f0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java @@ -0,0 +1,291 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.modify; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.lib.tree.LocalVariableNode; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.Locals; +import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable; +import org.spongepowered.asm.util.SignaturePrinter; + +public class LocalVariableDiscriminator { + + public static class Context implements IPrettyPrintable { + + public class Local { + + int ord = 0; + String name; + Type type; + + public Local(String name, Type type) { + this.name = name; + this.type = type; + } + + @Override + public String toString() { + return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type); + } + + } + + final Target target; + final Type returnType; + final AbstractInsnNode node; + final int baseArgIndex; + final Local[] locals; + + private final boolean isStatic; + + public Context(MixinTargetContext mixin, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + this(mixin.getTargetClass(), returnType, argsOnly, target, node); + } + + public Context(ClassNode targetClass, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + this.isStatic = ASMHelper.methodIsStatic(target.method); + this.returnType = returnType; + this.target = target; + this.node = node; + this.baseArgIndex = this.isStatic ? 0 : 1; + this.locals = this.initLocals(targetClass, target, argsOnly, node); + this.initOrdinals(); + } + + private Local[] initLocals(ClassNode targetClass, Target target, boolean argsOnly, AbstractInsnNode node) { + if (!argsOnly) { + LocalVariableNode[] locals = Locals.getLocalsAt(targetClass, target.method, node); + if (locals != null) { + Local[] lvt = new Local[locals.length]; + for (int l = 0; l < locals.length; l++) { + if (locals[l] != null) { + lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc)); + } + } + return lvt; + } + } + + Local[] lvt = new Local[this.baseArgIndex + target.arguments.length]; + if (!this.isStatic) { + lvt[0] = new Local("this", Type.getType(targetClass.name)); + } + for (int local = this.baseArgIndex; local < lvt.length; local++) { + Type arg = target.arguments[local - this.baseArgIndex]; + lvt[local] = new Local("arg" + local, arg); + } + return lvt; + } + + private void initOrdinals() { + Map ordinalMap = new HashMap(); + for (int l = 0; l < this.locals.length; l++) { + Integer ordinal = Integer.valueOf(0); + if (this.locals[l] != null) { + ordinal = ordinalMap.get(this.locals[l].type); + ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1)); + this.locals[l].ord = ordinal.intValue(); + } + } + } + + @Override + public void print(PrettyPrinter printer) { + printer.add("%5s %7s %20s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE"); + for (int l = this.baseArgIndex; l < this.locals.length; l++) { + Local local = this.locals[l]; + if (local != null) { + Type localType = local.type; + String localName = local.name; + int ordinal = local.ord; + String candidate = this.returnType.equals(localType) ? "YES" : "-"; + printer.add("[%3d] [%3d] %20s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate); + } else if (l > 0) { + Local prevLocal = this.locals[l - 1]; + boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1; + printer.add("[%3d] %20s", l, isTop ? "" : "-"); + } + } + } + + } + + /** + * True to consider only method args + */ + private final boolean argsOnly; + + /** + * Ordinal of the target variable or -1 to fail over to {@link index} + */ + private final int ordinal; + + /** + * Ordinal of the target variable or -1 to fail over to {@link names} + */ + private final int index; + + /** + * Candidate names for the local variable, if empty fails over to matching + * single local by type + */ + private final Set names; + + /** + * @param argsOnly + * @param ordinal target variable ordinal + * @param index target variable index + * @param names target variable names + */ + public LocalVariableDiscriminator(boolean argsOnly, int ordinal, int index, Set names) { + this.argsOnly = argsOnly; + this.ordinal = ordinal; + this.index = index; + this.names = Collections.unmodifiableSet(names); + } + + public boolean isArgsOnly() { + return this.argsOnly; + } + + public int getOrdinal() { + return this.ordinal; + } + + public int getIndex() { + return this.index; + } + + public Set getNames() { + return this.names; + } + + public boolean hasNames() { + return !this.names.isEmpty(); + } + + /** + * If the user specifies no values for {@link ordinal}, {@link index} or + * {@link names} then we are considered to be operating in "implicit mode" + * where only a single local variable of the specified type is expected to + * exist. + * + * @param context Target context + * @return true if operating in implicit mode + */ + protected boolean isImplicit(final Context context) { + return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty(); + } + + public int findLocal(MixinTargetContext mixin, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + try { + return this.findLocal(new Context(mixin, returnType, argsOnly, target, node)); + } catch (InvalidImplicitDiscriminatorException ex) { + return -1; + } + } + + public int findLocal(Context context) { + if (this.isImplicit(context)) { + return this.findImplicitLocal(context); + } + return this.findExplicitLocal(context); + } + + private int findImplicitLocal(final Context context) { + int found = 0; + int count = 0; + for (int index = context.baseArgIndex; index < context.locals.length; index++) { + Local local = context.locals[index]; + if (local == null || !local.type.equals(context.returnType)) { + continue; + } + count++; + found = index; + } + + if (count == 1) { + return found; + } + + throw new InvalidImplicitDiscriminatorException("Found " + count + " candidate variables but exactly 1 is required."); + } + + private int findExplicitLocal(final Context context) { + for (int index = context.baseArgIndex; index < context.locals.length; index++) { + Local local = context.locals[index]; + if (local == null || !local.type.equals(context.returnType)) { + continue; + } + if (this.ordinal > -1) { + if (this.ordinal == local.ord) { + return index; + } + continue; + } + if (this.index >= context.baseArgIndex) { + if (this.index == index) { + return index; + } + continue; + } + if (this.names.contains(local.name)) { + return index; + } + } + + return -1; + } + + public static LocalVariableDiscriminator parse(AnnotationNode annotation) { + boolean argsOnly = ASMHelper.getAnnotationValue(annotation, "argsOnly", Boolean.FALSE).booleanValue(); + int ordinal = ASMHelper.getAnnotationValue(annotation, "ordinal", -1); + int index = ASMHelper.getAnnotationValue(annotation, "index", -1); + + Set names = new HashSet(); + List namesList = ASMHelper.>getAnnotationValue(annotation, "name", (List)null); + if (namesList != null) { + names.addAll(namesList); + } + + return new LocalVariableDiscriminator(argsOnly, ordinal, index, names); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index aef5beb4..7868baae 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -24,26 +24,23 @@ */ package org.spongepowered.asm.mixin.injection.modify; -import java.util.HashMap; +import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.Set; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.AbstractInsnNode; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.LocalVariableNode; +import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.lib.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.modify.ModifyVariableInjector.Context.Local; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; -import org.spongepowered.asm.util.Locals; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.asm.util.SignaturePrinter; @@ -52,84 +49,33 @@ import org.spongepowered.asm.util.SignaturePrinter; * be altered. */ public class ModifyVariableInjector extends Injector { - - class Context extends InsnList { - class Local { - - int ord = 0; - String name; - Type type; + static class Context extends LocalVariableDiscriminator.Context { + final InsnList insns = new InsnList(); - public Local(String name, Type type) { - this.name = name; - this.type = type; - } - - @Override - public String toString() { - return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type); - } - + public Context(ClassNode targetClass, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { + super(targetClass, returnType, argsOnly, target, node); } - final Target target; - final AbstractInsnNode node; - final int baseArgIndex; - final Local[] locals; - - private final ClassNode targetClass; - private final boolean isStaticHandler; - - public Context(ClassNode targetClass, boolean isStaticHandler, Target target, AbstractInsnNode node, boolean argsOnly) { - this.targetClass = targetClass; - this.isStaticHandler = isStaticHandler; - this.target = target; - this.node = node; - this.baseArgIndex = this.isStaticHandler ? 0 : 1; - this.locals = this.initLocals(target, node, argsOnly); - this.initOrdinals(); - } - - private Local[] initLocals(Target target, AbstractInsnNode node, boolean argsOnly) { - if (!argsOnly) { - LocalVariableNode[] locals = Locals.getLocalsAt(this.targetClass, target.method, node); - if (locals != null) { - Local[] lvt = new Local[locals.length]; - for (int l = 0; l < locals.length; l++) { - if (locals[l] != null) { - lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc)); - } - } - return lvt; - } - } - - Local[] lvt = new Local[this.baseArgIndex + target.arguments.length]; - if (!this.isStaticHandler) { - lvt[0] = new Local("this", Type.getType(this.targetClass.name)); - } - for (int local = this.baseArgIndex; local < lvt.length; local++) { - Type arg = target.arguments[local - this.baseArgIndex]; - lvt[local] = new Local("arg" + local, arg); - } - return lvt; - } - - private void initOrdinals() { - Map ordinalMap = new HashMap(); - for (int l = 0; l < this.locals.length; l++) { - Integer ordinal = Integer.valueOf(0); - if (this.locals[l] != null) { - ordinal = ordinalMap.get(this.locals[l].type); - ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1)); - this.locals[l].ord = ordinal.intValue(); - } - } - } - } + + abstract static class ContextualInjectionPoint extends InjectionPoint { + + protected final MixinTargetContext mixin; + ContextualInjectionPoint(MixinTargetContext mixin) { + this.mixin = mixin; + } + + @Override + public boolean find(String desc, InsnList insns, Collection nodes) { + throw new InvalidInjectionException(this.mixin, "STORE injection point must be used in conjunction with @ModifyVariable"); + } + + abstract boolean find(Target target, Collection nodes); + + } + /** * Print LVT */ @@ -138,40 +84,24 @@ public class ModifyVariableInjector extends Injector { /** * True to consider only method args */ - private final boolean argsOnly; - - /** - * Ordinal of the target variable or -1 to fail over to {@link index} - */ - private final int ordinal; - - /** - * Ordinal of the target variable or -1 to fail over to {@link names} - */ - private final int index; - - /** - * Candidate names for the local variable, if empty fails over to matching - * single local by type - */ - private final Set names; + private final LocalVariableDiscriminator discriminator; /** * @param info Injection info * @param print - * @param argsOnly - * @param ordinal target variable ordinal - * @param index target variable index - * @param names target variable names */ - public ModifyVariableInjector(InjectionInfo info, boolean print, boolean argsOnly, int ordinal, int index, Set names) { + public ModifyVariableInjector(InjectionInfo info, boolean print, LocalVariableDiscriminator discriminator) { super(info); - this.print = print; - this.argsOnly = argsOnly; - this.ordinal = ordinal; - this.index = index; - this.names = names; + this.discriminator = discriminator; + } + + @Override + protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection nodes) { + if (injectionPoint instanceof ContextualInjectionPoint) { + return ((ContextualInjectionPoint)injectionPoint).find(this.info.getContext().getTargetMethod(into), nodes); + } + return injectionPoint.find(into.desc, insns, nodes); } /* (non-Javadoc) @@ -187,45 +117,37 @@ public class ModifyVariableInjector extends Injector { throw new InvalidInjectionException(this.info, "'static' of variable modifier method does not match target in " + this.methodNode.name); } - if (this.ordinal < -1) { - throw new InvalidInjectionException(this.info, "Invalid ordinal " + this.ordinal + " specified in " + this.methodNode.name); + int ordinal = this.discriminator.getOrdinal(); + if (ordinal < -1) { + throw new InvalidInjectionException(this.info, "Invalid ordinal " + ordinal + " specified in " + this.methodNode.name); } - if (this.index == 0 && !this.isStatic) { + if (this.discriminator.getIndex() == 0 && !this.isStatic) { throw new InvalidInjectionException(this.info, "Invalid index 0 specified in non-static variable modifier " + this.methodNode.name); } } - /** - * If the user specifies no values for {@link ordinal}, {@link index} or - * {@link names} then we are considered to be operating in "implicit mode" - * where only a single local variable of the specified type is expected to - * exist. - * - * @param context Target context - * @return true if operating in implicit mode - */ - protected boolean isImplicitMode(final Context context) { - return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty(); - } - /** * Do the injection */ @Override protected void inject(Target target, AbstractInsnNode node) { - Context context = new Context(this.classNode, this.isStatic, target, node, this.argsOnly); + Context context = new Context(this.classNode, this.returnType, this.discriminator.isArgsOnly(), target, node); if (this.print) { this.printLocals(context); } - int local = this.findLocal(context); - if (local > -1) { - this.inject(context, local); + try { + int local = this.discriminator.findLocal(context); + if (local > -1) { + this.inject(context, local); + } + } catch (InvalidImplicitDiscriminatorException ex) { + throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this.methodNode.name, ex); } - target.insns.insertBefore(node, context); + target.insns.insertBefore(node, context.insns); target.addToStack(this.isStatic ? 1 : 2); } @@ -242,90 +164,23 @@ public class ModifyVariableInjector extends Injector { printer.add("%20s : %s", "Callback Name", this.methodNode.name); printer.add("%20s : %s", "Capture Type", SignaturePrinter.getTypeName(this.returnType, false)); printer.add("%20s : %s %s", "Instruction", context.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(context.node.getOpcode())).hr(); - printer.add("%20s : %s", "Match mode", this.isImplicitMode(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)"); - printer.add("%20s : %s", "Match ordinal", this.ordinal < 0 ? "any" : this.ordinal); - printer.add("%20s : %s", "Match index", this.index < context.baseArgIndex ? "any" : this.index); - printer.add("%20s : %s", "Match name(s)", this.names.isEmpty() ? "any" : this.names); - printer.add("%20s : %s", "Args only", this.argsOnly).hr(); - printer.add("%5s %7s %20s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE"); - for (int l = context.baseArgIndex; l < context.locals.length; l++) { - Local local = context.locals[l]; - if (local != null) { - Type localType = local.type; - String localName = local.name; - int ordinal = local.ord; - String candidate = this.returnType.equals(localType) ? "YES" : "-"; - printer.add("[%3d] [%3d] %20s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate); - } else if (l > 0) { - Local prevLocal = context.locals[l - 1]; - boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1; - printer.add("[%3d] %20s", l, isTop ? "" : "-"); - } - } + printer.add("%20s : %s", "Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)"); + printer.add("%20s : %s", "Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal()); + printer.add("%20s : %s", "Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex()); + printer.add("%20s : %s", "Match name(s)", this.discriminator.hasNames() ? this.discriminator.getNames() : "any"); + printer.add("%20s : %s", "Args only", this.discriminator.isArgsOnly()).hr(); + printer.add(context); printer.print(System.err); } private void inject(final Context context, final int local) { if (!this.isStatic) { - context.add(new VarInsnNode(Opcodes.ALOAD, 0)); + context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); } - context.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local)); - this.invokeHandler(context); - context.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local)); - } - - private int findLocal(Context context) { - if (this.isImplicitMode(context)) { - return this.findImplicitLocal(context); - } - return this.findExplicitLocal(context); - } - - private int findImplicitLocal(final Context context) { - int found = 0; - int count = 0; - for (int index = context.baseArgIndex; index < context.locals.length; index++) { - Local local = context.locals[index]; - if (local == null || !local.type.equals(this.returnType)) { - continue; - } - count++; - found = index; - } - - if (count == 1) { - return found; - } - - throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this.methodNode.name + ", found " - + count + " candidate variables but exactly 1 is required."); - } - - private int findExplicitLocal(final Context context) { - for (int index = context.baseArgIndex; index < context.locals.length; index++) { - Local local = context.locals[index]; - if (local == null || !local.type.equals(this.returnType)) { - continue; - } - if (this.ordinal > -1) { - if (this.ordinal == local.ord) { - return index; - } - continue; - } - if (this.index >= context.baseArgIndex) { - if (this.index == index) { - return index; - } - continue; - } - if (this.names.contains(local.name)) { - return index; - } - } - - return -1; + context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local)); + this.invokeHandler(context.insns); + context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 0c68ba52..6874e714 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 @@ -179,7 +179,7 @@ public abstract class InjectionInfo { } for (AnnotationNode at : ats) { - InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, at); + InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at); if (injectionPoint != null) { this.injectionPoints.add(injectionPoint); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java index 5a0b4d39..cd841cd0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java @@ -24,13 +24,10 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.spongepowered.asm.lib.tree.AnnotationNode; import org.spongepowered.asm.lib.tree.MethodNode; import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.ASMHelper; @@ -44,17 +41,7 @@ public class ModifyVariableInjectionInfo extends InjectionInfo { @Override protected Injector initInjector(AnnotationNode injectAnnotation) { boolean print = ASMHelper.getAnnotationValue(injectAnnotation, "print", Boolean.FALSE).booleanValue(); - boolean argsOnly = ASMHelper.getAnnotationValue(injectAnnotation, "argsOnly", Boolean.FALSE).booleanValue(); - int ordinal = ASMHelper.getAnnotationValue(injectAnnotation, "ordinal", -1); - int index = ASMHelper.getAnnotationValue(injectAnnotation, "index", -1); - - Set names = new HashSet(); - List namesList = ASMHelper.>getAnnotationValue(injectAnnotation, "name", (List)null); - if (namesList != null) { - names.addAll(namesList); - } - - return new ModifyVariableInjector(this, print, argsOnly, ordinal, index, names); + return new ModifyVariableInjector(this, print, LocalVariableDiscriminator.parse(injectAnnotation)); } @Override diff --git a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java index 2f15285f..de2c5432 100644 --- a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java +++ b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java @@ -40,6 +40,12 @@ import com.google.common.base.Strings; */ public class PrettyPrinter { + public interface IPrettyPrintable { + + public abstract void print(PrettyPrinter printer); + + } + /** * "Horizontal rule" marker */ @@ -131,6 +137,13 @@ public class PrettyPrinter { return this; } + + public PrettyPrinter add(IPrettyPrintable printable) { + if (printable != null) { + printable.print(this); + } + return this; + } public PrettyPrinter addWrapped(String format, Object... args) { return this.addWrapped(this.wrapWidth, format, args);