Refactor and extract local var discriminator, add LOAD and STORE points

This commit is contained in:
Mumfrey committed 2016-02-01 23:48:20 +00:00
1 parent cd215795d2
commit 6ad3fce00f
11 files changed
+681 -226

No files matched your search

@@ -31,9 +31,14 @@ import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.points.AfterInvoke;
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
import org.spongepowered.asm.mixin.injection.points.BeforeInvoke;
@@ -308,12 +313,15 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param at {@link At} annotation to parse information from
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, At at) {
return InjectionPoint.parse(mixin, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, At at) {
List<String> args = Arrays.asList(at.args());
return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), args, at.target(), at.ordinal(), at.opcode());
}
/**
@@ -322,11 +330,13 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param node {@link At} annotation to parse information from
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, AnnotationNode node) {
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, AnnotationNode node) {
String at = ASMHelper.<String>getAnnotationValue(node, "value");
List<String> args = ASMHelper.<List<String>>getAnnotationValue(node, "args");
String target = ASMHelper.<String>getAnnotationValue(node, "target", "");
@@ -339,7 +349,7 @@ public abstract class InjectionPoint {
args = ImmutableList.<String>of();
}
return InjectionPoint.parse(mixin, at, shift, by, args, target, ordinal, opcode);
return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, ordinal, opcode);
}
/**
@@ -348,6 +358,8 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param at Injection point specifier
* @param shift Shift type to apply
* @param by Amount of shift to apply for the BY shift type
@@ -358,7 +370,7 @@ public abstract class InjectionPoint {
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, String at, At.Shift shift, int by,
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, At.Shift shift, int by,
List<String> args, String target, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode);
InjectionPoint point = null;
@@ -379,6 +391,12 @@ public abstract class InjectionPoint {
point = new MethodHead(data);
} else if (AfterInvoke.CODE.equals(at)) {
point = new AfterInvoke(data);
} else if (BeforeLoadLocal.CODE.equals(at)) {
LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent);
point = new BeforeLoadLocal(mixin, Type.getReturnType(method.desc), discriminator, data);
} else if (AfterStoreLocal.CODE.equals(at)) {
LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent);
point = new AfterStoreLocal(mixin, Type.getReturnType(method.desc), discriminator, data);
} else if (at.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) {
try {
@SuppressWarnings("unchecked") Class<? extends InjectionPoint> cls = (Class<? extends InjectionPoint>) Class.forName(at);
@@ -28,7 +28,6 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.transformer.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
public class InvalidInjectionException extends InvalidMixinException {
private static final long serialVersionUID = 1L;
@@ -147,7 +147,7 @@ public abstract class Injector {
return targetNodes;
}
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, ReadOnlyInsnList insns, Collection<AbstractInsnNode> nodes) {
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, insns, nodes);
}
@@ -0,0 +1,81 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
* injector which searches for STORE operations which match the local variables
* described by the injector's defined discriminators.</p>
*
* <p>This allows you consumers to specify an injection immediately after a
* local variable is written in a method. Specify an <tt>ordinal</tt> of <tt>n
* </tt> to match the <em>n + 1<sup>th</sup></em> access of the variable in
* question.</p>
*
* <dl>
* <dt>ordinal</dt>
* <dd>The ordinal position of the STORE opcode for the matching local
* variable to search for, if not specified then the injection point returns
* <em>all </em> opcodes for which the parent annotation's discriminators
* match. The default value is <b>-1</b> which supresses ordinal checking.
* </dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;ModifyVariable(
* method = "md",
* ordinal = 1,
* at = &#064;At(
* value = "STORE",
* ordinal = 0
* )
* )</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("STORE")</pre>
* </blockquote>
*
* <p><b>Important Note:</b> Unlike other standard injection points, this class
* matches the insn immediately <b>after</b> the matching point.</p>
*/
public class AfterStoreLocal extends BeforeLoadLocal {
@SuppressWarnings("hiding")
public static final String CODE = "STORE";
public AfterStoreLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator local, InjectionPointData data) {
super(mixin, returnType, local, data, Opcodes.ISTORE, true);
}
}
@@ -0,0 +1,172 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import java.util.Collection;
import java.util.ListIterator;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.ContextualInjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
* injector which searches for LOAD operations which match the local variables
* described by the injector's defined discriminators.</p>
*
* <p>This allows you consumers to specify an injection immediately before a
* local variable is accessed in a method. Specify an <tt>ordinal</tt> of <tt>n
* </tt> to match the <em>n + 1<sup>th</sup></em> access of the variable in
* question.</p>
*
* <dl>
* <dt>ordinal</dt>
* <dd>The ordinal position of the LOAD opcode for the matching local variable
* to search for, if not specified then the injection point returns <em>all
* </em> opcodes for which the parent annotation's discriminators match. The
* default value is <b>-1</b> which supresses ordinal checking.</dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;ModifyVariable(
* method = "md",
* ordinal = 1,
* at = &#064;At(
* value = "LOAD",
* ordinal = 0
* )
* )</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("LOAD")</pre>
* </blockquote>
*/
public class BeforeLoadLocal extends ContextualInjectionPoint {
static class SearchState {
private final int targetOrdinal;
private int ordinal = 0;
private boolean pendingCheck = false;
private boolean found = false;
private VarInsnNode varNode;
SearchState(int targetOrdinal) {
this.targetOrdinal = targetOrdinal;
}
boolean success() {
return this.found;
}
boolean isPendingCheck() {
return this.pendingCheck;
}
void setPendingCheck() {
this.pendingCheck = true;
}
void register(VarInsnNode node) {
this.varNode = node;
}
void check(Collection<AbstractInsnNode> nodes, AbstractInsnNode insn, int local) {
this.pendingCheck = false;
if (local != this.varNode.var) {
return;
}
if (this.targetOrdinal == -1 || this.targetOrdinal == this.ordinal) {
nodes.add(insn);
this.found = true;
}
this.ordinal++;
this.varNode = null;
}
}
public static final String CODE = "LOAD";
private final Type returnType;
private final LocalVariableDiscriminator discriminator;
private final int opcode;
private final int ordinal;
private boolean opcodeAfter;
public BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data) {
this(mixin, returnType, discriminator, data, Opcodes.ILOAD, false);
}
protected BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data,
int opcode, boolean opcodeAfter) {
super(mixin);
this.returnType = returnType;
this.discriminator = discriminator;
this.opcode = data.getOpcode(returnType.getOpcode(opcode));
this.ordinal = data.getOrdinal();
this.opcodeAfter = opcodeAfter;
}
@Override
boolean find(Target target, Collection<AbstractInsnNode> nodes) {
SearchState state = new SearchState(this.ordinal);
ListIterator<AbstractInsnNode> iter = target.method.instructions.iterator();
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (state.isPendingCheck()) {
int local = this.discriminator.findLocal(this.mixin, this.returnType, this.discriminator.isArgsOnly(), target, insn);
state.check(nodes, insn, local);
} else if (insn instanceof VarInsnNode && insn.getOpcode() == this.opcode && (this.ordinal == -1 || !state.success())) {
state.register((VarInsnNode)insn);
if (this.opcodeAfter) {
state.setPendingCheck();
} else {
int local = this.discriminator.findLocal(this.mixin, this.returnType, this.discriminator.isArgsOnly(), target, insn);
state.check(nodes, insn, local);
}
}
}
return state.success();
}
}
@@ -0,0 +1,39 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
public class InvalidImplicitDiscriminatorException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidImplicitDiscriminatorException(String message) {
super(message);
}
public InvalidImplicitDiscriminatorException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,291 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.modify;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.LocalVariableNode;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable;
import org.spongepowered.asm.util.SignaturePrinter;
public class LocalVariableDiscriminator {
public static class Context implements IPrettyPrintable {
public class Local {
int ord = 0;
String name;
Type type;
public Local(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type);
}
}
final Target target;
final Type returnType;
final AbstractInsnNode node;
final int baseArgIndex;
final Local[] locals;
private final boolean isStatic;
public Context(MixinTargetContext mixin, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
this(mixin.getTargetClass(), returnType, argsOnly, target, node);
}
public Context(ClassNode targetClass, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
this.isStatic = ASMHelper.methodIsStatic(target.method);
this.returnType = returnType;
this.target = target;
this.node = node;
this.baseArgIndex = this.isStatic ? 0 : 1;
this.locals = this.initLocals(targetClass, target, argsOnly, node);
this.initOrdinals();
}
private Local[] initLocals(ClassNode targetClass, Target target, boolean argsOnly, AbstractInsnNode node) {
if (!argsOnly) {
LocalVariableNode[] locals = Locals.getLocalsAt(targetClass, target.method, node);
if (locals != null) {
Local[] lvt = new Local[locals.length];
for (int l = 0; l < locals.length; l++) {
if (locals[l] != null) {
lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc));
}
}
return lvt;
}
}
Local[] lvt = new Local[this.baseArgIndex + target.arguments.length];
if (!this.isStatic) {
lvt[0] = new Local("this", Type.getType(targetClass.name));
}
for (int local = this.baseArgIndex; local < lvt.length; local++) {
Type arg = target.arguments[local - this.baseArgIndex];
lvt[local] = new Local("arg" + local, arg);
}
return lvt;
}
private void initOrdinals() {
Map<Type, Integer> ordinalMap = new HashMap<Type, Integer>();
for (int l = 0; l < this.locals.length; l++) {
Integer ordinal = Integer.valueOf(0);
if (this.locals[l] != null) {
ordinal = ordinalMap.get(this.locals[l].type);
ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1));
this.locals[l].ord = ordinal.intValue();
}
}
}
@Override
public void print(PrettyPrinter printer) {
printer.add("%5s %7s %20s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE");
for (int l = this.baseArgIndex; l < this.locals.length; l++) {
Local local = this.locals[l];
if (local != null) {
Type localType = local.type;
String localName = local.name;
int ordinal = local.ord;
String candidate = this.returnType.equals(localType) ? "YES" : "-";
printer.add("[%3d] [%3d] %20s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate);
} else if (l > 0) {
Local prevLocal = this.locals[l - 1];
boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1;
printer.add("[%3d] %20s", l, isTop ? "<top>" : "-");
}
}
}
}
/**
* True to consider only method args
*/
private final boolean argsOnly;
/**
* Ordinal of the target variable or -1 to fail over to {@link index}
*/
private final int ordinal;
/**
* Ordinal of the target variable or -1 to fail over to {@link names}
*/
private final int index;
/**
* Candidate names for the local variable, if empty fails over to matching
* single local by type
*/
private final Set<String> names;
/**
* @param argsOnly
* @param ordinal target variable ordinal
* @param index target variable index
* @param names target variable names
*/
public LocalVariableDiscriminator(boolean argsOnly, int ordinal, int index, Set<String> names) {
this.argsOnly = argsOnly;
this.ordinal = ordinal;
this.index = index;
this.names = Collections.<String>unmodifiableSet(names);
}
public boolean isArgsOnly() {
return this.argsOnly;
}
public int getOrdinal() {
return this.ordinal;
}
public int getIndex() {
return this.index;
}
public Set<String> getNames() {
return this.names;
}
public boolean hasNames() {
return !this.names.isEmpty();
}
/**
* If the user specifies no values for {@link ordinal}, {@link index} or
* {@link names} then we are considered to be operating in "implicit mode"
* where only a single local variable of the specified type is expected to
* exist.
*
* @param context Target context
* @return true if operating in implicit mode
*/
protected boolean isImplicit(final Context context) {
return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty();
}
public int findLocal(MixinTargetContext mixin, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
try {
return this.findLocal(new Context(mixin, returnType, argsOnly, target, node));
} catch (InvalidImplicitDiscriminatorException ex) {
return -1;
}
}
public int findLocal(Context context) {
if (this.isImplicit(context)) {
return this.findImplicitLocal(context);
}
return this.findExplicitLocal(context);
}
private int findImplicitLocal(final Context context) {
int found = 0;
int count = 0;
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(context.returnType)) {
continue;
}
count++;
found = index;
}
if (count == 1) {
return found;
}
throw new InvalidImplicitDiscriminatorException("Found " + count + " candidate variables but exactly 1 is required.");
}
private int findExplicitLocal(final Context context) {
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(context.returnType)) {
continue;
}
if (this.ordinal > -1) {
if (this.ordinal == local.ord) {
return index;
}
continue;
}
if (this.index >= context.baseArgIndex) {
if (this.index == index) {
return index;
}
continue;
}
if (this.names.contains(local.name)) {
return index;
}
}
return -1;
}
public static LocalVariableDiscriminator parse(AnnotationNode annotation) {
boolean argsOnly = ASMHelper.<Boolean>getAnnotationValue(annotation, "argsOnly", Boolean.FALSE).booleanValue();
int ordinal = ASMHelper.<Integer>getAnnotationValue(annotation, "ordinal", -1);
int index = ASMHelper.<Integer>getAnnotationValue(annotation, "index", -1);
Set<String> names = new HashSet<String>();
List<String> namesList = ASMHelper.<List<String>>getAnnotationValue(annotation, "name", (List<String>)null);
if (namesList != null) {
names.addAll(namesList);
}
return new LocalVariableDiscriminator(argsOnly, ordinal, index, names);
}
}
@@ -24,26 +24,23 @@
*/
package org.spongepowered.asm.mixin.injection.modify;
import java.util.HashMap;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.LocalVariableNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.Context.Local;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
@@ -52,84 +49,33 @@ import org.spongepowered.asm.util.SignaturePrinter;
* be altered.
*/
public class ModifyVariableInjector extends Injector {
class Context extends InsnList {
class Local {
int ord = 0;
String name;
Type type;
static class Context extends LocalVariableDiscriminator.Context {
final InsnList insns = new InsnList();
public Local(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type);
}
public Context(ClassNode targetClass, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
super(targetClass, returnType, argsOnly, target, node);
}
final Target target;
final AbstractInsnNode node;
final int baseArgIndex;
final Local[] locals;
private final ClassNode targetClass;
private final boolean isStaticHandler;
public Context(ClassNode targetClass, boolean isStaticHandler, Target target, AbstractInsnNode node, boolean argsOnly) {
this.targetClass = targetClass;
this.isStaticHandler = isStaticHandler;
this.target = target;
this.node = node;
this.baseArgIndex = this.isStaticHandler ? 0 : 1;
this.locals = this.initLocals(target, node, argsOnly);
this.initOrdinals();
}
private Local[] initLocals(Target target, AbstractInsnNode node, boolean argsOnly) {
if (!argsOnly) {
LocalVariableNode[] locals = Locals.getLocalsAt(this.targetClass, target.method, node);
if (locals != null) {
Local[] lvt = new Local[locals.length];
for (int l = 0; l < locals.length; l++) {
if (locals[l] != null) {
lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc));
}
}
return lvt;
}
}
Local[] lvt = new Local[this.baseArgIndex + target.arguments.length];
if (!this.isStaticHandler) {
lvt[0] = new Local("this", Type.getType(this.targetClass.name));
}
for (int local = this.baseArgIndex; local < lvt.length; local++) {
Type arg = target.arguments[local - this.baseArgIndex];
lvt[local] = new Local("arg" + local, arg);
}
return lvt;
}
private void initOrdinals() {
Map<Type, Integer> ordinalMap = new HashMap<Type, Integer>();
for (int l = 0; l < this.locals.length; l++) {
Integer ordinal = Integer.valueOf(0);
if (this.locals[l] != null) {
ordinal = ordinalMap.get(this.locals[l].type);
ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1));
this.locals[l].ord = ordinal.intValue();
}
}
}
}
abstract static class ContextualInjectionPoint extends InjectionPoint {
protected final MixinTargetContext mixin;
ContextualInjectionPoint(MixinTargetContext mixin) {
this.mixin = mixin;
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
throw new InvalidInjectionException(this.mixin, "STORE injection point must be used in conjunction with @ModifyVariable");
}
abstract boolean find(Target target, Collection<AbstractInsnNode> nodes);
}
/**
* Print LVT
*/
@@ -138,40 +84,24 @@ public class ModifyVariableInjector extends Injector {
/**
* True to consider only method args
*/
private final boolean argsOnly;
/**
* Ordinal of the target variable or -1 to fail over to {@link index}
*/
private final int ordinal;
/**
* Ordinal of the target variable or -1 to fail over to {@link names}
*/
private final int index;
/**
* Candidate names for the local variable, if empty fails over to matching
* single local by type
*/
private final Set<String> names;
private final LocalVariableDiscriminator discriminator;
/**
* @param info Injection info
* @param print
* @param argsOnly
* @param ordinal target variable ordinal
* @param index target variable index
* @param names target variable names
*/
public ModifyVariableInjector(InjectionInfo info, boolean print, boolean argsOnly, int ordinal, int index, Set<String> names) {
public ModifyVariableInjector(InjectionInfo info, boolean print, LocalVariableDiscriminator discriminator) {
super(info);
this.print = print;
this.argsOnly = argsOnly;
this.ordinal = ordinal;
this.index = index;
this.names = names;
this.discriminator = discriminator;
}
@Override
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
if (injectionPoint instanceof ContextualInjectionPoint) {
return ((ContextualInjectionPoint)injectionPoint).find(this.info.getContext().getTargetMethod(into), nodes);
}
return injectionPoint.find(into.desc, insns, nodes);
}
/* (non-Javadoc)
@@ -187,45 +117,37 @@ public class ModifyVariableInjector extends Injector {
throw new InvalidInjectionException(this.info, "'static' of variable modifier method does not match target in " + this.methodNode.name);
}
if (this.ordinal < -1) {
throw new InvalidInjectionException(this.info, "Invalid ordinal " + this.ordinal + " specified in " + this.methodNode.name);
int ordinal = this.discriminator.getOrdinal();
if (ordinal < -1) {
throw new InvalidInjectionException(this.info, "Invalid ordinal " + ordinal + " specified in " + this.methodNode.name);
}
if (this.index == 0 && !this.isStatic) {
if (this.discriminator.getIndex() == 0 && !this.isStatic) {
throw new InvalidInjectionException(this.info, "Invalid index 0 specified in non-static variable modifier " + this.methodNode.name);
}
}
/**
* If the user specifies no values for {@link ordinal}, {@link index} or
* {@link names} then we are considered to be operating in "implicit mode"
* where only a single local variable of the specified type is expected to
* exist.
*
* @param context Target context
* @return true if operating in implicit mode
*/
protected boolean isImplicitMode(final Context context) {
return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty();
}
/**
* Do the injection
*/
@Override
protected void inject(Target target, AbstractInsnNode node) {
Context context = new Context(this.classNode, this.isStatic, target, node, this.argsOnly);
Context context = new Context(this.classNode, this.returnType, this.discriminator.isArgsOnly(), target, node);
if (this.print) {
this.printLocals(context);
}
int local = this.findLocal(context);
if (local > -1) {
this.inject(context, local);
try {
int local = this.discriminator.findLocal(context);
if (local > -1) {
this.inject(context, local);
}
} catch (InvalidImplicitDiscriminatorException ex) {
throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this.methodNode.name, ex);
}
target.insns.insertBefore(node, context);
target.insns.insertBefore(node, context.insns);
target.addToStack(this.isStatic ? 1 : 2);
}
@@ -242,90 +164,23 @@ public class ModifyVariableInjector extends Injector {
printer.add("%20s : %s", "Callback Name", this.methodNode.name);
printer.add("%20s : %s", "Capture Type", SignaturePrinter.getTypeName(this.returnType, false));
printer.add("%20s : %s %s", "Instruction", context.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(context.node.getOpcode())).hr();
printer.add("%20s : %s", "Match mode", this.isImplicitMode(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)");
printer.add("%20s : %s", "Match ordinal", this.ordinal < 0 ? "any" : this.ordinal);
printer.add("%20s : %s", "Match index", this.index < context.baseArgIndex ? "any" : this.index);
printer.add("%20s : %s", "Match name(s)", this.names.isEmpty() ? "any" : this.names);
printer.add("%20s : %s", "Args only", this.argsOnly).hr();
printer.add("%5s %7s %20s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE");
for (int l = context.baseArgIndex; l < context.locals.length; l++) {
Local local = context.locals[l];
if (local != null) {
Type localType = local.type;
String localName = local.name;
int ordinal = local.ord;
String candidate = this.returnType.equals(localType) ? "YES" : "-";
printer.add("[%3d] [%3d] %20s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate);
} else if (l > 0) {
Local prevLocal = context.locals[l - 1];
boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1;
printer.add("[%3d] %20s", l, isTop ? "<top>" : "-");
}
}
printer.add("%20s : %s", "Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)");
printer.add("%20s : %s", "Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal());
printer.add("%20s : %s", "Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex());
printer.add("%20s : %s", "Match name(s)", this.discriminator.hasNames() ? this.discriminator.getNames() : "any");
printer.add("%20s : %s", "Args only", this.discriminator.isArgsOnly()).hr();
printer.add(context);
printer.print(System.err);
}
private void inject(final Context context, final int local) {
if (!this.isStatic) {
context.add(new VarInsnNode(Opcodes.ALOAD, 0));
context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
context.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local));
this.invokeHandler(context);
context.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local));
}
private int findLocal(Context context) {
if (this.isImplicitMode(context)) {
return this.findImplicitLocal(context);
}
return this.findExplicitLocal(context);
}
private int findImplicitLocal(final Context context) {
int found = 0;
int count = 0;
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(this.returnType)) {
continue;
}
count++;
found = index;
}
if (count == 1) {
return found;
}
throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this.methodNode.name + ", found "
+ count + " candidate variables but exactly 1 is required.");
}
private int findExplicitLocal(final Context context) {
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(this.returnType)) {
continue;
}
if (this.ordinal > -1) {
if (this.ordinal == local.ord) {
return index;
}
continue;
}
if (this.index >= context.baseArgIndex) {
if (this.index == index) {
return index;
}
continue;
}
if (this.names.contains(local.name)) {
return index;
}
}
return -1;
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local));
this.invokeHandler(context.insns);
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local));
}
}
@@ -179,7 +179,7 @@ public abstract class InjectionInfo {
}
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, at);
InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at);
if (injectionPoint != null) {
this.injectionPoints.add(injectionPoint);
}
@@ -24,13 +24,10 @@
*/
package org.spongepowered.asm.mixin.injection.struct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
@@ -44,17 +41,7 @@ public class ModifyVariableInjectionInfo extends InjectionInfo {
@Override
protected Injector initInjector(AnnotationNode injectAnnotation) {
boolean print = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "print", Boolean.FALSE).booleanValue();
boolean argsOnly = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "argsOnly", Boolean.FALSE).booleanValue();
int ordinal = ASMHelper.<Integer>getAnnotationValue(injectAnnotation, "ordinal", -1);
int index = ASMHelper.<Integer>getAnnotationValue(injectAnnotation, "index", -1);
Set<String> names = new HashSet<String>();
List<String> namesList = ASMHelper.<List<String>>getAnnotationValue(injectAnnotation, "name", (List<String>)null);
if (namesList != null) {
names.addAll(namesList);
}
return new ModifyVariableInjector(this, print, argsOnly, ordinal, index, names);
return new ModifyVariableInjector(this, print, LocalVariableDiscriminator.parse(injectAnnotation));
}
@Override
@@ -40,6 +40,12 @@ import com.google.common.base.Strings;
*/
public class PrettyPrinter {
public interface IPrettyPrintable {
public abstract void print(PrettyPrinter printer);
}
/**
* "Horizontal rule" marker
*/
@@ -131,6 +137,13 @@ public class PrettyPrinter {
return this;
}
public PrettyPrinter add(IPrettyPrintable printable) {
if (printable != null) {
printable.print(this);
}
return this;
}
public PrettyPrinter addWrapped(String format, Object... args) {
return this.addWrapped(this.wrapWidth, format, args);