Initial injection support, lots directly copy/pasted from LiteLoader

This commit is contained in:
Mumfrey committed 2014-12-25 01:32:50 +00:00
1 parent 2124f4f1a0
commit 6c9cab6559
25 files changed
+3291 -6

No files matched your search

@@ -67,9 +67,11 @@ public class MixinEnvironment {
/**
* Add a mixin configuration to the blackboard
* @return
*/
public void addConfiguration(String config) {
public MixinEnvironment addConfiguration(String config) {
this.getMixinConfigs().add(config);
return this;
}
public Object getActiveTransformer() {
@@ -0,0 +1,47 @@
/**
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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;
public @interface At {
public enum Shift {
NONE,
BEFORE,
AFTER
}
public String value();
public String[] args() default {};
public String target() default "";
public Shift shift() default Shift.NONE;
public int ordinal() default -1;
public int opcode() default -1;
}
@@ -0,0 +1,43 @@
/**
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
public String method();
public boolean cancellable() default false;
// public boolean captureLocals() default false;
public At[] at();
}
@@ -0,0 +1,227 @@
/**
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.util.ASMHelper;
/**
* Contructs information about an injection from an {@link Inject} annotation and allows the injection to be processed
*
* @author Adam Mummery-Smith
*/
public class InjectionInfo {
/**
* Class
*/
private final ClassNode classNode;
/**
* Annotated method
*/
private final MethodNode method;
/**
* Annotated method is static
*/
private final boolean isStatic;
/**
* True if the injection should be cancellable
*/
private boolean cancellable;
/**
* True if the injection should capture local variables
*/
private boolean captureLocals;
/**
* Target method(s)
*/
private final Deque<MethodNode> targets = new ArrayDeque<MethodNode>();
/**
* Injection points parsed from {@link At} annotations
*/
private final List<InjectionPoint> injectionPoints = new ArrayList<InjectionPoint>();
/**
* Bytecode injector
*/
private CallbackInjector injector;
/**
* ctor
*
* @param classNode Class
* @param method Method
* @param injectAnnotation Annotation to parse
*/
public InjectionInfo(ClassNode classNode, MethodNode method, AnnotationNode injectAnnotation) {
this.classNode = classNode;
this.method = method;
this.isStatic = ASMHelper.methodIsStatic(method);
this.parse(injectAnnotation);
}
/**
* Parse the info from the supplied annotation
*/
private void parse(AnnotationNode injectAnnotation) {
if (injectAnnotation == null) {
return;
}
String method = ASMHelper.<String>getAnnotationValue(injectAnnotation, "method");
if (method == null) {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " is missing method name");
}
List<AnnotationNode> ats = ASMHelper.<List<AnnotationNode>>getAnnotationValue(injectAnnotation, "at");
if (ats == null) {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " is missing 'at' value(s)");
}
MemberInfo targetMember = MemberInfo.parse(method);
if (targetMember.owner != null) {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " specifies a target class '" + targetMember.owner +
"', which is not supported");
}
this.findMethods(targetMember);
if (this.targets.size() == 0) {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " could not find specified method '" + method + "'");
}
this.cancellable = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "cancellable", false);
this.captureLocals = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "captureLocals", false);
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(at);
if (injectionPoint != null) {
this.injectionPoints.add(injectionPoint);
}
}
}
/**
* Get whether there is enough valid information in this info to actually perform an injection
*/
public boolean isValid() {
return this.targets.size() > 0 && this.injectionPoints.size() > 0;
}
/**
* Perform the injection
*/
public void inject() {
CallbackInjector injector = this.getInjector();
while (this.targets.size() > 0) {
injector.injectInto(this.targets.removeFirst(), this.injectionPoints);
}
}
/**
* Performs a full-body massage with scented oils
*/
private CallbackInjector getInjector() {
if (this.injector == null) {
this.injector = new CallbackInjector(this);
}
return this.injector;
}
/**
* Get the class node for this injection
*/
public ClassNode getClassNode() {
return this.classNode;
}
/**
* Get method being called
*/
public MethodNode getMethod() {
return this.method;
}
/**
* Get methods being injected into
*/
public Collection<MethodNode> getTargets() {
return this.targets;
}
/**
* Get whether cancellable or not
*/
public boolean getCancellable() {
return this.cancellable;
}
/**
* Get whether injection should capture locals
*/
public boolean getCaptureLocals() {
return this.captureLocals;
}
/**
* Finds methods in the target class which match searchFor
*
* @param searchFor member info to search for
*/
private void findMethods(MemberInfo searchFor) {
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) {
continue;
}
this.targets.add(target);
ordinal++;
}
}
}
}
@@ -0,0 +1,408 @@
package org.spongepowered.asm.mixin.injection;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.InsnList;
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
import org.spongepowered.asm.mixin.injection.points.BeforeInvoke;
import org.spongepowered.asm.mixin.injection.points.BeforeNew;
import org.spongepowered.asm.mixin.injection.points.BeforeReturn;
import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke;
import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint;
import org.spongepowered.asm.mixin.injection.points.MethodHead;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
/**
* Base class for injection point discovery classes. Each subclass describes a strategy for locating code injection
* points within a method, with the {@code find} method populating a collection with insn nodes from the method
* which satisfy its strategy.
*
* This base class also contains composite strategy factory methods such as {@code and} and {@code or} which allow
* strategies to be combined using intersection (and) or union (or) relationships to allow multiple strategies to
* be easily combined.
*
* You are free to create your own injection point subclasses, but take note that it is allowed for a single
* InjectionPoint instance to be used for multiple injections and thus implementing classes MUST NOT cache the insn
* list, event, or nodes instance passed to the {@code find} method, as each call to {@code find} must be considered
* a separate functional contract and the InjectionPoint's lifespan is not linked to the discovery lifespan, therefore
* it is important that the InjectionPoint implementation is fully STATELESS.
*
* @author Adam Mummery-Smith
*/
public abstract class InjectionPoint
{
/**
* Capture locals as well as args
*/
protected boolean captureLocals;
protected boolean logLocals;
/**
* Find injection points in the supplied insn list
*
* @param desc Method descriptor, supplied to allow return types and arguments etc. to be determined
* @param insns Insn list to search in, the strategy MUST ONLY add nodes from this list to the {@code nodes} collection
* @param nodes Collection of nodes to populate. Injectors should NOT make any assumptions about the state of this collection and should only call add()
* @param event Event being injected here, supplied to allow alteration of behaviour for specific event configurations (eg. cancellable)
* @return true if one or more injection points were found
*/
public abstract boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes); //, Event event);
// /**
// * Set whether this injection point should capture local variables as well as method arguments
// *
// * @param captureLocals
// * @return this, for fluent interface
// */
// public InjectionPoint setCaptureLocals(boolean captureLocals)
// {
// this.captureLocals = captureLocals;
// return this;
// }
//
// /**
// * Get whether capture locals is enabled
// */
// public boolean captureLocals()
// {
// return this.captureLocals;
// }
//
// /**
// * Since it's virtually impossible to know what locals are available at a given injection point by reading the source, this method causes the
// * injection point to dump the locals to the debug log at injection time.
// *
// * @param logLocals
// * @return this, for fluent interface
// */
// public InjectionPoint setLogLocals(boolean logLocals)
// {
// this.logLocals = logLocals;
// return this;
// }
//
// /**
// * Get whether log locals is enabled
// */
// public boolean logLocals()
// {
// return this.logLocals;
// }
@Override
public String toString()
{
return "InjectionPoint(" + this.getClass().getSimpleName() + ")";
}
/**
* Composite injection point
*
* @author Adam Mummery-Smith
*/
static abstract class CompositeInjectionPoint extends InjectionPoint
{
protected final InjectionPoint[] components;
protected CompositeInjectionPoint(InjectionPoint... components)
{
if (components == null || components.length < 2)
{
throw new IllegalArgumentException("Must supply two or more component injection points for composite point!");
}
this.components = components;
for (InjectionPoint component : this.components)
{
this.captureLocals |= component.captureLocals;
this.logLocals |= component.logLocals;
}
}
@Override
public String toString()
{
return "CompositeInjectionPoint(" + this.getClass().getSimpleName() + ")[" + Joiner.on(',').join(this.components) + "]";
}
}
static final class Intersection extends InjectionPoint.CompositeInjectionPoint
{
public Intersection(InjectionPoint... points)
{
super(points);
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
boolean found = false;
@SuppressWarnings("unchecked")
ArrayList<AbstractInsnNode>[] allNodes = new ArrayList[this.components.length];
for (int i = 0; i < this.components.length; i++)
{
allNodes[i] = new ArrayList<AbstractInsnNode>();
this.components[i].find(desc, insns, allNodes[i]); //, event);
}
ArrayList<AbstractInsnNode> alpha = allNodes[0];
for (int nodeIndex = 0; nodeIndex < alpha.size(); nodeIndex++)
{
AbstractInsnNode node = alpha.get(nodeIndex);
boolean in = true;
for (int b = 1; b < allNodes.length; b++)
if (!allNodes[b].contains(node))
break;
if (!in) continue;
nodes.add(node);
found = true;
}
return found;
}
}
static final class Union extends InjectionPoint.CompositeInjectionPoint
{
public Union(InjectionPoint... points)
{
super(points);
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
LinkedHashSet<AbstractInsnNode> allNodes = new LinkedHashSet<AbstractInsnNode>();
for (int i = 0; i < this.components.length; i++)
{
this.components[i].find(desc, insns, allNodes); //, event);
}
nodes.addAll(allNodes);
return allNodes.size() > 0;
}
}
static final class Shift extends InjectionPoint
{
private final InjectionPoint input;
private final int shift;
public Shift(InjectionPoint input, int shift)
{
if (input == null)
{
throw new IllegalArgumentException("Must supply an input injection point for SHIFT");
}
this.input = input;
this.shift = shift;
}
// @Override
// public InjectionPoint setCaptureLocals(boolean captureLocals)
// {
// return this.input.setCaptureLocals(captureLocals);
// }
//
// @Override
// public boolean captureLocals()
// {
// return this.input.captureLocals();
// }
//
// @Override
// public InjectionPoint setLogLocals(boolean logLocals)
// {
// return this.input.setLogLocals(logLocals);
// }
//
// @Override
// public boolean logLocals()
// {
// return this.input.logLocals();
// }
@Override
public String toString()
{
return "InjectionPoint(" + this.getClass().getSimpleName() + ")[" + this.input + "]";
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
List<AbstractInsnNode> list = (nodes instanceof List) ? (List<AbstractInsnNode>)nodes : new ArrayList<AbstractInsnNode>(nodes);
this.input.find(desc, insns, nodes); //, event);
for (int i = 0; i < list.size(); i++)
{
list.set(i, insns.get(insns.indexOf(list.get(i)) + this.shift));
}
if (nodes != list)
{
nodes.clear();
nodes.addAll(list);
}
return nodes.size() > 0;
}
}
/**
* Returns a composite injection point which returns the intersection of nodes from all component
* injection points
*
* @param operands
*/
public static InjectionPoint and(InjectionPoint... operands)
{
return new InjectionPoint.Intersection(operands);
}
/**
* Returns a composite injection point which returns the union of nodes from all component
* injection points
*
* @param operands
*/
public static InjectionPoint or(InjectionPoint... operands)
{
return new InjectionPoint.Union(operands);
}
/**
* Returns an injection point which returns all insns immediately following insns from the supplied injection point
*
* @param point
*/
public static InjectionPoint after(InjectionPoint point)
{
return new InjectionPoint.Shift(point, 1);
}
/**
* Returns an injection point which returns all insns immediately prior to insns from the supplied injection point
*
* @param point
*/
public static InjectionPoint before(InjectionPoint point)
{
return new InjectionPoint.Shift(point, -1);
}
/**
* Returns an injection point which returns all insns offset by the specified "count" from insns from the supplied injection point
*
* @param point
*/
public static InjectionPoint shift(InjectionPoint point, int count)
{
return new InjectionPoint.Shift(point, count);
}
public static InjectionPoint parse(At at)
{
return InjectionPoint.parse(at.value(), at.shift(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
}
public static InjectionPoint parse(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", "");
At.Shift shift = ASMHelper.<At.Shift>getAnnotationValue(node, "shift", At.Shift.NONE);
int ordinal = ASMHelper.<Integer>getAnnotationValue(node, "ordinal", Integer.valueOf(-1));
int opcode = ASMHelper.<Integer>getAnnotationValue(node, "opcode", Integer.valueOf(0));
if (args == null) args = ImmutableList.<String>of();
return InjectionPoint.parse(at, shift, args, target, ordinal, opcode);
}
public static InjectionPoint parse(String at, At.Shift shift, List<String> args, String target, int ordinal, int opcode)
{
InjectionPointData data = new InjectionPointData(args, target, ordinal, opcode);
InjectionPoint pt = null;
if (BeforeFieldAccess.CODE.equals(at))
{
pt = new BeforeFieldAccess(data);
}
else if (BeforeInvoke.CODE.equals(at))
{
pt = new BeforeInvoke(data);
}
else if (BeforeNew.CODE.equals(at))
{
pt = new BeforeNew(data);
}
else if (BeforeReturn.CODE.equals(at))
{
pt = new BeforeReturn(data);
}
else if (BeforeStringInvoke.CODE.equals(at))
{
pt = new BeforeStringInvoke(data);
}
else if (JumpInsnPoint.CODE.equals(at))
{
pt = new JumpInsnPoint(data);
}
else if (MethodHead.CODE.equals(at))
{
pt = new MethodHead(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);
Constructor<? extends InjectionPoint> ctor = cls.getDeclaredConstructor(InjectionPointData.class);
ctor.setAccessible(true);
pt = ctor.newInstance(data);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
if (pt != null)
{
if (shift == At.Shift.BEFORE)
{
return InjectionPoint.before(pt);
}
else if (shift == At.Shift.AFTER)
{
return InjectionPoint.after(pt);
}
}
return pt;
}
}
@@ -0,0 +1,46 @@
/**
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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;
import org.spongepowered.asm.mixin.InvalidMixinException;
public class InvalidInjectionException extends InvalidMixinException {
private static final long serialVersionUID = 1L;
public InvalidInjectionException(String message) {
super(message);
}
public InvalidInjectionException(Throwable cause) {
super(cause);
}
public InvalidInjectionException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,135 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.callback;
import org.objectweb.asm.Type;
//import com.mumfrey.liteloader.core.event.Cancellable;
//import com.mumfrey.liteloader.core.event.EventCancellationException;
/**
* Contains information about an injected event, including the source object and whether the event
* is cancellable and/or cancelled.
*
* @author Adam Mummery-Smith
*
* @param <S> Source object type. For non-static methods this will be the containing object instance.
*/
public class CallbackInfo implements Cancellable
{
protected static final String STRING = "Ljava/lang/String;";
protected static final String OBJECT = "Ljava/lang/Object;";
private final String name;
// private final S source;
private final boolean cancellable;
private boolean cancelled;
public CallbackInfo(String name, /*S source,*/ boolean cancellable)
{
this.name = name;
// this.source = source;
this.cancellable = cancellable;
}
// public S getSource()
// {
// return this.source;
// }
public String getName()
{
return this.name;
}
// protected String getSourceClass()
// {
// return this.source != null ? this.source.getClass().getSimpleName() : null;
// }
@Override
public String toString()
{
return String.format("CallbackInfo[TYPE=%s,NAME=%s,CANCELLABLE=%s]", this.getClass().getSimpleName(), this.name, this.cancellable);
}
/* (non-Javadoc)
* @see com.mumfrey.liteloader.core.event.Cancellable#isCancellable()
*/
@Override
public final boolean isCancellable()
{
return this.cancellable;
}
/* (non-Javadoc)
* @see com.mumfrey.liteloader.transformers.event.Cancellable#isCancelled()
*/
@Override
public final boolean isCancelled()
{
return this.cancelled;
}
/* (non-Javadoc)
* @see com.mumfrey.liteloader.transformers.event.Cancellable#cancel()
*/
@Override
public void cancel() throws CancellationException
{
if (!this.cancellable)
{
throw new CancellationException(String.format("The call %s is not cancellable.", this.name));
}
this.cancelled = true;
}
protected static String getCallInfoClassName()
{
return CallbackInfo.class.getName();
}
/**
* @param returnType
*/
protected static String getCallInfoClassName(Type returnType)
{
return (returnType.equals(Type.VOID_TYPE) ? CallbackInfo.class.getName() : CallbackInfoReturnable.class.getName()).replace('.', '/');
}
public static String getConstructorDescriptor(Type returnType)
{
if (returnType.equals(Type.VOID_TYPE))
{
return CallbackInfo.getConstructorDescriptor();
}
if (returnType.getSort() == Type.OBJECT)
{
return String.format("(%sZ%s)V", CallbackInfo.STRING, CallbackInfo.OBJECT);
}
return String.format("(%sZ%s)V", CallbackInfo.STRING, returnType.getDescriptor());
}
public static String getConstructorDescriptor()
{
return String.format("(%sZ)V", CallbackInfo.STRING);
}
public static String getIsCancelledMethodName()
{
return "isCancelled";
}
public static String getIsCancelledMethodSig()
{
return "()Z";
}
}
@@ -0,0 +1,137 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.callback;
import org.objectweb.asm.Type;
//import com.mumfrey.liteloader.core.event.EventCancellationException;
/**
* EventInfo for events which have a return type
*
* @author Adam Mummery-Smith
*
* @param <S> Source object type. For non-static methods this will be the containing object instance.
* @param <R> Return type
*/
public class CallbackInfoReturnable<R> extends CallbackInfo
{
private R returnValue;
public CallbackInfoReturnable(String name, boolean cancellable)
{
super(name, cancellable);
this.returnValue = null;
}
public CallbackInfoReturnable(String name, boolean cancellable, R returnValue)
{
super(name, cancellable);
this.returnValue = returnValue;
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, byte returnValue)
{
super(name, cancellable);
this.returnValue = (R)Byte.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, char returnValue)
{
super(name, cancellable);
this.returnValue = (R)Character.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, double returnValue)
{
super(name, cancellable);
this.returnValue = (R)Double.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, float returnValue)
{
super(name, cancellable);
this.returnValue = (R)Float.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, int returnValue)
{
super(name, cancellable);
this.returnValue = (R)Integer.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, long returnValue)
{
super(name, cancellable);
this.returnValue = (R)Long.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, short returnValue)
{
super(name, cancellable);
this.returnValue = (R)Short.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
public CallbackInfoReturnable(String name, boolean cancellable, boolean returnValue)
{
super(name, cancellable);
this.returnValue = (R)Boolean.valueOf(returnValue);
}
/**
* Sets a return value for this event and cancels the event (required in order to return the new value)
*
* @param returnValue
*/
public void setReturnValue(R returnValue) throws CancellationException
{
super.cancel();
this.returnValue = returnValue;
}
public R getReturnValue()
{
return this.returnValue;
}
// All of the accessors below are to avoid having to generate unboxing conversions in bytecode
public byte getReturnValueB() { if (this.returnValue == null) return 0; return (Byte) this.returnValue; }
public char getReturnValueC() { if (this.returnValue == null) return 0; return (Character)this.returnValue; }
public double getReturnValueD() { if (this.returnValue == null) return 0.0; return (Double) this.returnValue; }
public float getReturnValueF() { if (this.returnValue == null) return 0.0F; return (Float) this.returnValue; }
public int getReturnValueI() { if (this.returnValue == null) return 0; return (Integer) this.returnValue; }
public long getReturnValueJ() { if (this.returnValue == null) return 0; return (Long) this.returnValue; }
public short getReturnValueS() { if (this.returnValue == null) return 0; return (Short) this.returnValue; }
public boolean getReturnValueZ() { if (this.returnValue == null) return false; return (Boolean) this.returnValue; }
public static String getReturnAccessor(Type returnType)
{
if (returnType.getSort() == Type.OBJECT)
{
return "getReturnValue";
}
return String.format("getReturnValue%s", returnType.getDescriptor());
}
public static String getReturnDescriptor(Type returnType)
{
if (returnType.getSort() == Type.OBJECT)
{
return String.format("()%s", CallbackInfo.OBJECT);
}
return String.format("()%s", returnType.getDescriptor());
}
}
@@ -0,0 +1,297 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.callback;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import org.spongepowered.asm.mixin.injection.InjectionInfo;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.points.BeforeReturn;
import org.spongepowered.asm.mixin.injection.tree.ReadOnlyInsnList;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.ByteCodeUtilities;
public class CallbackInjector {
private static final String CTOR = "<init>";
class Target
{
final MethodNode method;
final Type returnType;
final int MAXS;
final String callbackDescriptor;
final String callInfoClass;
Target(MethodNode method)
{
this.method = method;
this.returnType = Type.getReturnType(method.desc);
this.MAXS = method.maxStack;
this.callInfoClass = CallbackInfo.getCallInfoClassName(this.returnType);
this.callbackDescriptor = String.format("(%sL%s;)V", method.desc.substring(1, method.desc.indexOf(')')), this.callInfoClass);
}
String getCallbackDescriptor(final boolean captureLocals, final Type[] locals, Type[] argumentTypes, int startIndex)
{
if (!captureLocals) return this.callbackDescriptor;
String descriptor = this.callbackDescriptor.substring(0, this.callbackDescriptor.indexOf(')'));
for (int l = startIndex; l < locals.length; l++)
{
if (locals[l] != null) descriptor += locals[l].getDescriptor();
}
return descriptor + ")V";
}
}
private final boolean isStatic;
private final ClassNode classNode;
private final MethodNode methodNode;
private final boolean cancellable;
private final boolean captureLocals;
public CallbackInjector(InjectionInfo info)
{
this(info.getClassNode(), info.getMethod(), info.getCancellable(), info.getCaptureLocals());
}
public CallbackInjector(ClassNode classNode, MethodNode methodNode, boolean cancellable, boolean captureLocals)
{
this.classNode = classNode;
this.methodNode = methodNode;
this.cancellable = cancellable;
this.captureLocals = captureLocals;
this.isStatic = ASMHelper.methodIsStatic(methodNode);
}
public void injectInto(MethodNode into, List<InjectionPoint> injectionPoints)
{
this.sanityCheck(into, injectionPoints);
for (AbstractInsnNode targetNode : this.findTargetNodes(into, injectionPoints))
{
Type[] localTypes = null;
if (this.captureLocals)
{
LocalVariableNode[] locals = ByteCodeUtilities.getLocalsAt(this.classNode, into, targetNode);
if (locals != null)
{
localTypes = new Type[locals.length];
for (int l = 0; l < locals.length; l++)
{
if (locals[l] != null)
{
localTypes[l] = Type.getType(locals[l].desc);
}
}
}
// if (injectionPoint.logLocals())
// {
// int startPos = ByteCodeUtilities.getFirstNonArgLocalIndex(into);
//
// LiteLoaderLogger.debug(ClassTransformer.HORIZONTAL_RULE);
// LiteLoaderLogger.debug("Logging local variables for " + injectionPoint);
// for (int i = startPos; i < locals.length; i++)
// {
// LocalVariableNode local = locals[i];
// if (local != null)
// {
// LiteLoaderLogger.debug(" Local[%d] %s %s", i, ByteCodeUtilities.getTypeName(Type.getType(local.desc)), local.name);
// }
// }
// LiteLoaderLogger.debug(ClassTransformer.HORIZONTAL_RULE);
// }
}
Target target = new Target(into);
this.inject(target, targetNode, localTypes);
}
}
private Set<AbstractInsnNode> findTargetNodes(MethodNode into, List<InjectionPoint> injectionPoints) {
Set<AbstractInsnNode> targetNodes = new HashSet<AbstractInsnNode>();
// Defensive objects, so that injectionPoint instances can't modify our working copies
ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions);
Collection<AbstractInsnNode> nodes = new ArrayList<AbstractInsnNode>(32);
for (InjectionPoint injectionPoint : injectionPoints)
{
nodes.clear();
if (injectionPoint.find(into.desc, insns, nodes))
{
targetNodes.addAll(nodes);
}
}
return targetNodes;
}
private void sanityCheck(MethodNode target, List<InjectionPoint> injectionPoints)
{
if (ASMHelper.methodIsStatic(target) != this.isStatic)
{
throw new InvalidInjectionException("'static' modifier of callback method does not match target in " + this.methodNode.name);
}
if (CallbackInjector.CTOR.equals(target.name))
{
for (InjectionPoint injectionPoint : injectionPoints)
{
if (!injectionPoint.getClass().equals(BeforeReturn.class))
{
throw new InvalidInjectionException("Found injection point type " + injectionPoint.getClass().getSimpleName() + " targetting a ctor in " + this.classNode.name + ". Only RETURN allowed for a ctor target");
}
}
}
}
private void inject(Target target, final AbstractInsnNode targetNode, final Type[] locals)
{
Type[] arguments = Type.getArgumentTypes(target.method.desc);
int initialFrameSize = ByteCodeUtilities.getFirstNonArgLocalIndex(arguments, !this.isStatic);
boolean doCaptureLocals = this.captureLocals && locals != null && locals.length > initialFrameSize;
String callbackDescriptor = target.getCallbackDescriptor(doCaptureLocals, locals, arguments, initialFrameSize);
if (!callbackDescriptor.equals(this.methodNode.desc))
{
throw new InvalidInjectionException("Invalid descriptor on callback method, expected " + callbackDescriptor);
}
int ctorMAXS = 0, invokeMAXS = arguments.length + (doCaptureLocals ? locals.length - initialFrameSize : 0);
// Marshall var is the local where we marshall the utility references we need during invoke of the callback
int marshallVar = target.method.maxLocals++;
InsnList insns = new InsnList();
boolean pushReturnValue = false;
// If this is a ReturnEventInfo AND we are right before a RETURN opcode (so we can expect the *original* return
// value to be on the stack, then we dup the return value into a local var so we can push it later when we invoke
// the ReturnEventInfo ctor
if (targetNode instanceof InsnNode && targetNode.getOpcode() >= Opcodes.IRETURN && targetNode.getOpcode() < Opcodes.RETURN)
{
pushReturnValue = true;
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new VarInsnNode(target.returnType.getOpcode(Opcodes.ISTORE), marshallVar));
}
// Instance the EventInfo for this event
insns.add(new TypeInsnNode(Opcodes.NEW, target.callInfoClass)); ctorMAXS++;
insns.add(new InsnNode(Opcodes.DUP)); ctorMAXS++; invokeMAXS++;
ctorMAXS += this.invokeCallbackInfoCtor(target, insns, this.cancellable, pushReturnValue, marshallVar);
insns.add(new VarInsnNode(Opcodes.ASTORE, marshallVar));
if (!this.isStatic)
{
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
// Call the event handler method in the proxy
ByteCodeUtilities.loadArgs(arguments, insns, this.isStatic ? 0 : 1);
insns.add(new VarInsnNode(Opcodes.ALOAD, marshallVar));
if (doCaptureLocals)
{
ByteCodeUtilities.loadLocals(locals, insns, initialFrameSize);
}
insns.add(new MethodInsnNode(this.isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, this.classNode.name, this.methodNode.name, this.methodNode.desc, false));
if (this.cancellable)
{
// Inject the if (e.isCancelled()) return e.getReturnValue();
this.injectCancellationCode(target, insns, targetNode, marshallVar);
}
// Inject our generated code into the method
target.method.instructions.insertBefore(targetNode, insns);
target.method.maxStack = Math.max(target.method.maxStack, Math.max(target.MAXS + ctorMAXS, target.MAXS + invokeMAXS));
}
protected int invokeCallbackInfoCtor(Target target, InsnList insns, boolean cancellable, boolean pushReturnValue, int marshallVar)
{
int ctorMAXS = 0;
insns.add(new LdcInsnNode(target.method.name)); ctorMAXS++;
// insns.add(target.methodIsStatic ? new InsnNode(Opcodes.ACONST_NULL) : new VarInsnNode(Opcodes.ALOAD, 0)); ctorMAXS++;
insns.add(new InsnNode(cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0)); ctorMAXS++;
if (pushReturnValue)
{
insns.add(new VarInsnNode(target.returnType.getOpcode(Opcodes.ILOAD), marshallVar));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, target.callInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(target.returnType), false));
}
else
{
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, target.callInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(), false));
}
return ctorMAXS;
}
/**
* if (e.isCancelled()) return e.getReturnValue();
*
* @param insns
* @param targetNode
* @param marshallVar
*/
protected void injectCancellationCode(Target target, final InsnList insns, final AbstractInsnNode targetNode, int marshallVar)
{
insns.add(new VarInsnNode(Opcodes.ALOAD, marshallVar));
insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, target.callInfoClass, CallbackInfo.getIsCancelledMethodName(), CallbackInfo.getIsCancelledMethodSig(), false));
LabelNode notCancelled = new LabelNode();
insns.add(new JumpInsnNode(Opcodes.IFEQ, notCancelled));
// If this is a void method, just injects a RETURN opcode, otherwise we need to get the return value from the EventInfo
this.injectReturnCode(target, insns, targetNode, marshallVar);
insns.add(notCancelled);
}
/**
* Inject the appropriate return code for the method type
*
* @param insns
* @param targetNode
* @param marshallVar
*/
protected void injectReturnCode(Target target, final InsnList insns, final AbstractInsnNode targetNode, int marshallVar)
{
if (target.returnType.equals(Type.VOID_TYPE))
{
// Void method, so just return void
insns.add(new InsnNode(Opcodes.RETURN));
}
else
{
// Non-void method, so work out which accessor to call to get the return value, and return it
insns.add(new VarInsnNode(Opcodes.ALOAD, marshallVar));
String accessor = CallbackInfoReturnable.getReturnAccessor(target.returnType);
String descriptor = CallbackInfoReturnable.getReturnDescriptor(target.returnType);
insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, target.callInfoClass, accessor, descriptor, false));
if (target.returnType.getSort() == Type.OBJECT)
{
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, target.returnType.getInternalName()));
}
insns.add(new InsnNode(target.returnType.getOpcode(Opcodes.IRETURN)));
}
}
}
@@ -0,0 +1,32 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Interface for (potentially) cancellable things :)
*
* @author Adam Mummery-Smith
*/
public interface Cancellable
{
/**
* Get whether this is actually cancellable
*/
public abstract boolean isCancellable();
/**
* Get whether this is cancelled
*/
public abstract boolean isCancelled();
/**
* If the object is cancellable, cancels the object, implementors may throw
* an EventCancellationException if the object is not actually cancellable.
*
* @throws CancellationException (optional) may be thrown if the object is not actually cancellable
*/
public abstract void cancel() throws CancellationException;
}
@@ -0,0 +1,29 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.callback;
public class CancellationException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public CancellationException()
{
}
public CancellationException(String message)
{
super(message);
}
public CancellationException(Throwable cause)
{
super(cause);
}
public CancellationException(String message, Throwable cause)
{
super(message, cause);
}
}
@@ -0,0 +1,36 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
/**
* An injection point which searches for GETFIELD and SETFIELD opcodes matching its arguments and returns a list of insns
* immediately prior to matching instructions. Only the field name is required, owners and signatures are optional and can
* be used to disambiguate between fields of the same name but with different types, or belonging to different classes.
*
* @author Adam Mummery-Smith
*/
public class BeforeFieldAccess extends BeforeInvoke
{
@SuppressWarnings("hiding")
public static final String CODE = "FIELD";
private final int opcode;
public BeforeFieldAccess(InjectionPointData data)
{
super(data);
this.opcode = data.getOpcode();
}
@Override
protected boolean matchesInsn(AbstractInsnNode insn)
{
return insn instanceof FieldInsnNode && ((FieldInsnNode)insn).getOpcode() == this.opcode;
}
}
@@ -0,0 +1,199 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import java.util.Collection;
import java.util.ListIterator;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
//import com.mumfrey.liteloader.transformers.ClassTransformer;
//import com.mumfrey.liteloader.transformers.event.Event;
//import com.mumfrey.liteloader.transformers.event.InjectionPoint;
//import com.mumfrey.liteloader.transformers.event.MethodInfo;
//import com.mumfrey.liteloader.util.log.LiteLoaderLogger;
/**
* An injection point which searches for method invokations matching its arguments and returns a list of insns immediately
* prior to matching invokations. Only the method name is required, owners and signatures are optional and can be used to disambiguate
* between methods of the same name but with different args, or belonging to different classes.
*
* @author Adam Mummery-Smith
*/
public class BeforeInvoke extends InjectionPoint
{
public static final String CODE = "INVOKE";
protected class InsnInfo
{
public final String owner;
public final String name;
public final String desc;
public InsnInfo(AbstractInsnNode insn)
{
if (insn instanceof MethodInsnNode)
{
MethodInsnNode methodNode = (MethodInsnNode)insn;
this.owner = methodNode.owner;
this.name = methodNode.name;
this.desc = methodNode.desc;
}
else if (insn instanceof FieldInsnNode)
{
FieldInsnNode fieldNode = (FieldInsnNode)insn;
this.owner = fieldNode.owner;
this.name = fieldNode.name;
this.desc = fieldNode.desc;
}
else
{
throw new IllegalArgumentException("insn must be an instance of MethodInsnNode or FieldInsnNode");
}
}
}
protected final MemberInfo target;
/**
* This strategy can be used to identify a particular invokation if the same method is invoked at multiple points, if this value is -1
* then the strategy returns ALL invokations of the method.
*/
protected final int ordinal;
/**
* True to turn on strategy debugging to the console
*/
protected boolean logging = false;
protected final String className;
public BeforeInvoke(InjectionPointData data)
{
this.target = data.getTarget();
this.ordinal = data.getOrdinal();
this.className = this.getClass().getSimpleName();
// this.convertClassRefs();
}
// private void convertClassRefs()
// {
// for (int i = 0; i < this.methodOwners.length; i++)
// {
// if (this.methodOwners[i] != null) this.methodOwners[i] = this.methodOwners[i].replace('.', '/');
// }
//
// if (this.methodSignatures != null)
// {
// for (int i = 0; i < this.methodSignatures.length; i++)
// {
// if (this.methodSignatures[i] != null) this.methodSignatures[i] = this.methodSignatures[i].replace('.', '/');
// }
// }
// }
public BeforeInvoke setLogging(boolean logging)
{
this.logging = logging;
return this;
}
/* (non-Javadoc)
* @see com.mumfrey.liteloader.transformers.event.InjectionStrategy#findInjectionPoint(java.lang.String, org.objectweb.asm.tree.InsnList, com.mumfrey.liteloader.transformers.event.Event, java.util.Collection)
*/
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
int ordinal = 0;
boolean found = false;
if (this.logging)
{
// LiteLoaderLogger.debug(ClassTransformer.HORIZONTAL_RULE);
// LiteLoaderLogger.debug(this.className + " is searching for an injection point in method with descriptor %s", desc);
}
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext())
{
AbstractInsnNode insn = iter.next();
if (this.matchesInsn(insn))
{
InsnInfo nodeInfo = new InsnInfo(insn);
// if (this.logging) LiteLoaderLogger.debug(this.className + " is considering insn NAME=%s DESC=%s OWNER=%s", nodeInfo.name, nodeInfo.desc, nodeInfo.owner);
// int index = BeforeInvoke.arrayIndexOf(this.methodNames, nodeInfo.name, -1);
// if (index > -1 && this.logging) LiteLoaderLogger.debug(this.className + " found a matching insn, checking owner/signature...");
// int ownerIndex = BeforeInvoke.arrayIndexOf(this.methodOwners, nodeInfo.owner, index);
// int descIndex = BeforeInvoke.arrayIndexOf(this.methodSignatures, nodeInfo.desc, index);
if (this.target.matches(nodeInfo.owner, nodeInfo.name, nodeInfo.desc))
{
// if (this.logging) LiteLoaderLogger.debug(this.className + " found a matching insn, checking preconditions...");
if (this.matchesInsn(nodeInfo, ordinal))
{
// if (this.logging) LiteLoaderLogger.debug(this.className + " found a matching insn at ordinal %d", ordinal);
nodes.add(insn);
found = true;
if (this.ordinal == ordinal)
break;
}
ordinal++;
}
}
this.inspectInsn(desc, insns, insn);
}
// if (this.logging) LiteLoaderLogger.debug(ClassTransformer.HORIZONTAL_RULE);
return found;
}
protected boolean matchesInsn(AbstractInsnNode insn)
{
return insn instanceof MethodInsnNode;
}
protected void inspectInsn(String desc, InsnList insns, AbstractInsnNode insn)
{
// stub for subclasses
}
protected boolean matchesInsn(InsnInfo nodeInfo, int ordinal)
{
// if (this.logging) LiteLoaderLogger.debug(this.className + " comparing target ordinal %d with current ordinal %d", this.ordinal, ordinal);
return this.ordinal == -1 || this.ordinal == ordinal;
}
//
// /**
// * Special version of contains which returns TRUE if the haystack array is null, which is an odd behaviour we actually
// * want here because null indicates that the value is not important
// *
// * @param haystack
// * @param needle
// */
// private static int arrayIndexOf(String[] haystack, String needle, int pos)
// {
// if (haystack == null) return pos;
// if (pos > -1 && pos < haystack.length && needle.equals(haystack[pos])) return pos;
//
// for (int index = 0; index < haystack.length; index++)
// if (needle.equals(haystack[index])) return index;
//
// return -1;
// }
}
@@ -0,0 +1,76 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import java.util.Collection;
import java.util.ListIterator;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.TypeInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
//import com.mumfrey.liteloader.core.runtime.Obf;
//import com.mumfrey.liteloader.transformers.event.Event;
//import com.mumfrey.liteloader.transformers.event.InjectionPoint;
public class BeforeNew extends InjectionPoint
{
public static final String CODE = "NEW";
private final String className;
private final int ordinal;
public BeforeNew(InjectionPointData data)
{
this.ordinal = data.getOrdinal();
this.className = data.get("class", "").replace('.', '/');
// for (int i = 0; i < this.classNames.length; i++)
// {
// this.classNames[i] = this.classNames[i].replace('.', '/');
// }
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
boolean found = false;
int ordinal = 0;
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext())
{
AbstractInsnNode insn = iter.next();
if (insn instanceof TypeInsnNode && insn.getOpcode() == Opcodes.NEW && this.matchesOwner((TypeInsnNode)insn))
{
if (this.ordinal == -1 || this.ordinal == ordinal)
{
nodes.add(insn);
found = true;
}
ordinal++;
}
}
return found;
}
private boolean matchesOwner(TypeInsnNode insn)
{
// for (String className : this.classNames)
// {
// if (className.equals(insn.desc)) return true;
// }
return this.className.equals(insn.desc);
}
}
@@ -0,0 +1,64 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import java.util.Collection;
import java.util.ListIterator;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
//import com.mumfrey.liteloader.transformers.event.Event;
//import com.mumfrey.liteloader.transformers.event.InjectionPoint;
/**
* An injection point which searches for RETURN opcodes in the supplied method and either finds all insns or
* the insn at the specified ordinal
*
* @author Adam Mummery-Smith
*/
public class BeforeReturn extends InjectionPoint
{
public static final String CODE = "RETURN";
private final int ordinal;
public BeforeReturn(InjectionPointData data)
{
this.ordinal = data.getOrdinal();
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
boolean found = false;
int returnOpcode = Type.getReturnType(desc).getOpcode(Opcodes.IRETURN);
int ordinal = 0;
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext())
{
AbstractInsnNode insn = iter.next();
if (insn instanceof InsnNode && insn.getOpcode() == returnOpcode)
{
if (this.ordinal == -1 || this.ordinal == ordinal)
{
nodes.add(insn);
found = true;
}
ordinal++;
}
}
return found;
}
}
@@ -0,0 +1,80 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import java.util.Collection;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LdcInsnNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
//import com.mumfrey.liteloader.transformers.event.Event;
//import com.mumfrey.liteloader.transformers.event.MethodInfo;
//import com.mumfrey.liteloader.util.log.LiteLoaderLogger;
/**
* An injection point which searches for a matching String LDC insn immediately prior to a qualifying invoke
*
* @author Adam Mummery-Smith
*/
public class BeforeStringInvoke extends BeforeInvoke
{
@SuppressWarnings("hiding")
public static final String CODE = "INVOKE_STRING";
// private static final String STRING_VOID_SIG = "(Ljava/lang/String;)V";
private final String ldcValue;
private boolean foundLdc;
// public BeforeStringInvoke(String ldcValue, String[] methodNames, String[] methodOwners)
// {
// this(ldcValue, methodNames, methodOwners, -1);
// }
public BeforeStringInvoke(InjectionPointData data)
{
super(data);
this.ldcValue = data.get("ldc", "");
// for (int i = 0; i < this.methodSignatures.length; i++)
// if (!STRING_VOID_SIG.equals(this.methodSignatures[i]))
// throw new IllegalArgumentException("BeforeStringInvoke requires method with with signature " + STRING_VOID_SIG);
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
this.foundLdc = false;
return super.find(desc, insns, nodes); //, event);
}
@Override
protected void inspectInsn(String desc, InsnList insns, AbstractInsnNode insn)
{
if (insn instanceof LdcInsnNode)
{
LdcInsnNode node = (LdcInsnNode)insn;
if (node.cst instanceof String && this.ldcValue.equals(node.cst))
{
// if (this.logging) LiteLoaderLogger.info("BeforeInvoke found a matching LDC with value %s", node.cst);
this.foundLdc = true;
return;
}
}
this.foundLdc = false;
}
@Override
protected boolean matchesInsn(InsnInfo nodeInfo, int ordinal)
{
// if (this.logging) LiteLoaderLogger.debug("BeforeInvoke foundLdc \"%s\" = %s", this.ldcValue, this.foundLdc);
return this.foundLdc && super.matchesInsn(nodeInfo, ordinal);
}
}
@@ -0,0 +1,65 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import java.util.Collection;
import java.util.ListIterator;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.JumpInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
//import com.mumfrey.liteloader.transformers.event.Event;
//import com.mumfrey.liteloader.transformers.event.InjectionPoint;
/**
* An injection point which searches for JUMP opcodes (if, try/catch, continue, break, conditional assignment, etc.)
* with either a particular opcode or at a particular ordinal in the method body (eg. "the Nth JUMP insn" where N is the
* ordinal of the instruction). By default it returns all JUMP instructions in a method body.
*
* @author Adam Mummery-Smith
*/
public class JumpInsnPoint extends InjectionPoint
{
public static final String CODE = "JUMP";
private final int opCode;
private final int ordinal;
public JumpInsnPoint(InjectionPointData data)
{
this.opCode = data.getOpcode();
this.ordinal = data.getOrdinal();
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
boolean found = false;
int ordinal = 0;
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext())
{
AbstractInsnNode insn = iter.next();
if (insn instanceof JumpInsnNode && (this.opCode == -1 || insn.getOpcode() == this.opCode))
{
if (this.ordinal == -1 || this.ordinal == ordinal)
{
nodes.add(insn);
found = true;
}
ordinal++;
}
}
return found;
}
}
@@ -0,0 +1,36 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.points;
import java.util.Collection;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
//import com.mumfrey.liteloader.transformers.event.Event;
//import com.mumfrey.liteloader.transformers.event.InjectionPoint;
/**
* An injection point which locates the first instruction in a method body
*
* @author Adam Mummery-Smith
*/
public class MethodHead extends InjectionPoint
{
public static final String CODE = "HEAD";
public MethodHead(InjectionPointData data)
{
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) //, Event event)
{
nodes.add(insns.getFirst());
return true;
}
}
@@ -0,0 +1,130 @@
/**
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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.struct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.spongepowered.asm.mixin.injection.At;
/**
* Data read from an {@link At} annotation and passed into an InjectionPoint ctor
*
* @author Adam Mummery-Smith
*/
public class InjectionPointData {
/**
* K/V arguments parsed from the "args" node in the {@link At} annotation
*/
private final Map<String, String> args = new HashMap<String, String>();
/**
* Target
*/
private final String target;
/**
* Ordinal
*/
private final int ordinal;
/**
* Opcode
*/
private final int opcode;
public InjectionPointData(List<String> args, String target, int ordinal, int opcode) {
this.target = target;
this.ordinal = Math.max(-1, ordinal);
this.opcode = opcode;
this.parseArgs(args);
this.args.put("target", target);
this.args.put("ordinal", String.valueOf(ordinal));
this.args.put("opcode", String.valueOf(opcode));
}
private void parseArgs(List<String> args) {
for (String arg : args) {
if (arg != null) {
int eqPos = arg.indexOf('=');
if (eqPos > -1) {
this.args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1));
} else {
this.args.put(arg, "");
}
}
}
}
public String get(String key, String defaultValue) {
String value = this.args.get(key);
return value != null ? value : defaultValue;
}
public int get(String key, int defaultValue) {
return this.parseInt(this.get(key, String.valueOf(defaultValue)), defaultValue);
}
public boolean get(String key, boolean defaultValue) {
return this.parseBoolean(this.get(key, String.valueOf(defaultValue)), defaultValue);
}
public MemberInfo get(String key) {
return MemberInfo.parse(this.get(key, ""));
}
private int parseInt(String string, int defaultValue) {
try {
return Integer.parseInt(string);
} catch (Exception ex) {
return defaultValue;
}
}
private boolean parseBoolean(String string, boolean defaultValue) {
try {
return Boolean.parseBoolean(string);
} catch (Exception ex) {
return defaultValue;
}
}
public MemberInfo getTarget() {
return MemberInfo.parse(this.target);
}
public int getOrdinal() {
return this.ordinal;
}
public int getOpcode() {
return this.opcode;
}
}
@@ -0,0 +1,188 @@
/**
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://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.struct;
/**
* <p>Information bundle about a member (method or field) parsed from a String token in another annotation, this is used where target members need to
* be specified as Strings in order to parse the String representation to something useful.</p>
*
* <p>Some examples: <blockquote><pre>
* // references a method called func_1234_a, if there are multiple methods with the same signature, matches the first occurrence
* func_1234_a
*
* // references a method called func_1234_a, if there are multiple methods with the same signature, matches all occurrences
* func_1234_a*
*
* // references a method called func_1234_a which takes 3 ints and returns a bool
* func_1234_a(III)Z
*
* // references a ctor which takes a single String argument
* <init>(Ljava/lang/String;)V
*
* // references a method called func_1234_a in class foo.bar.Baz
* Lfoo/bar/Baz;func_1234_a
*
* // references a method called func_1234_a in class foo.bar.Baz which takes 3 doubles and returns void
* Lfoo/bar/Baz;func_1234_a(DDD)V
*
* // alternate syntax for the same
* foo.bar.Baz.func_1234_a(DDD)V</pre></blockquote>
* </p>
*
* @author Adam Mummery-Smith
*/
public class MemberInfo {
/**
* Member owner in internal form but without L;, can be null
*/
public final String owner;
/**
* Member name, can be null to match any member
*/
public final String name;
/**
* Member descriptor, can be null
*/
public final String desc;
/**
* True to match all matching members, not just the first
*/
public final boolean matchAll;
/**
* @param name Member name, must not be null
*/
public MemberInfo(String name, boolean matchAll) {
this(name, null, null, matchAll);
}
/**
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form without L;
*/
public MemberInfo(String name, String owner, boolean matchAll) {
this(name, owner, null, matchAll);
}
/**
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form without L;
* @param desc Member descriptor, can be null
* @param matchAll True to match all matching members, not just the first
*/
public MemberInfo(String name, String owner, String desc, boolean matchAll) {
if (owner != null && owner.contains(".")) {
throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format");
}
this.owner = owner;
this.name = name;
this.desc = desc;
this.matchAll = matchAll;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("MemberInfo[OWNER=%s,NAME=%s,DESC=%s,ALL=%s]", this.owner, this.name, this.desc, this.matchAll);
}
/**
* Test whether this MemberInfo matches the supplied values. Null values are ignored.
*/
public boolean matches(String owner, String name, String desc) {
return this.matches(owner, name, desc, 0);
}
/**
* Test whether this MemberInfo matches the supplied values at the specified ordinal. Null values are ignored.
*/
public boolean matches(String owner, String name, String desc, int ordinal) {
if (this.desc != null && desc != null && !this.desc.equals(desc)) {
return false;
}
if (this.name != null && name != null && !this.name.equals(name)) {
return false;
}
if (this.owner != null && owner != null && !this.owner.equals(owner)) {
return false;
}
return ordinal == 0 || this.matchAll;
}
/**
* Test whether this MemberInfo matches the supplied values. Null values are ignored.
*/
public boolean matches(String name, String desc) {
return this.matches(name, desc, 0);
}
/**
* Test whether this MemberInfo matches the supplied values at the specified ordinal. Null values are ignored.
*/
public boolean matches(String name, String desc, int ordinal) {
return (this.name == null || this.name.equals(name))
&& (this.desc == null || (desc != null && desc.equals(this.desc)))
&& (ordinal == 0 || this.matchAll);
}
/**
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name) {
String desc = null;
String owner = null;
int lastDotPos = name.lastIndexOf('.');
int semiColonPos = name.indexOf(';');
if (lastDotPos > -1) {
owner = name.substring(0, lastDotPos).replace('.', '/');
name = name.substring(lastDotPos + 1);
} else if (semiColonPos > -1 && name.startsWith("L")) {
owner = name.substring(1, semiColonPos).replace('.', '/');
name = name.substring(semiColonPos + 1);
}
int parenPos = name.indexOf('(');
if (parenPos > -1) {
desc = name.substring(parenPos);
name = name.substring(0, parenPos);
}
boolean matchAll = name.endsWith("*");
if (matchAll) name = name.substring(0, name.length() - 1);
if (name.isEmpty()) name = null;
return new MemberInfo(name, owner, desc, matchAll);
}
}
@@ -0,0 +1,151 @@
/**
* This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.mixin.injection.tree;
import java.util.ListIterator;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
/**
* Read-only wrapper for InsnList
*
* @author Adam Mummery-Smith
*/
public class ReadOnlyInsnList extends InsnList
{
private InsnList insnList;
public ReadOnlyInsnList(InsnList insns)
{
this.insnList = insns;
}
void dispose()
{
this.insnList = null;
}
@Override
public void set(AbstractInsnNode location, AbstractInsnNode insn)
{
throw new UnsupportedOperationException();
}
@Override
public void add(AbstractInsnNode insn)
{
throw new UnsupportedOperationException();
}
@Override
public void add(InsnList insns)
{
throw new UnsupportedOperationException();
}
@Override
public void insert(AbstractInsnNode insn)
{
throw new UnsupportedOperationException();
}
@Override
public void insert(InsnList insns)
{
throw new UnsupportedOperationException();
}
@Override
public void insert(AbstractInsnNode location, AbstractInsnNode insn)
{
throw new UnsupportedOperationException();
}
@Override
public void insert(AbstractInsnNode location, InsnList insns)
{
throw new UnsupportedOperationException();
}
@Override
public void insertBefore(AbstractInsnNode location, AbstractInsnNode insn)
{
throw new UnsupportedOperationException();
}
@Override
public void insertBefore(AbstractInsnNode location, InsnList insns)
{
throw new UnsupportedOperationException();
}
@Override
public void remove(AbstractInsnNode insn)
{
throw new UnsupportedOperationException();
}
@Override
public AbstractInsnNode[] toArray()
{
// throw new UnsupportedOperationException();
return this.insnList.toArray();
}
@Override
public int size()
{
return this.insnList.size();
}
@Override
public AbstractInsnNode getFirst()
{
return this.insnList.getFirst();
}
@Override
public AbstractInsnNode getLast()
{
return this.insnList.getLast();
}
@Override
public AbstractInsnNode get(int index)
{
return this.insnList.get(index);
}
@Override
public boolean contains(AbstractInsnNode insn)
{
return this.insnList.contains(insn);
}
@Override
public int indexOf(AbstractInsnNode insn)
{
return this.insnList.indexOf(insn);
}
@Override
public ListIterator<AbstractInsnNode> iterator()
{
return this.insnList.iterator();
}
@Override
public ListIterator<AbstractInsnNode> iterator(int index)
{
return this.insnList.iterator(index);
}
@Override
public void resetLabels()
{
this.insnList.resetLabels();
}
}
@@ -55,7 +55,7 @@ class MixinInfo implements Comparable<MixinInfo> {
/**
* Logger
*/
private final transient Logger logger = LogManager.getLogger("sponge");
private final transient Logger logger = LogManager.getLogger("mixin");
/**
* Parent configuration which declares this mixin
@@ -32,7 +32,6 @@ import java.util.Iterator;
import java.util.List;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
@@ -41,6 +40,7 @@ import org.apache.logging.log4j.core.helpers.Booleans;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
@@ -51,6 +51,8 @@ import org.spongepowered.asm.mixin.InvalidMixinException;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionInfo;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.ASMHelper;
@@ -59,12 +61,14 @@ import org.spongepowered.asm.util.ASMHelper;
*/
public class MixinTransformer extends TreeTransformer {
private static final String CLINIT = "<clinit>";
private static final boolean DEBUG_EXPORT = Booleans.parseBoolean(System.getProperty("mixin.debug.export"), false);
/**
* Log all the things
*/
private final Logger logger = LogManager.getLogger("sponge");
private final Logger logger = LogManager.getLogger("mixin");
/**
* Mixin configuration bundle
@@ -182,6 +186,7 @@ public class MixinTransformer extends TreeTransformer {
this.applyMixinAttributes(targetClass, mixin);
this.applyMixinFields(targetClass, mixin);
this.applyMixinMethods(targetClass, mixin);
this.applyInjections(targetClass, mixin);
} catch (Exception ex) {
throw new InvalidMixinException("Unexpecteded error whilst applying the mixin class", ex);
}
@@ -296,7 +301,7 @@ public class MixinTransformer extends TreeTransformer {
throw new InvalidMixinException(String.format("Overwrite target %s was not located in the target class", mixinMethod.name));
}
targetClass.methods.add(mixinMethod);
} else if ("<clinit>".equals(mixinMethod.name)) {
} else if (MixinTransformer.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
this.appendInsns(targetClass, mixinMethod.name, mixinMethod);
}
@@ -371,6 +376,28 @@ public class MixinTransformer extends TreeTransformer {
}
}
/**
* Process {@link Inject} annotations and inject callbacks to annotated methods
*
* @param targetClass
* @param mixin
*/
private void applyInjections(ClassNode targetClass, MixinData mixin) {
for (MethodNode method : targetClass.methods) {
AnnotationNode injectAnnotation = ASMHelper.getVisibleAnnotation(method, Inject.class);
if (injectAnnotation == null) {
continue;
}
InjectionInfo injectInfo = new InjectionInfo(targetClass, method, injectAnnotation);
if (injectInfo.isValid()) {
injectInfo.inject();
}
method.visibleAnnotations.remove(injectAnnotation);
}
}
/**
* Finds a method in the target class
*
@@ -384,7 +411,7 @@ public class MixinTransformer extends TreeTransformer {
return target;
}
}
return null;
}
@@ -442,6 +442,19 @@ public class ASMHelper {
return ASMHelper.getAnnotationValue(annotation, "value");
}
/**
* Get the value of an annotation node and do pseudo-duck-typing via Java's crappy generics
*
* @param annotation Annotation node to query
* @param key Key to search for
* @param defaultValue Value to return if the specified key is not found or is null
* @return duck-typed annotation value, null if missing, or inevitable ClassCastException if your duck is actually a rooster
*/
public static <T> T getAnnotationValue(AnnotationNode annotation, String key, T defaultValue) {
T returnValue = ASMHelper.getAnnotationValue(annotation, key);
return returnValue != null ? returnValue : defaultValue;
}
/**
* Get the value of an annotation node and do pseudo-duck-typing via Java's crappy generics
*
@@ -469,4 +482,12 @@ public class ASMHelper {
return null;
}
public static boolean methodIsStatic(MethodNode method) {
return (method.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC;
}
public static boolean fieldIsStatic(FieldNode field) {
return (field.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC;
}
}
@@ -0,0 +1,809 @@
/**
* This file contributed from LiteLoader. Pending merge into ASMHelper. DO NOT ALTER THIS FILE.
*/
package org.spongepowered.asm.util;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import org.objectweb.asm.tree.analysis.Analyzer;
import org.objectweb.asm.tree.analysis.AnalyzerException;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.SimpleVerifier;
//import com.mumfrey.liteloader.core.runtime.Obf;
/**
* Utility methods for working with bytecode using ASM
*
* @author Adam Mummery-Smith
*/
public abstract class ByteCodeUtilities
{
private static Map<String, List<LocalVariableNode>> calculatedLocalVariables = new HashMap<String, List<LocalVariableNode>>();
private ByteCodeUtilities() {}
// /**
// * Replace all constructor invokations for the target class in the supplied classNode with invokations of the replacement class
// *
// * @param classNode Class to search in
// * @param target Target type
// * @param replacement Replacement type
// */
// public static void replaceConstructors(ClassNode classNode, Obf target, Obf replacement)
// {
// for (MethodNode method : classNode.methods)
// {
// ByteCodeUtilities.replaceConstructors(method, target, replacement);
// }
// }
// /**
// * Replace all constructor invokations for the target class in the supplied method with invokations of the replacement class
// *
// * @param method Method to look in
// * @param target Target type
// * @param replacement Replacement type
// */
// public static void replaceConstructors(MethodNode method, Obf target, Obf replacement)
// {
// Iterator<AbstractInsnNode> iter = method.instructions.iterator();
// while (iter.hasNext())
// {
// AbstractInsnNode insn = iter.next();
// if (insn.getOpcode() == Opcodes.NEW)
// {
// TypeInsnNode typeInsn = (TypeInsnNode)insn;
// if (target.obf.equals(typeInsn.desc) || target.ref.equals(typeInsn.desc))
// {
// typeInsn.desc = replacement.ref;
// }
// }
// else if (insn instanceof MethodInsnNode && insn.getOpcode() == Opcodes.INVOKESPECIAL)
// {
// MethodInsnNode methodInsn = (MethodInsnNode)insn;
// if ((target.obf.equals(methodInsn.owner) || target.ref.equals(methodInsn.owner)) && "<init>".equals(methodInsn.name))
// {
// methodInsn.owner = replacement.ref;
// }
// }
// }
// }
/**
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate for each entry in the args array starting at pos
*
* @param args Argument types
* @param insns Instruction List to inject into
* @param pos Start position
*/
public static void loadArgs(Type[] args, InsnList insns, int pos)
{
ByteCodeUtilities.loadArgs(args, insns, pos, -1);
}
/**
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate for each entry in the args array starting at start and ending at end
*
* @param args Argument types
* @param insns Instruction List to inject into
* @param start Start position
* @param end End position
*/
public static void loadArgs(Type[] args, InsnList insns, int start, int end)
{
int pos = start;
for (Type type : args)
{
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), pos));
pos += type.getSize();
if (end >= start && pos >= end) return;
}
}
/**
* Injects appropriate LOAD opcodes into the supplied InsnList for each entry in the supplied locals array starting at pos
*
* @param locals Local types (can contain nulls for uninitialised, TOP, or RETURN values in locals)
* @param insns Instruction List to inject into
* @param pos Start position
*/
public static void loadLocals(Type[] locals, InsnList insns, int pos)
{
for (; pos < locals.length; pos++)
{
if (locals[pos] != null)
{
insns.add(new VarInsnNode(locals[pos].getOpcode(Opcodes.ILOAD), pos));
}
}
}
/**
* Get the first variable index in the supplied method which is not an argument or "this" reference, this corresponds
* to the size of the arguments passed in to the method plus an extra spot for "this" if the method is non-static
*
* @param method MethodNode to inspect
* @return first available local index which is NOT used by a method argument or "this"
*/
public static int getFirstNonArgLocalIndex(MethodNode method)
{
return ByteCodeUtilities.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), (method.access & Opcodes.ACC_STATIC) == 0);
}
/**
* Get the first non-arg variable index based on the supplied arg array and whether to include the "this" reference,
* this corresponds to the size of the arguments passed in to the method plus an extra spot for "this" is specified
* @param args Method arguments
* @param includeThis Whether to include a slot for "this" (generally true for all non-static methods)
* @return first available local index which is NOT used by a method argument or "this"
*/
public static int getFirstNonArgLocalIndex(Type[] args, boolean includeThis)
{
return ByteCodeUtilities.getArgsSize(args) + (includeThis ? 1 : 0);
}
/**
* Get the size of the specified args array in local variable terms (eg. doubles and longs take two spaces)
*
* @param args Method argument types as array
* @return size of the specified arguments array in terms of stack slots
*/
public static int getArgsSize(Type[] args)
{
int size = 0;
for (Type type : args)
{
size += type.getSize();
}
return size;
}
/**
* Attempts to identify available locals at an arbitrary point in the bytecode specified by node.
*
* This method builds an approximate view of the locals available at an arbitrary point in the bytecode by examining the following
* features in the bytecode:
*
* * Any available stack map frames
* * STORE opcodes
* * The local variable table
*
* Inference proceeds by walking the bytecode from the start of the method looking for stack frames and STORE opcodes. When either
* of these is encountered, an attempt is made to cross-reference the values in the stack map or STORE opcode with the value in the
* local variable table which covers the code range. Stack map frames overwrite the entire simulated local variable table with their
* own value types, STORE opcodes overwrite only the local slot to which they pertain. Values in the simulated locals array are spaced
* according to their size (unlike the representation in FrameNode) and this TOP, NULL and UNINTITIALIZED_THIS opcodes will be
* represented as null values in the simulated frame.
*
* This code does not currently simulate the prescribed JVM behaviour where overwriting the second slot of a DOUBLE or LONG actually
* invalidates the DOUBLE or LONG stored in the previous location, so we have to hope (for now) that this behaviour isn't emitted by
* the compiler or any upstream transformers. I may have to re-think this strategy if this situation is encountered in the wild.
*
* @param classNode ClassNode containing the method, used to initialise the implicit "this" reference in simple methods with no stack frames
* @param method MethodNode to explore
* @param node Node indicating the position at which to determine the locals state. The locals will be enumerated UP TO the specified
* node, so bear in mind that if the specified node is itself a STORE opcode, then we will be looking at the state of the locals
* PRIOR to its invokation
* @return A sparse array containing a view (hopefully) of the locals at the specified location
*/
public static LocalVariableNode[] getLocalsAt(ClassNode classNode, MethodNode method, AbstractInsnNode node)
{
LocalVariableNode[] frame = new LocalVariableNode[method.maxLocals];
// Initialise implicit "this" reference in non-static methods
if ((method.access & Opcodes.ACC_STATIC) == 0)
{
frame[0] = new LocalVariableNode("this", classNode.name, null, null, null, 0);
}
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();)
{
AbstractInsnNode insn = iter.next();
if (insn instanceof FrameNode)
{
FrameNode frameNode = (FrameNode)insn;
// localPos tracks the location in the frame node's locals list, which doesn't leave space for TOP entries
for (int localPos = 0, framePos = 0; framePos < frame.length; framePos++, localPos++)
{
// Get the local at the current position in the FrameNode's locals list
final Object localType = (localPos < frameNode.local.size()) ? frameNode.local.get(localPos) : null;
if (localType instanceof String) // String refers to a reference type
{
frame[framePos] = ByteCodeUtilities.getLocalVariableAt(classNode, method, node, framePos);
}
else if (localType instanceof Integer) // Integer refers to a primitive type or other marker
{
boolean isMarkerType = localType == Opcodes.UNINITIALIZED_THIS || localType == Opcodes.TOP || localType == Opcodes.NULL;
boolean is32bitValue = localType == Opcodes.INTEGER || localType == Opcodes.FLOAT;
boolean is64bitValue = localType == Opcodes.DOUBLE || localType == Opcodes.LONG;
if (isMarkerType)
{
frame[framePos] = null;
}
else if (is32bitValue || is64bitValue)
{
frame[framePos] = ByteCodeUtilities.getLocalVariableAt(classNode, method, node, framePos);
if (is64bitValue)
{
framePos++;
frame[framePos] = null; // TOP
}
}
else
{
throw new RuntimeException("Unrecognised locals opcode " + localType + " in locals array at position " + localPos + " in " + classNode.name + "." + method.name + method.desc);
}
}
else if (localType == null)
{
frame[framePos] = null;
}
else
{
throw new RuntimeException("Invalid value " + localType + " in locals array at position " + localPos + " in " + classNode.name + "." + method.name + method.desc);
}
}
}
else if (insn instanceof VarInsnNode)
{
VarInsnNode varNode = (VarInsnNode)insn;
frame[varNode.var] = ByteCodeUtilities.getLocalVariableAt(classNode, method, node, varNode.var);
}
else if (insn == node)
{
break;
}
}
return frame;
}
/**
* Attempts to locate the appropriate entry in the local variable table for the specified local variable index at the location
* specified by node.
*
* @param classNode Containing class
* @param method Method
* @param node Instruction defining the location to get the local variable table at
* @param var Local variable index
* @return a LocalVariableNode containing information about the local variable at the specified location in the specified local slot
*/
public static LocalVariableNode getLocalVariableAt(ClassNode classNode, MethodNode method, AbstractInsnNode node, int var)
{
LocalVariableNode localVariableNode = null;
int pos = method.instructions.indexOf(node);
List<LocalVariableNode> localVariables = ByteCodeUtilities.getLocalVariableTable(classNode, method);
for (LocalVariableNode local : localVariables)
{
if (local.index != var) continue;
int start = method.instructions.indexOf(local.start);
int end = method.instructions.indexOf(local.end);
if (localVariableNode == null || start < pos && end > pos)
{
localVariableNode = local;
}
}
return localVariableNode;
}
/**
* Fetches or generates the local variable table for the specified method. Since Mojang strip the local variable table
* as part of the obfuscation process, we need to generate the local variable table when running obfuscated. We cache
* the generated tables so that we only need to do the relatively expensive calculation once per method we encounter.
*
* @param classNode Containing class
* @param method Method
*/
public static List<LocalVariableNode> getLocalVariableTable(ClassNode classNode, MethodNode method)
{
if (method.localVariables.isEmpty())
{
String signature = String.format("%s.%s%s", classNode.name, method.name, method.desc);
List<LocalVariableNode> localVars = ByteCodeUtilities.calculatedLocalVariables.get(signature);
if (localVars != null)
{
return localVars;
}
localVars = ByteCodeUtilities.generateLocalVariableTable(classNode, method);
ByteCodeUtilities.calculatedLocalVariables.put(signature, localVars);
return localVars;
}
return method.localVariables;
}
/**
* Use ASM Analyzer to generate the local variable table for the specified method
*
* @param classNode Containing class
* @param method Method
*/
public static List<LocalVariableNode> generateLocalVariableTable(ClassNode classNode, MethodNode method)
{
List<Type> interfaces = null;
if (classNode.interfaces != null)
{
interfaces = new ArrayList<Type>();
for (String iface : classNode.interfaces)
{
interfaces.add(Type.getObjectType(iface));
}
}
Type objectType = null;
if (classNode.superName != null)
{
objectType = Type.getObjectType(classNode.superName);
}
// Use Analyzer to generate the bytecode frames
Analyzer<BasicValue> analyzer = new Analyzer<BasicValue>(new SimpleVerifier(Type.getObjectType(classNode.name), objectType, interfaces, false));
try
{
analyzer.analyze(classNode.name, method);
}
catch (AnalyzerException ex)
{
ex.printStackTrace();
}
// Get frames from the Analyzer
Frame<BasicValue>[] frames = analyzer.getFrames();
// Record the original size of hte method
int methodSize = method.instructions.size();
// List of LocalVariableNodes to return
List<LocalVariableNode> localVariables = new ArrayList<LocalVariableNode>();
LocalVariableNode[] localNodes = new LocalVariableNode[method.maxLocals]; // LocalVariableNodes for current frame
BasicValue[] locals = new BasicValue[method.maxLocals]; // locals in previous frame, used to work out what changes between frames
LabelNode[] labels = new LabelNode[methodSize]; // Labels to add to the method, for the markers
// Traverse the frames and work out when locals begin and end
for (int i = 0; i < methodSize; i++)
{
Frame<BasicValue> f = frames[i];
if (f == null) continue;
LabelNode label = null;
for (int j = 0; j < f.getLocals(); j++)
{
BasicValue local = f.getLocal(j);
if (local == null && locals[j] == null) continue;
if (local != null && local.equals(locals[j])) continue;
if (label == null)
{
label = new LabelNode();
labels[i] = label;
}
if (local == null && locals[j] != null)
{
localVariables.add(localNodes[j]);
localNodes[j].end = label;
localNodes[j] = null;
}
else if (local != null)
{
if (locals[j] != null)
{
localVariables.add(localNodes[j]);
localNodes[j].end = label;
localNodes[j] = null;
}
String desc = (local.getType() != null) ? local.getType().getDescriptor() : null;
localNodes[j] = new LocalVariableNode("var" + j, desc, null, label, null, j);
}
locals[j] = local;
}
}
// Reached the end of the method so flush all current locals and mark the end
LabelNode label = null;
for (int k = 0; k < localNodes.length; k++)
{
if (localNodes[k] != null)
{
if (label == null)
{
label = new LabelNode();
method.instructions.add(label);
}
localNodes[k].end = label;
localVariables.add(localNodes[k]);
}
}
// Insert generated labels into the method body
for (int n = methodSize - 1; n >= 0; n--)
{
if (labels[n] != null)
{
method.instructions.insert(method.instructions.get(n), labels[n]);
}
}
return localVariables;
}
/**
* Get the source code name for the specified type
*
* @param type Type to generate a friendly name for
* @return String representation of the specified type, eg "int" for an integer primitive or "String" for java.lang.String
*/
public static String getTypeName(Type type)
{
switch (type.getSort())
{
case Type.BOOLEAN: return "boolean";
case Type.CHAR: return "char";
case Type.BYTE: return "byte";
case Type.SHORT: return "short";
case Type.INT: return "int";
case Type.FLOAT: return "float";
case Type.LONG: return "long";
case Type.DOUBLE: return "double";
case Type.ARRAY: return ByteCodeUtilities.getTypeName(type.getElementType()) + "[]";
case Type.OBJECT:
String typeName = type.getClassName();
typeName = typeName.substring(typeName.lastIndexOf('.') + 1);
return typeName;
}
return "Object";
}
// /**
// * Finds a method in the target class, uses names specified in the {@link Obfuscated} annotation if present
// *
// * @param targetClass Class to search in
// * @param searchFor Method to search for
// */
// public static MethodNode findTargetMethod(ClassNode targetClass, MethodNode searchFor)
// {
// for (MethodNode target : targetClass.methods)
// {
// if (target.name.equals(searchFor.name) && target.desc.equals(searchFor.desc))
// return target;
// }
//
// AnnotationNode obfuscatedAnnotation = ByteCodeUtilities.getVisibleAnnotation(searchFor, Obfuscated.class);
// if (obfuscatedAnnotation != null)
// {
// for (String obfuscatedName : ByteCodeUtilities.<List<String>>getAnnotationValue(obfuscatedAnnotation))
// {
// for (MethodNode target : targetClass.methods)
// {
// if (target.name.equals(obfuscatedName) && target.desc.equals(searchFor.desc))
// return target;
// }
// }
// }
//
// return null;
// }
// /**
// * Finds a field in the target class, uses names specified in the {@link Obfuscated} annotation if present
// *
// * @param targetClass Class to search in
// * @param searchFor Field to search for
// */
// public static FieldNode findTargetField(ClassNode targetClass, FieldNode searchFor)
// {
// for (FieldNode target : targetClass.fields)
// {
// if (target.name.equals(searchFor.name))
// return target;
// }
//
// AnnotationNode obfuscatedAnnotation = ByteCodeUtilities.getVisibleAnnotation(searchFor, Obfuscated.class);
// if (obfuscatedAnnotation != null)
// {
// for (String obfuscatedName : ByteCodeUtilities.<List<String>>getAnnotationValue(obfuscatedAnnotation))
// {
// for (FieldNode target : targetClass.fields)
// {
// if (target.name.equals(obfuscatedName))
// return target;
// }
// }
// }
//
// return null;
// }
// /**
// * Find a method in the target class which matches the specified method name and descriptor
// *
// * @param classNode
// * @param searchFor
// * @param desc
// */
// public static MethodNode findMethod(ClassNode classNode, Obf searchFor, String desc)
// {
// int ordinal = 0;
//
// for (MethodNode method : classNode.methods)
// {
// if (searchFor.matches(method.name, ordinal++) && method.desc.equals(desc))
// return method;
// }
//
// return null;
// }
// /**
// * Find a field in the target class which matches the specified field name
// *
// * @param classNode
// * @param searchFor
// */
// public static FieldNode findField(ClassNode classNode, Obf searchFor)
// {
// int ordinal = 0;
//
// for (FieldNode field : classNode.fields)
// {
// if (searchFor.matches(field.name, ordinal++))
// return field;
// }
//
// return null;
// }
public static ClassNode loadClass(String className) throws IOException
{
return ByteCodeUtilities.loadClass(className, true, null);
}
public static ClassNode loadClass(String className, boolean runTransformers) throws IOException
{
return ByteCodeUtilities.loadClass(className, runTransformers, null);
}
public static ClassNode loadClass(String className, IClassTransformer source) throws IOException
{
return ByteCodeUtilities.loadClass(className, source != null, source);
}
public static ClassNode loadClass(String className, boolean runTransformers, IClassTransformer source) throws IOException
{
byte[] bytes = Launch.classLoader.getClassBytes(className);
if (runTransformers)
{
bytes = ByteCodeUtilities.applyTransformers(className, bytes, source);
}
return ByteCodeUtilities.readClass(bytes);
}
public static ClassNode readClass(byte[] basicClass)
{
ClassReader classReader = new ClassReader(basicClass);
ClassNode classNode = new ClassNode();
classReader.accept(classNode, ClassReader.EXPAND_FRAMES);
return classNode;
}
public static byte[] applyTransformers(String className, byte[] basicClass)
{
return ByteCodeUtilities.applyTransformers(className, basicClass, null);
}
public static byte[] applyTransformers(String className, byte[] basicClass, IClassTransformer source)
{
final List<IClassTransformer> transformers = Launch.classLoader.getTransformers();
for (final IClassTransformer transformer : transformers)
{
if (transformer != source)
{
basicClass = transformer.transform(className, className, basicClass);
}
}
return basicClass;
}
/**
* Get an annotation of the specified class from the supplied field node
*/
public static AnnotationNode getVisibleAnnotation(FieldNode field, Class<? extends Annotation> annotationClass)
{
return ByteCodeUtilities.getAnnotation(field.visibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an annotation of the specified class from the supplied field node
*/
public static AnnotationNode getInvisibleAnnotation(FieldNode field, Class<? extends Annotation> annotationClass)
{
return ByteCodeUtilities.getAnnotation(field.invisibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an annotation of the specified class from the supplied method node
*/
public static AnnotationNode getVisibleAnnotation(MethodNode method, Class<? extends Annotation> annotationClass)
{
return ByteCodeUtilities.getAnnotation(method.visibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an annotation of the specified class from the supplied method node
*/
public static AnnotationNode getInvisibleAnnotation(MethodNode method, Class<? extends Annotation> annotationClass)
{
return ByteCodeUtilities.getAnnotation(method.invisibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an annotation of the specified class from the supplied class node
*/
public static AnnotationNode getVisibleAnnotation(ClassNode classNode, Class<? extends Annotation> annotationClass)
{
return ByteCodeUtilities.getAnnotation(classNode.visibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an annotation of the specified class from the supplied class node
*/
public static AnnotationNode getInvisibleAnnotation(ClassNode classNode, Class<? extends Annotation> annotationClass)
{
return ByteCodeUtilities.getAnnotation(classNode.invisibleAnnotations, Type.getDescriptor(annotationClass));
}
/**
* Get an annotation of the specified class from the supplied list of annotations, returns null if no matching annotation was found
*/
public static AnnotationNode getAnnotation(List<AnnotationNode> annotations, String annotationType)
{
if (annotations != null)
{
for (AnnotationNode annotation : annotations)
{
if (annotationType.equals(annotation.desc))
return annotation;
}
}
return null;
}
/**
* Get the value of an annotation node (the value at key "value")
*
* @param annotation Annotation node to inspect
*/
public static <T> T getAnnotationValue(AnnotationNode annotation)
{
return ByteCodeUtilities.getAnnotationValue(annotation, "value");
}
/**
* Get the value of an annotation node
*
* @param annotation
* @param key
*/
@SuppressWarnings("unchecked")
public static <T> T getAnnotationValue(AnnotationNode annotation, String key)
{
if (annotation == null || annotation.values == null)
return null;
boolean getNextValue = false;
for (Object value : annotation.values)
{
if (getNextValue) return (T)value;
if (value.equals(key)) getNextValue = true;
}
return null;
}
// /**
// * @param returnType
// * @param args
// */
// public static String generateDescriptor(Type returnType, Object... args)
// {
// return ByteCodeUtilities.generateDescriptor(Obf.MCP, returnType, args);
// }
//
// /**
// * @param returnType
// * @param args
// */
// public static String generateDescriptor(Obf returnType, Object... args)
// {
// return ByteCodeUtilities.generateDescriptor(Obf.MCP, returnType, args);
// }
//
// /**
// * @param returnType
// * @param args
// */
// public static String generateDescriptor(String returnType, Object... args)
// {
// return ByteCodeUtilities.generateDescriptor(Obf.MCP, returnType, args);
// }
// /**
// * @param obfType
// * @param returnType
// * @param args
// */
// public static String generateDescriptor(int obfType, Object returnType, Object... args)
// {
// StringBuilder sb = new StringBuilder().append('(');;
//
// for (Object arg : args)
// {
// sb.append(ByteCodeUtilities.toDescriptor(obfType, arg));
// }
//
// return sb.append(')').append(returnType != null ? ByteCodeUtilities.toDescriptor(obfType, returnType) : "V").toString();
// }
// /**
// * @param obfType
// * @param arg
// */
// private static String toDescriptor(int obfType, Object arg)
// {
// if (arg instanceof Obf)
// {
// return ((Obf)arg).getDescriptor(obfType);
// }
// else if (arg instanceof String)
// {
// return (String)arg;
// }
// else if (arg instanceof Type)
// {
// return arg.toString();
// }
// else if (arg instanceof Class)
// {
// return Type.getDescriptor((Class<?>)arg).toString();
// }
//
// return arg == null ? "" : arg.toString();
// }
}