From fc1742a54ef5f7a825cf68d5f17f75db270576fe Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Wed, 24 Dec 2014 15:59:48 +0000
Subject: [PATCH] Fixing code style from LiteLoader, fix checkstyle, complete
javadoc
---
checkstyle.xml | 4 +
.../asm/mixin/MixinEnvironment.java | 1 -
.../spongepowered/asm/mixin/injection/At.java | 67 +-
.../asm/mixin/injection/Inject.java | 24 +-
.../asm/mixin/injection/InjectionPoint.java | 660 +++++++-------
.../injection/InvalidInjectionException.java | 2 +-
.../injection/callback/CallbackInfo.java | 152 ++--
.../callback/CallbackInfoReturnable.java | 162 ++--
.../injection/callback/CallbackInjector.java | 380 ++++----
.../mixin/injection/callback/Cancellable.java | 40 +-
.../callback/CancellationException.java | 48 +-
.../injection/callback/ReadOnlyInsnList.java | 247 ++++++
.../injection/points/BeforeFieldAccess.java | 79 +-
.../mixin/injection/points/BeforeInvoke.java | 308 +++----
.../asm/mixin/injection/points/BeforeNew.java | 135 +--
.../mixin/injection/points/BeforeReturn.java | 116 ++-
.../injection/points/BeforeStringInvoke.java | 172 ++--
.../mixin/injection/points/JumpInsnPoint.java | 122 ++-
.../mixin/injection/points/MethodHead.java | 60 +-
.../injection/{ => struct}/InjectionInfo.java | 15 +-
.../injection/struct/InjectionPointData.java | 17 +-
.../mixin/injection/struct/MemberInfo.java | 53 +-
.../injection/tree/ReadOnlyInsnList.java | 151 ----
.../mixin/transformer/MixinTransformer.java | 13 +-
.../org/spongepowered/asm/util/ASMHelper.java | 70 ++
.../asm/util/ByteCodeUtilities.java | 809 ------------------
.../org/spongepowered/asm/util/Locals.java | 318 +++++++
27 files changed, 2102 insertions(+), 2123 deletions(-)
create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java
rename src/main/java/org/spongepowered/asm/mixin/injection/{ => struct}/InjectionInfo.java (95%)
delete mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/tree/ReadOnlyInsnList.java
delete mode 100644 src/main/java/org/spongepowered/asm/util/ByteCodeUtilities.java
create mode 100644 src/main/java/org/spongepowered/asm/util/Locals.java
diff --git a/checkstyle.xml b/checkstyle.xml
index 3cdcd424..6ec3ec96 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -158,5 +158,9 @@
+
+
+
+
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index 4c6d5ac0..d2833874 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -67,7 +67,6 @@ public class MixinEnvironment {
/**
* Add a mixin configuration to the blackboard
- * @return
*/
public MixinEnvironment addConfiguration(String config) {
this.getMixinConfigs().add(config);
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java
index e7ccf466..60c10dc1 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java
@@ -1,4 +1,4 @@
-/**
+/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org
@@ -24,23 +24,78 @@
*/
package org.spongepowered.asm.mixin.injection;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Annotation for specifying the type of {@link InjectionPoint} to use to perform an {@link Inject} process. This annotation allows the
+ * {@link InjectionPoint} class to be specified, as well as arguments to be passed to the {@link InjectionPoint} instance to configure it. The data
+ * contained in the annotation are wrapped into a {@link org.spongepowered.asm.mixin.injection.struct.InjectionInfo InjectionInfo} object before
+ * being passed to the {@link InjectionPoint} for parsing. All values are optional apart from {@link #value}, which specifies the type of
+ * {@link InjectionPoint} to use. All other parameters depend on the InjectionPoint chosen, and the javadoc for each {@link InjectionPoint} class
+ * should be consulted for the meaning of the argument to that particular class. A general description of each parameter is provided below.
+ */
+@Retention(RetentionPolicy.RUNTIME)
public @interface At {
+ /**
+ * Shift is used to shift resulting opcodes
+ */
public enum Shift {
NONE,
BEFORE,
- AFTER
+ AFTER,
+ BY
}
+ /**
+ * Type of {@link InjectionPoint} to use. Can be a built-in class or the fully-qualified name of a custom class which extends
+ * {@link InjectionPoint}.
+ *
+ * Built-in types are {@link org.spongepowered.asm.mixin.injection.points.MethodHead HEAD},
+ * {@link org.spongepowered.asm.mixin.injection.points.BeforeReturn RETURN},
+ * {@link org.spongepowered.asm.mixin.injection.points.BeforeInvoke INVOKE},
+ * {@link org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess FIELD},
+ * {@link org.spongepowered.asm.mixin.injection.points.BeforeNew NEW},
+ * {@link org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke INVOKE_STRING} and
+ * {@link org.spongepowered.asm.mixin.injection.points.JumpInsnPoint JUMP}. See the javadoc for each type for more details on the scheme used by
+ * each injection point.
+ */
public String value();
- public String[] args() default {};
-
- public String target() default "";
-
+ /**
+ * Shift type for returned opcodes. For example use {@link At.Shift#AFTER AFTER} with an INVOKE InjectionPoint to move the returned opcodes to
+ * after the invoation. Use {@link At.Shift#BY BY} in conjunction with the {@link #by} parameter to shift by an arbitrary number of
+ * opcodes.
+ */
public Shift shift() default Shift.NONE;
+ /**
+ * If {@link #shift} is specified as {@link At.Shift#BY BY}, specifies the number of opcodes to shift by (negative numbers are allowed).
+ */
+ public int by() default 0;
+
+ /**
+ * The named arguments list is used to expand the scope of the annotation beyond the fixed values below in order to accommodate the
+ * needs of custom injection point classes.
+ */
+ public String[] args() default { };
+
+ /**
+ * Target member used by INVOKE, INVOKE_STRING and FIELD
+ */
+ public String target() default "";
+
+ /**
+ * Ordinal offset. Many InjectionPoints will return every opcode matching their criteria, specifying ordinal allows a particular opcode
+ * to be identified from the returned list. The default value of -1 does not alter the behaviour and returns all matching opcodes. Specifying a
+ * value of 0 or higher returns only the requested opcode (if one exists: for example specifying an ordinal of 4 when only 2 opcodes are
+ * matched by the InjectionPoint is not going to work particularly well!)
+ */
public int ordinal() default -1;
+ /**
+ * Target opcode for FIELD and JUMP InjectionPoints. See the javadoc for the relevant injection point for more details.
+ */
public int opcode() default -1;
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java
index 21d4e3cc..7c5b2ed3 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java
@@ -1,4 +1,4 @@
-/**
+/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org
@@ -29,15 +29,33 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+/**
+ * Specifies that this mixin method should inject a callback (or callbacks) to itself in the target method(s) identified by {@link #method}.
+ */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
+ /**
+ * String representation of a {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} which identifies the target method.
+ */
public String method();
+ /**
+ * Array of {@link At} annotations which describe the {@link InjectionPoint}s in the target method. Allows one or more callbacks to be injected in
+ * the target method
+ */
+ public At[] at();
+
+ /**
+ * Setting an injected callback to cancellable 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.
+ */
public boolean cancellable() default false;
+ /**
+ * Set to true to allow local variables to be captured from the target method as well as method parameters.
+ */
// public boolean captureLocals() default false;
-
- public At[] at();
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java
index 0456dd00..fa8f7c0d 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java
@@ -1,3 +1,27 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.reflect.Constructor;
@@ -24,385 +48,287 @@ 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.
+ * Base class for injection point discovery classes. Each subclass describes a strategy for locating code injection points within a method, with
+ * the {@link #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.
+ * This base class also contains composite strategy factory methods such as {@link #and} and {@link #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
+ * 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 {@link #find}
+ * method, as each call to {@link #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.
*/
-public abstract class InjectionPoint
-{
- /**
- * Capture locals as well as args
- */
- protected boolean captureLocals;
-
- protected boolean logLocals;
+public abstract class InjectionPoint {
- /**
- * 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 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;
-// }
+ /**
+ * 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
+ * the add() method
+ * @return true if one or more injection points were found
+ */
+ public abstract boolean find(String desc, InsnList insns, Collection nodes);
- @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 nodes) //, Event event)
- {
- boolean found = false;
-
- @SuppressWarnings("unchecked")
- ArrayList[] allNodes = new ArrayList[this.components.length];
-
- for (int i = 0; i < this.components.length; i++)
- {
- allNodes[i] = new ArrayList();
- this.components[i].find(desc, insns, allNodes[i]); //, event);
- }
-
- ArrayList 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 nodes) //, Event event)
- {
- LinkedHashSet allNodes = new LinkedHashSet();
-
- 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 nodes) //, Event event)
- {
- List list = (nodes instanceof List) ? (List)nodes : new ArrayList(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());
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "InjectionPoint(" + this.getClass().getSimpleName() + ")";
}
-
- public static InjectionPoint parse(AnnotationNode node)
- {
+
+ /**
+ * Composite injection point
+ */
+ abstract static 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;
+ }
+
+ /* (non-Javadoc)
+ * @see org.spongepowered.asm.mixin.injection.InjectionPoint#toString()
+ */
+ @Override
+ public String toString() {
+ return "CompositeInjectionPoint(" + this.getClass().getSimpleName() + ")[" + Joiner.on(',').join(this.components) + "]";
+ }
+ }
+
+ /**
+ * Intersection of several injection points, returns common nodes that appear in all children
+ */
+ static final class Intersection extends InjectionPoint.CompositeInjectionPoint {
+
+ public Intersection(InjectionPoint... points) {
+ super(points);
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ boolean found = false;
+
+ @SuppressWarnings("unchecked") ArrayList[] allNodes = new ArrayList[this.components.length];
+
+ for (int i = 0; i < this.components.length; i++) {
+ allNodes[i] = new ArrayList();
+ this.components[i].find(desc, insns, allNodes[i]);
+ }
+
+ ArrayList 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;
+ }
+ }
+
+ /**
+ * Union of several injection points, returns all insns returned from all injections
+ */
+ static final class Union extends InjectionPoint.CompositeInjectionPoint {
+
+ public Union(InjectionPoint... points) {
+ super(points);
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ LinkedHashSet allNodes = new LinkedHashSet();
+
+ for (int i = 0; i < this.components.length; i++) {
+ this.components[i].find(desc, insns, allNodes);
+ }
+
+ nodes.addAll(allNodes);
+
+ return allNodes.size() > 0;
+ }
+ }
+
+ /**
+ * Shift injection point, takes an input injection point and shifts all returned nodes by a fixed amount
+ */
+ 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;
+ }
+
+ /* (non-Javadoc)
+ * @see org.spongepowered.asm.mixin.injection.InjectionPoint#toString()
+ */
+ @Override
+ public String toString() {
+ return "InjectionPoint(" + this.getClass().getSimpleName() + ")[" + this.input + "]";
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ List list = (nodes instanceof List) ? (List) nodes : new ArrayList(nodes);
+
+ this.input.find(desc, insns, nodes);
+
+ 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 injection points to perform intersection
+ */
+ 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 injection points to perform union
+ */
+ 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 injection points to perform shift
+ */
+ 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 injection points to perform shift
+ */
+ 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 injection points to perform shift
+ */
+ public static InjectionPoint shift(InjectionPoint point, int count) {
+ return new InjectionPoint.Shift(point, count);
+ }
+
+ /**
+ * Parse an InjectionPoint from the supplied {@link At} annotation
+ */
+ public static InjectionPoint parse(At at) {
+ return InjectionPoint.parse(at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
+ }
+
+ /**
+ * Parse an InjectionPoint from the supplied {@link At} annotation supplied as an AnnotationNode instance
+ */
+ public static InjectionPoint parse(AnnotationNode node) {
String at = ASMHelper.getAnnotationValue(node, "value");
List args = ASMHelper.>getAnnotationValue(node, "args");
String target = ASMHelper.getAnnotationValue(node, "target", "");
At.Shift shift = ASMHelper.getAnnotationValue(node, "shift", At.Shift.NONE);
+ int by = ASMHelper.getAnnotationValue(node, "by", Integer.valueOf(0));
int ordinal = ASMHelper.getAnnotationValue(node, "ordinal", Integer.valueOf(-1));
int opcode = ASMHelper.getAnnotationValue(node, "opcode", Integer.valueOf(0));
-
- if (args == null) args = ImmutableList.of();
-
- return InjectionPoint.parse(at, shift, args, target, ordinal, opcode);
- }
-
- public static InjectionPoint parse(String at, At.Shift shift, List 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;
+ if (args == null) {
+ args = ImmutableList.of();
+ }
+
+ return InjectionPoint.parse(at, shift, by, args, target, ordinal, opcode);
+ }
+
+ /**
+ * Parse and instantiate an InjectionPoint from the supplied information. Returns null if an InjectionPoint could not be created.
+ */
+ public static InjectionPoint parse(String at, At.Shift shift, int by, List args, String target, int ordinal, int opcode) {
+ InjectionPointData data = new InjectionPointData(args, target, ordinal, opcode);
+ InjectionPoint point = null;
+
+ if (BeforeFieldAccess.CODE.equals(at)) {
+ point = new BeforeFieldAccess(data);
+ } else if (BeforeInvoke.CODE.equals(at)) {
+ point = new BeforeInvoke(data);
+ } else if (BeforeNew.CODE.equals(at)) {
+ point = new BeforeNew(data);
+ } else if (BeforeReturn.CODE.equals(at)) {
+ point = new BeforeReturn(data);
+ } else if (BeforeStringInvoke.CODE.equals(at)) {
+ point = new BeforeStringInvoke(data);
+ } else if (JumpInsnPoint.CODE.equals(at)) {
+ point = new JumpInsnPoint(data);
+ } else if (MethodHead.CODE.equals(at)) {
+ point = 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);
+ point = ctor.newInstance(data);
+ } catch (Exception ex) {
+ throw new InvalidInjectionException("The specified class " + at + " could not be instanced or is not a valid InjectionPoint", ex);
+ }
+ } else {
+ throw new InvalidInjectionException(at + " is not a valid injection point specifier");
+ }
+
+ if (point != null) {
+ if (shift == At.Shift.BEFORE) {
+ return InjectionPoint.before(point);
+ } else if (shift == At.Shift.AFTER) {
+ return InjectionPoint.after(point);
+ } else if (shift == At.Shift.BY) {
+ return InjectionPoint.shift(point, by);
+ }
+ }
+
+ return point;
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java
index 88910518..985fe21f 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/InvalidInjectionException.java
@@ -1,4 +1,4 @@
-/**
+/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java
index 6a3befd1..26d6466a 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java
@@ -1,135 +1,137 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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;
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 Source object type. For non-static methods this will be the containing object instance.
+ * CallbackInfo instances are passed to callbacks in order to provide information and handling opportunities to the callback to interact with the
+ * callback itself. For example by allowing the callback to be "cancelled" and return from a method prematurely.
*/
-public class CallbackInfo implements Cancellable
-{
+public class CallbackInfo implements Cancellable {
+
protected static final String STRING = "Ljava/lang/String;";
protected static final String OBJECT = "Ljava/lang/Object;";
+ /**
+ * Method name being injected into, this is useful if a single callback is injecting into multiple methods
+ */
private final String name;
-
-// private final S source;
-
+
+ /**
+ * True if this callback is cancellable
+ */
private final boolean cancellable;
+ /**
+ * True if this callback has been cancelled
+ */
private boolean cancelled;
- public CallbackInfo(String name, /*S source,*/ boolean cancellable)
- {
+ /**
+ * This ctor is always called by injected code
+ */
+ public CallbackInfo(String name, boolean cancellable) {
this.name = name;
-// this.source = source;
this.cancellable = cancellable;
}
-
-// public S getSource()
-// {
-// return this.source;
-// }
-
- public String getName()
- {
+
+ /**
+ * Get the method name where this callback originated
+ */
+ 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()
+ * @see java.lang.Object#toString()
*/
@Override
- public final boolean isCancellable()
- {
+ public String toString() {
+ return String.format("CallbackInfo[TYPE=%s,NAME=%s,CANCELLABLE=%s]", this.getClass().getSimpleName(), this.name, this.cancellable);
+ }
+
+ /* (non-Javadoc)
+ * @see org.spongepowered.asm.mixin.injection.callback.Cancellable#isCancellable()
+ */
+ @Override
+ public final boolean isCancellable() {
return this.cancellable;
}
/* (non-Javadoc)
- * @see com.mumfrey.liteloader.transformers.event.Cancellable#isCancelled()
+ * @see org.spongepowered.asm.mixin.injection.callback.Cancellable#isCancelled()
*/
@Override
- public final boolean isCancelled()
- {
+ public final boolean isCancelled() {
return this.cancelled;
}
-
+
/* (non-Javadoc)
- * @see com.mumfrey.liteloader.transformers.event.Cancellable#cancel()
+ * @see org.spongepowered.asm.mixin.injection.callback.Cancellable#cancel()
*/
@Override
- public void cancel() throws CancellationException
- {
- if (!this.cancellable)
- {
+ public void cancel() throws CancellationException {
+ if (!this.cancellable) {
throw new CancellationException(String.format("The call %s is not cancellable.", this.name));
}
-
+
this.cancelled = true;
}
+
+ // Methods below this point used by the CallbackInjector
- protected static String getCallInfoClassName()
- {
+ static String getCallInfoClassName() {
return CallbackInfo.class.getName();
}
-
- /**
- * @param returnType
- */
- protected static String getCallInfoClassName(Type returnType)
- {
+
+ 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))
- {
+ static String getConstructorDescriptor(Type returnType) {
+ if (returnType.equals(Type.VOID_TYPE)) {
return CallbackInfo.getConstructorDescriptor();
}
-
- if (returnType.getSort() == Type.OBJECT)
- {
+
+ 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()
- {
+ static String getConstructorDescriptor() {
return String.format("(%sZ)V", CallbackInfo.STRING);
}
- public static String getIsCancelledMethodName()
- {
+ static String getIsCancelledMethodName() {
return "isCancelled";
}
- public static String getIsCancelledMethodSig()
- {
+ static String getIsCancelledMethodSig() {
return "()Z";
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java
index 5b6376fe..b7f1b4f1 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java
@@ -1,137 +1,139 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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;
import org.objectweb.asm.Type;
-//import com.mumfrey.liteloader.core.event.EventCancellationException;
-
/**
- * EventInfo for events which have a return type
+ * For callbacks with a non-void return type, a CallbackInfoReturnable is passed to the callback instead to allow the callback to interact with the
+ * method return value.
*
- * @author Adam Mummery-Smith
- *
- * @param Source object type. For non-static methods this will be the containing object instance.
* @param Return type
*/
-public class CallbackInfoReturnable extends CallbackInfo
-{
+public class CallbackInfoReturnable extends CallbackInfo {
+
private R returnValue;
-
- public CallbackInfoReturnable(String name, boolean cancellable)
- {
+
+ public CallbackInfoReturnable(String name, boolean cancellable) {
super(name, cancellable);
this.returnValue = null;
}
-
- public CallbackInfoReturnable(String name, boolean cancellable, R returnValue)
- {
+
+ public CallbackInfoReturnable(String name, boolean cancellable, R returnValue) {
super(name, cancellable);
this.returnValue = returnValue;
}
-
+
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, byte returnValue)
- {
+ 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);
+ this.returnValue = (R) Byte.valueOf(returnValue);
}
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, double returnValue)
- {
+ public CallbackInfoReturnable(String name, boolean cancellable, char returnValue) {
super(name, cancellable);
- this.returnValue = (R)Double.valueOf(returnValue);
+ this.returnValue = (R) Character.valueOf(returnValue);
}
-
+
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, float returnValue)
- {
+ public CallbackInfoReturnable(String name, boolean cancellable, double returnValue) {
super(name, cancellable);
- this.returnValue = (R)Float.valueOf(returnValue);
+ this.returnValue = (R) Double.valueOf(returnValue);
}
-
+
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, int returnValue)
- {
+ public CallbackInfoReturnable(String name, boolean cancellable, float returnValue) {
super(name, cancellable);
- this.returnValue = (R)Integer.valueOf(returnValue);
+ this.returnValue = (R) Float.valueOf(returnValue);
}
-
+
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, long returnValue)
- {
+ public CallbackInfoReturnable(String name, boolean cancellable, int returnValue) {
super(name, cancellable);
- this.returnValue = (R)Long.valueOf(returnValue);
+ this.returnValue = (R) Integer.valueOf(returnValue);
}
-
+
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, short returnValue)
- {
+ public CallbackInfoReturnable(String name, boolean cancellable, long returnValue) {
super(name, cancellable);
- this.returnValue = (R)Short.valueOf(returnValue);
+ this.returnValue = (R) Long.valueOf(returnValue);
}
-
+
@SuppressWarnings("unchecked")
- public CallbackInfoReturnable(String name, boolean cancellable, boolean returnValue)
- {
+ public CallbackInfoReturnable(String name, boolean cancellable, short returnValue) {
super(name, cancellable);
- this.returnValue = (R)Boolean.valueOf(returnValue);
+ 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)
+ * Sets a return value for this callback and cancels the callback (required in order to return the new value)
*
* @param returnValue
*/
- public void setReturnValue(R returnValue) throws CancellationException
- {
+ public void setReturnValue(R returnValue) throws CancellationException {
super.cancel();
-
+
this.returnValue = returnValue;
- }
-
- public R getReturnValue()
- {
+ }
+
+ 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)
- {
+ // All of the accessors below are to avoid having to generate unboxing conversions in bytecode
+ // CHECKSTYLE:OFF
+ 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; }
+ // CHECKSTYLE:ON
+
+ 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)
- {
+ static String getReturnDescriptor(Type returnType) {
+ if (returnType.getSort() == Type.OBJECT) {
return String.format("()%s", CallbackInfo.OBJECT);
}
-
+
return String.format("()%s", returnType.getDescriptor());
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
index dff52f6e..c5ef2d0d 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
@@ -1,7 +1,27 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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;
import java.util.ArrayList;
@@ -13,111 +33,152 @@ 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.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.util.ASMHelper;
-import org.spongepowered.asm.util.ByteCodeUtilities;
-
+import org.spongepowered.asm.util.Locals;
+/**
+ * This class is responsible for generating the bytecode for injected callbacks
+ */
public class CallbackInjector {
-
+
private static final String CTOR = "";
- class Target
- {
+ /**
+ * Information about the current injection target, mainly just convenience rather than passing a bunch of values around
+ */
+ class Target {
+
+ /**
+ * Target method
+ */
final MethodNode method;
+
+ /**
+ * Method arguments
+ */
+ final Type[] arguments;
+
+ /**
+ * Return type computed from the method descriptor
+ */
final Type returnType;
+
+ /**
+ * Method's (original) MAXS
+ */
+ // CHECKSTYLE:OFF
final int MAXS;
-
+ // CHECKSTYLE:ON
+
+ /**
+ * Callback method descriptor based on this target
+ */
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);
+ /**
+ * Callback info class
+ */
+ final String callbackInfoClass;
+
+ /**
+ * Make a new Target for the supplied method
+ */
+ Target(MethodNode method) {
+ this.method = method;
+ this.arguments = Type.getArgumentTypes(method.desc);
+
+ this.returnType = Type.getReturnType(method.desc);
+ this.MAXS = method.maxStack;
+ this.callbackInfoClass = CallbackInfo.getCallInfoClassName(this.returnType);
+ this.callbackDescriptor = String.format("(%sL%s;)V", method.desc.substring(1, method.desc.indexOf(')')), this.callbackInfoClass);
}
- 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();
+ /**
+ * Get the callback descriptor
+ */
+ 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";
}
}
+ /**
+ * True if the callback method is static
+ */
private final boolean isStatic;
- private final ClassNode classNode;
- private final MethodNode methodNode;
- private final boolean cancellable;
- private final boolean captureLocals;
- public CallbackInjector(InjectionInfo info)
- {
+ /**
+ * Class node
+ */
+ private final ClassNode classNode;
+
+ /**
+ * Callback method
+ */
+ private final MethodNode methodNode;
+
+ /**
+ * True if cancellable
+ */
+ private final boolean cancellable;
+
+ /**
+ * True if capturing locals
+ */
+ private final boolean captureLocals;
+
+ /**
+ * Make a new CallbackInjector for the supplied InjectionInfo
+ */
+ 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;
+
+ /**
+ * Make a new CallbackInjector with the supplied args
+ */
+ 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);
+ this.isStatic = ASMHelper.methodIsStatic(methodNode);
}
-
- public void injectInto(MethodNode into, List injectionPoints)
- {
+
+ /**
+ * Inject into the specified method at the specified injection points
+ */
+ public void injectInto(MethodNode into, List injectionPoints) {
this.sanityCheck(into, injectionPoints);
-
- for (AbstractInsnNode targetNode : this.findTargetNodes(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)
- {
+
+ if (this.captureLocals) {
+ LocalVariableNode[] locals = Locals.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)
- {
+ 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);
@@ -127,121 +188,135 @@ public class CallbackInjector {
private Set findTargetNodes(MethodNode into, List injectionPoints) {
Set targetNodes = new HashSet();
-
+
// Defensive objects, so that injectionPoint instances can't modify our working copies
ReadOnlyInsnList insns = new ReadOnlyInsnList(into.instructions);
Collection nodes = new ArrayList(32);
- for (InjectionPoint injectionPoint : injectionPoints)
- {
+ for (InjectionPoint injectionPoint : injectionPoints) {
nodes.clear();
- if (injectionPoint.find(into.desc, insns, nodes))
- {
+ if (injectionPoint.find(into.desc, insns, nodes)) {
targetNodes.addAll(nodes);
}
}
+
+ insns.dispose();
return targetNodes;
}
- private void sanityCheck(MethodNode target, List injectionPoints)
- {
- if (ASMHelper.methodIsStatic(target) != this.isStatic)
- {
+ private void sanityCheck(MethodNode target, List 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");
+
+ 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);
+ /**
+ * Generate the actual bytecode
+ */
+ private void inject(Target target, final AbstractInsnNode targetNode, final Type[] locals) {
+ // Calculate the initial frame size based on the target method's arguments
+ int initialFrameSize = ASMHelper.getFirstNonArgLocalIndex(target.arguments, !this.isStatic);
+
+ // Work out whether we have enough info to capture locals in this scenario
boolean doCaptureLocals = this.captureLocals && locals != null && locals.length > initialFrameSize;
- String callbackDescriptor = target.getCallbackDescriptor(doCaptureLocals, locals, arguments, initialFrameSize);
- if (!callbackDescriptor.equals(this.methodNode.desc))
- {
+
+ // Determine the descriptor for the callback based on the target method and current context
+ String callbackDescriptor = target.getCallbackDescriptor(doCaptureLocals, locals, target.arguments, initialFrameSize);
+
+ // If it doesn't match, then cry
+ 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
+
+ // These two variables keep track of the (additional) stack size required for the two actions we're going to be injecting insns to perform,
+ // namely calling the CallbackInfo ctor, and then invoking the callback itself. When we get to the end of this injection we will then set
+ // the MAXS value on the target method to its original value plus the larger of the two values.
+ int ctorMAXS = 0;
+ int invokeMAXS = target.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, those being the current return
+ // value for value-return scenarios (we store the topmost stack entry and then push it into the ctor of the CallbackInfo) and also the
+ // CallbackInfo reference itself (we use the same local var for these two purposes because they don't exist at the same time).
int marshallVar = target.method.maxLocals++;
-
+
+ // Insns we will inject
InsnList insns = new InsnList();
-
+
+ // Assume (for now) that we won't push the return value into the CallbackInfo ctor
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)
- {
+
+ // 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));
}
-
+
+ // CHECKSTYLE:OFF
// Instance the EventInfo for this event
- insns.add(new TypeInsnNode(Opcodes.NEW, target.callInfoClass)); ctorMAXS++;
+ insns.add(new TypeInsnNode(Opcodes.NEW, target.callbackInfoClass)); ctorMAXS++;
insns.add(new InsnNode(Opcodes.DUP)); ctorMAXS++; invokeMAXS++;
+ // CHECKSTYLE:ON
ctorMAXS += this.invokeCallbackInfoCtor(target, insns, this.cancellable, pushReturnValue, marshallVar);
insns.add(new VarInsnNode(Opcodes.ASTORE, marshallVar));
-
- if (!this.isStatic)
- {
+
+ // Push "this" onto the stack if the callback is not static
+ if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
+
+ // Push the target method's parameters onto the stack
+ ASMHelper.loadArgs(target.arguments, insns, this.isStatic ? 0 : 1);
- // Call the event handler method in the proxy
- ByteCodeUtilities.loadArgs(arguments, insns, this.isStatic ? 0 : 1);
+ // Push the callback info onto the stack
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)
- {
+ // (Maybe) push the locals onto the stack
+ if (doCaptureLocals) {
+ Locals.loadLocals(locals, insns, initialFrameSize);
+ }
+
+ // Call the callback!
+ 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)
- {
+ protected int invokeCallbackInfoCtor(Target target, InsnList insns, boolean cancellable, boolean pushReturnValue, int marshallVar) {
int ctorMAXS = 0;
-
+
+ // CHECKSTYLE:OFF
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)
- {
+ // CHECKSTYLE:ON
+
+ 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));
+ insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
+ target.callbackInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(target.returnType), false));
+ } else {
+ insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
+ target.callbackInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(), false));
}
- else
- {
- insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, target.callInfoClass, CallbackInjector.CTOR, CallbackInfo.getConstructorDescriptor(), false));
- }
-
+
return ctorMAXS;
}
@@ -252,17 +327,17 @@ public class CallbackInjector {
* @param targetNode
* @param marshallVar
*/
- protected void injectCancellationCode(Target target, final InsnList insns, final AbstractInsnNode targetNode, int 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));
+ insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, target.callbackInfoClass, 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);
}
@@ -273,22 +348,17 @@ public class CallbackInjector {
* @param targetNode
* @param marshallVar
*/
- protected void injectReturnCode(Target target, final InsnList insns, final AbstractInsnNode targetNode, int marshallVar)
- {
- if (target.returnType.equals(Type.VOID_TYPE))
- {
+ 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
- {
+ } 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 MethodInsnNode(Opcodes.INVOKEVIRTUAL, target.callbackInfoClass, 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)));
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java
index ac3917f8..3a416a74 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/Cancellable.java
@@ -1,17 +1,34 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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;
/**
- * Interface for (potentially) cancellable things :)
- *
- * @author Adam Mummery-Smith
+ * Interface for things which can be cancelled
*/
-public interface Cancellable
-{
+public interface Cancellable {
/**
* Get whether this is actually cancellable
*/
@@ -23,10 +40,11 @@ public interface Cancellable
public abstract boolean isCancelled();
/**
- * If the object is cancellable, cancels the object, implementors may throw
- * an EventCancellationException if the object is not actually cancellable.
+ * 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
+ * @throws CancellationException (optional) may be thrown if the object is not actually cancellable. Contractually, this object may not throw the
+ * exception if isCancellable() returns true.
*/
public abstract void cancel() throws CancellationException;
}
\ No newline at end of file
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java
index fd0c4452..e8cdb45c 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CancellationException.java
@@ -1,29 +1,45 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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;
-public class CancellationException extends RuntimeException
-{
+public class CancellationException extends RuntimeException {
+
private static final long serialVersionUID = 1L;
- public CancellationException()
- {
+ public CancellationException() {
}
-
- public CancellationException(String message)
- {
+
+ public CancellationException(String message) {
super(message);
}
-
- public CancellationException(Throwable cause)
- {
+
+ public CancellationException(Throwable cause) {
super(cause);
}
-
- public CancellationException(String message, Throwable cause)
- {
+
+ public CancellationException(String message, Throwable cause) {
super(message, cause);
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java
new file mode 100644
index 00000000..5bec4f62
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/ReadOnlyInsnList.java
@@ -0,0 +1,247 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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;
+
+import java.util.ListIterator;
+
+import org.objectweb.asm.tree.AbstractInsnNode;
+import org.objectweb.asm.tree.InsnList;
+
+/**
+ * Read-only wrapper for InsnList, defensively passed to InjectionPoint instances so that custom InjectionPoint implementations cannot modify the insn
+ * list whilst inspecting it.
+ */
+public class ReadOnlyInsnList extends InsnList {
+
+ private InsnList insnList;
+
+ public ReadOnlyInsnList(InsnList insns) {
+ this.insnList = insns;
+ }
+
+ void dispose() {
+ this.insnList = null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#set(org.objectweb.asm.tree.AbstractInsnNode, org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public void set(AbstractInsnNode location, AbstractInsnNode insn) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#add(org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public void add(AbstractInsnNode insn) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#add(org.objectweb.asm.tree.InsnList)
+ */
+ @Override
+ public void add(InsnList insns) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#insert(org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public void insert(AbstractInsnNode insn) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#insert(org.objectweb.asm.tree.InsnList)
+ */
+ @Override
+ public void insert(InsnList insns) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#insert(org.objectweb.asm.tree.AbstractInsnNode, org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public void insert(AbstractInsnNode location, AbstractInsnNode insn) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#insert(org.objectweb.asm.tree.AbstractInsnNode, org.objectweb.asm.tree.InsnList)
+ */
+ @Override
+ public void insert(AbstractInsnNode location, InsnList insns) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#insertBefore(org.objectweb.asm.tree.AbstractInsnNode, org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public void insertBefore(AbstractInsnNode location, AbstractInsnNode insn) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#insertBefore(org.objectweb.asm.tree.AbstractInsnNode, org.objectweb.asm.tree.InsnList)
+ */
+ @Override
+ public void insertBefore(AbstractInsnNode location, InsnList insns) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#remove(org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public void remove(AbstractInsnNode insn) {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#toArray()
+ */
+ @Override
+ public AbstractInsnNode[] toArray() {
+ return this.insnList.toArray();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#size()
+ */
+ @Override
+ public int size() {
+ return this.insnList.size();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#getFirst()
+ */
+ @Override
+ public AbstractInsnNode getFirst() {
+ return this.insnList.getFirst();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#getLast()
+ */
+ @Override
+ public AbstractInsnNode getLast() {
+ return this.insnList.getLast();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#get(int)
+ */
+ @Override
+ public AbstractInsnNode get(int index) {
+ return this.insnList.get(index);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#contains(org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public boolean contains(AbstractInsnNode insn) {
+ return this.insnList.contains(insn);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#indexOf(org.objectweb.asm.tree.AbstractInsnNode)
+ */
+ @Override
+ public int indexOf(AbstractInsnNode insn) {
+ return this.insnList.indexOf(insn);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#iterator()
+ */
+ @Override
+ public ListIterator iterator() {
+ return this.insnList.iterator();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#iterator(int)
+ */
+ @Override
+ public ListIterator iterator(int index) {
+ return this.insnList.iterator(index);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.objectweb.asm.tree.InsnList#resetLabels()
+ */
+ @Override
+ public void resetLabels() {
+ this.insnList.resetLabels();
+ }
+}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
index fdaddafb..a319f0c8 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java
@@ -1,36 +1,69 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.points;
+import org.objectweb.asm.Opcodes;
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.
+ * This injection point searches for GETFIELD and PUTFIELD (and static equivalent) opcodes matching its arguments and returns a list of insns
+ * immediately prior to matching instructions. It accepts the following parameters from {@link org.spongepowered.asm.mixin.injection.At At}:
*
- * @author Adam Mummery-Smith
+ *
+ * - target
+ * - A {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} which identifies the target field
+ * - opcode
+ * - The {@link Opcodes opcode} of the field access, must be one of GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
+ * - ordinal
+ * - The ordinal position of the field access to match. For example if the field is referenced 3 times and you want to match the 3rd then you can
+ * specify an ordinal of 2 (ordinals are zero-indexed). The default value is -1 which supresses ordinal matching
+ *
+ *
+ * Example:
+ * @At(value = "FIELD", target="field_5678_z:I", opcode = Opcodes.GETFIELD)
+ *
+ *
+ * Note that like all standard injection points, this class matches the insn itself, putting the injection point immediately before the
+ * access in question. Use the {@link org.spongepowered.asm.mixin.injection.At#shift shift} specifier to adjust the matched opcode as necessary.
*/
-public class BeforeFieldAccess extends BeforeInvoke
-{
+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;
- }
+
+ private final int opcode;
+
+ public BeforeFieldAccess(InjectionPointData data) {
+ super(data);
+ this.opcode = data.getOpcode(-1, Opcodes.GETFIELD, Opcodes.PUTFIELD, Opcodes.GETSTATIC, Opcodes.PUTSTATIC, -1);
+ }
+
+ @Override
+ protected boolean matchesInsn(AbstractInsnNode insn) {
+ return insn instanceof FieldInsnNode && (((FieldInsnNode) insn).getOpcode() == this.opcode || this.opcode == -1);
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java
index 22eee477..10f29512 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java
@@ -1,199 +1,159 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.points;
import java.util.Collection;
import java.util.ListIterator;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
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.
+ * This injection point searches for INVOKEVIRTUAL, INVOKESTATIC and INVOKESPECIAL opcodes matching its arguments and returns a list of insns
+ * immediately prior to matching instructions. It accepts the following parameters from {@link org.spongepowered.asm.mixin.injection.At At}:
*
- * @author Adam Mummery-Smith
+ *
+ * - target
+ * - A {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} which identifies the target method
+ * - ordinal
+ * - The ordinal position of the method invocation to match. For example if the method is invoked 3 times and you want to match the 3rd then you
+ * can specify an ordinal of 2 (ordinals are zero-indexed). The default value is -1 which supresses ordinal matching
+ *
+ *
+ * Example:
+ * @At(value = "INVOKE", target="func_1234_a(III)V")
+ *
+ *
+ * Note that like all standard injection points, this class matches the insn itself, putting the injection point immediately before the
+ * access in question. Use the {@link org.spongepowered.asm.mixin.injection.At#shift shift} specifier to adjust the matched opcode as necessary.
*/
-public class BeforeInvoke extends InjectionPoint
-{
+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();
+ protected final MemberInfo target;
-// 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 nodes) //, Event event)
- {
- int ordinal = 0;
- boolean found = false;
+ /**
+ * 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;
- 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 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++;
- }
- }
+ /**
+ * True to turn on strategy debugging to the console
+ */
+ protected boolean logging = false;
- this.inspectInsn(desc, insns, insn);
- }
-
-// if (this.logging) LiteLoaderLogger.debug(ClassTransformer.HORIZONTAL_RULE);
-
- return found;
- }
+ protected final Logger logger = LogManager.getLogger("mixin");
- protected boolean matchesInsn(AbstractInsnNode insn)
- {
- return insn instanceof MethodInsnNode;
- }
+ protected final String className;
- protected void inspectInsn(String desc, InsnList insns, AbstractInsnNode insn)
- {
- // stub for subclasses
- }
+ public BeforeInvoke(InjectionPointData data) {
+ this.target = data.getTarget();
+ this.ordinal = data.getOrdinal();
+ this.logging = data.get("log", false);
+ this.className = this.getClass().getSimpleName();
+ }
- 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;
-// }
+ 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 nodes) {
+ int ordinal = 0;
+ boolean found = false;
+
+ if (this.logging) {
+ this.logger.info("{} is searching for an injection point in method with descriptor {}", this.className, desc);
+ }
+
+ ListIterator iter = insns.iterator();
+ while (iter.hasNext()) {
+ AbstractInsnNode insn = iter.next();
+
+ if (this.matchesInsn(insn)) {
+ MemberInfo nodeInfo = new MemberInfo(insn);
+
+ if (this.logging) {
+ this.logger.info("{} is considering insn {}", this.className, nodeInfo);
+ }
+
+ if (this.target.matches(nodeInfo.owner, nodeInfo.name, nodeInfo.desc)) {
+ if (this.logging) {
+ this.logger.info("{} > found a matching insn, checking preconditions...", this.className);
+ }
+
+ if (this.matchesInsn(nodeInfo, ordinal)) {
+ if (this.logging) {
+ this.logger.info("{} > > > found a matching insn at ordinal {}", this.className, ordinal);
+ }
+
+ nodes.add(insn);
+ found = true;
+
+ if (this.ordinal == ordinal) {
+ break;
+ }
+ }
+
+ ordinal++;
+ }
+ }
+
+ this.inspectInsn(desc, insns, insn);
+ }
+
+ 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(MemberInfo nodeInfo, int ordinal) {
+ if (this.logging) {
+ this.logger.info("{} > > comparing target ordinal {} with current ordinal {}", this.className, this.ordinal, ordinal);
+ }
+ return this.ordinal == -1 || this.ordinal == ordinal;
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java
index d7e55a61..797f7181 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java
@@ -1,7 +1,27 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.points;
import java.util.Collection;
@@ -14,63 +34,68 @@ 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;
+/**
+ * This injection point searches for NEW opcodes matching its arguments and returns a list of insns immediately prior to matching instructions. It
+ * accepts the following parameters from {@link org.spongepowered.asm.mixin.injection.At At}:
+ *
+ *
+ * - named argument class
+ * - The value of the NEW node to look for, the fully-qualified class name
+ * - ordinal
+ * - The ordinal position of the NEW opcode to match. For example if the NEW opcode appears 3 times in the method and you want to match the 3rd
+ * then you can specify an ordinal of 2 (ordinals are zero-indexed). The default value is -1 which supresses ordinal
+ * matching
+ *
+ *
+ * Example:
+ * @At(value = "NEW", args = { "class=java/lang/String" })
+ *
+ *
+ * Note that like all standard injection points, this class matches the insn itself, putting the injection point immediately before the
+ * access in question. Use the {@link org.spongepowered.asm.mixin.injection.At#shift shift} specifier to adjust the matched opcode as necessary.
+ */
+public class BeforeNew extends InjectionPoint {
-public class BeforeNew extends InjectionPoint
-{
public static final String CODE = "NEW";
+ /**
+ * Class name we're looking for
+ */
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 nodes) //, Event event)
- {
- boolean found = false;
- int ordinal = 0;
-
- ListIterator 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;
- }
+ /**
+ * Ordinal value
+ */
+ private final int ordinal;
- private boolean matchesOwner(TypeInsnNode insn)
- {
-// for (String className : this.classNames)
-// {
-// if (className.equals(insn.desc)) return true;
-// }
-
- return this.className.equals(insn.desc);
- }
+ public BeforeNew(InjectionPointData data) {
+ this.ordinal = data.getOrdinal();
+ this.className = data.get("class", null).replace('.', '/');
+ }
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ boolean found = false;
+ int ordinal = 0;
+
+ ListIterator 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) {
+ return this.className == null || this.className.equals(insn.desc);
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java
index b6911115..204d85b3 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java
@@ -1,7 +1,27 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.points;
import java.util.Collection;
@@ -15,50 +35,62 @@ 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
+ * This injection point searches for RETURN opcodes in the target method and returns a list of insns immediately prior to matching instructions.
+ * Note that every RETURN opcode will be returned and thus every natural exit from the method except for exception throws will be implicitly
+ * specified. To specify a particular RETURN use the ordinal parameter. The injection point accepts the following parameters from
+ * {@link org.spongepowered.asm.mixin.injection.At At}:
*
- * @author Adam Mummery-Smith
+ *
+ * - ordinal
+ * - The ordinal position of the RETURN opcode to match, if not specified then the injection point returns all RETURN opcodes. For
+ * example if the RETURN opcode appears 3 times in the method and you want to match the 3rd then you can specify an ordinal of 2
+ * (ordinals are zero-indexed). The default value is -1 which supresses ordinal matching
+ *
+ *
+ * Example:
+ * @At(value = "RETURN")
+ *
+ * Note that if value is the only parameter specified, it can be omitted:
+ *
+ * @At("RETURN")
+ *
*/
-public class BeforeReturn extends InjectionPoint
-{
+public class BeforeReturn extends InjectionPoint {
+
public static final String CODE = "RETURN";
+ /**
+ * Ordinal of the target insn
+ */
private final int ordinal;
-
- public BeforeReturn(InjectionPointData data)
- {
- this.ordinal = data.getOrdinal();
- }
- @Override
- public boolean find(String desc, InsnList insns, Collection nodes) //, Event event)
- {
- boolean found = false;
- int returnOpcode = Type.getReturnType(desc).getOpcode(Opcodes.IRETURN);
- int ordinal = 0;
-
- ListIterator 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;
- }
+ public BeforeReturn(InjectionPointData data) {
+ this.ordinal = data.getOrdinal();
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ boolean found = false;
+
+ // RETURN opcode varies based on return type, thus we calculate what opcode we're actually looking for by inspecting the target method
+ int returnOpcode = Type.getReturnType(desc).getOpcode(Opcodes.IRETURN);
+ int ordinal = 0;
+
+ ListIterator 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;
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java
index 7c59590d..9fc8cbda 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java
@@ -1,7 +1,27 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.points;
import java.util.Collection;
@@ -10,71 +30,97 @@ 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;
+import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
/**
- * An injection point which searches for a matching String LDC insn immediately prior to a qualifying invoke
- *
- * @author Adam Mummery-Smith
+ * Like {@link BeforeInvoke}, this injection point searches for INVOKEVIRTUAL, INVOKESTATIC and INVOKESPECIAL opcodes matching its arguments and
+ * returns a list of insns immediately prior to matching instructions. This specialised version however only matches methods which accept a single
+ * string and return void, but allows the string itself to be matched as part of the search process. This is primarily used for matching particular
+ * invocations of Profiler::startSection with a specific argument. Note that because a string literal is required, this injection point can
+ * not be used to match invocations where the value being passed in is a variable.
+ *
+ * To be precise, this injection point matches invocations of the specified method which are preceded by an LDC instruction. The LDC instruction's
+ * payload can be specified with the ldc named argument (see below)
+ *
+ * The following parameters from {@link org.spongepowered.asm.mixin.injection.At At} are accepted
+ *
+ *
+ * - target
+ * - A {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} which identifies the target method, the method must be
+ * specified with a signature which accepts a single string and returns void, eg.
(Ljava/lang/String;)V
+ * - ordinal
+ * - The ordinal position of the method invocation to match. For example if the method is invoked 3 times and you want to match the 3rd then you
+ * can specify an ordinal of 2 (ordinals are zero-indexed). The default value is -1 which supresses ordinal matching
+ * - named argument ldc
+ * - The value of the LDC node to look for prior to the method invocation
+ *
+ *
+ * Example:
+ * @At(value = "INVOKE_STRING", target="startSection(Ljava/lang/String;)V", args = { "ldc=root" })
+ *
+ * Notice the use of the named argument "ldc" which specifies the value of the target LDC node.
+ *
+ * Note that like all standard injection points, this class matches the insn itself, putting the injection point immediately before the
+ * access in question. Use the {@link org.spongepowered.asm.mixin.injection.At#shift shift} specifier to adjust the matched opcode as necessary.
*/
-public class BeforeStringInvoke extends BeforeInvoke
-{
+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", "");
+ private static final String STRING_VOID_SIG = "(Ljava/lang/String;)V";
-// 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 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);
- }
+ /**
+ * LDC value we're searching for
+ */
+ private final String ldcValue;
+
+ /**
+ * True once a matching LDC node is found
+ */
+ private boolean foundLdc;
+
+ public BeforeStringInvoke(InjectionPointData data) {
+ super(data);
+ this.ldcValue = data.get("ldc", null);
+
+ if (this.ldcValue == null) {
+ throw new IllegalArgumentException(this.getClass().getSimpleName() + " requires named argument \"ldc\" to specify the desired target");
+ }
+
+ if (!STRING_VOID_SIG.equals(this.target.desc)) {
+ throw new IllegalArgumentException(this.getClass().getSimpleName() + " requires target method with with signature " + STRING_VOID_SIG);
+ }
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ this.foundLdc = false;
+
+ return super.find(desc, insns, nodes);
+ }
+
+ @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) {
+ this.logger.info("{} > found a matching LDC with value {}", this.className, node.cst);
+ }
+ this.foundLdc = true;
+ return;
+ }
+ }
+
+ this.foundLdc = false;
+ }
+
+ @Override
+ protected boolean matchesInsn(MemberInfo nodeInfo, int ordinal) {
+ if (this.logging) {
+ this.logger.info("{} > > found LDC \"{}\" = {}", this.className, this.ldcValue, this.foundLdc);
+ }
+ return this.foundLdc && super.matchesInsn(nodeInfo, ordinal);
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java
index aaecf4fe..a6074501 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java
@@ -1,65 +1,95 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.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.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.
+ * This injection point 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. It accepts the following parameters from {@link org.spongepowered.asm.mixin.injection.At At}:
*
- * @author Adam Mummery-Smith
+ *
+ * - opcode
+ * - The {@link Opcodes opcode} of the jump instruction, must be one of IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT,
+ * IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL. Defaults to -1 which matches any JUMP opcode.
+ *
+ * - ordinal
+ * - The ordinal position of the jump insn to match. For example if there are 3 jumps of the specified type and you want to match the 2nd then you
+ * can specify an ordinal of 1 (ordinals are zero-indexed). The default value is -1 which supresses ordinal matching
+ *
+ *
+ * Example:
+ * @At(value = "JUMP", opcode = Opcodes.IFLE, ordinal = 2)
+ *
+ *
+ * Note that like all standard injection points, this class matches the insn itself, putting the injection point immediately before the
+ * access in question. Use the {@link org.spongepowered.asm.mixin.injection.At#shift shift} specifier to adjust the matched opcode as necessary.
*/
-public class JumpInsnPoint extends InjectionPoint
-{
+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 nodes) //, Event event)
- {
- boolean found = false;
- int ordinal = 0;
-
- ListIterator 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;
- }
+
+ private final int ordinal;
+
+ public JumpInsnPoint(InjectionPointData data) {
+ this.opCode = data.getOpcode(-1, Opcodes.IFEQ, Opcodes.IFNE, Opcodes.IFLT, Opcodes.IFGE, Opcodes.IFGT, Opcodes.IFLE, Opcodes.IF_ICMPEQ,
+ Opcodes.IF_ICMPNE, Opcodes.IF_ICMPLT, Opcodes.IF_ICMPGE, Opcodes.IF_ICMPGT, Opcodes.IF_ICMPLE, Opcodes.IF_ACMPEQ, Opcodes.IF_ACMPNE,
+ Opcodes.GOTO, Opcodes.JSR, Opcodes.IFNULL, Opcodes.IFNONNULL, -1);
+ this.ordinal = data.getOrdinal();
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ boolean found = false;
+ int ordinal = 0;
+
+ ListIterator 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;
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java
index c7f16b55..484853d3 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java
@@ -1,7 +1,27 @@
-/**
- * This file contributed from LiteLoader. Pending refactor. DO NOT ALTER THIS FILE.
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.points;
import java.util.Collection;
@@ -11,26 +31,24 @@ 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
+ * This injection point simply returns the first instruction in the target method body, allowing the injection to be placed at the "head" of the
+ * target method. It accepts no parameters and only returns a single insn in all circumstances.
+ *
+ * Example:
+ * @At("HEAD")
+ *
*/
-public class MethodHead extends InjectionPoint
-{
+public class MethodHead extends InjectionPoint {
+
public static final String CODE = "HEAD";
- public MethodHead(InjectionPointData data)
- {
- }
-
- @Override
- public boolean find(String desc, InsnList insns, Collection nodes) //, Event event)
- {
- nodes.add(insns.getFirst());
- return true;
- }
+ public MethodHead(InjectionPointData data) {
+ }
+
+ @Override
+ public boolean find(String desc, InsnList insns, Collection nodes) {
+ nodes.add(insns.getFirst());
+ return true;
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java
similarity index 95%
rename from src/main/java/org/spongepowered/asm/mixin/injection/InjectionInfo.java
rename to src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java
index 29b1e214..33d86551 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java
@@ -1,4 +1,4 @@
-/**
+/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org
@@ -22,7 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-package org.spongepowered.asm.mixin.injection;
+package org.spongepowered.asm.mixin.injection.struct;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -33,15 +33,16 @@ 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.At;
+import org.spongepowered.asm.mixin.injection.Inject;
+import org.spongepowered.asm.mixin.injection.InjectionPoint;
+import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
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 {
@@ -120,8 +121,8 @@ public class InjectionInfo {
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");
+ throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " specifies a target class '" + targetMember.owner
+ + "', which is not supported");
}
this.findMethods(targetMember);
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java
index 7d52e98d..e440667f 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java
@@ -1,4 +1,4 @@
-/**
+/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org
@@ -33,8 +33,6 @@ 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 {
@@ -127,4 +125,17 @@ public class InjectionPointData {
public int getOpcode() {
return this.opcode;
}
+
+ public int getOpcode(int defaultOpcode) {
+ return this.opcode > 0 ? this.opcode : defaultOpcode;
+ }
+
+ public int getOpcode(int defaultOpcode, int... validOpcodes) {
+ for (int validOpcode : validOpcodes) {
+ if (this.opcode == validOpcode) {
+ return this.opcode;
+ }
+ }
+ return defaultOpcode;
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
index 5e14c80e..257ae3ea 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
@@ -1,4 +1,4 @@
-/**
+/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org
@@ -24,35 +24,43 @@
*/
package org.spongepowered.asm.mixin.injection.struct;
+import org.objectweb.asm.tree.AbstractInsnNode;
+import org.objectweb.asm.tree.FieldInsnNode;
+import org.objectweb.asm.tree.MethodInsnNode;
+
/**
* 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.
*
* Some examples:
- * // references a method called func_1234_a, if there are multiple methods with the same signature, matches the first occurrence
+ * // references a method or field called func_1234_a, if there are multiple members 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
+ * // references a method or field called func_1234_a, if there are multiple members 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 field called field_5678_z which is a String
+ * field_5678_z:Ljava/lang/String;
+ *
* // references a ctor which takes a single String argument
* (Ljava/lang/String;)V
*
* // references a method called func_1234_a in class foo.bar.Baz
* Lfoo/bar/Baz;func_1234_a
*
+ * // references a field called field_5678_z in class com.example.Dave
+ * Lcom/example/Dave;field_5678_z
+ *
* // 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
*
- *
- * @author Adam Mummery-Smith
*/
public class MemberInfo {
@@ -108,12 +116,33 @@ public class MemberInfo {
this.matchAll = matchAll;
}
+ /**
+ * Initialise a MemberInfo using the supplied insn which must be an instance of MethodInsnNode or FieldInsnNode
+ */
+ public MemberInfo(AbstractInsnNode insn) {
+ this.matchAll = false;
+
+ 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");
+ }
+ }
+
/* (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);
+ return String.format("[OWNER=%s,NAME=%s,DESC=%s,ALL=%s]", this.owner, this.name, this.desc, this.matchAll);
}
/**
@@ -173,15 +202,23 @@ public class MemberInfo {
}
int parenPos = name.indexOf('(');
+ int colonPos = name.indexOf(':');
if (parenPos > -1) {
desc = name.substring(parenPos);
name = name.substring(0, parenPos);
+ } else if (colonPos > -1) {
+ desc = name.substring(colonPos);
+ name = name.substring(0, colonPos);
}
boolean matchAll = name.endsWith("*");
- if (matchAll) name = name.substring(0, name.length() - 1);
+ if (matchAll) {
+ name = name.substring(0, name.length() - 1);
+ }
- if (name.isEmpty()) name = null;
+ if (name.isEmpty()) {
+ name = null;
+ }
return new MemberInfo(name, owner, desc, matchAll);
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/tree/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/tree/ReadOnlyInsnList.java
deleted file mode 100644
index ed378ac3..00000000
--- a/src/main/java/org/spongepowered/asm/mixin/injection/tree/ReadOnlyInsnList.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * 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 iterator()
- {
- return this.insnList.iterator();
- }
-
- @Override
- public ListIterator iterator(int index)
- {
- return this.insnList.iterator(index);
- }
-
- @Override
- public void resetLabels()
- {
- this.insnList.resetLabels();
- }
-}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
index 6525153a..d82f9578 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
@@ -52,7 +52,7 @@ 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.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.ASMHelper;
@@ -106,8 +106,7 @@ public class MixinTransformer extends TreeTransformer {
*/
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
- for (MixinConfig config : this.configs)
- {
+ for (MixinConfig config : this.configs) {
if (transformedName != null && transformedName.startsWith(config.getMixinPackage())) {
throw new RuntimeException(String.format("%s is a mixin class and cannot be referenced directly", transformedName));
}
@@ -156,8 +155,9 @@ public class MixinTransformer extends TreeTransformer {
if (MixinTransformer.DEBUG_EXPORT) {
try {
FileUtils.writeByteArrayToFile(new File(".mixin.out/" + transformedName.replace('.', '/') + ".class"), bytes);
+ } catch (IOException ex) {
+ // don't care
}
- catch (IOException ex) {}
}
return bytes;
@@ -179,7 +179,6 @@ public class MixinTransformer extends TreeTransformer {
* @param mixin
*/
protected void applyMixin(ClassNode targetClass, MixinData mixin) {
-
try {
this.verifyClasses(targetClass, mixin);
this.applyMixinInterfaces(targetClass, mixin);
@@ -200,7 +199,9 @@ public class MixinTransformer extends TreeTransformer {
*/
protected void verifyClasses(ClassNode targetClass, MixinData mixin) {
String superName = mixin.getClassNode().superName;
- if (targetClass.superName == null || superName == null || !(targetClass.superName.equals(superName) || "java/lang/Object".equals(superName))) {
+ if (targetClass.superName == null
+ || superName == null
+ || !(targetClass.superName.equals(superName) || "java/lang/Object".equals(superName))) {
throw new InvalidMixinException("Mixin classes must have the same superclass as their target class");
}
}
diff --git a/src/main/java/org/spongepowered/asm/util/ASMHelper.java b/src/main/java/org/spongepowered/asm/util/ASMHelper.java
index fbbe7efb..3ee7eea0 100644
--- a/src/main/java/org/spongepowered/asm/util/ASMHelper.java
+++ b/src/main/java/org/spongepowered/asm/util/ASMHelper.java
@@ -490,4 +490,74 @@ public class ASMHelper {
public static boolean fieldIsStatic(FieldNode field) {
return (field.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC;
}
+
+ /**
+ * 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 ASMHelper.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 ASMHelper.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;
+ }
+
+ /**
+ * 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) {
+ ASMHelper.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;
+ }
+ }
+ }
}
diff --git a/src/main/java/org/spongepowered/asm/util/ByteCodeUtilities.java b/src/main/java/org/spongepowered/asm/util/ByteCodeUtilities.java
deleted file mode 100644
index a5fc67b5..00000000
--- a/src/main/java/org/spongepowered/asm/util/ByteCodeUtilities.java
+++ /dev/null
@@ -1,809 +0,0 @@
-/**
- * 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> calculatedLocalVariables = new HashMap>();
-
- 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 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)) && "".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 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 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 getLocalVariableTable(ClassNode classNode, MethodNode method)
- {
- if (method.localVariables.isEmpty())
- {
- String signature = String.format("%s.%s%s", classNode.name, method.name, method.desc);
-
- List 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 generateLocalVariableTable(ClassNode classNode, MethodNode method)
- {
- List interfaces = null;
- if (classNode.interfaces != null)
- {
- interfaces = new ArrayList();
- 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 analyzer = new Analyzer(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[] frames = analyzer.getFrames();
-
- // Record the original size of hte method
- int methodSize = method.instructions.size();
-
- // List of LocalVariableNodes to return
- List localVariables = new ArrayList();
-
- 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 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.>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.>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 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 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 getAnnotationValue(AnnotationNode annotation)
- {
- return ByteCodeUtilities.getAnnotationValue(annotation, "value");
- }
-
- /**
- * Get the value of an annotation node
- *
- * @param annotation
- * @param key
- */
- @SuppressWarnings("unchecked")
- public static 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();
-// }
-}
diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java
new file mode 100644
index 00000000..46de4f40
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/util/Locals.java
@@ -0,0 +1,318 @@
+/*
+ * This file is part of Sponge, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 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.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.Type;
+import org.objectweb.asm.tree.AbstractInsnNode;
+import org.objectweb.asm.tree.ClassNode;
+import org.objectweb.asm.tree.FrameNode;
+import org.objectweb.asm.tree.InsnList;
+import org.objectweb.asm.tree.LabelNode;
+import org.objectweb.asm.tree.LocalVariableNode;
+import org.objectweb.asm.tree.MethodNode;
+import org.objectweb.asm.tree.VarInsnNode;
+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;
+
+
+/**
+ * Utility methods for working with local variables using ASM
+ */
+public class Locals {
+
+ /**
+ * Cached local variable lists, to avoid having to recalculate them (expensive) if multiple injectors are working with the same method
+ */
+ private static final Map> calculatedLocalVariables = new HashMap>();
+
+ /**
+ * 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));
+ }
+ }
+ }
+
+ /**
+ * 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 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] = Locals.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] = Locals.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] = Locals.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 localVariables = Locals.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 getLocalVariableTable(ClassNode classNode, MethodNode method) {
+ if (method.localVariables.isEmpty()) {
+ String signature = String.format("%s.%s%s", classNode.name, method.name, method.desc);
+
+ List localVars = Locals.calculatedLocalVariables.get(signature);
+ if (localVars != null) {
+ return localVars;
+ }
+
+ localVars = Locals.generateLocalVariableTable(classNode, method);
+ Locals.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 generateLocalVariableTable(ClassNode classNode, MethodNode method) {
+ List interfaces = null;
+ if (classNode.interfaces != null) {
+ interfaces = new ArrayList();
+ 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 analyzer = new Analyzer(
+ 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[] frames = analyzer.getFrames();
+
+ // Record the original size of hte method
+ int methodSize = method.instructions.size();
+
+ // List of LocalVariableNodes to return
+ List localVariables = new ArrayList();
+
+ 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 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;
+ }
+}