mirror of
https://github.com/LegacyModdingMC/UniMix.git
synced 2026-11-19 16:29:45 +00:00
Overhaul RedirectInjector for more consistent coerce behaviour
Also improve some javadoc. Closes #350
This commit is contained in:
1 parent
03e8ad59f0
commit
7b37a681ee
32 files changed
+856
-326
No files matched your search
@@ -43,4 +43,5 @@ public @interface Implements {
|
||||
* @return list of interfaces to implement
|
||||
*/
|
||||
public Interface[] value();
|
||||
|
||||
}
|
||||
@@ -24,15 +24,15 @@
|
||||
*/
|
||||
package org.spongepowered.asm.mixin;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* I'm probably going to the special hell for this
|
||||
* This annotation is used to define information for a soft-implemented
|
||||
* interface. See {@link Implements} for details.
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
public @interface Interface {
|
||||
|
||||
|
||||
@@ -1029,6 +1029,20 @@ public final class MixinEnvironment implements ITokenProvider {
|
||||
return mixinConfigs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a mixin configuration to the blackboard
|
||||
*
|
||||
* @param config Name of configuration resource to add
|
||||
* @return fluent interface
|
||||
* @deprecated use Mixins::addConfiguration instead
|
||||
*/
|
||||
@Deprecated
|
||||
public MixinEnvironment addConfiguration(String config) {
|
||||
MixinEnvironment.logger.warn("MixinEnvironment::addConfiguration is deprecated and will be removed. Use Mixins::addConfiguration instead!");
|
||||
Mixins.addConfiguration(config, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
void registerConfig(String config) {
|
||||
List<String> configs = this.getMixinConfigs();
|
||||
if (!configs.contains(config)) {
|
||||
|
||||
@@ -125,4 +125,5 @@ public @interface Shadow {
|
||||
* @return Aliases for this member
|
||||
*/
|
||||
public String[] aliases() default { };
|
||||
|
||||
}
|
||||
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
import org.spongepowered.asm.mixin.injection.points.*;
|
||||
@@ -44,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.points.*;
|
||||
* should be consulted for the meaning of the argument to that particular class.
|
||||
* A general description of each parameter is provided below.
|
||||
*/
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface At {
|
||||
|
||||
|
||||
@@ -33,13 +33,16 @@ import java.lang.annotation.Target;
|
||||
* <p>This annotation has two usages applicable to Callback Injectors (defined
|
||||
* using {@link Inject @Inject}. For local capture injectors, it indicates
|
||||
* that the injector should coerce top-level primitive types (int) to covariant
|
||||
* types defined on the handler. For other injectors, it can be used on a
|
||||
* reference type to indicate that the intended type is covariant over the
|
||||
* argument type (or that the argument type is contravariant on the target class
|
||||
* type). This can be used for multi-target injectors with a bounded type
|
||||
* argument on the class or target method.</p>
|
||||
* types defined on the handler. It can also be used on a reference type to
|
||||
* indicate that the intended type is covariant over the argument type (or that
|
||||
* the argument type is contravariant on the target class type). This can be
|
||||
* used for multi-target injectors with a bounded type argument on the class or
|
||||
* target method. It is also acceptable to use an interface directly or
|
||||
* indirectly implemented by the relevant class, including interfaces applied by
|
||||
* other mixins.</p>
|
||||
*
|
||||
* <p>During LVT generation it is not always possible to inflect the exact local
|
||||
* <p><tt>@Coerce</tt> also has an important usage with primitive types. It
|
||||
* is not always possible during LVT generation to determine the exact local
|
||||
* type for types represented internally as integers, for example booleans and
|
||||
* shorts. However adding a surrogate for these cases is overkill when the type
|
||||
* is known for certain by the injector. Since the bytecode for all types stored
|
||||
@@ -56,8 +59,15 @@ import java.lang.annotation.Target;
|
||||
* indicate that an incoming parameter can be consumed as a valid supertype, up
|
||||
* to and including {@link Object}. This is particularly useful when an argument
|
||||
* on the target method invocation is inaccessible or unknown.</p>
|
||||
*
|
||||
* <p>Since Mixin <tt>0.8</tt> it is also possible to use <tt>@Coerce</tt>
|
||||
* on the return type of a <em>field gettter</em> or <em>method invocation</em>
|
||||
* redirector. To do so simply annotate the method itself. Note that doing so
|
||||
* will cast the return type back to the original return type as part of the
|
||||
* injection, so the object must be of an appropriate type regardless of
|
||||
* visibility.</p>
|
||||
*/
|
||||
@Target({ ElementType.PARAMETER })
|
||||
@Target({ ElementType.PARAMETER, ElementType.METHOD })
|
||||
public @interface Coerce {
|
||||
|
||||
}
|
||||
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
@@ -39,6 +40,7 @@ import org.objectweb.asm.Opcodes;
|
||||
* appropriate argument. Specifying values of different types will cause an
|
||||
* error to be raised by the injector.</p>
|
||||
*/
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Constant {
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import java.lang.annotation.Target;
|
||||
|
||||
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
|
||||
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
|
||||
@@ -41,6 +42,65 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* Specifies that this mixin method should inject a callback (or
|
||||
* callback<b>s</b>) to itself in the target method(s) identified by
|
||||
* {@link #method}.
|
||||
*
|
||||
* <p>Callbacks are simple injectors which simply inject a call to the decorated
|
||||
* method (the <em>handler</em>) in the <em>target</em> method (or methods)
|
||||
* selected by the selectors specified in {@link #method}. Callback Injectors
|
||||
* can also capture arguments and local variables from the <em>target</em> for
|
||||
* use in the handler.</p>
|
||||
*
|
||||
* <p>Callback handler methods should always return <tt>void</tt> and should
|
||||
* have the same <tt>static</tt>-ness as their target (though it is allowable to
|
||||
* have a <tt>static</tt> callback injected into an instance method, and for
|
||||
* obvious reasons the inverse is not permitted).</p>
|
||||
*
|
||||
* <h3>Basic usage</h3>
|
||||
*
|
||||
* <p>The simplest usage of <tt>@Inject</tt> captures no context from the
|
||||
* target scope. This is particularly useful if the injector is targetting
|
||||
* multiple methods with different signatures. In this case only the
|
||||
* {@link CallbackInfo} (or {@link CallbackInfoReturnable} as appropriate) is
|
||||
* required.</p>
|
||||
*
|
||||
* <blockquote><tt>private void onSomeEvent(CallbackInfo ci)</tt></blockquote>
|
||||
*
|
||||
* <h3>Capture target arguments</h3>
|
||||
*
|
||||
* <p>Callbacks can also capture the arguments passed to the target method. To
|
||||
* do so specify the target arguments before the {@link CallbackInfo}:</p>
|
||||
*
|
||||
* <blockquote><tt>private void onSomeEvent(int arg1, String arg2,
|
||||
* CallbackInfo ci)</tt></blockquote>
|
||||
*
|
||||
* <h3>Surrogate methods</h3>
|
||||
*
|
||||
* <p>If injecting into multiple methods with different target arguments it is
|
||||
* obviously possible to ignore the target arguments (see "Basic Usage" above)
|
||||
* but this may be unsuitable if arguments from the target are required. If you
|
||||
* need to inject into multiple methods but also wish to capture method
|
||||
* arguments you may provide a <em>surrogate</em> method with the alternative
|
||||
* signature. In fact you may provide as many surrogates as required by the
|
||||
* injection. Surrogate methods much have the same name as the handler method
|
||||
* and must be decorated with {@link Surrogate}. A surrogate may also be
|
||||
* required where the LVT of a method with <em>local capture</em> (see below) is
|
||||
* known to change between different environments or injection points.</p>
|
||||
*
|
||||
* <h3>Capture local variables</h3>
|
||||
*
|
||||
* <p>In addition to capturing the target method arguments, it may be desirable
|
||||
* to capture locally-scoped variables from the target method at the point of
|
||||
* injection. This is usually executed in two stages:</p>
|
||||
*
|
||||
* <ol>
|
||||
* <li>Set the {@link #locals()} value of your injection to
|
||||
* {@link LocalCapture#PRINT} and run the application.</li>
|
||||
* <li>When the injector is processed, a listing of the LVT is produced
|
||||
* accompanied by a generated signature for your handler method including
|
||||
* the discovered args. Modify your handler signature accordingly.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>For more details see {@link #locals()}.</p>
|
||||
*
|
||||
*/
|
||||
@Target({ ElementType.METHOD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@@ -114,6 +174,13 @@ public @interface Inject {
|
||||
* surrogate targets for the orphaned injector by annotating them with an
|
||||
* {@link Surrogate} annotation.</p>
|
||||
*
|
||||
* <p>You can improve the robustness of your local capture injection by only
|
||||
* specifying locals up to the last variable you wish to use. For example if
|
||||
* the target LVT contains <tt><int, int, int, float, String></tt> and
|
||||
* you only need the <tt>float</tt> value, you can choose to omit the unused
|
||||
* <tt>String</tt> and changes to the LVT beyond that point will not affect
|
||||
* your injection.</p>
|
||||
*
|
||||
* <p>It is also important to nominate the failure behaviour to follow when
|
||||
* local capture fails and so all {@link LocalCapture} behaviours which
|
||||
* specify a capture action imply a particular behaviour for handling
|
||||
|
||||
@@ -31,6 +31,8 @@ import java.lang.annotation.Target;
|
||||
|
||||
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
|
||||
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
|
||||
import org.spongepowered.asm.mixin.injection.points.BeforeInvoke;
|
||||
import org.spongepowered.asm.mixin.injection.points.BeforeNew;
|
||||
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
|
||||
@@ -41,7 +43,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* method call, field access or object construction (via the <tt>new</tt>
|
||||
* keyword) to the method decorated with this annotation.</p>
|
||||
*
|
||||
* <h4>Method Redirect Mode</h4>
|
||||
* <h3>Method Redirect Mode</h3>
|
||||
*
|
||||
* <p>The handler method signature must match the hooked method precisely
|
||||
* <b>but</b> prepended with an arg of the owning object's type to accept the
|
||||
@@ -65,7 +67,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* </blockquote>
|
||||
*
|
||||
* <p>For obvious reasons this does not apply for static methods, for static
|
||||
* methods it is sufficient that the signature simply match the hooked method.
|
||||
* methods it is sufficient that the signature simply match the redirected
|
||||
* method.
|
||||
* </p>
|
||||
*
|
||||
* <p>It is also possible to capture the arguments of the target method in
|
||||
@@ -78,7 +81,12 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* int someInt, String someString)</pre>
|
||||
* </blockquote>
|
||||
*
|
||||
* <h4>Field Access Redirect Mode</h4>
|
||||
* <p>All arguments of a method redirect handler, and the return type, can be
|
||||
* decorated with {@link Coerce} if - for example - a package-private class
|
||||
* needs to be coerced to a duck interface or to (for example) <tt>Object</tt>.
|
||||
* </p>
|
||||
*
|
||||
* <h3>Field Access Redirect Mode</h3>
|
||||
*
|
||||
* <p>The handler method signature varies depending on whether the redirector is
|
||||
* handling a field <b>write</b> (<tt>PUTFIELD</tt>, <tt>PUTSTATIC</tt>) or a
|
||||
@@ -91,21 +99,22 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Read static field (<tt>GETSTATIC</tt>)</td>
|
||||
* <td><code>private <b>FieldType</b> getFieldValue()</code></td>
|
||||
* <td><code>private static <b>FieldType</b> getFieldValue()</code></td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Read instance field (<tt>GETFIELD</tt>)</td>
|
||||
* <td><code>private <b>FieldType</b> getFieldValue(<b>OwnerType</b>
|
||||
* owner)</code></td>
|
||||
* owner)</code></td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Write static field (<tt>PUTSTATIC</tt>)</td>
|
||||
* <td><code>private void setFieldValue(<b>FieldType</b> value)</code></td>
|
||||
* <td><code>private static void setFieldValue(<b>FieldType</b> value)
|
||||
* </code></td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>Write instance field (<tt>PUTFIELD</tt>)</td>
|
||||
* <td><code>private void setFieldValue(<b>OwnerType</b>
|
||||
* owner, <b>FieldType</b> value)</code></td>
|
||||
* owner, <b>FieldType</b> value)</code></td>
|
||||
* </tr>
|
||||
* </table>
|
||||
*
|
||||
@@ -114,7 +123,13 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* the code above this would be the <em>someInt</em> and <em>someString</em>
|
||||
* arguments) by appending the arguments to the method signature.</p>
|
||||
*
|
||||
* <h4>Array Element Access Redirect Mode</h4>
|
||||
* <p>All arguments of a field redirect handler, including the field type
|
||||
* itself, can be decorated with {@link Coerce} if - for example - a
|
||||
* package-private class needs to be coerced to a duck interface or to (for
|
||||
* example) <tt>Object</tt>.
|
||||
* </p>
|
||||
*
|
||||
* <h3>Array Element Access Redirect Mode</h3>
|
||||
*
|
||||
* <p>For fields of an array type, it is possible to redirect the access to the
|
||||
* actual array field itself using the behaviour above. However it is also
|
||||
@@ -155,7 +170,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* {@link BeforeFieldAccess BeforeFieldAccess args} for details
|
||||
* on matching array accesses using the <tt>FIELD</tt> injection point.</p>
|
||||
*
|
||||
* <h4>Array Length Redirect Mode</h4>
|
||||
* <h3>Array Length Redirect Mode</h3>
|
||||
*
|
||||
* <p>For fields of an array type, it is possible to redirect the call to the
|
||||
* builtin pseudo-property <tt>length</tt>. To do so, specify the argument
|
||||
@@ -174,28 +189,68 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
|
||||
* private <b>int</b> getLength(<b>ElementType</b>[][] array, int baseDim)
|
||||
* </code></blockquote>
|
||||
*
|
||||
* <h4>Constructor Redirect Mode</h4>
|
||||
* <h3>New Object Redirect Mode (Factory Mode)</h3>
|
||||
*
|
||||
* <p>Redirecting object creation requires redirection of the <tt>NEW</tt>
|
||||
* operation and constructor call. Your handler method should target the <tt>NEW
|
||||
* </tt> opcode using the {@link BeforeNew} Injection Point and construct an
|
||||
* appropriate object. The factory method <b>must return a new object</b> and
|
||||
* <b>must not</b> return <tt>null</tt> since the contract of the <tt>new</tt>
|
||||
* opcode does not allow for the possibility of <tt>null</tt>. Your factory may
|
||||
* throw an exception however.</p>
|
||||
*
|
||||
* <p>Note that {@link BeforeNew} differs from {@link BeforeInvoke} in that the
|
||||
* shape of <tt>target</tt> should contain <em>only</em> an <tt>owner</tt> (to
|
||||
* target any ctor of the specified class) or <em>only</em> a <tt>descriptor
|
||||
* </tt> consisting of the constructor descriptor with the return type changed
|
||||
* from <tt>void</tt> (<tt>V</tt>) to the type of object being constructed. In
|
||||
* other words to redirect an object creation for an object <tt>Foo</tt>:</p>
|
||||
*
|
||||
* <blockquote><pre>package baz.bar;
|
||||
*
|
||||
*class Foo {
|
||||
* private final int x, y;
|
||||
*
|
||||
* // ctor we wish to hook
|
||||
* Foo(int x, int y) {
|
||||
* this.x = x;
|
||||
* this.y = y;
|
||||
* }
|
||||
*}</pre>
|
||||
* </blockquote>
|
||||
*
|
||||
* <p>Valid signatures for this ctor would be:</p>
|
||||
*
|
||||
* <ul>
|
||||
* <li><tt>Lbaz/bar/Foo;</tt> - valid because Foo only has one ctor</li>
|
||||
* <li><tt>(II)Lbaz/bar/Foo;</tt> - includes signature of specific ctor</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The handler method signature must match the constructor being redirected
|
||||
* and the return type must match the type of object being constructed. For
|
||||
* example to redirect the following constructor call:</p>
|
||||
* example to redirect the following object creation call:</p>
|
||||
*
|
||||
* <blockquote><pre>public void baz(int someInt, String someString) {
|
||||
* <blockquote><pre>public void exampleFunc(String someString, int dx, int dy) {
|
||||
* // Hooking this constructor
|
||||
* Foo someObject = new Foo("bar");
|
||||
* Foo someFoo = new Foo(dx * 10, dy * 10);
|
||||
*}</pre>
|
||||
* </blockquote>
|
||||
*
|
||||
* <p>The signature of the handler method should be:</p>
|
||||
*
|
||||
* <blockquote>
|
||||
* <pre>public Foo constructFoo(String arg1)</pre>
|
||||
* <pre>public Foo constructFoo(int x, int y)</pre>
|
||||
* </blockquote>
|
||||
*
|
||||
* <p>Note that like other redirectors, it is possible to capture the target
|
||||
* method's arguments by appending them to the handler method's signature.</p>
|
||||
* method's arguments by appending them to the handler method's signature:</p>
|
||||
*
|
||||
* <h4>A note on <tt>static</tt> modifiers for handler methods</h4>
|
||||
* <blockquote>
|
||||
* <tt>public Foo constructFoo(int x, int y, String someString, int dx,
|
||||
* int dy)</tt>
|
||||
* </blockquote>
|
||||
*
|
||||
* <h3>A note on <tt>static</tt> modifiers for handler methods</h3>
|
||||
*
|
||||
* <p>In general, when declaring a redirect handler the <tt>static</tt> modifier
|
||||
* of the handler method must always match the target method. The exception to
|
||||
|
||||
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
|
||||
|
||||
@@ -123,6 +124,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
|
||||
* can distinguish different slices using {@link #id} and then specify the slice
|
||||
* to use in the {@link At#slice} argument.</p>
|
||||
*/
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Slice {
|
||||
|
||||
|
||||
@@ -531,6 +531,9 @@ public class CallbackInjector extends Injector {
|
||||
int position = callback.target.indexOf(callback.node);
|
||||
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
|
||||
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0));
|
||||
if (expected.equals(found)) {
|
||||
return String.format("Invalid descriptor on %s! Expected %s but found %s", this.info, callback.getDescriptor(), this.methodNode.desc);
|
||||
}
|
||||
return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s",
|
||||
callback.target, position, this, expected, found);
|
||||
}
|
||||
@@ -564,7 +567,7 @@ public class CallbackInjector extends Injector {
|
||||
private void printLocals(final Callback callback) {
|
||||
Type[] args = Type.getArgumentTypes(callback.getDescriptorWithAllLocals());
|
||||
SignaturePrinter methodSig = new SignaturePrinter(callback.target.method, callback.argNames);
|
||||
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, callback.target.returnType, args, callback.argNames);
|
||||
SignaturePrinter handlerSig = new SignaturePrinter(this.info.getMethodName(), callback.target.returnType, args, callback.argNames);
|
||||
handlerSig.setModifiers(this.methodNode);
|
||||
|
||||
PrettyPrinter printer = new PrettyPrinter();
|
||||
@@ -572,7 +575,7 @@ public class CallbackInjector extends Injector {
|
||||
printer.kv("Target Method", methodSig);
|
||||
printer.kv("Target Max LOCALS", callback.target.getMaxLocals());
|
||||
printer.kv("Initial Frame Size", callback.frameSize);
|
||||
printer.kv("Callback Name", this.methodNode.name);
|
||||
printer.kv("Callback Name", this.info.getMethodName());
|
||||
printer.kv("Instruction", "%s %s", callback.node.getClass().getSimpleName(),
|
||||
Bytecode.getOpcodeName(callback.node.getCurrentTarget().getOpcode()));
|
||||
printer.hr();
|
||||
|
||||
@@ -49,8 +49,8 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option;
|
||||
import org.spongepowered.asm.mixin.injection.InjectionPoint;
|
||||
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target;
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
|
||||
import org.spongepowered.asm.mixin.refmap.IMixinContext;
|
||||
@@ -161,7 +161,7 @@ public abstract class Injector {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s::%s", this.classNode.name, this.methodNode.name);
|
||||
return String.format("%s::%s", this.classNode.name, this.info.getMethodName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -377,7 +377,12 @@ public abstract class Injector {
|
||||
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
|
||||
*/
|
||||
public static boolean canCoerce(Type from, Type to) {
|
||||
if (from.getSort() == Type.OBJECT && to.getSort() == Type.OBJECT) {
|
||||
int fromSort = from.getSort();
|
||||
int toSort = to.getSort();
|
||||
if (fromSort >= Type.ARRAY && toSort >= Type.ARRAY && fromSort == toSort) {
|
||||
if (fromSort == Type.ARRAY && from.getDimensions() != to.getDimensions()) {
|
||||
return false;
|
||||
}
|
||||
return Injector.canCoerce(ClassInfo.forType(from, TypeLookup.ELEMENT_TYPE), ClassInfo.forType(to, TypeLookup.ELEMENT_TYPE));
|
||||
}
|
||||
|
||||
@@ -422,7 +427,7 @@ public abstract class Injector {
|
||||
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
|
||||
*/
|
||||
private static boolean canCoerce(ClassInfo from, ClassInfo to) {
|
||||
return from != null && to != null && (to == from || to.hasSuperClass(from, Traversal.NONE, true));
|
||||
return from != null && to != null && (to == from || to.hasSuperClass(from, Traversal.ALL, true));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -24,25 +24,95 @@
|
||||
*/
|
||||
package org.spongepowered.asm.mixin.injection.invoke;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.AnnotationNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
|
||||
import org.spongepowered.asm.mixin.injection.Coerce;
|
||||
import org.spongepowered.asm.mixin.injection.InjectionPoint;
|
||||
import org.spongepowered.asm.mixin.injection.code.Injector;
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target;
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
|
||||
import org.spongepowered.asm.util.Annotations;
|
||||
import org.spongepowered.asm.util.Bytecode;
|
||||
import org.spongepowered.asm.util.SignaturePrinter;
|
||||
|
||||
import com.google.common.collect.ObjectArrays;
|
||||
|
||||
/**
|
||||
* Base class for injectors which inject at method invokes
|
||||
*/
|
||||
public abstract class InvokeInjector extends Injector {
|
||||
|
||||
/**
|
||||
* Redirection data bundle base. No this isn't meant to be pretty, it's a
|
||||
* way of passing a bunch of state around the injector without having dumb
|
||||
* method signatures.
|
||||
*/
|
||||
static class InjectorData {
|
||||
|
||||
/**
|
||||
* Redirect target
|
||||
*/
|
||||
final Target target;
|
||||
|
||||
/**
|
||||
* Mutable description. The bundle is be passed to different types of
|
||||
* handler and the handler decorates the bundle with a description of
|
||||
* the <em>type</em> of injection, purely for use in error messages.
|
||||
*/
|
||||
String description;
|
||||
|
||||
/**
|
||||
* When passing through {@link RedirectInjector#validateParams} this
|
||||
* switch determines whether coercion is supported for both the primary
|
||||
* handler args and captured target args, or for target args only.
|
||||
*/
|
||||
boolean allowCoerceArgs;
|
||||
|
||||
/**
|
||||
* Number of arguments to capture from the target, determined by the
|
||||
* number of extra args on the handler method
|
||||
*/
|
||||
int captureTargetArgs = 0;
|
||||
|
||||
/**
|
||||
* True if the method itself is decorated with {@link Coerce} and the
|
||||
* return type is coerced. Instructs the injector to add a CHECKCAST
|
||||
* following the handler.
|
||||
*/
|
||||
boolean coerceReturnType = false;
|
||||
|
||||
InjectorData(Target target) {
|
||||
this(target, "handler");
|
||||
}
|
||||
|
||||
InjectorData(Target target, String description) {
|
||||
this(target, description, true);
|
||||
}
|
||||
|
||||
InjectorData(Target target, String description, boolean allowCoerceArgs) {
|
||||
this.target = target;
|
||||
this.description = description;
|
||||
this.allowCoerceArgs = allowCoerceArgs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.description;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param info Information about this injection
|
||||
@@ -154,6 +224,7 @@ public abstract class InvokeInjector extends Injector {
|
||||
|
||||
/**
|
||||
* Load args onto the stack from their positions allocated in argMap
|
||||
*
|
||||
* @param args argument types
|
||||
* @param insns instruction list to generate insns into
|
||||
* @param argMap generated argmap containing local indices for all args
|
||||
@@ -161,8 +232,134 @@ public abstract class InvokeInjector extends Injector {
|
||||
* @param end Ending index
|
||||
*/
|
||||
protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
|
||||
for (int arg = start; arg < end; arg++) {
|
||||
this.pushArgs(args, insns, argMap, start, end, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load args onto the stack from their positions allocated in argMap
|
||||
*
|
||||
* @param args argument types
|
||||
* @param insns instruction list to generate insns into
|
||||
* @param argMap generated argmap containing local indices for all args
|
||||
* @param start Starting index
|
||||
* @param end Ending index
|
||||
*/
|
||||
protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end, Extension extension) {
|
||||
for (int arg = start; arg < end && arg < args.length; arg++) {
|
||||
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg]));
|
||||
if (extension != null) {
|
||||
extension.add(args[arg].getSize());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all the logic from old validateParams/checkDescriptor so that we
|
||||
* can consistently apply coercion logic to method params, and also provide
|
||||
* more detailed errors when something doesn't line up.
|
||||
*
|
||||
* <p>The supplied return type and argument list will be verified first. Any
|
||||
* arguments on the handler beyond the base arguments consume arguments from
|
||||
* the target. The flag <tt>allowCoerceArgs</tt> on the <tt>redirect</tt>
|
||||
* instance determines whether coercion is supported for the base args and
|
||||
* return type, coercion is always allowed for captured target args.</p>
|
||||
*
|
||||
* <p>Following validation, the <tt>captureTargetArgs</tt> and
|
||||
* <tt>coerceReturnType</tt> values will be set on the bundle and the
|
||||
* calling injector function should adjust itself accordingly.</p>
|
||||
*
|
||||
* @param injector Data bundle for the injector
|
||||
* @param returnType Return type for the handler, must not be null
|
||||
* @param args Array of handler args, must not be null
|
||||
*/
|
||||
protected final void validateParams(InjectorData injector, Type returnType, Type... args) {
|
||||
String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext());
|
||||
int argIndex = 0;
|
||||
try {
|
||||
injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs);
|
||||
|
||||
for (Type arg : args) {
|
||||
if (arg != null) {
|
||||
this.checkCoerce(argIndex, arg, description, injector.allowCoerceArgs);
|
||||
argIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
if (argIndex == this.methodArgs.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int targetArg = 0; targetArg < injector.target.arguments.length && argIndex < this.methodArgs.length; targetArg++, argIndex++) {
|
||||
this.checkCoerce(argIndex, injector.target.arguments[targetArg], description, true);
|
||||
injector.captureTargetArgs++;
|
||||
}
|
||||
} catch (InvalidInjectionException ex) {
|
||||
String expected = this.methodArgs.length > args.length
|
||||
? Bytecode.generateDescriptor(returnType, ObjectArrays.concat(args, injector.target.arguments, Type.class))
|
||||
: Bytecode.generateDescriptor(returnType, args);
|
||||
throw new InvalidInjectionException(this.info, String.format("%s. Handler signature: %s Expected signature: %s", ex.getMessage(),
|
||||
this.methodNode.desc, expected));
|
||||
}
|
||||
|
||||
if (argIndex < this.methodArgs.length) {
|
||||
Type[] extraArgs = Arrays.copyOfRange(this.methodArgs, argIndex, this.methodArgs.length);
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Found %d unexpected additional method arguments: %s",
|
||||
description, this.methodArgs.length - argIndex, new SignaturePrinter(extraArgs).getFormattedArgs()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called inside {@link #validateParams} but can also be used directly. This
|
||||
* method checks whether the supplied type is compatible with the specified
|
||||
* handler argument, apply coercion logic where necessary.
|
||||
*
|
||||
* @param index Handler argument index, pass in a negative value (by
|
||||
* convention -1) to specify handler return type
|
||||
* @param toType Desired type based on the injector contract
|
||||
* @param description human-readable description of the handler method, used
|
||||
* in raised exception
|
||||
* @param allowCoercion True if coercion logic can be applied to this
|
||||
* argument, false to only allow a precise match
|
||||
* @return <tt>false</tt> if the argument matched perfectly, <tt>true</tt>
|
||||
* if coercion is required for the argument
|
||||
*/
|
||||
protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) {
|
||||
Type fromType = index < 0 ? this.returnType : this.methodArgs[index];
|
||||
if (index >= this.methodArgs.length) {
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Not enough arguments: expected argument type %s at index %d",
|
||||
description, SignaturePrinter.getTypeName(toType), index));
|
||||
}
|
||||
|
||||
AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index);
|
||||
boolean isReturn = index < 0;
|
||||
String argType = isReturn ? "return" : "argument";
|
||||
Object argIndex = isReturn ? "" : " at index " + index;
|
||||
|
||||
if (fromType.equals(toType)) {
|
||||
if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
|
||||
Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex,
|
||||
SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (coerce == null || !allowCoercion) {
|
||||
String coerceWarning = coerce != null ? ". @Coerce not allowed here" : "";
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Found unexpected %s type %s%s, expected %s%s", description, argType,
|
||||
SignaturePrinter.getTypeName(fromType), argIndex, SignaturePrinter.getTypeName(toType), coerceWarning));
|
||||
}
|
||||
|
||||
boolean canCoerce = Injector.canCoerce(fromType, toType);
|
||||
if (!canCoerce) {
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Cannot @Coerce %s type %s%s to %s", description, argType,
|
||||
SignaturePrinter.getTypeName(toType), argIndex, SignaturePrinter.getTypeName(fromType)));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
+10
-5
@@ -33,6 +33,7 @@ import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.JumpInsnNode;
|
||||
import org.objectweb.asm.tree.LocalVariableNode;
|
||||
import org.objectweb.asm.tree.TypeInsnNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
|
||||
import org.spongepowered.asm.mixin.injection.code.Injector;
|
||||
@@ -82,6 +83,11 @@ public class ModifyConstantInjector extends RedirectInjector {
|
||||
return;
|
||||
}
|
||||
|
||||
if (targetNode instanceof TypeInsnNode) {
|
||||
// TODO inject at type constant
|
||||
throw new InvalidInjectionException(this.info, "Inject at TypeInsnNode not implemented");
|
||||
}
|
||||
|
||||
if (Bytecode.isConstant(targetNode)) {
|
||||
this.checkTargetModifiers(target, false);
|
||||
this.injectConstantModifier(target, targetNode);
|
||||
@@ -130,17 +136,16 @@ public class ModifyConstantInjector extends RedirectInjector {
|
||||
}
|
||||
|
||||
private AbstractInsnNode invokeConstantHandler(Type constantType, Target target, Extension extraStack, InsnList before, InsnList after) {
|
||||
final String handlerDesc = Bytecode.generateDescriptor(constantType, constantType);
|
||||
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
|
||||
InjectorData handler = new InjectorData(target, "constant modifier");
|
||||
this.validateParams(handler, constantType, constantType);
|
||||
|
||||
if (!this.isStatic) {
|
||||
before.insert(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
extraStack.add();
|
||||
}
|
||||
|
||||
if (withArgs) {
|
||||
this.pushArgs(target.arguments, after, target.getArgIndices(), 0, target.arguments.length);
|
||||
extraStack.add(target.arguments);
|
||||
if (handler.captureTargetArgs > 0) {
|
||||
this.pushArgs(target.arguments, after, target.getArgIndices(), 0, handler.captureTargetArgs, extraStack);
|
||||
}
|
||||
|
||||
return this.invokeHandler(after);
|
||||
|
||||
+190
-213
@@ -31,26 +31,31 @@ import java.util.Set;
|
||||
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.*;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.FieldInsnNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.InsnNode;
|
||||
import org.objectweb.asm.tree.JumpInsnNode;
|
||||
import org.objectweb.asm.tree.LabelNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.TypeInsnNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
|
||||
import org.spongepowered.asm.mixin.injection.Coerce;
|
||||
import org.spongepowered.asm.mixin.injection.InjectionPoint;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
import org.spongepowered.asm.mixin.injection.code.Injector;
|
||||
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
|
||||
import org.spongepowered.asm.mixin.injection.points.BeforeNew;
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target;
|
||||
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
|
||||
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
|
||||
import org.spongepowered.asm.util.Annotations;
|
||||
import org.spongepowered.asm.util.Bytecode;
|
||||
import org.spongepowered.asm.util.Constants;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.collect.ObjectArrays;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
@@ -90,6 +95,8 @@ import com.google.common.primitives.Ints;
|
||||
*/
|
||||
public class RedirectInjector extends InvokeInjector {
|
||||
|
||||
private static final String NPE = "java/lang/NullPointerException";
|
||||
|
||||
private static final String KEY_NOMINATORS = "nominators";
|
||||
private static final String KEY_FUZZ = "fuzz";
|
||||
private static final String KEY_OPCODE = "opcode";
|
||||
@@ -129,36 +136,94 @@ public class RedirectInjector extends InvokeInjector {
|
||||
|
||||
public static final String KEY = "ctor";
|
||||
|
||||
public boolean wildcard = false;
|
||||
boolean wildcard = false;
|
||||
|
||||
public int injected = 0;
|
||||
int injected = 0;
|
||||
|
||||
InvalidInjectionException lastException;
|
||||
|
||||
public void throwOrCollect(InvalidInjectionException ex) {
|
||||
if (!this.wildcard) {
|
||||
throw ex;
|
||||
}
|
||||
this.lastException = ex;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Data bundle for invoke redirectors
|
||||
*/
|
||||
static class RedirectedInvoke {
|
||||
static class RedirectedInvokeData extends InjectorData {
|
||||
|
||||
final Target target;
|
||||
final MethodInsnNode node;
|
||||
final Type returnType;
|
||||
final Type[] args;
|
||||
final Type[] locals;
|
||||
final Type[] targetArgs;
|
||||
final Type[] handlerArgs;
|
||||
|
||||
boolean captureTargetArgs = false;
|
||||
|
||||
RedirectedInvoke(Target target, MethodInsnNode node) {
|
||||
this.target = target;
|
||||
RedirectedInvokeData(Target target, MethodInsnNode node) {
|
||||
super(target);
|
||||
this.node = node;
|
||||
this.returnType = Type.getReturnType(node.desc);
|
||||
this.args = Type.getArgumentTypes(node.desc);
|
||||
this.locals = node.getOpcode() == Opcodes.INVOKESTATIC
|
||||
? this.args
|
||||
: ObjectArrays.concat(Type.getType("L" + node.owner + ";"), this.args);
|
||||
this.targetArgs = Type.getArgumentTypes(node.desc);
|
||||
this.handlerArgs = node.getOpcode() == Opcodes.INVOKESTATIC
|
||||
? this.targetArgs
|
||||
: ObjectArrays.concat(Type.getObjectType(node.owner), this.targetArgs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Data bundle for field redirectors
|
||||
*/
|
||||
static class RedirectedFieldData extends InjectorData {
|
||||
|
||||
final FieldInsnNode node;
|
||||
final int opcode;
|
||||
final Type owner;
|
||||
final Type type;
|
||||
final int dimensions;
|
||||
final boolean isStatic;
|
||||
final boolean isGetter;
|
||||
final boolean isSetter;
|
||||
|
||||
// This is actually the return type for array access, might be int for
|
||||
// array length redirectors
|
||||
Type elementType;
|
||||
int extraDimensions = 1;
|
||||
|
||||
RedirectedFieldData(Target target, FieldInsnNode node) {
|
||||
super(target);
|
||||
this.node = node;
|
||||
this.opcode = node.getOpcode();
|
||||
this.owner = Type.getObjectType(node.owner);
|
||||
this.type = Type.getType(node.desc);
|
||||
this.dimensions = (this.type.getSort() == Type.ARRAY) ? this.type.getDimensions() : 0;
|
||||
this.isStatic = this.opcode == Opcodes.GETSTATIC || this.opcode == Opcodes.PUTSTATIC;
|
||||
this.isGetter = this.opcode == Opcodes.GETSTATIC || this.opcode == Opcodes.GETFIELD;
|
||||
this.isSetter = this.opcode == Opcodes.PUTSTATIC || this.opcode == Opcodes.PUTFIELD;
|
||||
this.description = this.isGetter ? "field getter" : this.isSetter ? "field setter" : "handler";
|
||||
}
|
||||
|
||||
int getTotalDimensions() {
|
||||
return this.dimensions + this.extraDimensions;
|
||||
}
|
||||
|
||||
Type[] getArrayArgs(Type... extra) {
|
||||
int dimensions = this.getTotalDimensions();
|
||||
Type[] args = new Type[dimensions + extra.length];
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] = i == 0 ? this.type : i < dimensions ? Type.INT_TYPE : extra[dimensions - i];
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Meta is used to decorate the target node with information about this
|
||||
* injection
|
||||
*/
|
||||
protected Meta meta;
|
||||
|
||||
private Map<BeforeNew, ConstructorRedirectData> ctorRedirectors = new HashMap<BeforeNew, ConstructorRedirectData>();
|
||||
@@ -297,7 +362,8 @@ public class RedirectInjector extends InvokeInjector {
|
||||
if (node.getOriginalTarget() instanceof TypeInsnNode && node.getOriginalTarget().getOpcode() == Opcodes.NEW) {
|
||||
ConstructorRedirectData meta = node.<ConstructorRedirectData>getDecoration(ConstructorRedirectData.KEY);
|
||||
if (meta.wildcard && meta.injected == 0) {
|
||||
throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target));
|
||||
throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target),
|
||||
meta.lastException);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,150 +373,99 @@ public class RedirectInjector extends InvokeInjector {
|
||||
*/
|
||||
@Override
|
||||
protected void injectAtInvoke(Target target, InjectionNode node) {
|
||||
RedirectedInvoke invoke = new RedirectedInvoke(target, (MethodInsnNode)node.getCurrentTarget());
|
||||
RedirectedInvokeData invoke = new RedirectedInvokeData(target, (MethodInsnNode)node.getCurrentTarget());
|
||||
|
||||
this.validateParams(invoke);
|
||||
this.validateParams(invoke, invoke.returnType, invoke.handlerArgs);
|
||||
|
||||
InsnList insns = new InsnList();
|
||||
Extension extraLocals = target.extendLocals().add(invoke.locals).add(1);
|
||||
Extension extraLocals = target.extendLocals().add(invoke.handlerArgs).add(1);
|
||||
Extension extraStack = target.extendStack().add(1); // Normally only need 1 extra stack pos to store target ref
|
||||
int[] argMap = this.storeArgs(target, invoke.locals, insns, 0);
|
||||
if (invoke.captureTargetArgs) {
|
||||
int argSize = Bytecode.getArgsSize(target.arguments);
|
||||
int[] argMap = this.storeArgs(target, invoke.handlerArgs, insns, 0);
|
||||
if (invoke.captureTargetArgs > 0) {
|
||||
int argSize = Bytecode.getArgsSize(target.arguments, 0, invoke.captureTargetArgs);
|
||||
extraLocals.add(argSize);
|
||||
extraStack.add(argSize);
|
||||
// No need to truncate target arg indices, pushArgs ignores args which don't exist
|
||||
argMap = Ints.concat(argMap, target.getArgIndices());
|
||||
}
|
||||
AbstractInsnNode insn = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
|
||||
target.replaceNode(invoke.node, insn, insns);
|
||||
AbstractInsnNode champion = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
|
||||
if (invoke.coerceReturnType && invoke.returnType.getSort() >= Type.ARRAY) {
|
||||
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, invoke.returnType.getInternalName()));
|
||||
}
|
||||
target.replaceNode(invoke.node, champion, insns);
|
||||
extraLocals.apply();
|
||||
extraStack.apply();
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform validation of an invoke handler parameters, each parameter in the
|
||||
* handler must match the expected type or be annotated with {@link Coerce}
|
||||
* and be a supported supertype of the incoming type.
|
||||
*
|
||||
* @param invoke invocation being redirected
|
||||
*/
|
||||
protected void validateParams(RedirectedInvoke invoke) {
|
||||
int argc = this.methodArgs.length;
|
||||
|
||||
String description = String.format("%s handler method %s", this.annotationType, this);
|
||||
if (!invoke.returnType.equals(this.returnType)) {
|
||||
throw new InvalidInjectionException(this.info, String.format("%s has an invalid signature. Expected return type %s found %s",
|
||||
description, this.returnType, invoke.returnType));
|
||||
}
|
||||
|
||||
for (int index = 0; index < argc; index++) {
|
||||
Type toType = null;
|
||||
if (index >= this.methodArgs.length) {
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Not enough arguments found for capture of target method args, expected %d but found %d",
|
||||
description, argc, this.methodArgs.length));
|
||||
}
|
||||
|
||||
Type fromType = this.methodArgs[index];
|
||||
|
||||
if (index < invoke.locals.length) {
|
||||
toType = invoke.locals[index];
|
||||
} else {
|
||||
invoke.captureTargetArgs = true;
|
||||
argc = Math.max(argc, invoke.locals.length + invoke.target.arguments.length);
|
||||
int arg = index - invoke.locals.length;
|
||||
if (arg >= invoke.target.arguments.length) {
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Found unexpected additional target argument with type %s at index %d",
|
||||
description, fromType, index));
|
||||
}
|
||||
toType = invoke.target.arguments[arg];
|
||||
}
|
||||
|
||||
AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index);
|
||||
|
||||
if (fromType.equals(toType)) {
|
||||
if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
|
||||
Injector.logger.warn("Redundant @Coerce on {} argument {}, {} is identical to {}", description, index, toType, fromType);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean canCoerce = Injector.canCoerce(fromType, toType);
|
||||
if (coerce == null) {
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Found unexpected argument type %s at index %d, expected %s",
|
||||
description, fromType, index, toType));
|
||||
}
|
||||
|
||||
if (!canCoerce) {
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"%s has an invalid signature. Cannot @Coerce argument type %s at index %d to %s",
|
||||
description, toType, index, fromType));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect a field get or set operation, or an array element access
|
||||
*/
|
||||
private void injectAtFieldAccess(Target target, InjectionNode node) {
|
||||
final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget();
|
||||
final int opCode = fieldNode.getOpcode();
|
||||
final Type ownerType = Type.getType("L" + fieldNode.owner + ";");
|
||||
final Type fieldType = Type.getType(fieldNode.desc);
|
||||
RedirectedFieldData field = new RedirectedFieldData(target, (FieldInsnNode)node.getCurrentTarget());
|
||||
|
||||
int targetDimensions = (fieldType.getSort() == Type.ARRAY) ? fieldType.getDimensions() : 0;
|
||||
int handlerDimensions = (this.returnType.getSort() == Type.ARRAY) ? this.returnType.getDimensions() : 0;
|
||||
|
||||
if (handlerDimensions > targetDimensions) {
|
||||
if (handlerDimensions > field.dimensions) {
|
||||
throw new InvalidInjectionException(this.info, "Dimensionality of handler method is greater than target array on " + this);
|
||||
} else if (handlerDimensions == 0 && targetDimensions > 0) {
|
||||
} else if (handlerDimensions == 0 && field.dimensions > 0) {
|
||||
int fuzz = node.<Integer>getDecoration(RedirectInjector.KEY_FUZZ).intValue();
|
||||
int opcode = node.<Integer>getDecoration(RedirectInjector.KEY_OPCODE).intValue();
|
||||
this.injectAtArrayField(target, fieldNode, opCode, ownerType, fieldType, fuzz, opcode);
|
||||
this.injectAtArrayField(field, fuzz, opcode);
|
||||
} else {
|
||||
this.injectAtScalarField(target, fieldNode, opCode, ownerType, fieldType);
|
||||
this.injectAtScalarField(field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect an array element access
|
||||
*/
|
||||
private void injectAtArrayField(Target target, FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType, int fuzz, int opcode) {
|
||||
Type elementType = fieldType.getElementType();
|
||||
if (opCode != Opcodes.GETSTATIC && opCode != Opcodes.GETFIELD) {
|
||||
private void injectAtArrayField(RedirectedFieldData field, int fuzz, int opcode) {
|
||||
Type elementType = field.type.getElementType();
|
||||
if (field.opcode != Opcodes.GETSTATIC && field.opcode != Opcodes.GETFIELD) {
|
||||
throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for array access %s",
|
||||
Bytecode.getOpcodeName(opCode), this.info));
|
||||
Bytecode.getOpcodeName(field.opcode), this.info));
|
||||
} else if (this.returnType.getSort() != Type.VOID) {
|
||||
if (opcode != Opcodes.ARRAYLENGTH) {
|
||||
opcode = elementType.getOpcode(Opcodes.IALOAD);
|
||||
}
|
||||
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, opcode, fuzz);
|
||||
this.injectAtGetArray(target, fieldNode, varNode, ownerType, fieldType);
|
||||
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(field.target.insns, field.node, opcode, fuzz);
|
||||
this.injectAtGetArray(field, varNode);
|
||||
} else {
|
||||
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, elementType.getOpcode(Opcodes.IASTORE), fuzz);
|
||||
this.injectAtSetArray(target, fieldNode, varNode, ownerType, fieldType);
|
||||
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(field.target.insns, field.node, elementType.getOpcode(Opcodes.IASTORE), fuzz);
|
||||
this.injectAtSetArray(field, varNode);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Array element read (xALOAD) or array.length (ARRAYLENGTH)
|
||||
*/
|
||||
private void injectAtGetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) {
|
||||
String handlerDesc = RedirectInjector.getGetArrayHandlerDescriptor(varNode, this.returnType, fieldType);
|
||||
boolean withArgs = this.checkDescriptor(handlerDesc, target, "array getter");
|
||||
this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array getter");
|
||||
private void injectAtGetArray(RedirectedFieldData field, AbstractInsnNode varNode) {
|
||||
field.description = "array getter";
|
||||
field.elementType = field.type.getElementType();
|
||||
|
||||
if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) {
|
||||
field.elementType = Type.INT_TYPE;
|
||||
field.extraDimensions = 0;
|
||||
}
|
||||
|
||||
this.validateParams(field, field.elementType, field.getArrayArgs());
|
||||
this.injectArrayRedirect(field, varNode, "array getter");
|
||||
}
|
||||
|
||||
/**
|
||||
* Array element write (xASTORE)
|
||||
*/
|
||||
private void injectAtSetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) {
|
||||
String handlerDesc = Bytecode.generateDescriptor(null, (Object[])RedirectInjector.getArrayArgs(fieldType, 1, fieldType.getElementType()));
|
||||
boolean withArgs = this.checkDescriptor(handlerDesc, target, "array setter");
|
||||
this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array setter");
|
||||
private void injectAtSetArray(RedirectedFieldData field, AbstractInsnNode varNode) {
|
||||
field.description = "array setter";
|
||||
Type elementType = field.type.getElementType();
|
||||
int valueArgIndex = field.getTotalDimensions();
|
||||
if (this.checkCoerce(valueArgIndex, elementType, String.format("%s array setter method %s from %s",
|
||||
this.annotationType, this, this.info.getContext()), true)) {
|
||||
elementType = this.methodArgs[valueArgIndex];
|
||||
}
|
||||
|
||||
this.validateParams(field, Type.VOID_TYPE, field.getArrayArgs(elementType));
|
||||
this.injectArrayRedirect(field, varNode, "array setter");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -459,35 +474,38 @@ public class RedirectInjector extends InvokeInjector {
|
||||
* actual handler signature, the correct arguments are already on the stack
|
||||
* thanks to the nature of xALOAD and xASTORE.
|
||||
*
|
||||
* @param varNode array access node
|
||||
* @param type description of access type for use in error messages
|
||||
* @param target target method
|
||||
* @param fieldNode field node
|
||||
* @param varNode array access node
|
||||
* @param withArgs true if the descriptor includes captured arguments from
|
||||
* the target method signature
|
||||
* @param type description of access type for use in error messages
|
||||
*/
|
||||
private void injectArrayRedirect(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, boolean withArgs, String type) {
|
||||
private void injectArrayRedirect(RedirectedFieldData field, AbstractInsnNode varNode, String type) {
|
||||
if (varNode == null) {
|
||||
String advice = "";
|
||||
throw new InvalidInjectionException(this.info, String.format(
|
||||
"Array element %s on %s could not locate a matching %s instruction in %s. %s",
|
||||
this.annotationType, this, type, target, advice));
|
||||
this.annotationType, this, type, field.target, advice));
|
||||
}
|
||||
|
||||
Extension extraStack = target.extendStack();
|
||||
Extension extraStack = field.target.extendStack();
|
||||
|
||||
if (!this.isStatic) {
|
||||
target.insns.insertBefore(fieldNode, new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
VarInsnNode loadThis = new VarInsnNode(Opcodes.ALOAD, 0);
|
||||
field.target.insns.insert(field.node, loadThis);
|
||||
field.target.insns.insert(loadThis, new InsnNode(Opcodes.SWAP));
|
||||
extraStack.add();
|
||||
}
|
||||
|
||||
InsnList invokeInsns = new InsnList();
|
||||
if (withArgs) {
|
||||
this.pushArgs(target.arguments, invokeInsns, target.getArgIndices(), 0, target.arguments.length);
|
||||
extraStack.add(target.arguments);
|
||||
InsnList insns = new InsnList();
|
||||
if (field.captureTargetArgs > 0) {
|
||||
this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack);
|
||||
}
|
||||
extraStack.apply();
|
||||
target.replaceNode(varNode, this.invokeHandler(invokeInsns), invokeInsns);
|
||||
AbstractInsnNode champion = this.invokeHandler(insns);
|
||||
if (field.coerceReturnType && field.type.getSort() >= Type.ARRAY) {
|
||||
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, field.elementType.getInternalName()));
|
||||
}
|
||||
field.target.replaceNode(varNode, champion, insns);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -499,18 +517,19 @@ public class RedirectInjector extends InvokeInjector {
|
||||
* @param ownerType type of the field owner
|
||||
* @param fieldType field type
|
||||
*/
|
||||
private void injectAtScalarField(Target target, final FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType) {
|
||||
private void injectAtScalarField(RedirectedFieldData field) {
|
||||
AbstractInsnNode invoke = null;
|
||||
InsnList insns = new InsnList();
|
||||
if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) {
|
||||
invoke = this.injectAtGetField(insns, target, fieldNode, opCode == Opcodes.GETSTATIC, ownerType, fieldType);
|
||||
} else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) {
|
||||
invoke = this.injectAtPutField(insns, target, fieldNode, opCode == Opcodes.PUTSTATIC, ownerType, fieldType);
|
||||
if (field.isGetter) {
|
||||
invoke = this.injectAtGetField(field, insns);
|
||||
} else if (field.isSetter) {
|
||||
invoke = this.injectAtPutField(field, insns);
|
||||
} else {
|
||||
throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for %s", Bytecode.getOpcodeName(opCode), this.info));
|
||||
throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for %s",
|
||||
Bytecode.getOpcodeName(field.opcode), this.info));
|
||||
}
|
||||
|
||||
target.replaceNode(fieldNode, invoke, insns);
|
||||
field.target.replaceNode(field.node, invoke, insns);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -519,27 +538,29 @@ public class RedirectInjector extends InvokeInjector {
|
||||
* possible scenarios based on the possible combinations of static on the
|
||||
* handler and the field itself.
|
||||
*/
|
||||
private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
|
||||
final String handlerDesc = staticField ? Bytecode.generateDescriptor(fieldType) : Bytecode.generateDescriptor(fieldType, owner);
|
||||
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
|
||||
private AbstractInsnNode injectAtGetField(RedirectedFieldData field, InsnList insns) {
|
||||
this.validateParams(field, field.type, field.isStatic ? null : field.owner);
|
||||
|
||||
Extension extraStack = target.extendStack();
|
||||
Extension extraStack = field.target.extendStack();
|
||||
|
||||
if (!this.isStatic) {
|
||||
extraStack.add();
|
||||
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
if (!staticField) {
|
||||
if (!field.isStatic) {
|
||||
insns.add(new InsnNode(Opcodes.SWAP));
|
||||
}
|
||||
}
|
||||
|
||||
if (withArgs) {
|
||||
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length);
|
||||
extraStack.add(target.arguments);
|
||||
if (field.captureTargetArgs > 0) {
|
||||
this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack);
|
||||
}
|
||||
|
||||
extraStack.apply();
|
||||
return this.invokeHandler(insns);
|
||||
AbstractInsnNode champion = this.invokeHandler(insns);
|
||||
if (field.coerceReturnType && field.type.getSort() >= Type.ARRAY) {
|
||||
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, field.type.getInternalName()));
|
||||
}
|
||||
return champion;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -548,60 +569,33 @@ public class RedirectInjector extends InvokeInjector {
|
||||
* possible scenarios based on the possible combinations of static on the
|
||||
* handler and the field itself.
|
||||
*/
|
||||
private AbstractInsnNode injectAtPutField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
|
||||
String handlerDesc = staticField ? Bytecode.generateDescriptor(null, fieldType) : Bytecode.generateDescriptor(null, owner, fieldType);
|
||||
boolean withArgs = this.checkDescriptor(handlerDesc, target, "setter");
|
||||
private AbstractInsnNode injectAtPutField(RedirectedFieldData field, InsnList insns) {
|
||||
this.validateParams(field, Type.VOID_TYPE, field.isStatic ? null : field.owner, field.type);
|
||||
|
||||
Extension extraStack = target.extendStack();
|
||||
Extension extraStack = field.target.extendStack();
|
||||
|
||||
if (!this.isStatic) {
|
||||
if (staticField) {
|
||||
if (field.isStatic) {
|
||||
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
insns.add(new InsnNode(Opcodes.SWAP));
|
||||
} else {
|
||||
extraStack.add();
|
||||
int marshallVar = target.allocateLocals(fieldType.getSize());
|
||||
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ISTORE), marshallVar));
|
||||
int marshallVar = field.target.allocateLocals(field.type.getSize());
|
||||
insns.add(new VarInsnNode(field.type.getOpcode(Opcodes.ISTORE), marshallVar));
|
||||
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
|
||||
insns.add(new InsnNode(Opcodes.SWAP));
|
||||
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ILOAD), marshallVar));
|
||||
insns.add(new VarInsnNode(field.type.getOpcode(Opcodes.ILOAD), marshallVar));
|
||||
}
|
||||
}
|
||||
|
||||
if (withArgs) {
|
||||
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length);
|
||||
extraStack.add(target.arguments);
|
||||
if (field.captureTargetArgs > 0) {
|
||||
this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack);
|
||||
}
|
||||
|
||||
extraStack.apply();
|
||||
return this.invokeHandler(insns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the handler descriptor matches the calculated descriptor for
|
||||
* the access being redirected.
|
||||
*
|
||||
* @param desc computed descriptor
|
||||
* @param target target method
|
||||
* @param type redirector type in human-readable text, for error messages
|
||||
* @return true if the descriptor was found and includes target method args,
|
||||
* false if the descriptor was found and does not capture target args
|
||||
*/
|
||||
protected boolean checkDescriptor(String desc, Target target, String type) {
|
||||
if (this.methodNode.desc.equals(desc)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int pos = desc.indexOf(')');
|
||||
String alternateDesc = String.format("%s%s%s", desc.substring(0, pos), Joiner.on("").join(target.arguments), desc.substring(pos));
|
||||
if (this.methodNode.desc.equals(alternateDesc)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new InvalidInjectionException(this.info, String.format("%s method %s %s has an invalid signature. Expected %s but found %s",
|
||||
this.annotationType, type, this, desc, this.methodNode.desc));
|
||||
}
|
||||
|
||||
protected void injectAtConstructor(Target target, InjectionNode node) {
|
||||
ConstructorRedirectData meta = node.<ConstructorRedirectData>getDecoration(ConstructorRedirectData.KEY);
|
||||
|
||||
@@ -616,22 +610,19 @@ public class RedirectInjector extends InvokeInjector {
|
||||
final MethodInsnNode initNode = target.findInitNodeFor(newNode);
|
||||
|
||||
if (initNode == null) {
|
||||
if (!meta.wildcard) {
|
||||
throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target));
|
||||
}
|
||||
meta.throwOrCollect(new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s",
|
||||
this.annotationType, target)));
|
||||
return;
|
||||
}
|
||||
|
||||
// True if the result of the object construction is being assigned
|
||||
boolean isAssigned = dupNode.getOpcode() == Opcodes.DUP;
|
||||
String desc = initNode.desc.replace(")V", ")L" + newNode.desc + ";");
|
||||
boolean withArgs = false;
|
||||
RedirectedInvokeData ctor = new RedirectedInvokeData(target, initNode);
|
||||
ctor.description = "factory";
|
||||
try {
|
||||
withArgs = this.checkDescriptor(desc, target, "constructor");
|
||||
this.validateParams(ctor, Type.getObjectType(newNode.desc), ctor.targetArgs);
|
||||
} catch (InvalidInjectionException ex) {
|
||||
if (!meta.wildcard) {
|
||||
throw ex;
|
||||
}
|
||||
meta.throwOrCollect(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -647,12 +638,14 @@ public class RedirectInjector extends InvokeInjector {
|
||||
|
||||
Extension extraStack = target.extendStack();
|
||||
InsnList insns = new InsnList();
|
||||
if (withArgs) {
|
||||
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length);
|
||||
extraStack.add(target.arguments);
|
||||
if (ctor.captureTargetArgs > 0) {
|
||||
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, ctor.captureTargetArgs, extraStack);
|
||||
}
|
||||
|
||||
this.invokeHandler(insns);
|
||||
if (ctor.coerceReturnType) {
|
||||
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, newNode.desc));
|
||||
}
|
||||
extraStack.apply();
|
||||
|
||||
if (isAssigned) {
|
||||
@@ -662,7 +655,7 @@ public class RedirectInjector extends InvokeInjector {
|
||||
LabelNode nullCheckSucceeded = new LabelNode();
|
||||
insns.add(new InsnNode(Opcodes.DUP));
|
||||
insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded));
|
||||
this.throwException(insns, "java/lang/NullPointerException", String.format("%s constructor handler %s returned null for %s",
|
||||
this.throwException(insns, RedirectInjector.NPE, String.format("%s constructor handler %s returned null for %s",
|
||||
this.annotationType, this, newNode.desc.replace('/', '.')));
|
||||
insns.add(nullCheckSucceeded);
|
||||
extraStack.add();
|
||||
@@ -676,20 +669,4 @@ public class RedirectInjector extends InvokeInjector {
|
||||
meta.injected++;
|
||||
}
|
||||
|
||||
private static String getGetArrayHandlerDescriptor(AbstractInsnNode varNode, Type returnType, Type fieldType) {
|
||||
if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) {
|
||||
return Bytecode.generateDescriptor(Type.INT_TYPE, (Object[])RedirectInjector.getArrayArgs(fieldType, 0));
|
||||
}
|
||||
return Bytecode.generateDescriptor(returnType, (Object[])RedirectInjector.getArrayArgs(fieldType, 1));
|
||||
}
|
||||
|
||||
private static Type[] getArrayArgs(Type fieldType, int extraDimensions, Type... extra) {
|
||||
int dimensions = fieldType.getDimensions() + extraDimensions;
|
||||
Type[] args = new Type[dimensions + extra.length];
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
args[i] = i == 0 ? fieldType : i < dimensions ? Type.INT_TYPE : extra[dimensions - i];
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
}
|
||||
+6
-5
@@ -147,7 +147,7 @@ public class ModifyVariableInjector extends Injector {
|
||||
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
|
||||
|
||||
if (this.discriminator.printLVT()) {
|
||||
this.printLocals(context);
|
||||
this.printLocals(target, context);
|
||||
}
|
||||
|
||||
String handlerDesc = Bytecode.getDescriptor(new Type[] { this.returnType }, this.returnType);
|
||||
@@ -178,17 +178,18 @@ public class ModifyVariableInjector extends Injector {
|
||||
/**
|
||||
* Pretty-print local variable information to stderr
|
||||
*/
|
||||
private void printLocals(final Context context) {
|
||||
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, this.returnType, this.methodArgs, new String[] { "var" });
|
||||
private void printLocals(Target target, Context context) {
|
||||
SignaturePrinter handlerSig = new SignaturePrinter(this.info.getMethodName(), this.returnType, this.methodArgs, new String[] { "var" });
|
||||
handlerSig.setModifiers(this.methodNode);
|
||||
|
||||
new PrettyPrinter()
|
||||
.kvWidth(20)
|
||||
.kv("Target Class", this.classNode.name.replace('/', '.'))
|
||||
.kv("Target Method", context.target.method.name)
|
||||
.kv("Callback Name", this.methodNode.name)
|
||||
.kv("Callback Name", this.info.getMethodName())
|
||||
.kv("Capture Type", SignaturePrinter.getTypeName(this.returnType, false))
|
||||
.kv("Instruction", "%s %s", context.node.getClass().getSimpleName(), Bytecode.getOpcodeName(context.node.getOpcode())).hr()
|
||||
.kv("Instruction", "[%d] %s %s", target.insns.indexOf(context.node), context.node.getClass().getSimpleName(),
|
||||
Bytecode.getOpcodeName(context.node.getOpcode())).hr()
|
||||
.kv("Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)")
|
||||
.kv("Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal())
|
||||
.kv("Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex())
|
||||
|
||||
@@ -35,7 +35,7 @@ import org.spongepowered.asm.util.asm.ElementNode;
|
||||
* defining the query parameters. They are used by injectors and other
|
||||
* components which need to identify a target element using a string.
|
||||
*
|
||||
* <h4>Explicit Target Selectors</h4>
|
||||
* <h3>Explicit Target Selectors</h3>
|
||||
*
|
||||
* <p><b>Explicit</b> Target Selectors are handled internally using
|
||||
* {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the
|
||||
@@ -43,6 +43,13 @@ import org.spongepowered.asm.util.asm.ElementNode;
|
||||
*/
|
||||
public interface ITargetSelector {
|
||||
|
||||
/**
|
||||
* Get the next target selector in this path (or <tt>null</tt> if this
|
||||
* selector is the last selector in the chain. Called at recurse points in
|
||||
* the subject in order to match against the child subject.
|
||||
*/
|
||||
public abstract ITargetSelector next();
|
||||
|
||||
/**
|
||||
* Configure and return a modified version of this selector by consuming the
|
||||
* supplied arguments. Results from this method should be idempotent in
|
||||
|
||||
@@ -278,7 +278,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
|
||||
protected Set<ITargetSelector> parseTargets(String type) {
|
||||
List<String> methods = Annotations.<String>getValue(this.annotation, "method", false);
|
||||
if (methods == null) {
|
||||
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", type, this.method.name));
|
||||
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", type, this.methodName));
|
||||
}
|
||||
|
||||
Set<ITargetSelector> selectors = new LinkedHashSet<ITargetSelector>();
|
||||
@@ -287,14 +287,14 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
|
||||
selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin));
|
||||
} catch (InvalidMemberDescriptorException ex) {
|
||||
throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", type,
|
||||
this.method.name, method, this.mixin.getReferenceMapper().getStatus()));
|
||||
this.methodName, method, this.mixin.getReferenceMapper().getStatus()));
|
||||
} catch (TargetNotSupportedException ex) {
|
||||
throw new InvalidInjectionException(this,
|
||||
String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.method.name,
|
||||
String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.methodName,
|
||||
ex.getMessage()));
|
||||
} catch (InvalidSelectorException ex) {
|
||||
throw new InvalidInjectionException(this,
|
||||
String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.method.name,
|
||||
String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.methodName,
|
||||
ex.getMessage()));
|
||||
}
|
||||
}
|
||||
@@ -304,7 +304,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
|
||||
protected List<AnnotationNode> readInjectionPoints(String type) {
|
||||
List<AnnotationNode> ats = Annotations.<AnnotationNode>getValue(this.annotation, this.atKey, false);
|
||||
if (ats == null) {
|
||||
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", type, this.method.name,
|
||||
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", type, this.methodName,
|
||||
this.atKey));
|
||||
}
|
||||
return ats;
|
||||
@@ -385,17 +385,17 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
|
||||
if ((this.mixin.getEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) {
|
||||
throw new InvalidInjectionException(this,
|
||||
String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. %s%s", description,
|
||||
this.method.name, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, refMapStatus,
|
||||
this.methodName, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, refMapStatus,
|
||||
dynamicInfo));
|
||||
} else if (this.injectedCallbackCount < this.requiredCallbackCount) {
|
||||
throw new InjectionError(
|
||||
String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded. %s%s", description,
|
||||
this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, refMapStatus,
|
||||
this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, refMapStatus,
|
||||
dynamicInfo));
|
||||
} else if (this.injectedCallbackCount > this.maxCallbackCount) {
|
||||
throw new InjectionError(
|
||||
String.format("Critical injection failure: %s %s%s in %s failed injection check, %d succeeded of %d allowed.%s",
|
||||
description, this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, dynamicInfo));
|
||||
description, this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, dynamicInfo));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -524,7 +524,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
|
||||
if (this.targets.size() == 0) {
|
||||
throw new InvalidInjectionException(this,
|
||||
String.format("%s annotation on %s could not find any targets matching %s in the target class %s. %s%s",
|
||||
type, this.method.name, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
|
||||
type, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
|
||||
this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,6 +261,11 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
|
||||
this.unparsed = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITargetSelector next() {
|
||||
return null; // Not supported yet
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOwner() {
|
||||
return this.owner;
|
||||
|
||||
+31
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.throwables;
|
||||
|
||||
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
|
||||
import org.spongepowered.asm.mixin.refmap.IMixinContext;
|
||||
import org.spongepowered.asm.mixin.transformer.ActivityStack;
|
||||
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
|
||||
|
||||
/**
|
||||
@@ -43,31 +44,61 @@ public class InvalidInjectionException extends InvalidMixinException {
|
||||
this.info = null;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(IMixinContext context, String message, ActivityStack activityContext) {
|
||||
super(context, message, activityContext);
|
||||
this.info = null;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(InjectionInfo info, String message) {
|
||||
super(info.getContext(), message);
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) {
|
||||
super(info.getContext(), message, activityContext);
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(IMixinContext context, Throwable cause) {
|
||||
super(context, cause);
|
||||
this.info = null;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(IMixinContext context, Throwable cause, ActivityStack activityContext) {
|
||||
super(context, cause, activityContext);
|
||||
this.info = null;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(InjectionInfo info, Throwable cause) {
|
||||
super(info.getContext(), cause);
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) {
|
||||
super(info.getContext(), cause, activityContext);
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(IMixinContext context, String message, Throwable cause) {
|
||||
super(context, message, cause);
|
||||
this.info = null;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(IMixinContext context, String message, Throwable cause, ActivityStack activityContext) {
|
||||
super(context, message, cause, activityContext);
|
||||
this.info = null;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) {
|
||||
super(info.getContext(), message, cause);
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) {
|
||||
super(info.getContext(), message, cause, activityContext);
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
public InjectionInfo getInjectionInfo() {
|
||||
return this.info;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import org.objectweb.asm.tree.MethodNode;
|
||||
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
|
||||
import org.spongepowered.asm.mixin.refmap.IMixinContext;
|
||||
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
|
||||
import org.spongepowered.asm.util.asm.MethodNodeEx;
|
||||
|
||||
/**
|
||||
* Information about a special mixin method such as an injector or accessor
|
||||
@@ -50,6 +51,11 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
|
||||
* Annotated method
|
||||
*/
|
||||
protected final MethodNode method;
|
||||
|
||||
/**
|
||||
* Original name of the method, if available
|
||||
*/
|
||||
protected final String methodName;
|
||||
|
||||
/**
|
||||
* Mixin data
|
||||
@@ -61,6 +67,7 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
|
||||
this.method = method;
|
||||
this.annotation = annotation;
|
||||
this.classNode = mixin.getTargetClassNode();
|
||||
this.methodName = method instanceof MethodNodeEx ? ((MethodNodeEx)this.method).getOriginalName() : method.name;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,5 +108,12 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
|
||||
public final MethodNode getMethod() {
|
||||
return this.method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the original name of the method, if available
|
||||
*/
|
||||
public String getMethodName() {
|
||||
return this.methodName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -69,6 +69,7 @@ import org.spongepowered.asm.service.IMixinService;
|
||||
import org.spongepowered.asm.util.Annotations;
|
||||
import org.spongepowered.asm.util.Bytecode;
|
||||
import org.spongepowered.asm.util.asm.ASM;
|
||||
import org.spongepowered.asm.util.asm.MethodNodeEx;
|
||||
import org.spongepowered.asm.util.perf.Profiler;
|
||||
import org.spongepowered.asm.util.perf.Profiler.Section;
|
||||
|
||||
@@ -84,22 +85,10 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
|
||||
/**
|
||||
* A MethodNode in a mixin
|
||||
*/
|
||||
class MixinMethodNode extends MethodNode {
|
||||
|
||||
private final String originalName;
|
||||
class MixinMethodNode extends MethodNodeEx {
|
||||
|
||||
public MixinMethodNode(int access, String name, String desc, String signature, String[] exceptions) {
|
||||
super(ASM.API_VERSION, access, name, desc, signature, exceptions);
|
||||
this.originalName = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s%s", this.originalName, this.desc);
|
||||
}
|
||||
|
||||
public String getOriginalName() {
|
||||
return this.originalName;
|
||||
super(access, name, desc, signature, exceptions, MixinInfo.this);
|
||||
}
|
||||
|
||||
public boolean isInjector() {
|
||||
@@ -121,10 +110,6 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
|
||||
public AnnotationNode getInjectorAnnotation() {
|
||||
return InjectionInfo.getInjectorAnnotation(MixinInfo.this, this);
|
||||
}
|
||||
|
||||
public IMixinInfo getOwner() {
|
||||
return MixinInfo.this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
+13
-3
@@ -158,7 +158,7 @@ public class ExtensionClassExporter implements IExtension {
|
||||
File outputFile = new File(this.classExportDir, fileName + ".class");
|
||||
outputFile.getParentFile().mkdirs();
|
||||
try {
|
||||
byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode);
|
||||
byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode, true);
|
||||
if (bytecode != null) {
|
||||
Files.write(bytecode, outputFile);
|
||||
}
|
||||
@@ -168,12 +168,22 @@ public class ExtensionClassExporter implements IExtension {
|
||||
return outputFile;
|
||||
}
|
||||
|
||||
private static byte[] getClassBytes(ClassNode classNode) {
|
||||
private static byte[] getClassBytes(ClassNode classNode, boolean computeFrames) {
|
||||
byte[] bytes = null;
|
||||
try {
|
||||
MixinClassWriter cw = new MixinClassWriter(ClassWriter.COMPUTE_FRAMES);
|
||||
MixinClassWriter cw = new MixinClassWriter(computeFrames ? ClassWriter.COMPUTE_FRAMES : 0);
|
||||
classNode.accept(cw);
|
||||
bytes = cw.toByteArray();
|
||||
} catch (NegativeArraySizeException ex) {
|
||||
// Try again with compute frames turned off, this gives us a better chance
|
||||
// of successful export when the class is corrupt which - given we are
|
||||
// exporting for debugging purposes - is worthwhile so that we have a
|
||||
// the bytecode to inspect!
|
||||
if (computeFrames) {
|
||||
ExtensionClassExporter.logger.warn("Exporting class {} with COMPUTE_FRAMES failed! Trying a raw export.", classNode.name);
|
||||
return ExtensionClassExporter.getClassBytes(classNode, false);
|
||||
}
|
||||
ex.printStackTrace();
|
||||
} catch (Exception ex) {
|
||||
// well, damn
|
||||
ex.printStackTrace();
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
*/
|
||||
package org.spongepowered.asm.mixin.transformer.meta;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
@@ -33,7 +32,7 @@ import java.lang.annotation.Target;
|
||||
* Decoration annotation used by the mixin inner class generator to mark inner
|
||||
* classes which have been generated from an existing inner class in a mixin
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
public @interface MixinInner {
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
*/
|
||||
package org.spongepowered.asm.mixin.transformer.meta;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
@@ -36,7 +35,7 @@ import java.lang.annotation.Target;
|
||||
* <p>Decoration annotation used by the mixin applicator to mark methods in a
|
||||
* class which have been added or overwritten by a mixin.</p>
|
||||
*/
|
||||
@Target({ ElementType.METHOD })
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MixinMerged {
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
*/
|
||||
package org.spongepowered.asm.mixin.transformer.meta;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
@@ -33,7 +32,7 @@ import java.lang.annotation.Target;
|
||||
* Decoration annotation used by postprocessor to mark methods which have had
|
||||
* their contents replaced with a proxy.
|
||||
*/
|
||||
@Target({ ElementType.METHOD })
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MixinProxy {
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
*/
|
||||
package org.spongepowered.asm.mixin.transformer.meta;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
@@ -35,7 +34,7 @@ import java.lang.annotation.Target;
|
||||
* <p>Decoration annotation used by MixinInfo and MixinPreProcessor to mark
|
||||
* methods in a mixin which have been renamed prior to being merged.</p>
|
||||
*/
|
||||
@Target({ ElementType.METHOD })
|
||||
@Target({ /* No targets allowed */ })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MixinRenamed {
|
||||
|
||||
|
||||
@@ -257,10 +257,14 @@ public final class Annotations {
|
||||
*
|
||||
* @param method Source method
|
||||
* @param annotationClass Type of annotation to search for
|
||||
* @param paramIndex Index of the parameter to fetch annotation for
|
||||
* @param paramIndex Index of the parameter to fetch annotation for, or the
|
||||
* method itself if less than zero
|
||||
* @return the annotation, or null if not present
|
||||
*/
|
||||
public static AnnotationNode getVisibleParameter(MethodNode method, Class<? extends Annotation> annotationClass, int paramIndex) {
|
||||
if (paramIndex < 0) {
|
||||
return Annotations.getVisible(method, annotationClass);
|
||||
}
|
||||
return Annotations.getParameter(method.visibleParameterAnnotations, Type.getDescriptor(annotationClass), paramIndex);
|
||||
}
|
||||
|
||||
@@ -270,10 +274,14 @@ public final class Annotations {
|
||||
*
|
||||
* @param method Source method
|
||||
* @param annotationClass Type of annotation to search for
|
||||
* @param paramIndex Index of the parameter to fetch annotation for
|
||||
* @param paramIndex Index of the parameter to fetch annotation for, or the
|
||||
* method itself if less than zero
|
||||
* @return the annotation, or null if not present
|
||||
*/
|
||||
public static AnnotationNode getInvisibleParameter(MethodNode method, Class<? extends Annotation> annotationClass, int paramIndex) {
|
||||
if (paramIndex < 0) {
|
||||
return Annotations.getInvisible(method, annotationClass);
|
||||
}
|
||||
return Annotations.getParameter(method.invisibleParameterAnnotations, Type.getDescriptor(annotationClass), paramIndex);
|
||||
}
|
||||
|
||||
@@ -506,12 +514,16 @@ public final class Annotations {
|
||||
}
|
||||
|
||||
int existingIndex = 0;
|
||||
for (int pos = 0; pos < annotation.values.size() - 1; pos += 2) {
|
||||
String keyName = annotation.values.get(pos).toString();
|
||||
if (key.equals(keyName)) {
|
||||
existingIndex = pos + 1;
|
||||
break;
|
||||
if (annotation.values != null) {
|
||||
for (int pos = 0; pos < annotation.values.size() - 1; pos += 2) {
|
||||
String keyName = annotation.values.get(pos).toString();
|
||||
if (key.equals(keyName)) {
|
||||
existingIndex = pos + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
annotation.values = new ArrayList<Object>();
|
||||
}
|
||||
|
||||
if (existingIndex > 0) {
|
||||
|
||||
@@ -183,13 +183,15 @@ public final class Bytecode {
|
||||
Opcodes.LCONST_0, Opcodes.LCONST_1,
|
||||
Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2,
|
||||
Opcodes.DCONST_0, Opcodes.DCONST_1,
|
||||
Opcodes.BIPUSH, // 15
|
||||
Opcodes.SIPUSH, // 16
|
||||
Opcodes.LDC, // 17
|
||||
Opcodes.BIPUSH, // 15
|
||||
Opcodes.SIPUSH, // 16
|
||||
Opcodes.LDC, // 17
|
||||
Opcodes.CHECKCAST, // 18
|
||||
Opcodes.INSTANCEOF // 19
|
||||
};
|
||||
|
||||
private static final Object[] CONSTANTS_VALUES = {
|
||||
null,
|
||||
Type.VOID_TYPE,
|
||||
Integer.valueOf(-1),
|
||||
Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5),
|
||||
Long.valueOf(0L), Long.valueOf(1L),
|
||||
@@ -538,7 +540,7 @@ public final class Bytecode {
|
||||
* argument or "this"
|
||||
*/
|
||||
public static int getFirstNonArgLocalIndex(MethodNode method) {
|
||||
return Bytecode.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), (method.access & Opcodes.ACC_STATIC) == 0);
|
||||
return Bytecode.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), !Bytecode.isStatic(method));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -565,15 +567,29 @@ public final class Bytecode {
|
||||
* @return size of the specified arguments array in terms of stack slots
|
||||
*/
|
||||
public static int getArgsSize(Type[] args) {
|
||||
return Bytecode.getArgsSize(args, 0, args.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the specified args array in local variable terms (eg.
|
||||
* doubles and longs take two spaces) using startIndex (inclusive) and
|
||||
* endIndex (exclusive) to determine which arguments to process.
|
||||
*
|
||||
* @param args Method argument types as array
|
||||
* @param startIndex Start index in the array, not related to arg size
|
||||
* @param endIndex End index (exclusive) in the array, not related to size
|
||||
* @return size of the specified arguments array in terms of stack slots
|
||||
*/
|
||||
public static int getArgsSize(Type[] args, int startIndex, int endIndex) {
|
||||
int size = 0;
|
||||
|
||||
for (Type type : args) {
|
||||
size += type.getSize();
|
||||
|
||||
for (int index = startIndex; index < args.length && index < endIndex; index++) {
|
||||
size += args[index].getSize();
|
||||
}
|
||||
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate
|
||||
* for each entry in the args array starting at pos
|
||||
@@ -588,7 +604,8 @@ public final class Bytecode {
|
||||
|
||||
/**
|
||||
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate
|
||||
* for each entry in the args array starting at start and ending at end
|
||||
* for each entry in the args array starting at start (inclusive) and ending
|
||||
* at end (inclusive)
|
||||
*
|
||||
* @param args Argument types
|
||||
* @param insns Instruction List to inject into
|
||||
@@ -601,7 +618,8 @@ public final class Bytecode {
|
||||
|
||||
/**
|
||||
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate
|
||||
* for each entry in the args array starting at start and ending at end
|
||||
* for each entry in the args array starting at start (inclusive) and ending
|
||||
* at end (inclusive)
|
||||
*
|
||||
* @param args Argument types
|
||||
* @param insns Instruction List to inject into
|
||||
@@ -610,18 +628,17 @@ public final class Bytecode {
|
||||
* @param casts Type casts array
|
||||
*/
|
||||
public static void loadArgs(Type[] args, InsnList insns, int start, int end, Type[] casts) {
|
||||
int pos = start, index = 0;
|
||||
int pos = start;
|
||||
|
||||
for (Type type : args) {
|
||||
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), pos));
|
||||
for (int index = 0; index < args.length; index++) {
|
||||
insns.add(new VarInsnNode(args[index].getOpcode(Opcodes.ILOAD), pos));
|
||||
if (casts != null && index < casts.length && casts[index] != null) {
|
||||
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, casts[index].getInternalName()));
|
||||
}
|
||||
pos += type.getSize();
|
||||
pos += args[index].getSize();
|
||||
if (end >= start && pos >= end) {
|
||||
return;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -646,6 +663,17 @@ public final class Bytecode {
|
||||
return labels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a bytecode descriptor from the supplied types.
|
||||
*
|
||||
* @param returnType the method return type, can be <tt>null</tt> for
|
||||
* <tt>void</tt>
|
||||
* @param args argument types
|
||||
*/
|
||||
public static String generateDescriptor(Type returnType, Type... args) {
|
||||
return Bytecode.generateDescriptor(returnType, (Object[])args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a bytecode descriptor from the supplied tokens. Each token can
|
||||
* be a {@link Type}, a {@link Class} or otherwise is converted in-place by
|
||||
@@ -783,7 +811,7 @@ public final class Bytecode {
|
||||
*
|
||||
* @param insn constant instruction to process
|
||||
* @return the constant value or <tt>null</tt> if the value cannot be parsed
|
||||
* (or is null)
|
||||
* (<tt>null</tt> constant is returned as <tt>Type.VOID_TYPE</tt>)
|
||||
*/
|
||||
public static Object getConstant(AbstractInsnNode insn) {
|
||||
if (insn == null) {
|
||||
@@ -796,6 +824,11 @@ public final class Bytecode {
|
||||
return Integer.valueOf(value);
|
||||
}
|
||||
throw new IllegalArgumentException("IntInsnNode with invalid opcode " + insn.getOpcode() + " in getConstant");
|
||||
} else if (insn instanceof TypeInsnNode) {
|
||||
if (insn.getOpcode() < Opcodes.CHECKCAST) {
|
||||
return null; // Don't treat NEW and ANEWARRAY as constants
|
||||
}
|
||||
return Type.getObjectType(((TypeInsnNode)insn).desc);
|
||||
}
|
||||
|
||||
int index = Ints.indexOf(Bytecode.CONSTANTS_ALL, insn.getOpcode());
|
||||
@@ -806,8 +839,8 @@ public final class Bytecode {
|
||||
* Returns the {@link Type} of a particular constant instruction's payload
|
||||
*
|
||||
* @param insn constant instruction
|
||||
* @return type of constant or <tt>null</tt> if it cannot be parsed (or is
|
||||
* null)
|
||||
* @return type of constant or <tt>null</tt> if it cannot be parsed (<tt>
|
||||
* null</tt> constant is returned as <tt>Type.VOID_TYPE</tt>)
|
||||
*/
|
||||
public static Type getConstantType(AbstractInsnNode insn) {
|
||||
if (insn == null) {
|
||||
@@ -828,6 +861,11 @@ public final class Bytecode {
|
||||
return Type.getType(Constants.CLASS_DESC);
|
||||
}
|
||||
throw new IllegalArgumentException("LdcInsnNode with invalid payload type " + cst.getClass() + " in getConstant");
|
||||
} else if (insn instanceof TypeInsnNode) {
|
||||
if (insn.getOpcode() < Opcodes.CHECKCAST) {
|
||||
return null; // Don't treat NEW and ANEWARRAY as constants
|
||||
}
|
||||
return Type.getType(Constants.CLASS_DESC);
|
||||
}
|
||||
|
||||
int index = Ints.indexOf(Bytecode.CONSTANTS_ALL, insn.getOpcode());
|
||||
|
||||
@@ -782,8 +782,8 @@ public class PrettyPrinter {
|
||||
public PrettyPrinter addWrapped(int width, String format, Object... args) {
|
||||
String indent = "";
|
||||
String line = String.format(format, args).replace("\t", " ");
|
||||
Matcher indentMatcher = Pattern.compile("^(\\s+)(.*)$").matcher(line);
|
||||
if (indentMatcher.matches()) {
|
||||
Matcher indentMatcher = Pattern.compile("^(\\s+)[^\\s]").matcher(line);
|
||||
if (indentMatcher.find()) {
|
||||
indent = indentMatcher.group(1);
|
||||
}
|
||||
|
||||
@@ -801,7 +801,7 @@ public class PrettyPrinter {
|
||||
List<String> lines = new ArrayList<String>();
|
||||
|
||||
while (line.length() > width) {
|
||||
int wrapPoint = line.lastIndexOf(' ', width);
|
||||
int wrapPoint = PrettyPrinter.lastBreakIndex(line, width);
|
||||
if (wrapPoint < 10) {
|
||||
wrapPoint = width;
|
||||
}
|
||||
@@ -817,6 +817,11 @@ public class PrettyPrinter {
|
||||
return lines;
|
||||
}
|
||||
|
||||
private static int lastBreakIndex(String line, int width) {
|
||||
int lineBreakPos = line.lastIndexOf('\n', width);
|
||||
return lineBreakPos > -1 ? lineBreakPos : Math.max(line.lastIndexOf(' ', width), line.lastIndexOf('\t', width));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a formatted key/value pair to the output
|
||||
*
|
||||
|
||||
@@ -85,7 +85,15 @@ public class SignaturePrinter {
|
||||
public SignaturePrinter(String name, String desc) {
|
||||
this(name, Type.getReturnType(desc), Type.getArgumentTypes(desc));
|
||||
}
|
||||
|
||||
public SignaturePrinter(Type[] args) {
|
||||
this(null, null, args);
|
||||
}
|
||||
|
||||
public SignaturePrinter(Type returnType, Type[] args) {
|
||||
this(null, returnType, args);
|
||||
}
|
||||
|
||||
public SignaturePrinter(String name, Type returnType, Type[] args) {
|
||||
this.name = name;
|
||||
this.returnType = returnType;
|
||||
@@ -193,7 +201,8 @@ public class SignaturePrinter {
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(this.name), false, true).toString();
|
||||
String name = this.name != null ? this.name : "method";
|
||||
return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(name), false, true).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -254,6 +263,17 @@ public class SignaturePrinter {
|
||||
}
|
||||
return sb;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
return SignaturePrinter.getTypeName(type, false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the source code name for the specified type
|
||||
@@ -277,6 +297,9 @@ public class SignaturePrinter {
|
||||
* integer primitive or "String" for java.lang.String
|
||||
*/
|
||||
public static String getTypeName(Type type, boolean box, boolean fullyQualified) {
|
||||
if (type == null) {
|
||||
return "{null?}";
|
||||
}
|
||||
switch (type.getSort()) {
|
||||
case Type.VOID: return box ? "Void" : "void";
|
||||
case Type.BOOLEAN: return box ? "Boolean" : "boolean";
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* This file is part of Mixin, licensed under the MIT License (MIT).
|
||||
*
|
||||
* Copyright (c) SpongePowered <https://www.spongepowered.org>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package org.spongepowered.asm.util.asm;
|
||||
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
|
||||
|
||||
/**
|
||||
* MethodNode with some extra convenience functionality
|
||||
*/
|
||||
public class MethodNodeEx extends MethodNode {
|
||||
|
||||
private final IMixinInfo owner;
|
||||
|
||||
private final String originalName;
|
||||
|
||||
public MethodNodeEx(int access, String name, String descriptor, String signature, String[] exceptions, IMixinInfo owner) {
|
||||
super(ASM.API_VERSION, access, name, descriptor, signature, exceptions);
|
||||
this.originalName = name;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s%s", this.originalName, this.desc);
|
||||
}
|
||||
|
||||
public String getQualifiedName() {
|
||||
return String.format("%s::%s", this.owner.getName(), this.originalName);
|
||||
}
|
||||
|
||||
public String getOriginalName() {
|
||||
return this.originalName;
|
||||
}
|
||||
|
||||
public IMixinInfo getOwner() {
|
||||
return this.owner;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user