From 2220503eb9de16fc58f5918dcb5186f47ade54c8 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 3 Jan 2018 18:18:57 +0000 Subject: [PATCH] Warn on narrowing conversion resulting from ModifyConstant, fixes #229 --- .../invoke/ModifyConstantInjector.java | 57 +++++- .../injection/invoke/util/InsnFinder.java | 174 ++++++++++++++++++ 2 files changed, 230 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java 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 index 688dbf11..61ed3796 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -24,18 +24,26 @@ */ package org.spongepowered.asm.mixin.injection.invoke; +import org.apache.logging.log4j.Level; 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.FieldInsnNode; import org.spongepowered.asm.lib.tree.InsnList; import org.spongepowered.asm.lib.tree.InsnNode; import org.spongepowered.asm.lib.tree.JumpInsnNode; +import org.spongepowered.asm.lib.tree.LocalVariableNode; import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.invoke.util.InsnFinder; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Locals; +import org.spongepowered.asm.util.SignaturePrinter; /** * A bytecode injector which allows a specific @@ -105,6 +113,11 @@ public class ModifyConstantInjector extends RedirectInjector { private void injectConstantModifier(Target target, AbstractInsnNode constNode) { final Type constantType = Bytecode.getConstantType(constNode); + + if (constantType.getSort() <= Type.INT && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + this.checkNarrowing(target, constNode, constantType); + } + final InsnList before = new InsnList(); final InsnList after = new InsnList(); AbstractInsnNode invoke = this.invokeConstantHandler(constantType, target, before, after); @@ -127,4 +140,46 @@ public class ModifyConstantInjector extends RedirectInjector { return this.invokeHandler(after); } + + private void checkNarrowing(Target target, AbstractInsnNode constNode, Type constantType) { + AbstractInsnNode pop = new InsnFinder().findPopInsn(target, constNode); + + if (pop == null) { // Not found, give up early + return; + } else if (pop instanceof FieldInsnNode) { // Integer return, check for narrowing conversion + FieldInsnNode fieldNode = (FieldInsnNode)pop; + Type fieldType = Type.getType(fieldNode.desc); + this.checkNarrowing(target, constNode, constantType, fieldType, target.indexOf(pop), String.format("%s %s %s.%s", + Bytecode.getOpcodeName(pop), SignaturePrinter.getTypeName(fieldType, false), fieldNode.owner.replace('/', '.'), fieldNode.name)); + } else if (pop.getOpcode() == Opcodes.IRETURN) { // Integer return, check for narrowing conversion + this.checkNarrowing(target, constNode, constantType, target.returnType, target.indexOf(pop), "RETURN " + + SignaturePrinter.getTypeName(target.returnType, false)); + } else if (pop.getOpcode() == Opcodes.ISTORE) { // Integer store, attempt to get the relevant local type + int var = ((VarInsnNode)pop).var; + LocalVariableNode localVar = Locals.getLocalVariableAt(target.classNode, target.method, pop, var); + + // Frankly this will not work in 90% of cases, it basically only works if the variable being assigned is actually + // a method argument, and is pretty much never going to work for any other type of local variable + if (localVar != null && localVar.desc != null) { + String name = localVar.name != null ? localVar.name : "unnamed"; + Type localType = Type.getType(localVar.desc); + this.checkNarrowing(target, constNode, constantType, localType, target.indexOf(pop), String.format("ISTORE[var=%d] %s %s", var, + SignaturePrinter.getTypeName(localType, false), name)); + } + } + } + + private void checkNarrowing(Target target, AbstractInsnNode constNode, Type constantType, Type type, int index, String description) { + int fromSort = constantType.getSort(); + int toSort = type.getSort(); + if (toSort < fromSort) { + String fromType = SignaturePrinter.getTypeName(constantType, false); + String toType = SignaturePrinter.getTypeName(type, false); + String message = toSort == Type.BOOLEAN ? ". Implicit conversion to can cause nondeterministic (JVM-specific) behaviour!" : ""; + Level level = toSort == Type.BOOLEAN ? Level.ERROR : Level.WARN; + Injector.logger.log(level, "Narrowing conversion of <{}> to <{}> in {} target {} at opcode {} ({}){}", fromType, toType, this.info, + target, index, description, message); + } + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java new file mode 100644 index 00000000..af82ca74 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java @@ -0,0 +1,174 @@ +/* + * 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.util; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.spongepowered.asm.lib.tree.analysis.Analyzer; +import org.spongepowered.asm.lib.tree.analysis.AnalyzerException; +import org.spongepowered.asm.lib.tree.analysis.BasicInterpreter; +import org.spongepowered.asm.lib.tree.analysis.BasicValue; +import org.spongepowered.asm.lib.tree.analysis.Frame; +import org.spongepowered.asm.lib.tree.analysis.Interpreter; +import org.spongepowered.asm.mixin.injection.struct.Target; + +/** + * Utility class for finding instructions using static analysis + */ +public class InsnFinder { + + /** + * Exception to be throw to quick-exit the analyser once result is found + */ + static class AnalysisResultException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private AbstractInsnNode result; + + public AnalysisResultException(AbstractInsnNode popNode) { + this.result = popNode; + } + + public AbstractInsnNode getResult() { + return this.result; + } + + } + + /** + * Current analyser state + */ + enum AnalyzerState { + + /** + * Searching for the candidate instruction + */ + SEARCH, + + /** + * Walking through following instructions looking for matching pop + */ + ANALYSE, + + /** + * Analysis complete, unwinding rest of method so analyser completes + * normally + */ + COMPLETE + + } + + /** + * Specialised {@link Analyzer} which searches for an instruction which pops + * the value pushed by the supplied instruction. + */ + static class PopAnalyzer extends Analyzer { + + /** + * Frame which is used as proxy to observe push/pop operations and find + * the candidate nodes + */ + class PopFrame extends Frame { + + private AbstractInsnNode current; + + private AnalyzerState state = AnalyzerState.SEARCH; + private int depth = 0; + + public PopFrame(int locals, int stack) { + super(locals, stack); + } + + @Override + public void execute(AbstractInsnNode insn, Interpreter interpreter) throws AnalyzerException { + this.current = insn; + super.execute(insn, interpreter); + } + + @Override + public void push(BasicValue value) throws IndexOutOfBoundsException { + if (this.current == PopAnalyzer.this.node && this.state == AnalyzerState.SEARCH) { + this.state = AnalyzerState.ANALYSE; + this.depth++; + } else if (this.state == AnalyzerState.ANALYSE) { + this.depth++; + } + super.push(value); + } + + @Override + public BasicValue pop() throws IndexOutOfBoundsException { + if (this.state == AnalyzerState.ANALYSE) { + if (--this.depth == 0) { + this.state = AnalyzerState.COMPLETE; + throw new AnalysisResultException(this.current); + } + } + return super.pop(); + } + + } + + protected final AbstractInsnNode node; + + public PopAnalyzer(AbstractInsnNode node) { + super(new BasicInterpreter()); + this.node = node; + } + + @Override + protected Frame newFrame(final int locals, final int stack) { + return new PopFrame(locals, stack); + } + } + + /** + * Log more things + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Find the instruction which pops the value pushed by the specified + * instruction + * + * @param target target method + * @param node push node + * @return pop instruction or null if not found + */ + public AbstractInsnNode findPopInsn(Target target, AbstractInsnNode node) { + try { + new PopAnalyzer(node).analyze(target.classNode.name, target.method); + } catch (AnalyzerException ex) { + if (ex.getCause() instanceof AnalysisResultException) { + return ((AnalysisResultException)ex.getCause()).getResult(); + } + InsnFinder.logger.catching(ex); + } + return null; + } + +}