Add failure handling for local capture, enable local capture in @Inject

This commit is contained in:
Mumfrey committed 2015-03-05 19:02:06 +00:00
1 parent 02948566fd
commit 6f09fade5c
14 files changed
+795 -53

No files matched your search

@@ -29,6 +29,9 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
/**
* Specifies that this mixin method should inject a callback (or
* callback<b>s</b>) to itself in the target method(s) identified by
@@ -60,9 +63,7 @@ public @interface Inject {
* Setting an injected callback to <em>cancellable</em> allows the injected
* callback to inject optional RETURN opcodes into the target method, the
* return behaviour can then be controlled from within the callback by
* interacting with the supplied
* {@link org.spongepowered.asm.mixin.injection.callback.CallbackInfo}
* object.
* interacting with the supplied {@link CallbackInfo} object.
*
* @return true if this injector should inject appropriate RETURN opcodes
* which allow it to be cancelled
@@ -70,13 +71,45 @@ public @interface Inject {
public boolean cancellable() default false;
/**
* Set to true to allow local variables to be captured from the target
* method as well as method parameters.
* Specifies the local variable capture behaviour for this injector.
*
* @return true if the injector should capture local variables in the frame
* at the injection point
* <p>When capturing local variables in scope, the variables are appended to
* the callback invocation after the {@link CallbackInfo} argument.</p>
*
* <p>Capturing local variables from the target scope requires careful
* planning because unlike other aspects of an injection (such as the target
* method name and signature), the local variable table is <b>not</b> safe
* from modification by other transformers which may be in use in the
* production environment. Even other injectors which target the same target
* method have the ability to modify the local variable table and thus it is
* in no way safe to assume that local variables in scope at development
* time will be so in production.</p>
*
* <p>To provide some level of flexibility, especially where changes can be
* anticipated (for example a well-known mod makes changes which result in a
* particular structure for the local variable table) it is possible to
* provide <em>overloads</em> for the handler method which will become
* surrogate targets for the orphaned injector by annotating them with an
* {@link Surrogate} annotation.</p>
*
* <p>It is also important to nominate the failure behaviour to follow when
* local capture fails and so all {@link LocalCapture} behaviours which
* specify a capture action imply a particular behaviour for handling
* failure. See the javadoc on the {@link LocalCapture} members for more
* details.</p>
*
* <p>Determining what local variables are available to you and in what
* order can be somewhat tricky, and so a simple mechanism for enumerating
* available locals is provided. By setting <code>locals</code> to
* {@link LocalCapture#PRINT}, the injector writes the local capture state
* to STDERR instead of injecting the callback. Using the output thus
* obtained it is then a straightforward matter of altering the callback
* method signature to match the signature proposed by the Callback
* Injector.</p>
*
* @return the desired local capture behaviour for this injector
*/
// public boolean captureLocals() default false;
public LocalCapture locals() default LocalCapture.NO_CAPTURE;
/**
@@ -0,0 +1,54 @@
/*
* 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;
/**
* Error to throw for critical injection problems
*/
public class InjectionError extends Error {
private static final long serialVersionUID = 1L;
public InjectionError() {
}
public InjectionError(String message) {
super(message);
}
public InjectionError(Throwable cause) {
super(cause);
}
public InjectionError(String message, Throwable cause) {
super(message, cause);
}
public InjectionError(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,41 @@
/*
* 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;
/**
* Annotation used to decorate surrogate injector methods. See
* {@link Inject#locals()} for information.
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Surrogate {
}
@@ -24,8 +24,11 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
@@ -36,16 +39,21 @@ import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionError;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.points.BeforeReturn;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* This class is responsible for generating the bytecode for injected callbacks
@@ -68,9 +76,14 @@ public class CallbackInjector extends Injector {
final AbstractInsnNode node;
/**
* Inflected local variable types
* Calculated local variables
*/
final Type[] locals;
final LocalVariableNode[] locals;
/**
* Local variable types
*/
final Type[] localTypes;
/**
* The initial frame size based on the target method's arguments
@@ -89,9 +102,21 @@ public class CallbackInjector extends Injector {
final boolean isAtReturn;
/**
* Callback descriptor based on the target method and current context
* Callback descriptor without locals
*/
final String descriptor;
final String desc;
/**
* Callback descriptor with locals
*/
final String descl;
/**
* Callback argument names, unlike the locals arrays this array does not
* contain null entries for TOP slots, so each index in this array
* matches the corresponding argument index in the callback
*/
final String[] argNames;
/**
* These two variables keep track of the (additional) stack size
@@ -113,17 +138,36 @@ public class CallbackInjector extends Injector {
*/
final int marshallVar;
Callback(Target target, final AbstractInsnNode node, final Type[] locals) {
Callback(Target target, final AbstractInsnNode node, final LocalVariableNode[] locals, boolean captureLocals) {
this.target = target;
this.node = node;
this.locals = locals;
this.localTypes = locals != null ? new Type[locals.length] : null;
this.frameSize = ASMHelper.getFirstNonArgLocalIndex(target.arguments, !CallbackInjector.this.isStatic());
this.canCaptureLocals = CallbackInjector.this.captureLocals && locals != null && locals.length > this.frameSize;
this.isAtReturn = this.node instanceof InsnNode && this.isValueReturnOpcode(this.node.getOpcode());
this.descriptor = target.getCallbackDescriptor(this.canCaptureLocals, locals, target.arguments, this.frameSize);
List<String> argNames = null;
if (locals != null) {
argNames = new ArrayList<String>();
for (int l = 0; l <= locals.length; l++) {
if (l == this.frameSize) {
argNames.add(target.returnType == Type.VOID_TYPE ? "ci" : "cir");
}
if (l < locals.length && locals[l] != null) {
this.localTypes[l] = Type.getType(locals[l].desc);
if (l > 0) {
argNames.add(locals[l].name);
}
}
}
}
this.invoke = target.arguments.length + (this.canCaptureLocals ? locals.length - this.frameSize : 0);
this.argNames = argNames != null ? argNames.toArray(new String[argNames.size()]) : null;
this.canCaptureLocals = captureLocals && locals != null && locals.length > this.frameSize;
this.isAtReturn = this.node instanceof InsnNode && this.isValueReturnOpcode(this.node.getOpcode());
this.desc = target.getCallbackDescriptor(false, this.localTypes, target.arguments, this.frameSize);
this.descl = target.getCallbackDescriptor(true, this.localTypes, target.arguments, this.frameSize);
this.invoke = target.arguments.length + (this.canCaptureLocals ? this.localTypes.length - this.frameSize : 0);
this.marshallVar = target.method.maxLocals++;
}
@@ -137,6 +181,10 @@ public class CallbackInjector extends Injector {
private boolean isValueReturnOpcode(int opcode) {
return opcode >= Opcodes.IRETURN && opcode < Opcodes.RETURN;
}
String getDescriptor() {
return this.canCaptureLocals ? this.descl : this.desc;
}
/**
* Add an instruction to this callback and increment the appropriate
@@ -162,29 +210,30 @@ public class CallbackInjector extends Injector {
}
}
private final Logger logger = LogManager.getLogger("mixin");
/**
* True if cancellable
*/
protected final boolean cancellable;
private final boolean cancellable;
/**
* True if capturing locals
* Local variable capture behaviour
*/
protected final boolean captureLocals;
private final LocalCapture localCapture;
/**
* Make a new CallbackInjector with the supplied args
*
* @param info information about this injector
* @param cancellable True if injections performed by this injector should
* be cancellable
* @param captureLocals True to capture local variables from the frame at
* the target location
* @param localCapture Local variable capture behaviour
*/
public CallbackInjector(InjectionInfo info, boolean cancellable, boolean captureLocals) {
public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture) {
super(info);
this.cancellable = cancellable;
this.captureLocals = captureLocals;
this.localCapture = localCapture;
}
/* (non-Javadoc)
@@ -215,22 +264,13 @@ public class CallbackInjector extends Injector {
*/
@Override
protected void inject(Target target, AbstractInsnNode node) {
Type[] localTypes = null;
LocalVariableNode[] locals = null;
if (this.captureLocals) {
LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, target.method, node);
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 (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
locals = Locals.getLocalsAt(this.classNode, target.method, node);
}
this.inject(new Callback(target, node, localTypes));
this.inject(new Callback(target, node, locals, this.localCapture.isCaptureLocals()));
}
/**
@@ -239,18 +279,131 @@ public class CallbackInjector extends Injector {
* @param callback callback handle
*/
private void inject(final Callback callback) {
if (!callback.descriptor.equals(this.methodNode.desc)) {
throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: expected " + callback.descriptor
+ " found " + this.methodNode.desc);
if (this.localCapture.isPrintLocals()) {
this.printLocals(callback);
return;
}
// The actual callback method, to start with this is set to the handler
// method but we will redirect to our generated handler if the signature
// is invalid and we have to generate an error handler stub method
MethodNode callbackMethod = this.methodNode;
if (!callback.getDescriptor().equals(this.methodNode.desc)) {
if (callback.canCaptureLocals) {
// First check whether there is a compatible method in the class
// the method must have an identical name and an appropriate
// signature for the current locals. This allows silent failover
// if changes to the local variable table are EXPECTED for some
// reason.
MethodNode handler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (handler != null && ASMHelper.getVisibleAnnotation(handler, Surrogate.class) != null) {
// Found a matching method, use it
callbackMethod = handler;
} else {
// No matching method, generate a message to bitch about it
String message = this.generateBadLVTMessage(callback);
switch (this.localCapture) {
case CAPTURE_FAILEXCEPTION:
this.logger.error("Injection error: {}", message);
callbackMethod = this.generateErrorMethod(callback, "org/spongepowered/asm/mixin/injection/InjectionError", message);
break;
case CAPTURE_FAILSOFT:
this.logger.warn("Injection warning: {}", message);
return;
default:
this.logger.error("Critical injection failure: {}", message);
throw new InjectionError(message);
}
}
} else {
throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: expected " + callback.getDescriptor()
+ " but found " + this.methodNode.desc);
}
}
this.createCallbackInfo(callback);
this.invokeCallback(callback);
this.invokeCallback(callback, callbackMethod);
this.injectCancellationCode(callback);
callback.inject();
}
/**
* Generate the "bad local variable table" message
*
* @param callback callback handle
* @return generated message
*/
private String generateBadLVTMessage(final Callback callback) {
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
List<String> found = CallbackInjector.summariseLocals(callback.localTypes, callback.frameSize);
String message = String.format("Local variable table in %s::%s has incompatible changes. Expected %s but found %s. Callback %s%s",
this.classNode.name.replace('/', '.'), callback.target.method.name, expected, found, this.methodNode.name, this.methodNode.desc);
return message;
}
/**
* Generates a method which throws an error
*
* @param callback callback handle
* @param errorClass error class to throw
* @param message message for the error
* @return generated method
*/
private MethodNode generateErrorMethod(Callback callback, String errorClass, String message) {
MethodNode method = this.info.addMethod(this.methodNode.access, this.methodNode.name + "$missing", callback.getDescriptor());
method.maxLocals = ASMHelper.getFirstNonArgLocalIndex(Type.getArgumentTypes(callback.getDescriptor()), !this.isStatic);
method.maxStack = 3;
InsnList insns = method.instructions;
insns.add(new TypeInsnNode(Opcodes.NEW, errorClass));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new LdcInsnNode(message));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, "<init>", "(Ljava/lang/String;)V", false));
insns.add(new InsnNode(Opcodes.ATHROW));
return method;
}
/**
* Pretty-print local variable information to stderr
*
* @param callback callback handle
*/
private void printLocals(final Callback callback) {
Type[] args = Type.getArgumentTypes(callback.descl);
SignaturePrinter methodSig = new SignaturePrinter(callback.target.method, callback.argNames);
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, callback.target.returnType, args, callback.argNames);
handlerSig.setModifiers(this.methodNode);
PrettyPrinter printer = new PrettyPrinter();
printer.add("%20s : %s", "Target Class", this.classNode.name.replace('/', '.'));
printer.add("%20s : %s", "Target Method", methodSig);
printer.add("%20s : %d", "Target Max LOCALS", callback.target.maxLocals);
printer.add("%20s : %d", "Initial Frame Size", callback.frameSize);
printer.add("%20s : %s", "Callback Name", this.methodNode.name);
printer.add("%20s : %s %s", "Instruction", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode()));
printer.hr();
if (callback.locals.length > callback.frameSize) {
printer.add(" LOCAL TYPE NAME");
for (int l = 0; l < callback.locals.length; l++) {
String marker = l == callback.frameSize ? ">" : " ";
if (callback.locals[l] != null) {
printer.add("%s [%3d] %20s %-50s %s", marker, l, SignaturePrinter.getTypeName(callback.localTypes[l], false),
callback.locals[l].name, l >= callback.frameSize ? "<capture>" : "");
} else {
boolean isTop = l > 0 && callback.localTypes[l - 1] != null && callback.localTypes[l - 1].getSize() > 1;
printer.add("%s [%3d] %20s", marker, l, isTop ? "<top>" : "-");
}
}
printer.hr();
}
printer.add().add("/**").add(" * Expected callback signature").add(" * /");
printer.add("%s {", handlerSig);
printer.add(" // Method body").add("}").add().print(System.err);
}
/**
* @param callback callback handle
*/
@@ -301,7 +454,7 @@ public class CallbackInjector extends Injector {
/**
* @param callback callback handle
*/
private void invokeCallback(final Callback callback) {
private void invokeCallback(final Callback callback, final MethodNode callbackMethod) {
// Push "this" onto the stack if the callback is not static
if (!this.isStatic) {
callback.add(new VarInsnNode(Opcodes.ALOAD, 0));
@@ -315,11 +468,11 @@ public class CallbackInjector extends Injector {
// (Maybe) push the locals onto the stack
if (callback.canCaptureLocals) {
Locals.loadLocals(callback.locals, callback, callback.frameSize);
Locals.loadLocals(callback.localTypes, callback, callback.frameSize);
}
// Call the callback!
this.invokeHandler(callback);
this.invokeMethod(callback, callbackMethod);
}
/**
@@ -377,4 +530,20 @@ public class CallbackInjector extends Injector {
protected boolean isStatic() {
return this.isStatic;
}
private static List<String> summariseLocals(String desc, int pos) {
return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos);
}
private static List<String> summariseLocals(Type[] locals, int pos) {
List<String> list = new ArrayList<String>();
if (locals != null) {
for (; pos < locals.length; pos++) {
if (locals[pos] != null) {
list.add(locals[pos].toString());
}
}
}
return list;
}
}
@@ -0,0 +1,92 @@
/*
* 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.callback;
/**
* Specifies the behaviour for capturing local variables at an injection point.
*
* <p>Since local capture relies on calculating the local variable table for the
* target method it is disabled by default for performance reasons. When
* capturing is enabled, local variables are passed to the handler method after
* the {@link CallbackInfo} argument. Since it is entirely possible for another
* transformer to make an incompatible change to the the local variable table at
* run time, the purpose of this enum is to specify the behaviour for local
* capture and the type of recovery to be performed when an incompatible change
* is detected.</p>
*/
public enum LocalCapture {
/**
* Do not capture locals, this is the default behaviour
*/
NO_CAPTURE(false, false),
/**
* Do not capture locals. Print the expected method signature to stderr
* instead.
*/
PRINT(false, true),
/**
* Capture locals. If the calculated locals are different from the expected
* values, log a warning and skip this injection.
*/
CAPTURE_FAILSOFT,
/**
* Capture locals. If the calculated locals are different from the expected
* values, throw an {@link Error}.
*/
CAPTURE_FAILHARD,
/**
* Capture locals. If the calculated locals are different from the expected
* values, generate a method stub containing an exception. This will allow
* normal execution to continue unless the callback is encountered.
*/
CAPTURE_FAILEXCEPTION;
private final boolean captureLocals;
private final boolean printLocals;
private LocalCapture() {
this(true, false);
}
private LocalCapture(boolean captureLocals, boolean printLocals) {
this.captureLocals = captureLocals;
this.printLocals = printLocals;
}
boolean isCaptureLocals() {
return this.captureLocals;
}
boolean isPrintLocals() {
return this.printLocals;
}
}
@@ -148,9 +148,13 @@ public abstract class Injector {
* @param insns Instruction list to inject into
*/
protected void invokeHandler(InsnList insns) {
boolean isPrivate = (this.methodNode.access & Opcodes.ACC_PRIVATE) != 0;
this.invokeMethod(insns, this.methodNode);
}
protected void invokeMethod(InsnList insns, MethodNode methodNode) {
boolean isPrivate = (methodNode.access & Opcodes.ACC_PRIVATE) != 0;
int invokeOpcode = this.isStatic ? Opcodes.INVOKESTATIC : isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL;
insns.add(new MethodInsnNode(invokeOpcode, this.classNode.name, this.methodNode.name, this.methodNode.desc, false));
insns.add(new MethodInsnNode(invokeOpcode, this.classNode.name, methodNode.name, methodNode.desc, false));
}
protected static String printArgs(Type[] args) {
@@ -27,6 +27,7 @@ package org.spongepowered.asm.mixin.injection.struct;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
@@ -40,8 +41,8 @@ public class CallbackInjectionInfo extends InjectionInfo {
@Override
protected Injector initInjector(AnnotationNode injectAnnotation) {
boolean cancellable = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "cancellable", false);
boolean captureLocals = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "captureLocals", false);
LocalCapture locals = ASMHelper.<LocalCapture>getAnnotationValue(injectAnnotation, "locals", LocalCapture.class, LocalCapture.NO_CAPTURE);
return new CallbackInjector(this, cancellable, captureLocals);
return new CallbackInjector(this, cancellable, locals);
}
}
@@ -30,6 +30,7 @@ import java.util.Collection;
import java.util.Deque;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
@@ -90,6 +91,11 @@ public abstract class InjectionInfo {
*/
protected Injector injector;
/**
* Methods injected by injectors
*/
private final List<MethodNode> injectedMethods = new ArrayList<MethodNode>(0);
/**
* ctor
*
@@ -179,6 +185,15 @@ public abstract class InjectionInfo {
}
}
/**
* Perform cleanup and post-injection tasks
*/
public void postInject() {
for (MethodNode method : this.injectedMethods) {
this.classNode.methods.add(method);
}
}
/**
* Get the mixin target context for this injection
*
@@ -224,6 +239,21 @@ public abstract class InjectionInfo {
return this.targets;
}
/**
* Inject a method into the target class
*
* @param access
* @param name
* @param desc
*
* @return new method
*/
public MethodNode addMethod(int access, String name, String desc) {
MethodNode method = new MethodNode(Opcodes.ASM5, access | Opcodes.ACC_SYNTHETIC, name, desc, null, null);
this.injectedMethods.add(method);
return method;
}
/**
* Finds methods in the target class which match searchFor
*
@@ -118,7 +118,7 @@ public class Target {
* @return generated descriptor
*/
public String getCallbackDescriptor(final boolean captureLocals, final Type[] locals, Type[] argumentTypes, int startIndex) {
if (!captureLocals) {
if (!captureLocals || locals == null) {
return this.callbackDescriptor;
}
@@ -916,6 +916,8 @@ public class MixinTransformer extends TreeTransformer {
* @param mixin
*/
private void applyInjections(ClassNode targetClass, MixinTargetContext mixin) {
List<InjectionInfo> injected = new ArrayList<InjectionInfo>();
for (MethodNode method : targetClass.methods) {
InjectionInfo injectInfo = InjectionInfo.parse(mixin, method);
if (injectInfo == null) {
@@ -924,10 +926,15 @@ public class MixinTransformer extends TreeTransformer {
if (injectInfo.isValid()) {
injectInfo.inject();
injected.add(injectInfo);
}
method.visibleAnnotations.remove(injectInfo.getAnnotation());
}
for (InjectionInfo injectInfo : injected) {
injectInfo.postInject();
}
}
/**
@@ -425,7 +425,7 @@ public class ASMHelper {
}
}
return String.valueOf(opcode);
return opcode >= 0 ? String.valueOf(opcode) : "";
}
/**
@@ -119,10 +119,17 @@ public class Locals {
*/
public static LocalVariableNode[] getLocalsAt(ClassNode classNode, MethodNode method, AbstractInsnNode node) {
LocalVariableNode[] frame = new LocalVariableNode[method.maxLocals];
int local = 0, index = 0;
// 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);
frame[local++] = new LocalVariableNode("this", classNode.name, null, null, null, 0);
}
// Initialise method arguments
for (Type argType : Type.getArgumentTypes(method.desc)) {
frame[local] = new LocalVariableNode("arg" + index++, argType.toString(), null, null, null, local);
local += argType.getSize();
}
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
@@ -0,0 +1,109 @@
/*
* 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.util;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
/**
* Prints information in a pretty box
*/
public class PrettyPrinter {
/**
* "Horizontal rule" marker
*/
private static final String HR = "---";
/**
* Box with (adapts to contents)
*/
private int width = 100;
/**
* Content lines
*/
private final List<String> lines = new ArrayList<String>();
/**
* Adds a blank line to the output
*
* @return fluent interface
*/
public PrettyPrinter add() {
this.lines.add("");
return this;
}
/**
* Adds a formatted line to the output
*
* @param format format string
* @param args arguments
*
* @return fluent interface
*/
public PrettyPrinter add(String format, Object... args) {
String line = String.format(format, args);
this.lines.add(line);
this.width = Math.max(this.width, line.length());
return this;
}
/**
* Adds a horizontal rule to the output
*
* @return fluent interface
*/
public PrettyPrinter hr() {
this.lines.add(PrettyPrinter.HR);
return this;
}
/**
* Print this printer to the specified output
*
* @param stream stream to print to
*/
public void print(PrintStream stream) {
this.printHr(stream);
for (String line : this.lines) {
if (line == PrettyPrinter.HR) {
this.printHr(stream);
} else {
stream.printf("/* %-" + this.width + "s */\n", line);
}
}
this.printHr(stream);
}
private void printHr(PrintStream stream) {
stream.printf("/*%s*/\n", Strings.repeat("*", this.width + 2));
}
}
@@ -0,0 +1,195 @@
/*
* 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.util;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.base.Strings;
/**
* Generates callback signature for callback pretty-print
*/
public class SignaturePrinter {
/**
* Method name
*/
private final String name;
/**
* The return type of the <b>target</b> method (used to fill in the generic
* bound on a CallbackInfoReturnable.
*/
private final Type returnType;
/**
* Argument type array (sparse, with no TOP entries)
*/
private final Type[] argTypes;
/**
* Argument names
*/
private final String[] argNames;
/**
* Method prefix
*/
private String modifiers = "private void";
public SignaturePrinter(MethodNode method) {
this(method.name, Type.VOID_TYPE, Type.getArgumentTypes(method.desc));
this.setModifiers(method);
}
public SignaturePrinter(MethodNode method, String[] argNames) {
this(method.name, Type.VOID_TYPE, Type.getArgumentTypes(method.desc), argNames);
this.setModifiers(method);
}
public SignaturePrinter(String name, String desc) {
this(name, Type.getReturnType(desc), Type.getArgumentTypes(desc));
}
public SignaturePrinter(String name, Type returnType, Type[] args) {
this.name = name;
this.returnType = returnType;
this.argTypes = new Type[args.length];
this.argNames = new String[args.length];
for (int l = 0, v = 0; l < args.length; l++) {
if (args[l] != null) {
this.argTypes[l] = args[l];
this.argNames[l] = "var" + v++;
}
}
}
public SignaturePrinter(String name, Type returnType, LocalVariableNode[] args) {
this.name = name;
this.returnType = returnType;
this.argTypes = new Type[args.length];
this.argNames = new String[args.length];
for (int l = 0; l < args.length; l++) {
if (args[l] != null) {
this.argTypes[l] = Type.getType(args[l].desc);
this.argNames[l] = args[l].name;
}
}
}
public SignaturePrinter(String name, Type returnType, Type[] argTypes, String[] argNames) {
this.name = name;
this.returnType = returnType;
this.argTypes = argTypes;
this.argNames = argNames;
}
public void setModifiers(MethodNode method) {
String returnType = SignaturePrinter.getTypeName(Type.getReturnType(method.desc), false);
if ((method.access & Opcodes.ACC_PUBLIC) != 0) {
this.setModifiers("public " + returnType);
} else if ((method.access & Opcodes.ACC_PROTECTED) != 0) {
this.setModifiers("protected " + returnType);
} else if ((method.access & Opcodes.ACC_PRIVATE) != 0) {
this.setModifiers("private " + returnType);
} else {
this.setModifiers(returnType);
}
}
public void setModifiers(String modifiers) {
this.modifiers = modifiers;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.modifiers).append(" ").append(this.name).append('(');
for (int var = 0; var < this.argTypes.length; var++) {
if (this.argTypes[var] == null) {
continue;
} else if (var > 0) {
sb.append(", ");
}
String name = Strings.isNullOrEmpty(this.argNames[var]) ? "unnamed" + var : this.argNames[var];
this.appendType(sb, this.argTypes[var], name);
}
sb.append(")");
return sb.toString();
}
private StringBuilder appendType(StringBuilder sb, Type type, String name) {
switch (type.getSort()) {
case Type.ARRAY:
return this.appendType(sb, type.getElementType(), name).append("[]");
case Type.OBJECT:
return this.appendType(sb, type.getClassName(), name);
default:
return sb.append(SignaturePrinter.getTypeName(type, false)).append(' ').append(name);
}
}
private StringBuilder appendType(StringBuilder sb, String typeName, String name) {
typeName = typeName.substring(typeName.lastIndexOf('.') + 1);
sb.append(typeName);
if (typeName.endsWith("CallbackInfoReturnable")) {
sb.append('<').append(SignaturePrinter.getTypeName(this.returnType, true)).append('>');
}
return sb.append(' ').append(name);
}
/**
* Get the source code name for the specified type
*
* @param type Type to generate a friendly name for
* @param box True to return the equivalent boxing type for primitives
* @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, boolean box) {
switch (type.getSort()) {
case Type.VOID: return box ? "Void" : "void";
case Type.BOOLEAN: return box ? "Boolean" : "boolean";
case Type.CHAR: return box ? "Character" : "char";
case Type.BYTE: return box ? "Byte" : "byte";
case Type.SHORT: return box ? "Short" : "short";
case Type.INT: return box ? "Integer" : "int";
case Type.FLOAT: return box ? "Float" : "float";
case Type.LONG: return box ? "Long" : "long";
case Type.DOUBLE: return box ? "Double" : "double";
case Type.ARRAY: return SignaturePrinter.getTypeName(type.getElementType(), box) + "[]";
case Type.OBJECT:
String typeName = type.getClassName();
typeName = typeName.substring(typeName.lastIndexOf('.') + 1);
return typeName;
default:
return "Object";
}
}
}