diff --git a/gradle.properties b/gradle.properties index 475a7c84..e2f84d7f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,5 +4,5 @@ packaging=jar description=Mixin url=https://www.spongepowered.org organization=SpongePowered -buildVersion=0.5.4 +buildVersion=0.5.5 buildType=SNAPSHOT diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java index 99861657..832b5600 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java @@ -39,6 +39,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.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.tools.MirrorUtils; @@ -71,6 +72,7 @@ public class InjectionObfuscationProcessor extends MixinProcessor { this.processInjectors(roundEnv, ModifyArg.class); this.processInjectors(roundEnv, Redirect.class); this.processInjectors(roundEnv, ModifyVariable.class); + this.processInjectors(roundEnv, ModifyConstant.class); this.postProcess(roundEnv); return true; diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index 7f49b9ca..c7ccddea 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -60,7 +60,7 @@ public abstract class MixinBootstrap { /** * Subsystem version */ - public static final String VERSION = "0.5.4"; + public static final String VERSION = "0.5.5"; /** * Blackboard key where the subsystem version will be stored to indicate diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java new file mode 100644 index 00000000..8600d46e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java @@ -0,0 +1,111 @@ +/* + * 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.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Annotation for specifying the injection point for an {@link ModifyConstant} + * injector. Leaving all values unset causes the injection point to match all + * constants with the same type as the {@link ModifyConstant} handler's return + * type. + * + *

To match a specific constant, specify the appropriate value for the + * appropriate argument. Specifying values of different types will cause an + * error to be raised by the injector.

+ */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Constant { + + /** + * Causes this injector to match ACONST_NULL (null object) literals + * + * @return true to match null + */ + public boolean nullValue() default false; + + /** + * Specify an integer constant to match, includes byte and short values + * + * @return integer value to match + */ + public int intValue() default 0; + + /** + * Specify a float constant to match + * + * @return float value to match + */ + public float floatValue() default 0.0F; + + /** + * Specify a long constant to match + * + * @return long value to match + */ + public long longValue() default 0L; + + /** + * Specify a double constant to match + * + * @return double value to match + */ + public double doubleValue() default 0.0; + + /** + * Specify a String constant to match + * + * @return string value to match + */ + public String stringValue() default ""; + + /** + * Specify a type literal to match + * + * @return type literal to match + */ + public Class classValue() default Object.class; + + /** + * Ordinal offset. Many InjectionPoints will return every opcode matching + * their criteria, specifying ordinal allows a particular opcode to + * be identified from the returned list. The default value of -1 does not + * alter the behaviour and returns all matching opcodes. Specifying a value + * of 0 or higher returns only the requested opcode (if one exists: + * for example specifying an ordinal of 4 when only 2 opcodes are matched by + * the InjectionPoint is not going to work particularly well!) + * + * @return ordinal value for supported InjectionPoint types + */ + public int ordinal() default -1; + + /** + * @return true to enable verbose debug logging for this injection point + */ + public boolean log() default false; +} + + diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java new file mode 100644 index 00000000..bfa1a6d5 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java @@ -0,0 +1,124 @@ +/* + * 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; + +/** + * Specifies that this mixin method should inject a constant modifier callback + * to itself in the target method(s) identified by {@link #method} at the + * specified LDC (or specialised const opcode) instruction in order to adjust + * the constant value returned. + * + *

ModifyConstant callbacks should always take one argument of the + * appropriate constant type and return the same type. For example a + * ModifyConstant for a local of type {@link String} should have the + * signature:

+ * + * private String methodName(String variable) { ... + * + *

The callback receives the original value of the constant, and should + * return the new value.

+ */ + +@Target({ ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ModifyConstant { + + /** + * String representation of a + * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo + * MemberInfo} which identifies the target method. + * + * @return method to inject into + */ + public String method(); + + /** + * Discriminator for the constant to match (injection point), if not + * specified then all constants matching the annotated handler's return type + * are matched + * + * @return the constant discriminator + */ + public Constant constant() default @Constant; + + /** + * By default, the annotation processor will attempt to locate an + * obfuscation mapping for all {@link ModifyConstant} methods since it is + * anticipated that in general the target of a {@link ModifyConstant} + * 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; + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java index e3a6c7b3..e05cee7e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.callback; import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.util.Constants; /** * CallbackInfo instances are passed to callbacks in order to provide @@ -35,9 +36,6 @@ import org.spongepowered.asm.mixin.injection.Inject; */ public class CallbackInfo implements Cancellable { - protected static final String STRING = "Ljava/lang/String;"; - protected static final String OBJECT = "Ljava/lang/Object;"; - /** * Method name being injected into, this is useful if a single callback is * injecting into multiple methods. @@ -122,14 +120,14 @@ public class CallbackInfo implements Cancellable { } if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { - return String.format("(%sZ%s)V", CallbackInfo.STRING, CallbackInfo.OBJECT); + return String.format("(%sZ%s)V", Constants.STRING, Constants.OBJECT); } - return String.format("(%sZ%s)V", CallbackInfo.STRING, returnType.getDescriptor()); + return String.format("(%sZ%s)V", Constants.STRING, returnType.getDescriptor()); } static String getConstructorDescriptor() { - return String.format("(%sZ)V", CallbackInfo.STRING); + return String.format("(%sZ)V", Constants.STRING); } static String getIsCancelledMethodName() { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java index 8d152a66..588baf42 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.injection.callback; import org.spongepowered.asm.lib.Type; +import org.spongepowered.asm.util.Constants; /** * For callbacks with a non-void return type, a CallbackInfoReturnable is passed @@ -133,7 +134,7 @@ public class CallbackInfoReturnable extends CallbackInfo { static String getReturnDescriptor(Type returnType) { if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { - return String.format("()%s", CallbackInfo.OBJECT); + return String.format("()%s", Constants.OBJECT); } return String.format("()%s", returnType.getDescriptor()); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java new file mode 100644 index 00000000..84d487df --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -0,0 +1,94 @@ +/* + * 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.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.InsnList; +import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.InvalidInjectionException; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.util.ASMHelper; + +/** + * A bytecode injector which allows a specific + */ +public class ModifyConstantInjector extends RedirectInjector { + + /** + * @param info Injection info + */ + public ModifyConstantInjector(InjectionInfo info) { + super(info, "@ModifyConstant"); + } + + @Override + protected void inject(Target target, InjectionNode node) { + if (!this.preInject(node)) { + return; + } + + if (node.isReplaced()) { + throw new UnsupportedOperationException("Target failure for " + this.info); + } + + if (ASMHelper.isConstant(node.getCurrentTarget())) { + this.injectConstantModifier(target, node); + return; + } + + throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in " + + target + " in " + this); + } + + private void injectConstantModifier(Target target, InjectionNode node) { + final AbstractInsnNode constNode = node.getCurrentTarget(); + final Type constantType = ASMHelper.getConstantType(constNode); + final InsnList before = new InsnList(); + final InsnList after = new InsnList(); + AbstractInsnNode invoke = this.invokeConstantHandler(constNode, constantType, target, before, after); + target.wrapNode(constNode, invoke, before, after); + } + + private AbstractInsnNode invokeConstantHandler(AbstractInsnNode targetNode, Type constantType, Target target, InsnList before, InsnList after) { + final String handlerDesc = ASMHelper.generateDescriptor(constantType, constantType); + final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); + + if (!this.isStatic) { + before.add(new VarInsnNode(Opcodes.ALOAD, 0)); + target.addToStack(1); + } + + if (withArgs) { + this.pushArgs(target.arguments, after, target.argIndices, 0, target.arguments.length); + target.addToStack(ASMHelper.getArgsSize(target.arguments)); + } + + return this.invokeHandler(after); + } +} 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 f35efdeb..4882d234 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 @@ -107,13 +107,17 @@ public class RedirectInjector extends InvokeInjector { } - private Meta meta; + protected Meta meta; /** * @param info Injection info */ public RedirectInjector(InjectionInfo info) { - super(info, "@Redirect"); + this(info, "@Redirect"); + } + + protected RedirectInjector(InjectionInfo info, String annotationType) { + super(info, annotationType); int priority = info.getContext().getPriority(); boolean isFinal = ASMHelper.getVisibleAnnotation(this.methodNode, Final.class) != null; @@ -144,10 +148,7 @@ public class RedirectInjector extends InvokeInjector { @Override protected void inject(Target target, InjectionNode node) { - Meta other = node.getDecoration(Meta.KEY); - if (other.getOwner() != this) { - Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}", - this.annotationType, this.info, this.meta.priority, other.name, other.priority); + if (!this.preInject(node)) { return; } @@ -168,19 +169,29 @@ public class RedirectInjector extends InvokeInjector { throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in " + target + " in " + this); } + + protected boolean preInject(InjectionNode node) { + Meta other = node.getDecoration(Meta.KEY); + if (other.getOwner() != this) { + Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}", + this.annotationType, this.info, this.meta.priority, other.name, other.priority); + return false; + } + return true; + } /** * Redirect a method invocation */ @Override protected void injectAtInvoke(Target target, InjectionNode node) { - MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget(); + final MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget(); + final boolean targetIsStatic = methodNode.getOpcode() == Opcodes.INVOKESTATIC; + final Type ownerType = Type.getType("L" + methodNode.owner + ";"); + final Type returnType = Type.getReturnType(methodNode.desc); + final Type[] args = Type.getArgumentTypes(methodNode.desc); + final Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args); boolean injectTargetParams = false; - boolean targetIsStatic = methodNode.getOpcode() == Opcodes.INVOKESTATIC; - Type ownerType = Type.getType("L" + methodNode.owner + ";"); - Type returnType = Type.getReturnType(methodNode.desc); - Type[] args = Type.getArgumentTypes(methodNode.desc); - Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args); String desc = Injector.printArgs(stackVars) + returnType; if (!desc.equals(this.methodNode.desc)) { @@ -213,19 +224,20 @@ public class RedirectInjector extends InvokeInjector { * Redirect a field get or set operation */ private void injectAtFieldAccess(Target target, InjectionNode node) { - FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget(); - boolean staticField = fieldNode.getOpcode() == Opcodes.GETSTATIC || fieldNode.getOpcode() == Opcodes.PUTSTATIC; - Type ownerType = Type.getType("L" + fieldNode.owner + ";"); - Type fieldType = Type.getType(fieldNode.desc); + final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget(); + final int opCode = fieldNode.getOpcode(); + final boolean staticField = opCode == Opcodes.GETSTATIC || opCode == Opcodes.PUTSTATIC; + final Type ownerType = Type.getType("L" + fieldNode.owner + ";"); + final Type fieldType = Type.getType(fieldNode.desc); AbstractInsnNode invoke = null; InsnList insns = new InsnList(); - if (fieldNode.getOpcode() == Opcodes.GETSTATIC || fieldNode.getOpcode() == Opcodes.GETFIELD) { + if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) { invoke = this.injectAtGetField(insns, target, fieldNode, staticField, ownerType, fieldType); - } else if (fieldNode.getOpcode() == Opcodes.PUTSTATIC || fieldNode.getOpcode() == Opcodes.PUTFIELD) { + } else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) { invoke = this.injectAtPutField(insns, target, fieldNode, staticField, ownerType, fieldType); } else { - throw new InvalidInjectionException(this.info, "Unspported opcode " + fieldNode.getOpcode() + " on FieldInsnNode for " + this.info); + throw new InvalidInjectionException(this.info, "Unspported opcode " + opCode + " on FieldInsnNode for " + this.info); } target.replaceNode(fieldNode, invoke, insns); @@ -238,8 +250,8 @@ public class RedirectInjector extends InvokeInjector { * handler and the field itself. */ private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) { - String handlerDesc = staticField ? ASMHelper.generateDescriptor(fieldType) : ASMHelper.generateDescriptor(fieldType, owner); - boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); + final String handlerDesc = staticField ? ASMHelper.generateDescriptor(fieldType) : ASMHelper.generateDescriptor(fieldType, owner); + final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); if (!this.isStatic) { insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); @@ -293,7 +305,7 @@ public class RedirectInjector extends InvokeInjector { * Check that the handler descriptor matches the calculated descriptor for * the field access being redirected. */ - private boolean checkDescriptor(String desc, Target target, String type) { + protected boolean checkDescriptor(String desc, Target target, String type) { if (this.methodNode.desc.equals(desc)) { return false; } @@ -304,7 +316,7 @@ public class RedirectInjector extends InvokeInjector { return true; } - throw new InvalidInjectionException(this.info, this.annotationType + " field " + type + " " + this + throw new InvalidInjectionException(this.info, this.annotationType + " method " + type + " " + this + " has an invalid signature. Expected " + desc + " but found " + this.methodNode.desc); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java index da9871e2..a6689266 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java @@ -43,7 +43,7 @@ public class CallbackInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { boolean cancellable = ASMHelper.getAnnotationValue(injectAnnotation, "cancellable", false); LocalCapture locals = ASMHelper.getAnnotationValue(injectAnnotation, "locals", LocalCapture.class, LocalCapture.NO_CAPTURE); String identifier = ASMHelper.getAnnotationValue(injectAnnotation, "id", ""); 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 0de2641b..83d9f3a7 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 @@ -47,6 +47,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.InvalidInjectionException; import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; @@ -148,56 +149,61 @@ public abstract class InjectionInfo { /** * Parse the info from the supplied annotation */ - @SuppressWarnings("unchecked") protected void readAnnotation() { if (this.annotation == null) { return; } String type = "@" + ASMHelper.getSimpleName(this.annotation); - + List injectionPoints = this.readInjectionPoints(type); + this.findMethods(this.parseTarget(type), type); + this.parseInjectionPoints(injectionPoints); + this.parseRequirements(); + this.injector = this.parseInjector(this.annotation); + } + + protected MemberInfo parseTarget(String type) { String method = ASMHelper.getAnnotationValue(this.annotation, "method"); if (method == null) { throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing method name"); } - List ats = null; - Object atValue = ASMHelper.getAnnotationValue(this.annotation, "at"); - if (atValue instanceof List) { - ats = (List)atValue; - } else if (atValue instanceof AnnotationNode) { - ats = new ArrayList(); - ats.add((AnnotationNode)atValue); - } else { - throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)"); - } - - MemberInfo targetMember; try { - targetMember = MemberInfo.parseAndValidate(method, this.mixin); + MemberInfo targetMember = MemberInfo.parseAndValidate(method, this.mixin); + if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) { + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '" + + targetMember.owner + "', which is not supported"); + } + return targetMember; } catch (InvalidMemberDescriptorException ex) { throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + ", has invalid target descriptor: \"" + method + "\""); } - - if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) { - throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '" - + targetMember.owner + "', which is not supported"); + } + + @SuppressWarnings("unchecked") + protected List readInjectionPoints(String type) { + Object atValue = ASMHelper.getAnnotationValue(this.annotation, "at"); + if (atValue instanceof List) { + return (List)atValue; + } else if (atValue instanceof AnnotationNode) { + List ats = new ArrayList(); + ats.add((AnnotationNode)atValue); + return ats; } - - this.findMethods(targetMember); - - if (this.targets.size() == 0) { - throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'"); - } - + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)"); + } + + protected void parseInjectionPoints(List ats) { for (AnnotationNode at : ats) { InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at); if (injectionPoint != null) { this.injectionPoints.add(injectionPoint); } } - + } + + protected void parseRequirements() { this.group = this.mixin.getInjectorGroups().parseGroup(this.method, this.mixin.getDefaultInjectorGroup()).add(this); Integer expect = ASMHelper.getAnnotationValue(this.annotation, "expect"); @@ -211,12 +217,10 @@ public abstract class InjectionInfo { } else if (this.group.isDefault()) { this.requiredCallbackCount = this.mixin.getDefaultRequiredInjections(); } - - this.injector = this.initInjector(this.annotation); } // stub - protected abstract Injector initInjector(AnnotationNode injectAnnotation); + protected abstract Injector parseInjector(AnnotationNode injectAnnotation); /** * Get whether there is enough valid information in this info to actually @@ -364,14 +368,16 @@ public abstract class InjectionInfo { * Finds methods in the target class which match searchFor * * @param searchFor member info to search for + * @param type annotation type */ - private void findMethods(MemberInfo searchFor) { + private void findMethods(MemberInfo searchFor, String type) { this.targets.clear(); int ordinal = 0; for (MethodNode target : this.classNode.methods) { if (searchFor.matches(target.name, target.desc, ordinal)) { - if (searchFor.matchAll && ASMHelper.methodIsStatic(target) != this.isStatic) { + boolean isMixinMethod = ASMHelper.getVisibleAnnotation(target, MixinMerged.class) != null; + if (searchFor.matchAll && (ASMHelper.methodIsStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { continue; } @@ -381,6 +387,10 @@ public abstract class InjectionInfo { ordinal++; } } + + if (this.targets.size() == 0) { + throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + searchFor.name + "'"); + } } private void checkTarget(MethodNode target) { @@ -418,6 +428,8 @@ public abstract class InjectionInfo { return new RedirectInjectionInfo(mixin, method, annotation); } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { return new ModifyVariableInjectionInfo(mixin, method, annotation); + } else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) { + return new ModifyConstantInjectionInfo(mixin, method, annotation); } return null; @@ -427,7 +439,13 @@ public abstract class InjectionInfo { public static AnnotationNode getInjectorAnnotation(MixinTargetContext mixin, MethodNode method) { AnnotationNode annotation = null; try { - annotation = ASMHelper.getSingleVisibleAnnotation(method, Inject.class, ModifyArg.class, Redirect.class, ModifyVariable.class); + annotation = ASMHelper.getSingleVisibleAnnotation(method, + Inject.class, + ModifyArg.class, + Redirect.class, + ModifyVariable.class, + ModifyConstant.class + ); } catch (IllegalArgumentException ex) { throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": " + ex.getMessage()); @@ -443,6 +461,8 @@ public abstract class InjectionInfo { return "redirect"; } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { return "localvar"; + } else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) { + return "constant"; } } return "handler"; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index bd5130f9..9d1e5078 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -98,6 +98,9 @@ public class InjectionPointData { } private void parseArgs(List args) { + if (args == null) { + return; + } for (String arg : args) { if (arg != null) { int eqPos = arg.indexOf('='); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java index bc90793d..681f5466 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java @@ -42,7 +42,7 @@ public class ModifyArgInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { int index = ASMHelper.getAnnotationValue(injectAnnotation, "index", -1); return new ModifyArgInjector(this, index); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java new file mode 100644 index 00000000..2000c39f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -0,0 +1,222 @@ +/* + * 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 java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.ListIterator; + +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.InjectionPoint; +import org.spongepowered.asm.mixin.injection.InvalidInjectionException; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.invoke.ModifyConstantInjector; +import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.ASMHelper; +import org.spongepowered.asm.util.Constants; + +/** + * 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 String matchByType; + + private final boolean log; + + public BeforeConstant(InjectionInfo info, AnnotationNode node, String returnType) { + Boolean empty = ASMHelper.getAnnotationValue(node, "nullValue", (Boolean)null); + this.ordinal = ASMHelper.getAnnotationValue(node, "ordinal", Integer.valueOf(-1)); + this.nullValue = empty != null ? empty.booleanValue() : false;; + this.intValue = ASMHelper.getAnnotationValue(node, "intValue", (Integer)null); + this.floatValue = ASMHelper.getAnnotationValue(node, "floatValue", (Float)null); + this.longValue = ASMHelper.getAnnotationValue(node, "longValue", (Long)null); + this.doubleValue = ASMHelper.getAnnotationValue(node, "doubleValue", (Double)null); + this.stringValue = ASMHelper.getAnnotationValue(node, "stringValue", (String)null); + this.typeValue = ASMHelper.getAnnotationValue(node, "classValue", (Type)null); + + 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); + } + + this.matchByType = returnType; + + this.log = ASMHelper.getAnnotationValue(node, "log", Boolean.FALSE).booleanValue(); + } + + @Override + public boolean find(String desc, InsnList insns, Collection nodes) { + boolean found = false; + + if (this.log) { + BeforeConstant.logger.info("BeforeConstant is searching for an constants in method with descriptor {}", desc); + } + + ListIterator iter = insns.iterator(); + for (int ordinal = 0; iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + + boolean matchesInsn = this.matchesInsn(insn); + if (matchesInsn) { + if (this.log) { + String byType = this.matchByType != null ? " TYPE" : " value"; + BeforeConstant.logger.info(" BeforeConstant found a matching constant{} at ordinal {}", byType, ordinal); + } + if (this.ordinal == -1 || this.ordinal == ordinal) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found {}", ASMHelper.getNodeDescriptionForDebug(insn).trim()); + } + nodes.add(insn); + found = true; + } + ordinal++; + } + } + + return found; + } + + private boolean matchesInsn(AbstractInsnNode insn) { + if (!ASMHelper.isConstant(insn)) { + return false; + } + + Object value = ASMHelper.getConstant(insn); + if (value == null) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue); + } + return this.nullValue || Constants.OBJECT.equals(this.matchByType); + } else if (value instanceof Integer) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found INTEGER constant: value = {}, intValue = {}", value, this.intValue); + } + return value.equals(this.intValue) || "I".equals(this.matchByType); + } else if (value instanceof Float) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found FLOAT constant: value = {}, floatValue = {}", value, this.floatValue); + } + return value.equals(this.floatValue) || "F".equals(this.matchByType); + } else if (value instanceof Long) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found LONG constant: value = {}, longValue = {}", value, this.longValue); + } + return value.equals(this.longValue) || "J".equals(this.matchByType); + } else if (value instanceof Double) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found DOUBLE constant: value = {}, doubleValue = {}", value, this.doubleValue); + } + return value.equals(this.doubleValue) || "D".equals(this.matchByType); + } else if (value instanceof String) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found STRING constant: value = {}, stringValue = {}", value, this.stringValue); + } + return value.equals(this.stringValue) || Constants.STRING.equals(this.matchByType); + } else if (value instanceof Type) { + if (this.log) { + BeforeConstant.logger.info(" BeforeConstant found CLASS constant: value = {}, typeValue = {}", value, this.typeValue); + } + return value.equals(this.typeValue) || Constants.CLASS.equals(this.matchByType); + } + + return false; + } + + private static int count(Object... values) { + int counter = 0; + for (Object value : values) { + if (value != null) { + counter++; + } + } + return counter; + } + + } + + public ModifyConstantInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { + super(mixin, method, annotation); + } + + @Override + protected List readInjectionPoints(String type) { + AnnotationNode constantAnnotation = ASMHelper.getAnnotationValue(this.annotation, "constant"); + List ats = new ArrayList(); + ats.add(constantAnnotation); + return ats; + } + + @Override + protected void parseInjectionPoints(List ats) { + Type returnType = Type.getReturnType(this.method.desc); + + for (AnnotationNode at : ats) { + this.injectionPoints.add(new BeforeConstant(this, at, returnType.getDescriptor())); + } + } + + @Override + protected Injector parseInjector(AnnotationNode injectAnnotation) { + return new ModifyConstantInjector(this); + } + + @Override + protected String getDescription() { + return "Constant modifier method"; + } + +} 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 048622b0..0c254f82 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 @@ -43,7 +43,7 @@ public class ModifyVariableInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { boolean print = ASMHelper.getAnnotationValue(injectAnnotation, "print", Boolean.FALSE).booleanValue(); return new ModifyVariableInjector(this, print, LocalVariableDiscriminator.parse(injectAnnotation)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java index d56531c8..f46332f3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java @@ -40,7 +40,7 @@ public class RedirectInjectionInfo extends InjectionInfo { } @Override - protected Injector initInjector(AnnotationNode injectAnnotation) { + protected Injector parseInjector(AnnotationNode injectAnnotation) { return new RedirectInjector(this); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java index 88a9c429..21c6e0dd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java @@ -315,6 +315,20 @@ public class Target implements Comparable { this.injectionNodes.replace(location, champion); } + /** + * Wrap instruction in this target with the specified instructions and mark + * the node as replaced with the specified champion node from the list. + * + * @param location Instruction to replace + * @param champion Instruction which notionally replaces the original insn + * @param before Instructions to actually insert (must contain champion) + */ + public void wrapNode(AbstractInsnNode location, AbstractInsnNode champion, InsnList before, InsnList after) { + this.insns.insertBefore(location, before); + this.insns.insert(location, after); + this.injectionNodes.replace(location, champion); + } + /** * Replace an instruction in this target with the specified instructions and * mark the original node as removed 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 67541c3f..ff8bcb91 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -526,9 +526,10 @@ public class MixinTransformer extends TreeTransformer { } return basicClass; - } catch (Exception ex) { + } catch (Throwable th) { + th.printStackTrace(); this.dumpClassOnFailure(transformedName, basicClass, environment); - throw new MixinTransformerError("An unexpected critical error was encountered", ex); + throw new MixinTransformerError("An unexpected critical error was encountered", th); } finally { this.lock.pop(); } diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java index 3c5bc534..41130e2d 100644 --- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java +++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.util; +import static com.google.common.base.Preconditions.*; import static org.spongepowered.asm.lib.ClassWriter.*; import java.io.PrintWriter; @@ -41,14 +42,61 @@ import org.spongepowered.asm.lib.Type; import org.spongepowered.asm.lib.tree.*; import org.spongepowered.asm.lib.util.CheckClassAdapter; +import com.google.common.primitives.Ints; + /** * Utility methods for working with ASM */ public class ASMHelper { - private static final int[] intConstants = new int[] - {Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5}; + public static final int[] CONSTANTS_INT = { + Opcodes.ICONST_M1, Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5 + }; + public static final int[] CONSTANTS_FLOAT = { + Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2 + }; + + public static final int[] CONSTANTS_DOUBLE = { + Opcodes.DCONST_0, Opcodes.DCONST_1 + }; + + public static final int[] CONSTANTS_LONG = { + Opcodes.LCONST_0, Opcodes.LCONST_1 + }; + + public static final int[] CONSTANTS_ALL = { + Opcodes.ACONST_NULL, + Opcodes.ICONST_M1, + Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5, + Opcodes.LCONST_0, Opcodes.LCONST_1, + Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2, + Opcodes.DCONST_0, Opcodes.DCONST_1, + Opcodes.BIPUSH, // 15 + Opcodes.SIPUSH, // 16 + Opcodes.LDC, // 17 + }; + + private static final Object[] CONSTANTS_VALUES = { + null, + Integer.valueOf(-1), + Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), + Long.valueOf(0L), Long.valueOf(1L), + Float.valueOf(0.0F), Float.valueOf(1.0F), Float.valueOf(2.0F), + Double.valueOf(0.0), Double.valueOf(1.0) + }; + + private static final String[] CONSTANTS_TYPES = { + null, + "I", + "I", "I", "I", "I", "I", "I", + "J", "J", + "F", "F", "F", + "D", "D", + "I", //"B", + "I", //"S" + }; + /** * Generate a new method "boolean name()", which returns a constant value. * @@ -282,7 +330,7 @@ public class ASMHelper { if (c == -1) { return new InsnNode(Opcodes.ICONST_M1); } else if (c >= 0 && c <= 5) { - return new InsnNode(intConstants[c]); + return new InsnNode(ASMHelper.CONSTANTS_INT[c + 1]); } else if (c >= Byte.MIN_VALUE && c <= Byte.MAX_VALUE) { return new IntInsnNode(Opcodes.BIPUSH, c); } else if (c >= Short.MIN_VALUE && c <= Short.MAX_VALUE) { @@ -741,6 +789,7 @@ public class ASMHelper { */ @SuppressWarnings("unchecked") public static T getAnnotationValue(AnnotationNode annotation, String key, Class annotationClass) { + checkNotNull(annotationClass, "annotationClass cannot be null"); T value = ASMHelper.getAnnotationValue(annotation, key); if (value == null) { try { @@ -914,7 +963,7 @@ public class ASMHelper { StringBuilder sb = new StringBuilder().append('('); for (Object arg : args) { - sb.append(ASMHelper.toDescriptor(/*obfType, */arg)); + sb.append(ASMHelper.toDescriptor(arg)); } return sb.append(')').append(returnType != null ? ASMHelper.toDescriptor(returnType) : "V").toString(); @@ -942,4 +991,52 @@ public class ASMHelper { return desc.substring(desc.lastIndexOf('/') + 1).replace(";", ""); } + public static boolean isConstant(AbstractInsnNode insn) { + if (insn == null) { + return false; + } + return Ints.contains(ASMHelper.CONSTANTS_ALL, insn.getOpcode()); + } + + public static Object getConstant(AbstractInsnNode insn) { + if (insn == null) { + return null; + } else if (insn instanceof LdcInsnNode) { + return ((LdcInsnNode)insn).cst; + } else if (insn instanceof IntInsnNode) { + int value = ((IntInsnNode)insn).operand; + if (insn.getOpcode() == Opcodes.BIPUSH || insn.getOpcode() == Opcodes.SIPUSH) { + return Integer.valueOf(value); + } + throw new IllegalArgumentException("IntInsnNode with invalid opcode " + insn.getOpcode() + " in getConstant"); + } + + int index = Ints.indexOf(ASMHelper.CONSTANTS_ALL, insn.getOpcode()); + return index < 0 ? null : ASMHelper.CONSTANTS_VALUES[index]; + } + + public static Type getConstantType(AbstractInsnNode insn) { + if (insn == null) { + return null; + } else if (insn instanceof LdcInsnNode) { + Object cst = ((LdcInsnNode)insn).cst; + if (cst instanceof Integer) { + return Type.getType("I"); + } else if (cst instanceof Float) { + return Type.getType("F"); + } else if (cst instanceof Long) { + return Type.getType("J"); + } else if (cst instanceof Double) { + return Type.getType("D"); + } else if (cst instanceof String) { + return Type.getType(Constants.STRING); + } else if (cst instanceof Type) { + return Type.getType(Constants.CLASS); + } + throw new IllegalArgumentException("LdcInsnNode with invalid payload type " + cst.getClass() + " in getConstant"); + } + + int index = Ints.indexOf(ASMHelper.CONSTANTS_ALL, insn.getOpcode()); + return index < 0 ? null : Type.getType(ASMHelper.CONSTANTS_TYPES[index]); + } } diff --git a/src/main/java/org/spongepowered/asm/util/Constants.java b/src/main/java/org/spongepowered/asm/util/Constants.java index 45c69f42..4f940293 100644 --- a/src/main/java/org/spongepowered/asm/util/Constants.java +++ b/src/main/java/org/spongepowered/asm/util/Constants.java @@ -38,5 +38,9 @@ public abstract class Constants { public static final String MIXIN_PACKAGE = Mixin.class.getPackage().getName(); public static final String MIXIN_PACKAGE_REF = Constants.MIXIN_PACKAGE.replace('.', '/'); + public static final String STRING = "Ljava/lang/String;"; + public static final String OBJECT = "Ljava/lang/Object;"; + public static final String CLASS = "Ljava/lang/Class;"; + private Constants() {} }