diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java index 5159f564..611f4249 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java @@ -27,15 +27,7 @@ package org.spongepowered.asm.mixin.injection; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.spongepowered.asm.mixin.injection.points.AfterInvoke; -import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; -import org.spongepowered.asm.mixin.injection.points.BeforeFinalReturn; -import org.spongepowered.asm.mixin.injection.points.BeforeInvoke; -import org.spongepowered.asm.mixin.injection.points.BeforeNew; -import org.spongepowered.asm.mixin.injection.points.BeforeReturn; -import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke; -import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint; -import org.spongepowered.asm.mixin.injection.points.MethodHead; +import org.spongepowered.asm.mixin.injection.points.*; /** * Annotation for specifying the type of {@link InjectionPoint} to use to @@ -94,8 +86,9 @@ public @interface At { * {@link AfterInvoke INVOKE_ASSIGN}, * {@link BeforeFieldAccess FIELD}, * {@link BeforeNew NEW}, - * {@link BeforeStringInvoke INVOKE_STRING} and - * {@link JumpInsnPoint JUMP}. + * {@link BeforeStringInvoke INVOKE_STRING}, + * {@link JumpInsnPoint JUMP} and + * {@link BeforeConstant CONSTANT}. * See the javadoc for each type for more details on the scheme used by each * injection point.

* diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java index 0cf8669b..be175aaa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java @@ -117,7 +117,6 @@ public @interface Constant { } - /** * Causes this injector to match ACONST_NULL (null object) literals * 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 4d29fae8..034edbe6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -45,15 +45,7 @@ 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.points.AfterInvoke; -import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; -import org.spongepowered.asm.mixin.injection.points.BeforeFinalReturn; -import org.spongepowered.asm.mixin.injection.points.BeforeInvoke; -import org.spongepowered.asm.mixin.injection.points.BeforeNew; -import org.spongepowered.asm.mixin.injection.points.BeforeReturn; -import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke; -import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint; -import org.spongepowered.asm.mixin.injection.points.MethodHead; +import org.spongepowered.asm.mixin.injection.points.*; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -153,6 +145,7 @@ public abstract class InjectionPoint { InjectionPoint.register(BeforeLoadLocal.class); InjectionPoint.register(AfterStoreLocal.class); InjectionPoint.register(BeforeFinalReturn.class); + InjectionPoint.register(BeforeConstant.class); } private final String slice; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java index 5ca5eb65..8b4ff503 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java @@ -77,13 +77,13 @@ public @interface ModifyConstant { public Slice slice() default @Slice; /** - * Discriminator for the constant to match (injection point), if not + * Discriminator for the constant(s) to match (injection points), if not * specified then all constants matching the annotated handler's return type * are matched * * @return the constant discriminator */ - public Constant constant() default @Constant; + public Constant[] constant() default {}; /** * By default, the annotation processor will attempt to locate an diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index b7bcdc5d..c60ca134 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -145,7 +145,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * * Write element * private void setElement(ElementType[] array, int index, - * ElementType value) + * ElementType value) * * * @@ -154,6 +154,25 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * {@link BeforeFieldAccess BeforeFieldAccess args} for details * on matching array accesses using the FIELD injection point.

* + *

Array Length Redirect Mode

+ * + *

For fields of an array type, it is possible to redirect the call to the + * builtin pseudo-property length. To do so, specify the argument + * array=length and configure your handler signature to return int + * and consume the array as an argument:

+ * + *
private int getLength(ElementType[] array) + *
+ * + *

For multi-dimensional arrays, provide one int argument for each + * additional dimension of the array:

+ * + *
// Multidimensional array
+ * private ElementType[][] array;

+ * // Handler signature:
+ * private int getLength(ElementType[][] array, int baseDim) + *
+ * *

Constructor Redirect Mode

* *

The handler method signature must match the constructor being redirected 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 0c581934..9fb6e94f 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 @@ -96,6 +96,7 @@ public class RedirectInjector extends InvokeInjector { private static final String KEY_NOMINATORS = "nominators"; private static final String KEY_WILD = "wildcard"; private static final String KEY_FUZZ = "fuzz"; + private static final String KEY_OPCODE = "opcode"; /** * Meta decoration object for redirector target nodes @@ -169,6 +170,7 @@ public class RedirectInjector extends InvokeInjector { InjectionNode node = target.injectionNodes.get(insn); ConstructorRedirectData ctorData = null; int fuzz = BeforeFieldAccess.ARRAY_SEARCH_FUZZ_DEFAULT; + int opcode = 0; if (node != null ) { Meta other = node.getDecoration(Meta.KEY); @@ -189,7 +191,9 @@ public class RedirectInjector extends InvokeInjector { if (ip instanceof BeforeNew && !((BeforeNew)ip).hasDescriptor()) { ctorData = this.getCtorRedirect((BeforeNew)ip); } else if (ip instanceof BeforeFieldAccess) { - fuzz = ((BeforeFieldAccess)ip).getFuzzFactor(); + BeforeFieldAccess bfa = (BeforeFieldAccess)ip; + fuzz = bfa.getFuzzFactor(); + opcode = bfa.getArrayOpcode(); } } @@ -201,6 +205,7 @@ public class RedirectInjector extends InvokeInjector { targetNode.decorate(ConstructorRedirectData.KEY, ctorData); } else { targetNode.decorate(RedirectInjector.KEY_FUZZ, Integer.valueOf(fuzz)); + targetNode.decorate(RedirectInjector.KEY_OPCODE, Integer.valueOf(opcode)); } myNodes.add(targetNode); } @@ -328,7 +333,8 @@ public class RedirectInjector extends InvokeInjector { throw new InvalidInjectionException(this.info, "Dimensionality of handler method is greater than target array on " + this); } else if (handlerDimensions == 0 && targetDimensions > 0) { int fuzz = node.getDecoration(RedirectInjector.KEY_FUZZ).intValue(); - this.injectAtArrayField(target, fieldNode, opCode, ownerType, fieldType, fuzz); + int opcode = node.getDecoration(RedirectInjector.KEY_OPCODE).intValue(); + this.injectAtArrayField(target, fieldNode, opCode, ownerType, fieldType, fuzz, opcode); } else { this.injectAtScalarField(target, fieldNode, opCode, ownerType, fieldType); } @@ -337,12 +343,15 @@ public class RedirectInjector extends InvokeInjector { /** * Redirect an array element access */ - private void injectAtArrayField(Target target, FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType, int fuzz) { + private void injectAtArrayField(Target target, FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType, int fuzz, int opcode) { Type elementType = fieldType.getElementType(); if (opCode != Opcodes.GETSTATIC && opCode != Opcodes.GETFIELD) { throw new InvalidInjectionException(this.info, "Unspported opcode " + Bytecode.getOpcodeName(opCode) + " for array access " + this.info); } else if (this.returnType.getSort() != Type.VOID) { - AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, elementType.getOpcode(Opcodes.IALOAD), fuzz); + if (opcode != Opcodes.ARRAYLENGTH) { + opcode = elementType.getOpcode(Opcodes.IALOAD); + } + AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, opcode, fuzz); this.injectAtGetArray(target, fieldNode, varNode, ownerType, fieldType); } else { AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, elementType.getOpcode(Opcodes.IASTORE), fuzz); @@ -351,10 +360,10 @@ public class RedirectInjector extends InvokeInjector { } /** - * Array element read (xALOAD) + * Array element read (xALOAD) or array.length (ARRAYLENGTH) */ private void injectAtGetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) { - String handlerDesc = Bytecode.generateDescriptor(this.returnType, (Object[])RedirectInjector.getArrayArgs(fieldType)); + String handlerDesc = RedirectInjector.getGetArrayHandlerDescriptor(varNode, this.returnType, fieldType); boolean withArgs = this.checkDescriptor(handlerDesc, target, "array getter"); this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array getter"); } @@ -363,7 +372,7 @@ public class RedirectInjector extends InvokeInjector { * Array element write (xASTORE) */ private void injectAtSetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) { - String handlerDesc = Bytecode.generateDescriptor(null, (Object[])RedirectInjector.getArrayArgs(fieldType, fieldType.getElementType())); + String handlerDesc = Bytecode.generateDescriptor(null, (Object[])RedirectInjector.getArrayArgs(fieldType, 1, fieldType.getElementType())); boolean withArgs = this.checkDescriptor(handlerDesc, target, "array setter"); this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array setter"); } @@ -572,9 +581,16 @@ public class RedirectInjector extends InvokeInjector { target.replaceNode(initNode, insns); meta.injected++; } - - private static Type[] getArrayArgs(Type fieldType, Type... extra) { - int dimensions = fieldType.getDimensions() + 1; + + private static String getGetArrayHandlerDescriptor(AbstractInsnNode varNode, Type returnType, Type fieldType) { + if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) { + return Bytecode.generateDescriptor(Type.INT_TYPE, (Object[])RedirectInjector.getArrayArgs(fieldType, 0)); + } + return Bytecode.generateDescriptor(returnType, (Object[])RedirectInjector.getArrayArgs(fieldType, 1)); + } + + private static Type[] getArrayArgs(Type fieldType, int extraDimensions, Type... extra) { + int dimensions = fieldType.getDimensions() + extraDimensions; Type[] args = new Type[dimensions + extra.length]; for (int i = 0; i < args.length; i++) { args[i] = i == 0 ? fieldType : i < dimensions ? Type.INT_TYPE : extra[dimensions - i]; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java new file mode 100644 index 00000000..8a651deb --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -0,0 +1,309 @@ +/* + * 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.points; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +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.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.Constant.Condition; +import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Constants; + +import com.google.common.primitives.Doubles; +import com.google.common.primitives.Floats; +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; + +/** + * Special injection point which can be defined by an {@link Constant} + * annotation or using the at code CONSTANT. + * + *

This injection point searches for LDC and other constant opcodes + * matching its arguments and returns a list of injection points matching those + * instructions. When used with {@link At} it accepts the following parameters: + *

+ * + *
+ *
ordinal
+ *
The ordinal position of the constant opcode to match. The default value + * is -1 which supresses ordinal matching
+ *
named argument nullValue
+ *
To match null literals in the method body, set this to + * true
+ *
named argument intValue
+ *
To match int literals in the method body. See also the + * expandZeroConditions argument below for concerns when matching + * conditional zeroes.
+ *
named argument floatValue
+ *
To match float literals in the method body.
+ *
named argument longValue
+ *
To match long literals in the method body.
+ *
named argument doubleValue
+ *
To match double literals in the method body.
+ *
named argument stringValue
+ *
To match {@link String} literals in the method body.
+ *
named argument classValue
+ *
To match {@link Class} literals in the method body.
+ *
named argument log
+ *
Enable debug logging when searching for matching opcodes.
+ *
named argument expandZeroConditions
+ *
See the {@link Constant#expandZeroConditions} option, this argument + * should be a list of {@link Constant.Condition} names
+ *
+ * + *

Examples:

+ *
+ *   // Find all integer constans with value 4
+ *   @At(value = "CONSTANT", args = "intValue=4")
+ *
+ *
+ *   // Find the String literal "foo"
+ *   @At(value = "CONSTANT", args = "stringValue=foo"
+ *
+ *
+ *   // Find all integer constans with value 0 and expand conditionals
+ *   @At(
+ *     value = "CONSTANT",
+ *     args = {
+ *       "intValue=0",
+ *       "expandZeroConditions=LESS_THAN_ZERO,GREATER_THAN_ZERO"
+ *     }
+ *   )
+ *   
+ *
+ * + *

Note that like all standard injection points, this class matches the insn + * itself, putting the injection point immediately before the access in + * question. Use {@link org.spongepowered.asm.mixin.injection.At#shift shift} + * specifier to adjust the matched opcode as necessary.

+ */ +@AtCode("CONSTANT") +public class BeforeConstant extends InjectionPoint { + + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Ordinal of the target insn + */ + private final int ordinal; + + private final boolean nullValue; + private final Integer intValue; + private final Float floatValue; + private final Long longValue; + private final Double doubleValue; + private final String stringValue; + private final Type typeValue; + + private final int[] expandOpcodes; + private final boolean expand; + + private final String matchByType; + + private final boolean log; + + public BeforeConstant(IMixinContext context, AnnotationNode node, String returnType) { + Boolean empty = Annotations.getValue(node, "nullValue", (Boolean)null); + this.ordinal = Annotations.getValue(node, "ordinal", Integer.valueOf(-1)); + this.nullValue = empty != null ? empty.booleanValue() : false; + this.intValue = Annotations.getValue(node, "intValue", (Integer)null); + this.floatValue = Annotations.getValue(node, "floatValue", (Float)null); + this.longValue = Annotations.getValue(node, "longValue", (Long)null); + this.doubleValue = Annotations.getValue(node, "doubleValue", (Double)null); + this.stringValue = Annotations.getValue(node, "stringValue", (String)null); + this.typeValue = Annotations.getValue(node, "classValue", (Type)null); + + this.matchByType = this.validateDiscriminator(context, returnType, empty, "on @Constant annotation"); + this.expandOpcodes = this.parseExpandOpcodes(Annotations.getValue(node, "expandZeroConditions", true, Condition.class)); + this.expand = this.expandOpcodes.length > 0; + + this.log = Annotations.getValue(node, "log", Boolean.FALSE).booleanValue(); + } + + public BeforeConstant(InjectionPointData data) { + super(data); + + String strNullValue = data.get("nullValue", null); + Boolean empty = strNullValue != null ? Boolean.parseBoolean(strNullValue) : null; + + this.ordinal = data.getOrdinal(); + this.nullValue = empty != null ? empty.booleanValue() : false; + this.intValue = Ints.tryParse(data.get("intValue", "")); + this.floatValue = Floats.tryParse(data.get("floatValue", "")); + this.longValue = Longs.tryParse(data.get("longValue", "")); + this.doubleValue = Doubles.tryParse(data.get("doubleValue", "")); + this.stringValue = data.get("stringValue", null); + String strClassValue = data.get("classValue", null); + this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null; + + this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args"); + if ("V".equals(this.matchByType)) { + throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args"); + } + + List conditions = new ArrayList(); + String strConditions = data.get("expandZeroConditions", "").toLowerCase(); + for (Condition condition : Condition.values()) { + if (strConditions.contains(condition.name().toLowerCase())) { + conditions.add(condition); + } + } + + this.expandOpcodes = this.parseExpandOpcodes(conditions); + this.expand = this.expandOpcodes.length > 0; + + this.log = data.get("log", false); + } + + private String validateDiscriminator(IMixinContext context, String returnType, Boolean empty, String type) { + int c = BeforeConstant.count(empty, this.intValue, this.floatValue, this.longValue, this.doubleValue, this.stringValue, this.typeValue); + if (c == 1) { + returnType = null; + } else if (c > 1) { + throw new InvalidInjectionException(context, "Conflicting constant discriminators specified " + type + " for " + context); + } + return returnType; + } + + private int[] parseExpandOpcodes(List conditions) { + Set opcodes = new HashSet(); + for (Condition condition : conditions) { + Condition actual = condition.getEquivalentCondition(); + for (int opcode : actual.getOpcodes()) { + opcodes.add(Integer.valueOf(opcode)); + } + } + return Ints.toArray(opcodes); + } + + @Override + public boolean find(String desc, InsnList insns, Collection nodes) { + boolean found = false; + + this.log("BeforeConstant is searching for constants in method with descriptor {}", desc); + + ListIterator iter = insns.iterator(); + for (int ordinal = 0; iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + + boolean matchesInsn = this.expand ? this.matchesConditionalInsn(insn) : this.matchesConstantInsn(insn); + if (matchesInsn) { + this.log(" BeforeConstant found a matching constant{} at ordinal {}", this.matchByType != null ? " TYPE" : " value", ordinal); + if (this.ordinal == -1 || this.ordinal == ordinal) { + this.log(" BeforeConstant found {}", Bytecode.describeNode(insn).trim()); + nodes.add(insn); + found = true; + } + ordinal++; + } + } + + return found; + } + + private boolean matchesConditionalInsn(AbstractInsnNode insn) { + for (int conditionalOpcode : this.expandOpcodes) { + if (insn.getOpcode() == conditionalOpcode) { + this.log(" BeforeConstant found %s instruction", Bytecode.getOpcodeName(conditionalOpcode)); + return true; + } + } + + if (this.intValue != null && this.intValue.intValue() == 0 && Bytecode.isConstant(insn)) { + Object value = Bytecode.getConstant(insn); + this.log(" BeforeConstant found INTEGER constant: value = {}", value); + return value instanceof Integer && ((Integer)value).intValue() == 0; + } + + return false; + } + + private boolean matchesConstantInsn(AbstractInsnNode insn) { + if (!Bytecode.isConstant(insn)) { + return false; + } + + Object value = Bytecode.getConstant(insn); + if (value == null) { + this.log(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue); + return this.nullValue || Constants.OBJECT.equals(this.matchByType); + } else if (value instanceof Integer) { + this.log(" BeforeConstant found INTEGER constant: value = {}, intValue = {}", value, this.intValue); + return value.equals(this.intValue) || "I".equals(this.matchByType); + } else if (value instanceof Float) { + this.log(" BeforeConstant found FLOAT constant: value = {}, floatValue = {}", value, this.floatValue); + return value.equals(this.floatValue) || "F".equals(this.matchByType); + } else if (value instanceof Long) { + this.log(" BeforeConstant found LONG constant: value = {}, longValue = {}", value, this.longValue); + return value.equals(this.longValue) || "J".equals(this.matchByType); + } else if (value instanceof Double) { + this.log(" BeforeConstant found DOUBLE constant: value = {}, doubleValue = {}", value, this.doubleValue); + return value.equals(this.doubleValue) || "D".equals(this.matchByType); + } else if (value instanceof String) { + this.log(" BeforeConstant found STRING constant: value = {}, stringValue = {}", value, this.stringValue); + return value.equals(this.stringValue) || Constants.STRING.equals(this.matchByType); + } else if (value instanceof Type) { + this.log(" BeforeConstant found CLASS constant: value = {}, typeValue = {}", value, this.typeValue); + return value.equals(this.typeValue) || Constants.CLASS.equals(this.matchByType); + } + + return false; + } + + protected void log(String message, Object... params) { + if (this.log) { + BeforeConstant.logger.info(message, params); + } + } + + private static int count(Object... values) { + int counter = 0; + for (Object value : values) { + if (value != null) { + counter++; + } + } + return counter; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java index 57314bc4..5f1834c6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java @@ -67,9 +67,9 @@ import org.spongepowered.asm.util.Bytecode; * *

Matching array access:

*

For array fields, it is possible to match field accesses followed by a - * corresponding array element get or set operation. To enable - * this behaviour specify the array named-argument with the desired - * operation:

+ * corresponding array element get, set or length + * operation. To enable this behaviour specify the array named-argument + * with the desired operation:

* *
  *   @At(value = "FIELD", target="myIntArray:[I", args = "array=get")
@@ -86,6 +86,10 @@ import org.spongepowered.asm.util.Bytecode;
 @AtCode("FIELD")
 public class BeforeFieldAccess extends BeforeInvoke {
     
+    private static final String ARRAY_GET = "get";
+    private static final String ARRAY_SET = "set";
+    private static final String ARRAY_LENGTH = "length";
+
     /**
      * Default fuzz factor for searching for array access opcodes
      */
@@ -113,13 +117,26 @@ public class BeforeFieldAccess extends BeforeInvoke {
         this.opcode = data.getOpcode(-1, Opcodes.GETFIELD, Opcodes.PUTFIELD, Opcodes.GETSTATIC, Opcodes.PUTSTATIC, -1);
         
         String array = data.get("array", "");
-        this.arrOpcode = "get".equalsIgnoreCase(array) ? Opcodes.IALOAD : "set".equalsIgnoreCase(array) ? Opcodes.IASTORE : 0;
+        this.arrOpcode = BeforeFieldAccess.ARRAY_GET.equalsIgnoreCase(array) ? Opcodes.IALOAD
+                : BeforeFieldAccess.ARRAY_SET.equalsIgnoreCase(array) ? Opcodes.IASTORE
+                : BeforeFieldAccess.ARRAY_LENGTH.equalsIgnoreCase(array) ? Opcodes.ARRAYLENGTH : 0;
         this.fuzzFactor = Math.min(Math.max(data.get("fuzz", BeforeFieldAccess.ARRAY_SEARCH_FUZZ_DEFAULT), 1), 32);
     }
     
     public int getFuzzFactor() {
         return this.fuzzFactor;
     }
+    
+    public int getArrayOpcode() {
+        return this.arrOpcode;
+    }
+
+    private int getArrayOpcode(String desc) {
+        if (this.arrOpcode != Opcodes.ARRAYLENGTH) {
+            return Type.getType(desc).getElementType().getOpcode(this.arrOpcode); 
+        }
+        return this.arrOpcode;
+    }
 
     @Override
     protected boolean matchesInsn(AbstractInsnNode insn) {
@@ -142,7 +159,7 @@ public class BeforeFieldAccess extends BeforeInvoke {
     protected boolean addInsn(InsnList insns, Collection nodes, AbstractInsnNode insn) {
         if (this.arrOpcode > 0) {
             FieldInsnNode fieldInsn = (FieldInsnNode)insn;
-            int accOpcode = Type.getType(fieldInsn.desc).getElementType().getOpcode(this.arrOpcode);
+            int accOpcode = this.getArrayOpcode(fieldInsn.desc);
             this.log("{} > > > > searching for array access opcode {} fuzz={}", this.className, Bytecode.getOpcodeName(accOpcode), this.fuzzFactor);
             
             if (BeforeFieldAccess.findArrayNode(insns, fieldInsn, accOpcode, this.fuzzFactor) == null) {
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 c2f2701d..0440abde 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
@@ -84,6 +84,11 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
      * Method slice descriptors parsed from the annotation
      */
     protected final MethodSlices slices;
+    
+    /**
+     * The key into the annotation which contains the injection points
+     */
+    protected final String atKey;
 
     /**
      * Injection points parsed from
@@ -134,9 +139,14 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
      * @param annotation Annotation to parse
      */
     protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
+        this(mixin, method, annotation, "at");
+    }
+    
+    protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation, String atKey) {
         super(mixin, method, annotation);
         this.isStatic = Bytecode.methodIsStatic(method);
         this.slices = MethodSlices.parse(this);
+        this.atKey = atKey;
         this.readAnnotation();
     }
 
@@ -176,9 +186,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
     }
 
     protected List readInjectionPoints(String type) {
-        List ats = Annotations.getValue(this.annotation, "at", false);
+        List ats = Annotations.getValue(this.annotation, this.atKey, false);
         if (ats == null) {
-            throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
+            throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing '" + this.atKey + "' value(s)");
         }
         return ats;
     }
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java
index 7ed60388..13a68afa 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java
@@ -24,206 +24,38 @@
  */
 package org.spongepowered.asm.mixin.injection.struct;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
 import java.util.List;
-import java.util.ListIterator;
-import java.util.Set;
 
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
 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.Constant;
-import org.spongepowered.asm.mixin.injection.Constant.Condition;
-import org.spongepowered.asm.mixin.injection.InjectionPoint;
 import org.spongepowered.asm.mixin.injection.code.Injector;
 import org.spongepowered.asm.mixin.injection.invoke.ModifyConstantInjector;
-import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
+import org.spongepowered.asm.mixin.injection.points.BeforeConstant;
 import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
-import org.spongepowered.asm.util.Bytecode;
-import org.spongepowered.asm.util.Annotations;
-import org.spongepowered.asm.util.Constants;
 
-import com.google.common.primitives.Ints;
+import com.google.common.collect.ImmutableList;
 
 /**
  * Information about a constant modifier injector
  */
 public class ModifyConstantInjectionInfo extends InjectionInfo {
-    
-    /**
-     * Special injection point which is defined by an {@link Constant}
-     * annotation.
-     */
-    static class BeforeConstant extends InjectionPoint {
-        
-        private static final Logger logger = LogManager.getLogger("mixin");
 
-        /**
-         * Ordinal of the target insn
-         */
-        private final int ordinal;
-        
-        private final boolean nullValue;
-        private final Integer intValue;
-        private final Float floatValue;
-        private final Long longValue;
-        private final Double doubleValue;
-        private final String stringValue;
-        private final Type typeValue;
-        
-        private final int[] expandOpcodes;
-        private final boolean expand;
-        
-        private final String matchByType;
-        
-        private final boolean log;
-
-        public BeforeConstant(InjectionInfo info, AnnotationNode node, String returnType) {
-            Boolean empty = Annotations.getValue(node, "nullValue", (Boolean)null);
-            this.ordinal = Annotations.getValue(node, "ordinal", Integer.valueOf(-1));
-            this.nullValue = empty != null ? empty.booleanValue() : false;
-            this.intValue = Annotations.getValue(node, "intValue", (Integer)null);
-            this.floatValue = Annotations.getValue(node, "floatValue", (Float)null);
-            this.longValue = Annotations.getValue(node, "longValue", (Long)null);
-            this.doubleValue = Annotations.getValue(node, "doubleValue", (Double)null);
-            this.stringValue = Annotations.getValue(node, "stringValue", (String)null);
-            this.typeValue = Annotations.getValue(node, "classValue", (Type)null);
-            
-            this.matchByType = this.validateDiscriminator(info, returnType, empty);
-            this.expandOpcodes = this.parseExpandOpcodes(node);
-            this.expand = this.expandOpcodes.length > 0;
-            
-            this.log = Annotations.getValue(node, "log", Boolean.FALSE).booleanValue();
-        }
-
-        private String validateDiscriminator(InjectionInfo info, String returnType, Boolean empty) {
-            int c = BeforeConstant.count(empty, this.intValue, this.floatValue, this.longValue, this.doubleValue, this.stringValue, this.typeValue);
-            if (c == 1) {
-                returnType = null;
-            } else if (c > 1) {
-                throw new InvalidInjectionException(info, "Conflicting constant discriminators specified on @Constant annotation for " + info);
-            }
-            return returnType;
-        }
-
-        private int[] parseExpandOpcodes(AnnotationNode node) {
-            Set opcodes = new HashSet();
-            for (Condition condition : Annotations.getValue(node, "expandZeroConditions", true, Condition.class)) {
-                Condition actual = condition.getEquivalentCondition();
-                for (int opcode : actual.getOpcodes()) {
-                    opcodes.add(Integer.valueOf(opcode));
-                }
-            }
-            return Ints.toArray(opcodes);
-        }
-
-        @Override
-        public boolean find(String desc, InsnList insns, Collection nodes) {
-            boolean found = false;
-
-            this.log("BeforeConstant is searching for constants in method with descriptor {}", desc);
-            
-            ListIterator iter = insns.iterator();
-            for (int ordinal = 0; iter.hasNext();) {
-                AbstractInsnNode insn = iter.next();
-
-                boolean matchesInsn = this.expand ? this.matchesConditionalInsn(insn) : this.matchesConstantInsn(insn);
-                if (matchesInsn) {
-                    this.log("    BeforeConstant found a matching constant{} at ordinal {}", this.matchByType != null ? " TYPE" : " value", ordinal);
-                    if (this.ordinal == -1 || this.ordinal == ordinal) {
-                        this.log("      BeforeConstant found {}", Bytecode.describeNode(insn).trim());
-                        nodes.add(insn);
-                        found = true;
-                    }
-                    ordinal++;
-                }
-            }
-
-            return found;
-        }
-
-        private boolean matchesConditionalInsn(AbstractInsnNode insn) {
-            for (int conditionalOpcode : this.expandOpcodes) {
-                if (insn.getOpcode() == conditionalOpcode) {
-                    this.log("  BeforeConstant found %s instruction", Bytecode.getOpcodeName(conditionalOpcode));
-                    return true;
-                }
-            }
-            
-            if (this.intValue != null && this.intValue.intValue() == 0 && Bytecode.isConstant(insn)) {
-                Object value = Bytecode.getConstant(insn);
-                this.log("  BeforeConstant found INTEGER constant: value = {}", value);
-                return value instanceof Integer && ((Integer)value).intValue() == 0;
-            }
-            
-            return false;
-        }
-
-        private boolean matchesConstantInsn(AbstractInsnNode insn) {
-            if (!Bytecode.isConstant(insn)) {
-                return false;
-            }
-            
-            Object value = Bytecode.getConstant(insn);
-            if (value == null) {
-                this.log("  BeforeConstant found NULL constant: nullValue = {}", this.nullValue);
-                return this.nullValue || Constants.OBJECT.equals(this.matchByType);
-            } else if (value instanceof Integer) {
-                this.log("  BeforeConstant found INTEGER constant: value = {}, intValue = {}", value, this.intValue);
-                return value.equals(this.intValue) || "I".equals(this.matchByType);
-            } else if (value instanceof Float) {
-                this.log("  BeforeConstant found FLOAT constant: value = {}, floatValue = {}", value, this.floatValue);
-                return value.equals(this.floatValue) || "F".equals(this.matchByType);
-            } else if (value instanceof Long) {
-                this.log("  BeforeConstant found LONG constant: value = {}, longValue = {}", value, this.longValue);
-                return value.equals(this.longValue) || "J".equals(this.matchByType);
-            } else if (value instanceof Double) {
-                this.log("  BeforeConstant found DOUBLE constant: value = {}, doubleValue = {}", value, this.doubleValue);
-                return value.equals(this.doubleValue) || "D".equals(this.matchByType);
-            } else if (value instanceof String) {
-                this.log("  BeforeConstant found STRING constant: value = {}, stringValue = {}", value, this.stringValue);
-                return value.equals(this.stringValue) || Constants.STRING.equals(this.matchByType);
-            } else if (value instanceof Type) {
-                this.log("  BeforeConstant found CLASS constant: value = {}, typeValue = {}", value, this.typeValue);
-                return value.equals(this.typeValue) || Constants.CLASS.equals(this.matchByType);
-            }
-            
-            return false;
-        }
-
-        protected void log(String message, Object... params) {
-            if (this.log) {
-                BeforeConstant.logger.info(message, params);
-            }
-        }
-        
-        private static int count(Object... values) {
-            int counter = 0;
-            for (Object value : values) {
-                if (value != null) {
-                    counter++;
-                }
-            }
-            return counter;
-        }
-
-    }
+    private static final String CONSTANT_ANNOTATION_CLASS = Constant.class.getName().replace('.', '/');
 
     public ModifyConstantInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
-        super(mixin, method, annotation);
+        super(mixin, method, annotation, "constant");
     }
     
     @Override
     protected List readInjectionPoints(String type) {
-        AnnotationNode constantAnnotation = Annotations.getValue(this.annotation, "constant");
-        List ats = new ArrayList();
-        ats.add(constantAnnotation);
+        List ats = super.readInjectionPoints(type);
+        if (ats.isEmpty()) {
+            AnnotationNode c = new AnnotationNode(ModifyConstantInjectionInfo.CONSTANT_ANNOTATION_CLASS);
+            c.visit("log", Boolean.TRUE);
+            ats = ImmutableList.of(c);
+        }
         return ats;
     }
 
@@ -232,7 +64,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo {
         Type returnType = Type.getReturnType(this.method.desc);
         
         for (AnnotationNode at : ats) {
-            this.injectionPoints.add(new BeforeConstant(this, at, returnType.getDescriptor()));
+            this.injectionPoints.add(new BeforeConstant(this.getContext(), at, returnType.getDescriptor()));
         }
     }