Merge remote-tracking branch 'SpongePowered/0.8.3' into upstream_merge

# Conflicts:
#	build.gradle
#	gradle.properties
#	src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
#	src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java
This commit is contained in:
modmuss50 committed 2021-06-27 10:55:25 +01:00
commit 0ce2d4f8c4
184 files changed
+9666 -1595

No files matched your search

@@ -24,6 +24,8 @@
*/
package org.spongepowered.asm.launch;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
@@ -32,6 +34,9 @@ import org.spongepowered.asm.launch.platform.CommandLineOptions;
import org.spongepowered.asm.launch.platform.MixinPlatformManager;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.throwables.MixinError;
import org.spongepowered.asm.service.IMixinInternal;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
/**
@@ -61,13 +66,19 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.8.2";
public static final String VERSION = "0.8.3";
/**
* Transformer factory
*/
private static final String MIXIN_TRANSFORMER_FACTORY_CLASS = "org.spongepowered.asm.mixin.transformer.MixinTransformer$Factory";
/**
* Log all the things
*/
private static final Logger logger = LogManager.getLogger("mixin");
// These are Klass local, with luck this shouldn't be a problem
private static boolean initialised = false;
private static boolean initState = true;
@@ -77,7 +88,7 @@ public abstract class MixinBootstrap {
MixinService.boot();
MixinService.getService().prepare();
}
/**
* Platform manager instance
*/
@@ -134,6 +145,7 @@ public abstract class MixinBootstrap {
}
MixinBootstrap.registerSubsystem(MixinBootstrap.VERSION);
MixinBootstrap.offerInternals();
if (!MixinBootstrap.initialised) {
MixinBootstrap.initialised = true;
@@ -207,4 +219,31 @@ public abstract class MixinBootstrap {
GlobalProperties.put(GlobalProperties.Keys.INIT, version);
}
private static void offerInternals() {
IMixinService service = MixinService.getService();
try {
for (IMixinInternal internal : MixinBootstrap.getInternals()) {
service.offer(internal);
}
} catch (AbstractMethodError ex) {
// outdated service
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static List<IMixinInternal> getInternals() throws MixinError {
List<IMixinInternal> internals = new ArrayList<IMixinInternal>();
try {
Class<IMixinInternal> clTransformerFactory = (Class<IMixinInternal>)Class.forName(MixinBootstrap.MIXIN_TRANSFORMER_FACTORY_CLASS);
Constructor<IMixinInternal> ctor = clTransformerFactory.getDeclaredConstructor();
ctor.setAccessible(true);
internals.add(ctor.newInstance());
} catch (ReflectiveOperationException ex) {
throw new MixinError(ex);
}
return internals;
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Classes which support environment-agnostic launch logic for the Mixin
* subsystem and base classes and interfaces for environment-specific adapters.
*/
package org.spongepowered.asm.launch;
@@ -80,7 +80,7 @@ public class MixinConnectorManager {
}
try {
IMixinConnector connector = connectorClass.newInstance();
IMixinConnector connector = connectorClass.getDeclaredConstructor().newInstance();
this.connectors.add(connector);
MixinConnectorManager.logger.info("Successfully loaded Mixin Connector [" + connectorClassName + "]");
} catch (ReflectiveOperationException ex) {
@@ -28,6 +28,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -69,7 +70,7 @@ public class MixinContainer {
String simpleName = clazz.getSimpleName();
MixinContainer.logger.debug("Instancing new {} for {}", simpleName, this.handle);
IMixinPlatformAgent agent = clazz.newInstance();
IMixinPlatformAgent agent = clazz.getDeclaredConstructor().newInstance();
AcceptResult acceptAction = agent.accept(manager, this.handle);
if (acceptAction == AcceptResult.ACCEPTED) {
@@ -79,7 +80,7 @@ public class MixinContainer {
continue;
}
MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(), this.handle);
MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(Locale.ROOT), this.handle);
} catch (InstantiationException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
@@ -297,7 +297,6 @@ public class MixinPlatformManager {
*/
final void addConnector(String connectorClass) {
this.connectors.addConnector(connectorClass);
}
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Default (platform-agnostic) container handles
*/
package org.spongepowered.asm.launch.platform.container;
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Base classes for environment-specific adapters and default platform-agnostic
* handlers for environment and mixin containers.
*/
package org.spongepowered.asm.launch.platform;
@@ -31,7 +31,13 @@ import java.lang.annotation.Target;
/**
* Pseudo-implements decorator for Mixins with conflicting methods in a
* superclass to soft-implement an interface
* superclass to soft-implement an interface.
*
* <p>See <a target="_top"
* href="https://github.com/SpongePowered/Mixin/wiki/Introduction-to-Mixins -
* Resolving-Method-Signature-Conflicts">Introduction to Mixins - Resolving
* Method Signature Conflicts</a> for details on soft implementation of
* interfaces.</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@@ -46,10 +46,10 @@ import java.lang.annotation.Target;
* <p>Consider the following code:</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* public int soft$getSomething() {
* return this.getSomething();
* }</pre></blockquote>
*
*public int soft$getSomething() {
* return this.getSomething();
*}</pre></blockquote>
*
* <p>This type of accessor is common when an interface conflict occurs, but has
* the problem that the injected accessor will be effectively self-referential
@@ -61,9 +61,9 @@ import java.lang.annotation.Target;
*
* <blockquote><pre>&#064;Shadow private int something;
*
* public int soft$getSomething() {
* return this.something;
* }</pre></blockquote>
*public int soft$getSomething() {
* return this.something;
*}</pre></blockquote>
*
* <p>But this has the drawback of forcing the mixin to re-implement the target
* method, and thus forces ongoing maintenance of the mixin to include updating
@@ -75,21 +75,21 @@ import java.lang.annotation.Target;
* accessor with {@link Intrinsic &#064;Intrinsic}:</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* &#064;Intrinsic // don't merge the method if the target already exists
* public int soft$getSomething() {
* return this.getSomething();
* }</pre></blockquote>
*
*&#064;Intrinsic <del>// don't merge the method if the target already exists
*</del>public int soft$getSomething() {
* return this.getSomething();
*}</pre></blockquote>
*
* <p>This is ideal if the accessor is simply providing a proxy through to an
* underlying obfuscated method, as in the example above. However, if the new
* method contains additional code, such as in this example:</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
* }</pre></blockquote>
*
*public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
*}</pre></blockquote>
*
* <p>Then we still have the original problem that the method becomes re-entrant
* without specifying the additional Overwrite. We can solve this with the
@@ -108,11 +108,11 @@ import java.lang.annotation.Target;
* accessor will call the overwritten method.</p>
*
* <blockquote><pre>&#064;Shadow public int getSomething();
*
* &#064;Intrinsic(displace = true) // if the target already exists, displace it
* public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
* }</pre></blockquote>
*
*&#064;Intrinsic(displace = true) // if the target already exists, displace it
*public int soft$getSomething() {
* return this.someCondition ? this.someOtherValue : this.getSomething();
*}</pre></blockquote>
*
*/
@Target({ ElementType.METHOD })
@@ -30,7 +30,22 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Decorator for mixin classes
* The main decorator for mixin classes, this annotation denotes a class as a
* mixin and specifies two key attributes:
*
* <dl>
* <dt>The target classes</dt>
* <dd>Every mixin requires at least one target class in order to be valid.
* The target classes should be specified via {@link #value} where possible
* using class literals. However for anonymous inner classes,
* package-private classes, or unavailable classes (eg. synthetic classes)
* being targetted via {@link Pseudo &#64;Pseudo}, the targets should be
* specified via the {@link #targets} instead.</dd>
* <dt>The priority</dt>
* <dd>The mixin {@link #priority} is used to express the mixin's desired
* ordering with respect to other mixins being applied to the same target
* class.</dd>
* </dl>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@@ -46,18 +61,34 @@ public @interface Mixin {
/**
* Since specifying targets in {@link #value} requires that the classes be
* publicly visible, this property is provided to allow package-private,
* anonymous innner, and private inner classes to be referenced. Referencing
* an otherwise public class using this property is an error condition and
* will throw an exception at runtime. It is completely fine to specify both
* public and private targets for the same mixin however.
* anonymous innner, and private inner, or unavailable ({@link Pseudo
* &#64;Pseudo} classes to be referenced. Referencing an otherwise public
* class using this property is an error condition and will raise a warning
* at runtime or an error if {@link MixinEnvironment.Option#DEBUG_STRICT
* strict checks} are enabled. It is completely fine to specify both publi
* and private targets for the same mixin however.
*
* <p>Note that unlike class literals specified in {@link #value}, imports
* are not supported and therefore the class specified here must be
* fully-qualified with the package name.</p>
*
* @return protected or package-private classes this mixin targets
* @return protected, package-private, or {@link Pseudo pseudo} classes this
* mixin targets
*/
public String[] targets() default { };
/**
* Priority for the mixin, relative to other mixins targetting the same
* classes
* classes. By default mixins inherit their priority from the parent
* configuration that contains them, setting this value allows the priority
* to be overridden on a per-mixin basis.
*
* <p>Priorities sort mixins into <em>natural order</em> with lower priority
* mixins being applied first. This changes the nature of priority based on
* your intentions. Especially with respect to injectors, which must be
* considered on a case-by-case basis since the semantics of priority vary
* by injector because of first-come-first-served versus implied ordering of
* injectors such as inject-at-HEAD.</p>
*
* @return the mixin priority (relative to other mixins targetting the same
* class)
@@ -66,7 +97,7 @@ public @interface Mixin {
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link Shadow} and
* obfuscation mapping for all {@link Overwrite}, {@link Shadow} and
* {@link org.spongepowered.asm.mixin.injection.Inject} annotated members
* since it is anticipated that in general the target of a {@link Mixin}
* will be an obfuscated class and all annotated members will need to be
@@ -84,4 +115,5 @@ public @interface Mixin {
* obfuscation mappings for this annotation (default true).
*/
public boolean remap() default true;
}
@@ -56,6 +56,7 @@ import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.IConsumer;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.JavaVersion;
import org.spongepowered.asm.util.LanguageFeatures;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.asm.ASM;
import org.spongepowered.asm.util.perf.Profiler;
@@ -591,12 +592,12 @@ public final class MixinEnvironment implements ITokenProvider {
public static enum CompatibilityLevel {
/**
* Java 6 and above
* Java 6 (1.6) or above is required
*/
JAVA_6(6, Opcodes.V1_6, 0),
/**
* Java 7 and above
* Java 7 (1.7) or above is required
*/
JAVA_7(7, Opcodes.V1_7, 0) {
@@ -608,9 +609,9 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 8 and above
* Java 8 (1.8) or above is required
*/
JAVA_8(8, Opcodes.V1_8, LanguageFeature.METHODS_IN_INTERFACES) {
JAVA_8(8, Opcodes.V1_8, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES) {
@Override
boolean isSupported() {
@@ -620,9 +621,10 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 9 and above
* Java 9 or above is required
*/
JAVA_9(9, Opcodes.V9, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) {
JAVA_9(9, Opcodes.V9, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES) {
@Override
boolean isSupported() {
@@ -632,9 +634,10 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 10 and above
* Java 10 or above is required
*/
JAVA_10(10, Opcodes.V10, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) {
JAVA_10(10, Opcodes.V10, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES) {
@Override
boolean isSupported() {
@@ -644,10 +647,10 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 10 and above
* Java 11 or above is required
*/
JAVA_11(11, Opcodes.V11, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_11(11, Opcodes.V11, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -659,8 +662,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 12 and above
*/
JAVA_12(12, Opcodes.V12, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_12(12, Opcodes.V12, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -672,8 +675,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 13 and above
*/
JAVA_13(13, Opcodes.V13, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_13(13, Opcodes.V13, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -685,8 +688,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 14 and above
*/
JAVA_14(14, Opcodes.V14, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_14(14, Opcodes.V14, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -698,8 +701,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 16 and above
*/
JAVA_15(15, Opcodes.V15, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_15(15, Opcodes.V15, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -711,8 +714,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 16 and above
*/
JAVA_16(16, Opcodes.V16, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_16(16, Opcodes.V16, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -724,8 +727,8 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Java 17 and above
*/
JAVA_17(17, Opcodes.V17, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) {
JAVA_17(17, Opcodes.V17, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES
| LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
@@ -734,33 +737,6 @@ public final class MixinEnvironment implements ITokenProvider {
};
/**
* Bitmask values for language features supported
*/
public static class LanguageFeature {
/**
* Language version supports methods in interfaces
*/
public static final int METHODS_IN_INTERFACES = 1;
/**
* Language version supports private methods in interfaces
*/
public static final int PRIVATE_METHODS_IN_INTERFACES = 2;
/**
* Native nesting
*/
public static final int NESTING = 4;
/**
* Dynamic constants
*/
public static final int DYNAMIC_CONSTANTS = 8;
}
/**
* Default compatibility level to use if not specified by the service
*/
@@ -790,11 +766,35 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Class version expected at this compatibility level
*
* @deprecated Use getClassVersion
*/
@Deprecated
public int classVersion() {
return this.classVersion;
}
/**
* Class version expected at this compatibility level
*/
public int getClassVersion() {
return this.classVersion;
}
/**
* Get the major class version expected at this compatibility level
*/
public int getClassMajorVersion() {
return this.classVersion & 0xFFFF;
}
/**
* Get all supported language features
*/
public int getLanguageFeatures() {
return this.languageFeatures;
}
/**
* Get whether this environment supports non-abstract methods in
* interfaces, true in Java 1.8 and above
@@ -803,18 +803,18 @@ public final class MixinEnvironment implements ITokenProvider {
*/
@Deprecated
public boolean supportsMethodsInInterfaces() {
return (this.languageFeatures & LanguageFeature.METHODS_IN_INTERFACES) != 0;
return (this.languageFeatures & LanguageFeatures.METHODS_IN_INTERFACES) != 0;
}
/**
* Get whether the specified {@link LanguageFeature} is supported by
* Get whether the specified {@link LanguageFeatures} is supported by
* this runtime.
*
* @param languageFeature language feature (or features) to check
* @param languageFeatures language feature (or features) to check
* @return true if all specified language features are supported
*/
public boolean supports(int languageFeature) {
return (this.languageFeatures & languageFeature) != 0;
public boolean supports(int languageFeatures) {
return (this.languageFeatures & languageFeatures) == languageFeatures;
}
/**
@@ -864,6 +864,25 @@ public final class MixinEnvironment implements ITokenProvider {
return level.canElevateTo(this);
}
/**
* Return the minimum language level required to support the specified
* language feature(s). Returns <tt>null</tt> if no compatibility level
* available can support the requested language features.
*
* @param languageFeatures Language feature(s) to check for
* @return Lowest compatibility level which supports the requested
* language feature, or null if no levels support the requested
* feature
*/
public static CompatibilityLevel requiredFor(int languageFeatures) {
for (CompatibilityLevel level : CompatibilityLevel.values()) {
if (level.supports(languageFeatures)) {
return level;
}
}
return null;
}
static String getSupportedVersions() {
StringBuilder sb = new StringBuilder();
@@ -1058,7 +1077,8 @@ public final class MixinEnvironment implements ITokenProvider {
printer.kv("Internal Version", version);
printer.kv("Java Versions Supported", CompatibilityLevel.getSupportedVersions());
printer.kv("Current Compatibility Level", MixinEnvironment.getCompatibilityLevel());
printer.kv("Detected ASM API Version", ASM.getApiVersionString()).hr();
printer.kv("Detected ASM API Version", ASM.getApiVersionString());
printer.kv("Detected ASM Supports Java", ASM.getClassVersionString()).hr();
printer.kv("Service Name", serviceName);
printer.kv("Mixin Service Class", this.service.getClass().getName());
printer.kv("Global Property Service Class", MixinService.getGlobalPropertyService().getClass().getName()).hr();
@@ -1147,7 +1167,7 @@ public final class MixinEnvironment implements ITokenProvider {
@SuppressWarnings("unchecked")
Class<? extends IEnvironmentTokenProvider> providerClass =
(Class<? extends IEnvironmentTokenProvider>)this.service.getClassProvider().findClass(providerName, true);
IEnvironmentTokenProvider provider = providerClass.newInstance();
IEnvironmentTokenProvider provider = providerClass.getDeclaredConstructor().newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
MixinEnvironment.logger.error("Error instantiating " + providerName, th);
@@ -30,23 +30,38 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A Mixin marked as <b>Pseudo</b> is allowed to target classes which are not
* available at compile time and may not be available at runtime. This means
* that certain restrictions apply:
* A Mixin marked as <tt>&#64;Pseudo</tt> is allowed to target classes which are
* not available at <em>compile time</em> and may not be available at runtime.
* This can be used in situations where - for one reason or another - a target
* class is not available to a project being compiled and would therefore fail
* AP verification. The target class is simulated by the AP using knowledge of
* only the superclass of the target (or at least, any <em>available</em> known
* superclass of the target. This means that certain restrictions apply:
*
* <p>In particular, the superclass requirement for pseudo mixins is extremely
* important if the target has an obfuscated class in its hierarchy. For example
* let's assume that we're mixing into a class <tt>SomeCustomScreen</tt> from
* another party which extends <tt>GuiScreen</tt> which is obfuscated.
* Attempting to inject into <tt>initGui</tt> will succeed at dev time and fail
* at production time, because the reference is obfuscated. We can overcome this
* by ensuring the mixin inherits from the same superclass, thus allowing
* <tt>initGui</tt> to be resolved in the superclass hierarchy (this is not the
* case for normal mixins).</p>
* <p>The superclass requirement for pseudo mixins is extremely important <b>if
* the target has an obfuscated class in its hierarchy</b>. For example
* let's assume that we're mixing into a class <tt>CustomGuiScreen</tt> from
* another party which extends <tt>GuiScreen</tt>, where <tt>GuiScreen</tt> is
* an obfuscated class. <tt>GuiScreen</tt> contains an obfuscated method
* <tt>initGui</tt> which the (&#64;Pseudo) target class overrides. Attempting
* to inject into <tt>initGui</tt> would succeed at dev time but would fail
* at production time, because the reference is obfuscated. Normally when a
* target overrides an obfuscated method in this way, the AP can resolve the
* obfuscation by walking the superclass hierarchy of the target in order to
* discover a mapping. However when the target is not available at compile time
* the AP cannot do this and must rely on only information from the mixin
* itself. We can overcome this problem by ensuring the mixin inherits from the
* same superclass (or at least a superclass which contains the obfuscated
* methods or fields used in the mixin), thus allowing our example <tt>initGui
* </tt> method to be resolved in the superclass hierarchy. This behaviour is
* not available to normal mixins as the AP always resolves the hierarchy via
* the target class metadata when it is available.</p>
*
* <p>{@link Overwrite} methods which are <b>not</b> inherited from a superclass
* (if the target is obfuscated) <b>must</b> be decorated manually with aliases.
* </p>
* <p>If the target class contains obfuscated methods which the mixin needs to
* {@link Overwrite} or {@link Shadow} which are <b>not</b> inherited from a
* superclass (eg. the target is obfuscated), the {@link Overwrite} or
* {@link Shadow} <b>must</b> be decorated manually with <tt>aliases</tt> since
* there is no mechanism for the AP to resolve the mappings automatically.</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* See {@link org.spongepowered.asm.mixin.connect.IMixinConnector}
*/
package org.spongepowered.asm.mixin.connect;
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Interfaces for internal Mixin objects which provide extensibility for mixin
* consumers.
*/
package org.spongepowered.asm.mixin.extensibility;
@@ -55,7 +55,7 @@ public abstract class AccessorGenerator {
protected void checkModifiers() {
if (this.info.isStatic() && !this.targetIsStatic) {
IMixinContext context = this.info.getContext();
IMixinContext context = this.info.getMixin();
throw new InvalidInjectionException(context, String.format("%s is invalid. Accessor method is%s static but the target is not.",
this.info, this.info.isStatic() ? "" : " not"));
}
@@ -73,7 +73,7 @@ public abstract class AccessorGenerator {
MethodNode accessor = new MethodNode(ASM.API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name,
method.desc, null, null);
accessor.visibleAnnotations = new ArrayList<AnnotationNode>();
accessor.visibleAnnotations.add(this.info.getAnnotation());
accessor.visibleAnnotations.add(this.info.getAnnotationNode());
accessor.maxLocals = maxLocals;
accessor.maxStack = maxStack;
return accessor;
@@ -60,9 +60,9 @@ public class AccessorGeneratorFieldSetter extends AccessorGeneratorField {
return;
}
if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
LogManager.getLogger("mixin").warn("{} for final field {}::{} is not @Mutable", this.info,
((MixinTargetContext)this.info.getContext()).getTarget(), this.targetField.name);
((MixinTargetContext)this.info.getMixin()).getTarget(), this.targetField.name);
}
}
@@ -74,7 +74,7 @@ public class AccessorGeneratorMethodProxy extends AccessorGenerator {
if (!this.targetIsStatic) {
method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
Bytecode.loadArgs(this.argTypes, method.instructions, this.targetIsStatic ? 0 : 1);
Bytecode.loadArgs(this.argTypes, method.instructions, this.info.isStatic ? 0 : 1);
boolean isPrivate = Bytecode.hasFlag(this.targetMethod, Opcodes.ACC_PRIVATE);
int opcode = this.targetIsStatic ? Opcodes.INVOKESTATIC : (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL);
method.instructions.add(new MethodInsnNode(opcode, this.info.getClassNode().name, this.targetMethod.name, this.targetMethod.desc, false));
@@ -41,7 +41,7 @@ public class AccessorGeneratorObjectFactory extends AccessorGeneratorMethodProxy
public AccessorGeneratorObjectFactory(AccessorInfo info) {
super(info, true);
if (!info.isStatic()) {
throw new InvalidInjectionException(info.getContext(), String.format("%s is invalid. Factory method must be static.", this.info));
throw new InvalidInjectionException(info.getMixin(), String.format("%s is invalid. Factory method must be static.", this.info));
}
}
@@ -39,16 +39,17 @@ import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.struct.SpecialMethodInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.asm.ElementNode;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
@@ -302,6 +303,7 @@ public class AccessorInfo extends SpecialMethodInfo {
this.type = this.initType();
this.targetFieldType = this.initTargetFieldType();
this.target = this.initTarget();
this.annotation.visit("target", this.target.toString());
}
protected AccessorType initType() {
@@ -331,9 +333,7 @@ public class AccessorInfo extends SpecialMethodInfo {
}
protected ITargetSelector initTarget() {
MemberInfo target = new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor());
this.annotation.visit("target", target.toString());
return target;
return new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor());
}
protected String getTargetName(String name) {
@@ -345,7 +345,7 @@ public class AccessorInfo extends SpecialMethodInfo {
}
return inflectedTarget;
}
return TargetSelector.parseName(name, this.mixin);
return TargetSelector.parseName(name, this);
}
/**
@@ -355,7 +355,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* <tt>foo</tt> for example.
*/
protected String inflectTarget() {
return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin,
return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this,
this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE));
}
@@ -376,7 +376,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* @return inflected target member name or <tt>null</tt> if name cannot be
* inflected
*/
public static String inflectTarget(String name, AccessorType type, String description, IMixinContext context, boolean verbose) {
public static String inflectTarget(String name, AccessorType type, String description, ISelectorContext context, boolean verbose) {
return AccessorInfo.inflectTarget(AccessorName.of(name), type, description, context, verbose);
}
@@ -397,7 +397,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* @return inflected target member name or <tt>null</tt> if name cannot be
* inflected
*/
public static String inflectTarget(AccessorName name, AccessorType type, String description, IMixinContext context, boolean verbose) {
public static String inflectTarget(AccessorName name, AccessorType type, String description, ISelectorContext context, boolean verbose) {
if (name != null) {
if (!type.isExpectedPrefix(name.prefix) && verbose) {
LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", description, name.prefix,
@@ -462,7 +462,7 @@ public class AccessorInfo extends SpecialMethodInfo {
@Override
public String toString() {
String typeString = this.type != null ? this.type.toString() : "UNPARSED_ACCESSOR";
return String.format("%s->@%s[%s]::%s%s", this.mixin, Bytecode.getSimpleName(this.annotation), typeString,
return String.format("%s->@%s[%s]::%s%s", this.mixin, Annotations.getSimpleName(this.annotation), typeString,
this.methodName, this.method.desc);
}
@@ -510,7 +510,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* @return best match
*/
protected <TNode> TNode findTarget(List<ElementNode<TNode>> nodes) {
Result<TNode> result = TargetSelector.<TNode>run(this.target.configure("orphan"), nodes);
Result<TNode> result = TargetSelector.<TNode>run(this.target.configure(Configure.ORPHAN), nodes);
try {
return result.getSingleResult(true);
@@ -27,7 +27,9 @@ package org.spongepowered.asm.mixin.gen;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result;
@@ -35,7 +37,6 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.asm.ElementNode;
/**
* Information about an invoker
@@ -102,7 +103,8 @@ class InvokerInfo extends AccessorInfo {
}
private MethodNode findTargetMethod() {
Result<MethodNode> result = TargetSelector.<MethodNode>run(this.target.configure("orphan"), ElementNode.methodList(this.classNode));
Result<MethodNode> result = TargetSelector.<MethodNode>run(this.target.configure(Configure.ORPHAN),
ElementNode.methodList(this.classNode));
try {
return result.getSingleResult(true);
@@ -0,0 +1,32 @@
/*
* 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.
*/
/**
* Generators, a special type of injector which replace the annotated method
* with synthetic content, see
* {@link org.spongepowered.asm.mixin.gen.Accessor &#64;Accessor} and
* {@link org.spongepowered.asm.mixin.gen.Invoker &#64;Invoker}.
*/
package org.spongepowered.asm.mixin.gen;
@@ -43,7 +43,7 @@ public class InvalidAccessorException extends InvalidMixinException {
}
public InvalidAccessorException(AccessorInfo info, String message) {
super(info.getContext(), message);
super(info.getMixin(), message);
this.info = info;
}
@@ -53,7 +53,7 @@ public class InvalidAccessorException extends InvalidMixinException {
}
public InvalidAccessorException(AccessorInfo info, Throwable cause) {
super(info.getContext(), cause);
super(info.getMixin(), cause);
this.info = info;
}
@@ -63,7 +63,7 @@ public class InvalidAccessorException extends InvalidMixinException {
}
public InvalidAccessorException(AccessorInfo info, String message, Throwable cause) {
super(info.getContext(), message, cause);
super(info.getMixin(), message, cause);
this.info = info;
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Exceptions for generators.
*/
package org.spongepowered.asm.mixin.gen.throwables;
@@ -165,6 +165,12 @@ public @interface At {
*/
public String target() default "";
/**
* Target descriptor used in place of string-based descriptors for
* {@link #target}
*/
public Desc desc() default @Desc("");
/**
* Ordinal offset. Many InjectionPoints will return every opcode matching
* their criteria, specifying <em>ordinal</em> allows a particular opcode to
@@ -0,0 +1,150 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
/**
* <p>A descriptor for matching a target element, for details of usage see
* {@link DynamicSelectorDesc}.</p>
*
* <p>Unlike {@link MemberInfo Explicit Target Selectors} which can match any
* element of a candidate member, <tt>&#064;Desc</tt> descriptors always match
* all elements of a target explicitly. Element defaults are as follows:</p>
*
* <blockquote><dl>
* <dt>{@link #owner}</dt>
* <dd>Defaults to the current target of the mixin if not specified</dd>
* <dt>{@link #ret}</dt>
* <dd>Defaults to <tt>void</tt></dd>
* <dt>{@link #args}</dt>
* <dd>Defaults to an empty array matching a target with <b>no arguments</b>,
* omitting this value does <em>not</em> mean "match any" signature and
* will explicitly match targets with no arguments. This value is ignored
* for fields.</dd>
* </dl></blockquote>
*
* <h4>Notes</h4>
*
* <ul>
* <li>It should be noted that specifying the only required value
* ({@link #value}) will therefore match elements with owner type equal to the
* current mixin target, taking no arguments and returning void.</li>
*
* <li>Note that when matching fields the value of {@link #args} is ignored.
* </li>
* </ul>
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Descriptors.class)
public @interface Desc {
/**
* The identifier for this descriptor. Can be an implicit coordinate or a
* user-defined string. IDs are not case-sensitive but must be unique within
* a mixin or resolution scope. For more details on resolution for
* descriptors see {@link DynamicSelectorDesc}.
*/
public String id() default "";
/**
* The owner of the member to match. The "owner" is the class which declares
* the member <b>or, ocasionally</b> the type of class upon which a virtual
* call is being made. For example if a class <tt>SuperType</tt> defines a
* method <tt>doSomething</tt>, usually <tt>owner</tt> will be
* <tt>SuperType</tt>. However note that where a method retrieves a
* reference to a derived type <tt>DerivedType</tt> which overrides
* <tt>doSomething</tt>, it's possible the invocation will be made using
* that type. To ensure usage of the correct type, inspect the disassembled
* bytecode for your target.
*
* <p>When <tt>owner</tt> is not specified, it defaults to the <em>current
* </em> target of the mixin.</p>
*/
public Class<?> owner() default void.class;
/**
* The name of the member to match. Must be specified. Matched
* case-sensitively against targets.
*/
public String value();
/**
* The return type of a method to match, or the declared type of a field.
* Defaults to <tt>void</tt>.
*/
public Class<?> ret() default void.class;
/**
* The argument types of a method to match, ignored for fields. Note that
* failing to specify this value <b>matches a target with no arguments</b>.
*/
public Class<?>[] args() default { };
/**
* The next elements of this descriptor path, evaluated in order for each
* recurse point.
*/
// public Next[] next() default { };
/**
* The minimum number of times this selector should match. By default the
* selector is allowed to match no targets. When selecting fields or methods
* setting this value to anything other than 0 or 1 is pointless since the
* member can either be present or absent. However when matching method <em>
* calls</em> or field <em>accesses</em> (eg. when using this value inside
* {@link At#desc &#64;At.desc}) this allows a minimum number of matches to
* be specified in order to provide early validation that the selector
* matched the correct number of candidates. To specify an exact number of
* matches, set {@link #max max} to the same value as <tt>min</tt>. Values
* less than zero are ignored since selectors cannot match a negative number
* of times.
*/
public int min() default 0;
/**
* The maximum number of times this selector can match. By default the
* selector is allowed to match an unlimited number of targets. When
* selecting fields or methods, setting this value to anything other than 1
* is pointless since the member can either be present or absent. However
* when matching method <em>calls</em> or field <em>accesses</em> (eg. when
* using this value inside {@link At#desc &#64;At.desc}) this allows a
* maximum number of matches to be specified in order to limit the number of
* times that the selector can match candidates. To specify an exact number
* of matches, set <tt>max</tt> to the same value as {@link #min min}.
* Values less than 1 are treated as <tt>Integer.MAX_VALUE</tt> (the
* default) since setting a value of 0 or less has no meaning.
*/
public int max() default Integer.MAX_VALUE;
}
@@ -0,0 +1,45 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Collection type for {@link Desc} to allow {@link Repeatable} to work.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Descriptors {
/**
* Desc annotations for element
*/
Desc[] value();
}
@@ -26,28 +26,24 @@ package org.spongepowered.asm.mixin.injection;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.util.IMessageSink;
/**
* Context for an injection point, used to access the mixin as well as the owner
* method and annotation for the injection point
*/
public interface IInjectionPointContext extends IMessageSink {
/**
* Get the mixin context for this injection
*/
public abstract IMixinContext getContext();
public interface IInjectionPointContext extends IMessageSink, ISelectorContext {
/**
* Get the injection handler method
*/
@Override
public abstract MethodNode getMethod();
/**
* Get the parent annotation (eg. the &#064;Inject annotation)
*/
public abstract AnnotationNode getAnnotation();
public abstract AnnotationNode getAnnotationNode();
}
@@ -122,7 +122,15 @@ public @interface Inject {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* Array of {@link Slice} annotations which describe the method bisections
@@ -30,12 +30,15 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
@@ -49,38 +52,89 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.points.*;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.IMessageSink;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
/**
* <p>Base class for injection point discovery classes. Each subclass describes
* a strategy for locating code injection points within an instruction list,
* with the {@link #find} method populating a collection with insn nodes from
* the supplied list which satisfy its strategy.</p>
* with the {@link #find find} method populating a collection with insn nodes
* from the supplied list which satisfy its strategy.</p>
*
* <p>This base class also contains composite strategy factory methods such as
* {@link #and} and {@link #or} which allow strategies to be combined using
* intersection (and) or union (or) relationships to allow multiple strategies
* to be easily combined.</p>
* {@link #and and} and {@link #or or} which allow strategies to be combined
* using intersection (and) or union (or) relationships to allow multiple
* strategies to be easily combined.</p>
*
* <p>You are free to create your own injection point subclasses, but take note
* that it <b>is allowed</b> for a single InjectionPoint instance to be used for
* multiple injections and thus implementing classes MUST NOT cache the insn
* list, event, or nodes instance passed to the {@link #find} method, as each
* call to {@link #find} must be considered a separate functional contract and
* the InjectionPoint's lifespan is not linked to the discovery lifespan,
* therefore it is important that the InjectionPoint implementation is fully
* <b>stateless</b>.</p>
* <h4>Built-in Injection Points</h4>
*
* <p>The following built-in Injection Points are available:</p>
*
* <ul>
* <li>{@link MethodHead HEAD} - Selects the first insn</li>
* <li>{@link BeforeReturn RETURN} - Selects RETURN insns</li>
* <li>{@link BeforeFinalReturn TAIL} - Selects the last RETURN insn</li>
* <li>{@link BeforeInvoke INVOKE} - Selects method invocations</li>
* <li>{@link AfterInvoke INVOKE_ASSIGN} - Selects STORE insns after method
* invocations which return a value</li>
* <li>{@link BeforeFieldAccess FIELD} - Selects field access insns</li>
* <li>{@link BeforeNew NEW} - Selects object constructions</li>
* <li>{@link BeforeStringInvoke INVOKE_STRING} - Selects method invocations
* where a specific string is passed to the invocation.</li>
* <li>{@link JumpInsnPoint JUMP} - Selects branching (jump) instructions</li>
* <li>{@link BeforeConstant CONSTANT} - Selects constant values</li>
* </ul>
*
* <p>Additionally, the two special injection points are available which are
* only supported for use with {@link ModifyVariable &#64;ModifyVariable}:</p>
*
* <ul>
* <li>{@link BeforeLoadLocal LOAD} - Selects xLOAD insns matching the <tt>
* ModifyVariable</tt> discriminators.</li>
* <li>{@link AfterStoreLocal STORE} - Selects xSTORE insns matching the <tt>
* ModifyVariable</tt> discriminators.</li>
* </ul>
*
* <p>See the javadoc for each type for more details on the scheme used by each
* injection point.</p>
*
* <h4>Custom Injection Points</h4>
*
* <p>You are free to create your own injection point subclasses. Once defined,
* they can be used by your mixins in one of two ways:</p>
*
* <ol>
* <li>Specify the fully-qualified name of the injection point class in the
* {@link At#value &#64;At.value}.</li>
* <li>Decorate your injection point class with {@link AtCode &#64;AtCode}
* annotation which specifies a namespace and shortcode for the injection
* point, and register the class in your mixin config. You can then specify
* the namespaced code (eg. <tt>MYMOD:CUSTOMPOINT</tt>) in {@link At#value
* &#64;At.value}.</li>
* </ol>
*
* <p>When writing custom injection points, note that the general contract of
* injection points is that they be entirely - or at least behaviourally -
* stateless. It <b>is allowed</b> for a single InjectionPoint instance to be
* used by the mixin processor for multiple injections and thus implementing
* classes <em>MUST NOT</em> cache the insn list, event, or nodes instance
* passed to the {@link #find find} method, as each call to {@link #find find}
* must be considered a separate contract and the InjectionPoint's lifespan is
* not linked to the discovery lifespan. It is therefore important that the
* InjectionPoint implementation is fully stateless and that calls to
* {@link #find find} are idempotent.</p>
*/
public abstract class InjectionPoint {
@@ -91,9 +145,18 @@ public abstract class InjectionPoint {
@Target(ElementType.TYPE)
public @interface AtCode {
/**
* Namespace for this code. Final selectors will be specified as
* <tt>&lt;namespace&gt;:&lt;code&gt;</tt> in order to avoid overlaps
* between consumer-provided injection points. Uses namespace from
* parent config if not specified.
*/
public String namespace() default "";
/**
* The string code used to specify the annotated injection point in At
* annotations
* annotations, prefixed with namespace from the annotation or from the
* declaring configuration.
*/
public String value();
@@ -199,18 +262,18 @@ public abstract class InjectionPoint {
static {
// Standard Injection Points
InjectionPoint.register(BeforeFieldAccess.class);
InjectionPoint.register(BeforeInvoke.class);
InjectionPoint.register(BeforeNew.class);
InjectionPoint.register(BeforeReturn.class);
InjectionPoint.register(BeforeStringInvoke.class);
InjectionPoint.register(JumpInsnPoint.class);
InjectionPoint.register(MethodHead.class);
InjectionPoint.register(AfterInvoke.class);
InjectionPoint.register(BeforeLoadLocal.class);
InjectionPoint.register(AfterStoreLocal.class);
InjectionPoint.register(BeforeFinalReturn.class);
InjectionPoint.register(BeforeConstant.class);
InjectionPoint.registerBuiltIn(BeforeFieldAccess.class);
InjectionPoint.registerBuiltIn(BeforeInvoke.class);
InjectionPoint.registerBuiltIn(BeforeNew.class);
InjectionPoint.registerBuiltIn(BeforeReturn.class);
InjectionPoint.registerBuiltIn(BeforeStringInvoke.class);
InjectionPoint.registerBuiltIn(JumpInsnPoint.class);
InjectionPoint.registerBuiltIn(MethodHead.class);
InjectionPoint.registerBuiltIn(AfterInvoke.class);
InjectionPoint.registerBuiltIn(BeforeLoadLocal.class);
InjectionPoint.registerBuiltIn(AfterStoreLocal.class);
InjectionPoint.registerBuiltIn(BeforeFinalReturn.class);
InjectionPoint.registerBuiltIn(BeforeConstant.class);
}
private final String slice;
@@ -467,9 +530,23 @@ public abstract class InjectionPoint {
List<AbstractInsnNode> list = (nodes instanceof List) ? (List<AbstractInsnNode>) nodes : new ArrayList<AbstractInsnNode>(nodes);
this.input.find(desc, insns, nodes);
for (int i = 0; i < list.size(); i++) {
list.set(i, insns.get(insns.indexOf(list.get(i)) + this.shift));
for (ListIterator<AbstractInsnNode> iter = list.listIterator(); iter.hasNext();) {
int sourceIndex = insns.indexOf(iter.next());
int newIndex = sourceIndex + this.shift;
if (newIndex >= 0 && newIndex < insns.size()) {
iter.set(insns.get(newIndex));
} else {
// Shifted beyond the start or end of the insnlist, into the dark void
iter.remove();
// Decorate the injector with the info in case it fails
int absShift = Math.abs(this.shift);
char operator = absShift != this.shift ? '-' : '+';
this.input.addMessage(
"@At.shift offset outside the target bounds: Index (index(%d) %s offset(%d) = %d) is outside the allowed range (0-%d)",
sourceIndex, operator, absShift, newIndex, insns.size());
}
}
if (nodes != list) {
@@ -566,7 +643,7 @@ public abstract class InjectionPoint {
public static List<InjectionPoint> parse(IInjectionPointContext context, List<AnnotationNode> ats) {
Builder<InjectionPoint> injectionPoints = ImmutableList.<InjectionPoint>builder();
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(context, at);
InjectionPoint injectionPoint = InjectionPoint.parse(new InjectionPointAnnotationContext(context, at, "at"), at);
if (injectionPoint != null) {
injectionPoints.add(injectionPoint);
}
@@ -617,7 +694,7 @@ public abstract class InjectionPoint {
* failed
*/
public static InjectionPoint parse(IMixinContext context, MethodNode method, AnnotationNode parent, AnnotationNode at) {
return InjectionPoint.parse(new AnnotatedMethodInfo(context, method, parent), at);
return InjectionPoint.parse(new InjectionPointAnnotationContext(new AnnotatedMethodInfo(context, method, parent), at, "at"), at);
}
/**
@@ -694,19 +771,19 @@ public abstract class InjectionPoint {
public static InjectionPoint parse(IInjectionPointContext context, String at, At.Shift shift, int by,
List<String> args, String target, String slice, int ordinal, int opcode, String id) {
InjectionPointData data = new InjectionPointData(context, at, args, target, slice, ordinal, opcode, id);
Class<? extends InjectionPoint> ipClass = findClass(context.getContext(), data);
InjectionPoint point = InjectionPoint.create(context.getContext(), data, ipClass);
Class<? extends InjectionPoint> ipClass = InjectionPoint.findClass(context.getMixin(), data);
InjectionPoint point = InjectionPoint.create(context.getMixin(), data, ipClass);
return InjectionPoint.shift(context, point, shift, by);
}
@SuppressWarnings("unchecked")
private static Class<? extends InjectionPoint> findClass(IMixinContext context, InjectionPointData data) {
String type = data.getType();
Class<? extends InjectionPoint> ipClass = InjectionPoint.types.get(type);
Class<? extends InjectionPoint> ipClass = InjectionPoint.types.get(type.toUpperCase(Locale.ROOT));
if (ipClass == null) {
if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) {
if (type.matches("^([A-Za-z_][A-Za-z0-9_]*[\\.\\$])+[A-Za-z_][A-Za-z0-9_]*$")) {
try {
ipClass = (Class<? extends InjectionPoint>)Class.forName(type);
ipClass = (Class<? extends InjectionPoint>)MixinService.getService().getClassProvider().findClass(type);
InjectionPoint.types.put(type, ipClass);
} catch (Exception ex) {
throw new InvalidInjectionException(context, data + " could not be loaded or is not a valid InjectionPoint", ex);
@@ -730,6 +807,8 @@ public abstract class InjectionPoint {
InjectionPoint point = null;
try {
point = ipCtor.newInstance(data);
} catch (InvocationTargetException ex) {
throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex.getCause());
} catch (Exception ex) {
throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex);
}
@@ -746,7 +825,7 @@ public abstract class InjectionPoint {
} else if (shift == At.Shift.AFTER) {
return InjectionPoint.after(point);
} else if (shift == At.Shift.BY) {
InjectionPoint.validateByValue(context.getContext(), context.getMethod(), context.getAnnotation(), point, by);
InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotationNode(), point, by);
return InjectionPoint.shift(point, by);
}
}
@@ -778,7 +857,7 @@ public abstract class InjectionPoint {
allowed = InjectionPoint.MAX_ALLOWED_SHIFT_BY;
}
String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Bytecode.getSimpleName(parent), point,
String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Annotations.getSimpleName(parent), point,
by, context, method.name, limitBreached, allowed, advice);
if (err == ShiftByViolationBehaviour.WARN && allowed < InjectionPoint.MAX_ALLOWED_SHIFT_BY) {
@@ -791,7 +870,7 @@ public abstract class InjectionPoint {
protected String getAtCode() {
AtCode code = this.getClass().<AtCode>getAnnotation(AtCode.class);
return code == null ? this.getClass().getName() : code.value();
return code == null ? this.getClass().getName() : code.value().toUpperCase();
}
/**
@@ -800,19 +879,56 @@ public abstract class InjectionPoint {
*
* @param type injection point type to register
*/
@Deprecated
public static void register(Class<? extends InjectionPoint> type) {
InjectionPoint.register(type, null);
}
/**
* Register an injection point class. The supplied class must be decorated
* with an {@link AtCode} annotation for registration purposes.
*
* @param type injection point type to register
* @param namespace namespace for AtCode
*/
public static void register(Class<? extends InjectionPoint> type, String namespace) {
AtCode code = type.<AtCode>getAnnotation(AtCode.class);
if (code == null) {
throw new IllegalArgumentException("Injection point class " + type + " is not annotated with @AtCode");
}
String annotationNamespace = code.namespace();
if (!Strings.isNullOrEmpty(annotationNamespace)) {
namespace = annotationNamespace;
}
Class<? extends InjectionPoint> existing = InjectionPoint.types.get(code.value());
if (existing != null && !existing.equals(type)) {
LogManager.getLogger("mixin").debug("Overriding InjectionPoint {} with {} (previously {})", code.value(), type.getName(),
existing.getName());
} else if (Strings.isNullOrEmpty(namespace)) {
LogManager.getLogger("mixin").warn("Registration of InjectionPoint {} with {} without specifying namespace is deprecated.",
code.value(), type.getName());
}
InjectionPoint.types.put(code.value(), type);
String id = code.value().toUpperCase(Locale.ROOT);
if (!Strings.isNullOrEmpty(namespace)) {
id = namespace.toUpperCase(Locale.ROOT) + ":" + id;
}
InjectionPoint.types.put(id, type);
}
/**
* Register a built-in injection point class. Skips validation and
* namespacing checks
*
* @param type injection point type to register
*/
private static void registerBuiltIn(Class<? extends InjectionPoint> type) {
String code = type.<AtCode>getAnnotation(AtCode.class).value().toUpperCase(Locale.ROOT);
InjectionPoint.types.put(code, type);
InjectionPoint.types.put("MIXIN:" + code, type);
}
}
@@ -38,24 +38,35 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject an argument modifier to itself
* in the target method(s) identified by {@link #method}. This type of injection
* provides a lightweight mechanism for changing a single argument of a target
* method invocation. To affect multiple arguments at once, use {@link
* ModifyArgs} instead.
* provides a lightweight mechanism for changing a single argument of a selected
* method invocation within the target method(s). To affect multiple arguments
* of an invocation all at once, use {@link ModifyArgs} instead.
*
* <p>Consider the following method call:</p>
* <p>Use this injector when a method contains an method invocation and you wish
* to change a single value being <em>passed to</em> that method. If you need to
* alter an argument <em>received by</em> a target method, use {@link
* ModifyVariable} instead.</p>
*
* <blockquote><pre>// x, y and z are of type float
*someObject.setLocation(x, y, z, true);</pre></blockquote>
* <p>Consider the following method:</p>
*
* <p>Let us assume that we wish to modify the <tt>y</tt> value in the method
* call. We know that the arguments are <tt>float</tt>s and that the <tt>y</tt>
* value is the <em>second</em> (index = 1) <tt>float</tt> argument. Thus our
* injector requires the following signature:
* <blockquote><pre><code>private void targetMethod() {
* Entity someEntity = this.obtainEntity();
* float x = 1.0F, y = 3.0F, z = 0.1F;
* someEntity.<ins>setLocation</ins>(x, <ins>y</ins>, z, true);
*}</code></pre>
*</blockquote>
*
* <p>Let us assume that we wish to modify the <ins><tt>y</tt></ins> value when
* calling the <ins><tt>setLocation</tt></ins> method. We know that the
* arguments are <tt>float</tt>s and that the <tt>y</tt> value is the <em>second
* </em> (index = 1) <tt>float</tt> argument. Thus our injector requires the
* following signature:
*
* <blockquote><pre>&#064;ModifyArg(method = "...", at = ..., index = 1)
*private float adjustYCoord(float y) {
* return y + 64.0F;
*}</pre></blockquote>
* <blockquote><code>&#064;ModifyArg(method = "targetMethod", at = &#64;At(value
* = "INVOKE", target = "<ins>setLocation(FFFZ)V</ins>"), index = 1)<br />
* private float adjustYCoord(float y) {<br />
* &nbsp; &nbsp; return y + 64.0F;<br />
* }</code></blockquote>
*
* <p>The callback consumes the original value of <tt>y</tt> and returns the
* adjusted value.</p>
@@ -64,10 +75,11 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* arguments if required, to provide additional context for the callback. In
* this case the arguments of the callback should match the target method:</p>
*
* <blockquote><pre>&#064;ModifyArg(method = "...", at = ..., index = 1)
*private float adjustYCoord(float x, float y, float z, boolean interpolate) {
* return (x == 0 && y == 0) ? 0 : y;
*}</pre></blockquote>
* <blockquote><code>&#064;ModifyArg(method = "targetMethod", at = &#64;At(value
* = "INVOKE", target = "<ins>setLocation(FFFZ)V</ins>"), index = 1)<br />
* private float adjustYCoord(float x, float y, float z, boolean interpolate) {
* <br />&nbsp; &nbsp; return (x == 0 &amp;&amp; y == 0) ? 0 : y;<br />
* }</code></blockquote>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -80,7 +92,15 @@ public @interface ModifyArg {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -85,7 +85,15 @@ public @interface ModifyArgs {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -67,7 +67,15 @@ public @interface ModifyConstant {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* Array of {@link Slice} annotations which describe the method bisections
@@ -30,6 +30,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
@@ -37,20 +39,29 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject a variable modifier callback
* to itself in the target method(s) identified by {@link #method}.
* to itself in the target method(s) identified by {@link #method}. The variable
* modifier can modify a single local variable in the target method frame.
*
* <p>If the variable being modified is a method argument, specifying the
* <tt>{@link #argsOnly argsOnly=true}</tt> reduces the overhead of calculating
* the local variable table for the method.</p>
*
* <p><tt>ModifyVariable</tt> callbacks should always take one argument of the
* type to capture and return the same type. For example a <tt>ModifyVariable
* </tt> for a local of type {@link String} should have the signature:</p>
* </tt> for a local of type <ins>{@link String}</ins> should have the
* signature:</p>
*
* <code>private String methodName(String variable) { ...</code>
* <blockquote><code>private <ins>String</ins> myHandlerMethod(<ins>String</ins>
* variable) {<br />&nbsp; &nbsp; ...</code></blockquote>
*
* <p>The callback receives the current value of the local variable, and should
* return the new value.</p>
*
* <p>The injector has two operating modes, <em>explicit</em> and <em>implicit
* </em>, and can operate either on the entire LVT or on the method arguments
* only</p>.
* </em>, and can operate either on the entire LVT or on the {@link #argsOnly
* method arguments only}.</p>
*
* <h4>Explicit mode</h4>
*
* <p>In <em>explicit</em> mode, the variable to capture can be specified by
* specifying values for the discriminator arguments {@link #ordinal},
@@ -58,12 +69,32 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* order to attempt to locate the variable to capture. If no local variable
* matches any discriminators, the capture fails.</p>
*
* <h4>Implicit mode</h4>
*
* <p>If no values for the capture discrimiators are specified, the injector
* operates in <em>implicit</em> mode. If exactly one variable of the capture
* type exists in the target LVT, then capture will succeed. However, if more
* than one variable of the required type is encountered in the LVT then an
* {@link InvalidInjectionException} is thrown.</p>
*
* <h4>Context-sensitive injection points</h4>
*
* <p>Normally the {@link InjectionPoint injection points} specified by {@link
* #at} are independent of the injector being used. With <tt>ModifyVariable</tt>
* there are two special injection points which consume the discriminator from
* the annotation:</p>
*
* <ul>
* <li>{@link BeforeLoadLocal LOAD} - matches <tt>xLOAD</tt> insns <em>for
* the variable matched by the discriminator</em> in the target method.</li>
* <li>{@link AfterStoreLocal STORE} - matches <tt>xSTORE</tt> insns <em>for
* the variable matched by the discriminator</em> in the target method.</li>
* </ul>
*
* <p>See the javadoc for each injection point for details.</p>
*
* <h4>Notes</h4>
*
* <p>Like other injectors, the callback signature can optionally include the
* target method arguments by simply appending them to the handler method
* signature.</p>
@@ -79,7 +110,15 @@ public @interface ModifyVariable {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -93,7 +132,8 @@ public @interface ModifyVariable {
* An {@link At} annotation which describes the {@link InjectionPoint} in
* the target method.
*
* @return {@link At} which identifies the target method invocation
* @return {@link At} which identifies the location to inject inside the
* target method.
*/
public At at();
@@ -55,7 +55,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* int def = 1;
* Foo someObject = new Foo();
*
* // Hooking this method
* <del>// Hooking this method</del>
* boolean xyz = someObject.bar(abc, def);
*}</pre>
* </blockquote>
@@ -63,7 +63,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <p>The signature of the redirected method should be:</p>
*
* <blockquote>
* <pre>public boolean barProxy(Foo someObject, int abc, int def)</pre>
* <code>public boolean barProxy(Foo someObject, int abc, int def)</code>
* </blockquote>
*
* <p>For obvious reasons this does not apply for static methods, for static
@@ -77,8 +77,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* arguments) by appending the arguments to the method signature:</p>
*
* <blockquote>
* <pre>public boolean barProxy(Foo someObject, int abc, int def,
* int someInt, String someString)</pre>
* <code>public boolean barProxy(Foo someObject, int abc, int def,
* int someInt, String someString)</code>
* </blockquote>
*
* <p>All arguments of a method redirect handler, and the return type, can be
@@ -92,7 +92,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* handling a field <b>write</b> (<tt>PUTFIELD</tt>, <tt>PUTSTATIC</tt>) or a
* field <b>read</b> (<tt>GETFIELD</tt>, <tt>GETSTATIC</tt>).</p>
*
* <table width="100%">
* <table width="100%" class="infoTable">
* <tr>
* <th width="25%">Operation (OPCODE)</th>
* <th>Handler signature</th>
@@ -148,7 +148,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <em>indices</em>, for multi-dimensional arrays) and returns <em>the element
* type</em> (in this case <tt>String</tt>) as follows:</p>
*
* <table width="100%">
* <table width="100%" class="infoTable">
* <tr>
* <th width="25%">Operation</th>
* <th>Handler signature</th>
@@ -177,16 +177,16 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <tt>array=length</tt> and configure your handler signature to return <tt>int
* </tt> and consume the array as an argument:</p>
*
* <blockquote><code>private int getLength(<b>ElementType</b>[] array)
* <blockquote><code>private int getLength(<ins>ElementType</ins>[] array)
* </code></blockquote>
*
* -
* <p>For multi-dimensional arrays, provide one <tt>int</tt> argument for each
* additional dimension of the array:</p>
*
* <blockquote><code>// Multidimensional array<br />
* private <b>ElementType</b>[][] array;<br /><br />
* // Handler signature:<br />
* private <b>int</b> getLength(<b>ElementType</b>[][] array, int baseDim)
* <blockquote><code><del>// Multidimensional array</del><br />
* private <ins>ElementType</ins>[][] array;<br /><br />
* <del>// Handler signature:</del><br /> private <ins>int</ins>
* getLength(<ins>ElementType</ins>[][] array, int baseDim)
* </code></blockquote>
*
* <h3>New Object Redirect Mode (Factory Mode)</h3>
@@ -211,7 +211,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
*class Foo {
* private final int x, y;
*
* // ctor we wish to hook
* <del>// ctor we wish to hook</del>
* Foo(int x, int y) {
* this.x = x;
* this.y = y;
@@ -231,7 +231,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* example to redirect the following object creation call:</p>
*
* <blockquote><pre>public void exampleFunc(String someString, int dx, int dy) {
* // Hooking this constructor
* <del>// Hooking this constructor</del>
* Foo someFoo = new Foo(dx * 10, dy * 10);
*}</pre>
* </blockquote>
@@ -239,15 +239,15 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <p>The signature of the handler method should be:</p>
*
* <blockquote>
* <pre>public Foo constructFoo(int x, int y)</pre>
* <code>public Foo constructFoo(int x, int y)</code>
* </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>
*
* <blockquote>
* <tt>public Foo constructFoo(int x, int y, String someString, int dx,
* int dy)</tt>
* <code>public Foo constructFoo(int x, int y, String someString, int dx,
* int dy)</code>
* </blockquote>
*
* <h3><tt>instanceof</tt> Redirect Mode</h3>
@@ -277,8 +277,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
*
* <p>Note that this results in the injected code being less efficient, because
* the <tt>instanceof</tt> opcode is replaced with discrete code similar to <tt>
* reference != null && yourClass.isAssignableFrom(reference.getClass())</tt> in
* the target method body.</p>
* reference != null &amp;&amp; yourClass.isAssignableFrom(reference.getClass())
* </tt> in the target method body.</p>
*
* <p>The arguments to an <tt>instanceof</tt> redirect handler <b>must always be
* <tt>Object, Class</tt> even if the variable type is known</b>. This is
@@ -298,7 +298,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
*
* <blockquote><pre>class Foo : Bar {
* Foo(int arg) {
* super(<span style="background: #FF0">Foo.isEven(arg)</span>);
* super(<ins>Foo.isEven(arg)</ins>);
* }
*
* static int isEven(int arg) {
@@ -326,7 +326,15 @@ public @interface Redirect {
*
* @return target method(s) for this injector
*/
public String[] method();
public String[] method() default {};
/**
* Literal representation of one or more {@link Desc &#064;Desc} annotations
* which identify the target methods.
*
* @return target method(s) for this injector as descriptors
*/
public Desc[] target() default {};
/**
* A {@link Slice} annotation which describes the method bisection used in
@@ -85,7 +85,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
* thing.<b>processStuff</b>();
* }
*
* // A new call to processStuff, which now has the ordinal 1
* <del>// A new call to processStuff, which now has the ordinal 1</del>
* bar.getActiveThing().<b>processStuff</b>();
*
* Thing specialThing = bar.getSpecialThing();
@@ -34,13 +34,14 @@ import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.code.Injector;
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;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Annotations;
@@ -53,7 +54,8 @@ import org.spongepowered.asm.util.SignaturePrinter;
import com.google.common.base.Strings;
/**
* This class is responsible for generating the bytecode for injected callbacks
* This class is responsible for generating the bytecode for injected callbacks,
* for details of usage see {@link Inject &#64;Inject}.
*/
public class CallbackInjector extends Injector {
@@ -324,6 +326,11 @@ public class CallbackInjector extends Injector {
}
/**
* Decorator key for local variables decoration
*/
private static final String LOCALS_KEY = "locals";
/**
* True if cancellable
*/
@@ -425,6 +432,19 @@ public class CallbackInjector extends Injector {
myNodes.add(injectionNode);
this.totalInjections++;
}
@Override
protected void preInject(Target target, InjectionNode node) {
if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget());
for (int j = 0; j < locals.length; j++) {
if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) {
locals[j] = null;
}
}
node.<LocalVariableNode[]>decorate(CallbackInjector.LOCALS_KEY, locals);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector
@@ -433,17 +453,7 @@ public class CallbackInjector extends Injector {
*/
@Override
protected void inject(Target target, InjectionNode node) {
LocalVariableNode[] locals = null;
if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget());
for (int j = 0; j < locals.length; j++) {
if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) {
locals[j] = null;
}
}
}
LocalVariableNode[] locals = node.<LocalVariableNode[]>getDecoration(CallbackInjector.LOCALS_KEY);
this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals()));
}
@@ -465,7 +475,7 @@ public class CallbackInjector extends Injector {
MethodNode callbackMethod = this.methodNode;
if (!callback.checkDescriptor(this.methodNode.desc)) {
if (this.info.getTargets().size() > 1) {
if (this.info.getTargetCount() > 1) {
return; // Look for a match in other targets before failing
}
@@ -539,13 +549,15 @@ public class CallbackInjector extends Injector {
*/
private String generateBadLVTMessage(final Callback callback) {
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));
int targetArgc = callback.target.arguments.length + 1;
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, targetArgc, 255);
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), targetArgc, expected.size());
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);
List<String> available = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), targetArgc, 255);
return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\n Expected: %s\n Found: %s\nAvailable: %s",
callback.target, position, this.info, expected, found, available);
}
/**
@@ -793,14 +805,14 @@ public class CallbackInjector extends Injector {
return this.isStatic;
}
private static List<String> summariseLocals(String desc, int pos) {
return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos);
private static List<String> summariseLocals(String desc, int pos, int count) {
return CallbackInjector.summariseLocals(Type.getArgumentTypes(desc), pos, count);
}
private static List<String> summariseLocals(Type[] locals, int pos) {
private static List<String> summariseLocals(Type[] locals, int pos, int count) {
List<String> list = new ArrayList<String>();
if (locals != null) {
for (; pos < locals.length; pos++) {
for (; pos < locals.length && list.size() < count; pos++) {
if (locals[pos] != null) {
list.add(locals[pos].toString());
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Implementation of callback injector functionality provided by
* {@link org.spongepowered.asm.mixin.injection.Inject @#64;Inject}.
*/
package org.spongepowered.asm.mixin.injection.callback;
@@ -247,6 +247,18 @@ public abstract class Injector {
myNodes.add(target.addInjectionNode(node));
}
/**
* Performs pre-injection checks and tasks on the specified target
*
* @param target target potentially being injected into
* @param nodes selected target nodes
*/
public final void preInject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
this.preInject(target, node);
}
}
/**
* Performs the injection on the specified target
*
@@ -256,7 +268,7 @@ public abstract class Injector {
public final void inject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
if (node.isRemoved()) {
if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target);
}
continue;
@@ -279,7 +291,7 @@ public abstract class Injector {
* @return Target insn nodes in the target method
*/
private Collection<TargetNode> findTargetNodes(InjectorTarget injectorTarget, List<InjectionPoint> injectionPoints) {
IMixinContext mixin = this.info.getContext();
IMixinContext mixin = this.info.getMixin();
MethodNode method = injectorTarget.getMethod();
Map<Integer, TargetNode> targetNodes = new TreeMap<Integer, TargetNode>();
Collection<AbstractInsnNode> nodes = new ArrayList<AbstractInsnNode>(32);
@@ -295,7 +307,7 @@ public abstract class Injector {
injectorTarget, injectorTarget.getMergedBy(), injectorTarget.getMergedPriority()));
}
if (this.findTargetNodes(method, injectionPoint, injectorTarget.getSlice(injectionPoint), nodes)) {
if (this.findTargetNodes(method, injectionPoint, injectorTarget, nodes)) {
for (AbstractInsnNode insn : nodes) {
Integer key = method.instructions.indexOf(insn);
TargetNode targetNode = targetNodes.get(key);
@@ -311,8 +323,9 @@ public abstract class Injector {
return targetNodes.values();
}
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, insns, nodes);
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget,
Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes);
}
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
@@ -380,6 +393,10 @@ public abstract class Injector {
this.checkTargetModifiers(target, true);
}
protected void preInject(Target target, InjectionNode node) {
// stub
}
protected abstract void inject(Target target, InjectionNode node);
protected void postInject(Target target, InjectionNode node) {
@@ -438,7 +455,7 @@ public abstract class Injector {
this.pushArgs(args, insns, argMap, startArg, endArg);
return this.invokeHandler(insns);
}
/**
* Store args on the stack starting at the end and working back to position
* specified by start, return the generated argMap
@@ -450,8 +467,24 @@ public abstract class Injector {
* @return the generated argmap
*/
protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) {
return this.storeArgs(target, args, insns, start, null, null);
}
/**
* Store args on the stack starting at the end and working back to position
* specified by start, return the generated argMap
*
* @param target target method
* @param args argument types
* @param insns instruction list to generate insns into
* @param start Starting index
* @param from The label marking the start of the region for the locals
* @param to The label marking the end of the region for the stored locals
* @return the generated argmap
*/
protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start, LabelNode from, LabelNode to) {
int[] argMap = target.generateArgMap(args, start);
this.storeArgs(args, insns, argMap, start, args.length);
this.storeArgs(target, args, insns, argMap, start, args.length, from, to);
return argMap;
}
@@ -464,9 +497,25 @@ public abstract class Injector {
* @param start Starting index
* @param end Ending index
*/
protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
protected void storeArgs(Target target, Type[] args, InsnList insns, int[] argMap, int start, int end) {
this.storeArgs(target, args, insns, argMap, start, end, null, null);
}
/**
* Store args on the stack to their positions allocated based on 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
* @param from The label marking the start of the region for the locals
* @param to The label marking the end of the region for the stored locals
*/
protected void storeArgs(Target target, Type[] args, InsnList insns, int[] argMap, int start, int end, LabelNode from, LabelNode to) {
for (int arg = end - 1; arg >= start; arg--) {
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg]));
target.addLocalVariable(argMap[arg], String.format("injectorAllocatedLocal%d", argMap[arg]), args[arg].getDescriptor(), from, to);
}
}
@@ -521,7 +570,7 @@ public abstract class Injector {
* @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());
String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getMixin());
int argIndex = 0;
try {
injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs);
@@ -573,12 +622,13 @@ public abstract class Injector {
* 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));
}
Type fromType = index < 0 ? this.returnType : this.methodArgs[index];
AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index);
boolean isReturn = index < 0;
@@ -586,7 +636,7 @@ public abstract class Injector {
Object argIndex = isReturn ? "" : " at index " + index;
if (fromType.equals(toType)) {
if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (coerce != null && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex,
SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType));
}
@@ -618,12 +668,13 @@ public abstract class Injector {
* @param exceptionType Type of exception to throw (binary name)
* @param message Message to pass to the exception constructor
*/
protected void throwException(InsnList insns, String exceptionType, String message) {
protected void throwException(InsnList insns, Extension extraStack, String exceptionType, String message) {
insns.add(new TypeInsnNode(Opcodes.NEW, exceptionType));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new LdcInsnNode(message));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, exceptionType, "<init>", "(Ljava/lang/String;)V", false));
insns.add(new InsnNode(Opcodes.ATHROW));
extraStack.add(3);
}
/**
@@ -32,6 +32,7 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.util.Annotations;
@@ -50,15 +51,26 @@ public class InjectorTarget {
/**
* Cache of slices
*/
private final Map<String, ReadOnlyInsnList> cache = new HashMap<String, ReadOnlyInsnList>();
private final Map<String, InsnListReadOnly> cache = new HashMap<String, InsnListReadOnly>();
/**
* Target method data
*/
private final Target target;
/**
* Selector which selected this method
*/
private final ITargetSelector selector;
/**
* Name of the mixin which merged the target, if any
*/
private final String mergedBy;
/**
* Priority of the mixin which merged the target, if any
*/
private final int mergedPriority;
/**
@@ -67,9 +79,10 @@ public class InjectorTarget {
* @param context owner
* @param target target
*/
public InjectorTarget(ISliceContext context, Target target) {
public InjectorTarget(ISliceContext context, Target target, ITargetSelector selector) {
this.context = context;
this.target = target;
this.selector = selector;
AnnotationNode merged = Annotations.getVisible(target.method, MixinMerged.class);
this.mergedBy = Annotations.<String>getValue(merged, "mixin");
@@ -95,6 +108,13 @@ public class InjectorTarget {
return this.target.method;
}
/**
* Get the selector which selected this target
*/
public ITargetSelector getSelector() {
return this.selector;
}
/**
* Get whether this target method was merged by another mixin
*/
@@ -125,14 +145,14 @@ public class InjectorTarget {
* @return insn slice
*/
public InsnList getSlice(String id) {
ReadOnlyInsnList slice = this.cache.get(id);
InsnListReadOnly slice = this.cache.get(id);
if (slice == null) {
MethodSlice sliceInfo = this.context.getSlice(id);
if (sliceInfo != null) {
slice = sliceInfo.getSlice(this.target.method);
} else {
// No slice exists so just wrap the method insns
slice = new ReadOnlyInsnList(this.target.method.instructions);
slice = new InsnListReadOnly(this.target.method.instructions);
}
this.cache.put(id, slice);
}
@@ -154,7 +174,7 @@ public class InjectorTarget {
* Dispose all cached instruction lists
*/
public void dispose() {
for (ReadOnlyInsnList insns : this.cache.values()) {
for (InsnListReadOnly insns : this.cache.values()) {
insns.dispose();
}
@@ -34,11 +34,11 @@ import org.objectweb.asm.tree.InsnList;
* instances so that custom InjectionPoint implementations cannot modify the
* insn list whilst inspecting it.
*/
class ReadOnlyInsnList extends InsnList {
class InsnListReadOnly extends InsnList {
private InsnList insnList;
public ReadOnlyInsnList(InsnList insns) {
public InsnListReadOnly(InsnList insns) {
this.insnList = insns;
}
@@ -40,9 +40,9 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
import com.google.common.base.Strings;
@@ -57,7 +57,7 @@ public final class MethodSlice {
* identified by <tt>start</tt> and <tt>end</tt> to be accessed. In essence
* this class provides a <em>view</em> of the underlying InsnList.
*/
static final class InsnListSlice extends ReadOnlyInsnList {
static final class InsnListSlice extends InsnListReadOnly {
/**
* ListIterator for the slice view, wraps an iterator returned by the
@@ -359,7 +359,7 @@ public final class MethodSlice {
* @param method method to slice
* @return read only slice
*/
public ReadOnlyInsnList getSlice(MethodNode method) {
public InsnListReadOnly getSlice(MethodNode method) {
int max = method.instructions.size() - 1;
int start = this.find(method, this.from, 0, 0, this.name + "(from)");
int end = this.find(method, this.to, max, start, this.name + "(to)");
@@ -373,7 +373,7 @@ public final class MethodSlice {
}
if (start == 0 && end == max) {
return new ReadOnlyInsnList(method.instructions);
return new InsnListReadOnly(method.instructions);
}
return new InsnListSlice(method.instructions, start, end);
@@ -398,7 +398,7 @@ public final class MethodSlice {
}
Deque<AbstractInsnNode> nodes = new LinkedList<AbstractInsnNode>();
ReadOnlyInsnList insns = new ReadOnlyInsnList(method.instructions);
InsnListReadOnly insns = new InsnListReadOnly(method.instructions);
boolean result = injectionPoint.find(method.desc, insns, nodes);
Selector select = injectionPoint.getSelector();
if (nodes.size() != 1 && select == Selector.ONE) {
@@ -406,7 +406,7 @@ public final class MethodSlice {
}
if (!result) {
if (this.owner.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (this.owner.getMixin().getOption(Option.DEBUG_VERBOSE)) {
MethodSlice.logger.warn("{} did not match any instructions", this.describe(description));
}
return failValue;
@@ -432,9 +432,9 @@ public final class MethodSlice {
}
private static String describeSlice(String description, ISliceContext owner) {
String annotation = Bytecode.getSimpleName(owner.getAnnotation());
String annotation = Annotations.getSimpleName(owner.getAnnotationNode());
MethodNode method = owner.getMethod();
return String.format("%s->%s(%s)::%s%s", owner.getContext(), annotation, description, method.name, method.desc);
return String.format("%s->%s(%s)::%s%s", owner.getMixin(), annotation, description, method.name, method.desc);
}
private static String getSliceName(String id) {
@@ -469,12 +469,17 @@ public final class MethodSlice {
*/
public static MethodSlice parse(ISliceContext info, AnnotationNode node) {
String id = Annotations.<String>getValue(node, "id");
String coord = "slice";
if (!Strings.isNullOrEmpty(id)) {
coord += "." + id;
}
InjectionPointAnnotationContext sliceContext = new InjectionPointAnnotationContext(info, node, coord);
AnnotationNode from = Annotations.<AnnotationNode>getValue(node, "from");
AnnotationNode to = Annotations.<AnnotationNode>getValue(node, "to");
InjectionPoint fromPoint = from != null ? InjectionPoint.parse(info, from) : null;
InjectionPoint toPoint = to != null ? InjectionPoint.parse(info, to) : null;
InjectionPoint fromPoint = from != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, from, "from"), from) : null;
InjectionPoint toPoint = to != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, to, "to"), to) : null;
return new MethodSlice(info, id, fromPoint, toPoint);
}
@@ -99,7 +99,7 @@ public final class MethodSlices {
public static MethodSlices parse(InjectionInfo info) {
MethodSlices slices = new MethodSlices(info);
AnnotationNode annotation = info.getAnnotation();
AnnotationNode annotation = info.getAnnotationNode();
if (annotation != null) {
for (AnnotationNode node : Annotations.<AnnotationNode>getValue(annotation, "slice", true)) {
MethodSlice slice = MethodSlice.parse(info, node);
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Common base classes for injector implementations.
*/
package org.spongepowered.asm.mixin.injection.code;
@@ -32,16 +32,17 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.ModifyArg;
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;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Bytecode;
/**
* A bytecode injector which allows a single argument of a chosen method call to
* be altered.
* be altered. For details see javadoc for {@link ModifyArg &#64;ModifyArg}.
*/
public class ModifyArgInjector extends InvokeInjector {
@@ -31,17 +31,18 @@ import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.ModifyArgs;
import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator;
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;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Bytecode;
/**
* A bytecode injector which allows a single argument of a chosen method call to
* be altered.
* be altered. For details see javadoc for {@link ModifyArgs &#64;ModifyArgs}.
*/
public class ModifyArgsInjector extends InvokeInjector {
@@ -53,7 +54,7 @@ public class ModifyArgsInjector extends InvokeInjector {
public ModifyArgsInjector(InjectionInfo info) {
super(info, "@ModifyArgs");
this.argsClassGenerator = info.getContext().getExtensions().<ArgsClassGenerator>getGenerator(ArgsClassGenerator.class);
this.argsClassGenerator = info.getMixin().getExtensions().<ArgsClassGenerator>getGenerator(ArgsClassGenerator.class);
}
/* (non-Javadoc)
@@ -84,7 +85,7 @@ public class ModifyArgsInjector extends InvokeInjector {
+ targetMethod.name + targetMethod.desc + " with no arguments!");
}
String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getContext().getMixin()).getName();
String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getMixin().getMixin()).getName();
boolean withArgs = this.verifyTarget(target);
InsnList insns = new InsnList();
@@ -36,6 +36,7 @@ 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.ModifyConstant;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.util.InsnFinder;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
@@ -49,7 +50,8 @@ import org.spongepowered.asm.util.SignaturePrinter;
/**
* A bytecode injector which allows a specific constant value to be identified
* and replaced with a callback
* and replaced with a callback. For details see javadoc for
* {@link ModifyConstant &#64;ModifyConstant}.
*/
public class ModifyConstantInjector extends RedirectInjector {
@@ -133,7 +135,7 @@ public class ModifyConstantInjector extends RedirectInjector {
private void injectConstantModifier(Target target, AbstractInsnNode constNode) {
final Type constantType = Bytecode.getConstantType(constNode);
if (constantType.getSort() <= Type.INT && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
if (constantType.getSort() <= Type.INT && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) {
this.checkNarrowing(target, constNode, constantType);
}
@@ -58,14 +58,17 @@ import com.google.common.primitives.Ints;
* method. For method redirects, 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 object instance the method was going to be
* invoked upon. For example when hooking the following call:</p>
* invoked upon. For more details see the javadoc for the {@link Redirect
* &#64;Redirect} annotation.</p>
*
* <p>For example when hooking the following call:</p>
*
* <blockquote><pre>
* int abc = 0;
* int def = 1;
* Foo someObject = new Foo();
*
* // Hooking this method
* <del>// Hooking this method</del>
* boolean xyz = someObject.bar(abc, def);</pre>
* </blockquote>
*
@@ -79,8 +82,8 @@ import com.google.common.primitives.Ints;
* methods it is sufficient that the signature simply match the hooked method.
* </p>
*
* <p>For field redirections, see the details in {@link Redirect} for the
* required signature of the handler method.</p>
* <p>For field redirections, see the details in {@link Redirect &#64;Redirect}
* for the required signature of the handler method.</p>
*
* <p>For constructor redirections, the signature of the handler method should
* match the constructor itself, return type should be of the type of object
@@ -234,7 +237,7 @@ public class RedirectInjector extends InvokeInjector {
protected RedirectInjector(InjectionInfo info, String annotationType) {
super(info, annotationType);
int priority = info.getContext().getPriority();
int priority = info.getMixin().getPriority();
boolean isFinal = Annotations.getVisible(this.methodNode, Final.class) != null;
this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc);
}
@@ -463,7 +466,7 @@ public class RedirectInjector extends InvokeInjector {
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)) {
this.annotationType, this, this.info.getMixin()), true)) {
elementType = this.methodArgs[valueArgIndex];
}
@@ -774,7 +777,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, RedirectInjector.NPE, String.format("%s %s %s returned null for %s",
this.throwException(insns, extraStack, RedirectInjector.NPE, String.format("%s %s %s returned null for %s",
this.annotationType, type, this, value));
insns.add(nullCheckSucceeded);
extraStack.add();
@@ -0,0 +1,32 @@
/*
* 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.
*/
/**
* Support classes for
* {@link org.spongepowered.asm.mixin.injection.ModifyArgs &#64;ModifyArgs}
* which handle argument bundles
* ({@link org.spongepowered.asm.mixin.injection.invoke.arg.Args}).
*/
package org.spongepowered.asm.mixin.injection.invoke.arg;
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Implementation of injectors which primarily mutate method invocations.
*/
package org.spongepowered.asm.mixin.injection.invoke;
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Utility classes for invoke injectors.
*/
package org.spongepowered.asm.mixin.injection.invoke.util;
@@ -30,6 +30,7 @@ import java.util.ListIterator;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
@@ -199,10 +200,10 @@ public class BeforeLoadLocal extends LocalVariableInjectionPoint {
}
@Override
boolean find(InjectionInfo info, Target target, Collection<AbstractInsnNode> nodes) {
boolean find(InjectionInfo info, InsnList insns, Collection<AbstractInsnNode> nodes, Target target) {
SearchState state = new SearchState();
ListIterator<AbstractInsnNode> iter = target.method.instructions.iterator();
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (state.isPendingCheck()) {
@@ -145,13 +145,16 @@ public class LocalVariableDiscriminator {
}
}
Local[] lvt = new Local[this.baseArgIndex + target.arguments.length];
Local[] lvt = new Local[this.baseArgIndex + Bytecode.getArgsSize(target.arguments)];
if (!this.isStatic) {
lvt[0] = new Local("this", Type.getObjectType(target.classNode.name));
}
for (int local = this.baseArgIndex; local < lvt.length; local++) {
Type arg = target.arguments[local - this.baseArgIndex];
lvt[local] = new Local("arg" + local, arg);
for (int local = this.baseArgIndex, arg = 0; local < lvt.length; local++) {
Type argType = target.arguments[arg++];
lvt[local] = new Local("arg" + local, argType);
if (argType.getSize() == 2) {
lvt[++local] = null;
}
}
return lvt;
}
@@ -37,11 +37,13 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.code.InjectorTarget;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.Bytecode;
@@ -54,7 +56,7 @@ import org.spongepowered.asm.util.SignaturePrinter;
* {@link ModifyVariable}.
*/
public class ModifyVariableInjector extends Injector {
/**
* Target context information
*/
@@ -80,7 +82,7 @@ public class ModifyVariableInjector extends Injector {
LocalVariableInjectionPoint(InjectionPointData data) {
super(data);
this.mixin = data.getContext();
this.mixin = data.getMixin();
}
@Override
@@ -88,15 +90,20 @@ public class ModifyVariableInjector extends Injector {
throw new InvalidInjectionException(this.mixin, this.getAtCode() + " injection point must be used in conjunction with @ModifyVariable");
}
abstract boolean find(InjectionInfo info, Target target, Collection<AbstractInsnNode> nodes);
abstract boolean find(InjectionInfo info, InsnList insns, Collection<AbstractInsnNode> nodes, Target target);
}
/**
* Decorator key for Context decoration
*/
private static final String LOCALS_CONTEXT_KEY = "localcontext";
/**
* True to consider only method args
*/
private final LocalVariableDiscriminator discriminator;
/**
* @param info Injection info
* @param discriminator discriminator
@@ -107,12 +114,13 @@ public class ModifyVariableInjector extends Injector {
}
@Override
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InjectorTarget injectorTarget,
Collection<AbstractInsnNode> nodes) {
if (injectionPoint instanceof LocalVariableInjectionPoint) {
Target target = this.info.getContext().getTargetMethod(into);
return ((LocalVariableInjectionPoint)injectionPoint).find(this.info, target, nodes);
return ((LocalVariableInjectionPoint)injectionPoint).find(this.info, injectorTarget.getSlice(injectionPoint), nodes,
injectorTarget.getTarget());
}
return injectionPoint.find(into.desc, insns, nodes);
return injectionPoint.find(into.desc, injectorTarget.getSlice(injectionPoint), nodes);
}
/* (non-Javadoc)
@@ -134,6 +142,12 @@ public class ModifyVariableInjector extends Injector {
}
}
@Override
protected void preInject(Target target, InjectionNode node) {
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
node.<Context>decorate(ModifyVariableInjector.LOCALS_CONTEXT_KEY, context);
}
/**
* Do the injection
*/
@@ -143,15 +157,27 @@ public class ModifyVariableInjector extends Injector {
throw new InvalidInjectionException(this.info, "Variable modifier target for " + this + " was removed by another injector");
}
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
Context context = node.<Context>getDecoration(ModifyVariableInjector.LOCALS_CONTEXT_KEY);
if (context == null) {
throw new InjectionError(String.format(
"%s injector target is missing CONTEXT decoration for %s. PreInjection failure or illegal internal state change",
this.annotationType, this.info));
}
if (this.discriminator.printLVT()) {
this.printLocals(target, context);
}
this.checkTargetForNode(target, node, RestrictTargetLevel.ALLOW_ALL);
InjectorData handler = new InjectorData(target, "handler", false);
if (this.returnType == Type.VOID_TYPE) {
throw new InvalidInjectionException(this.info, String.format(
"%s %s method %s from %s has an invalid signature, cannot return a VOID type.",
this.annotationType, handler, this, this.info.getMixin()));
}
this.validateParams(handler, this.returnType, this.returnType);
Extension extraStack = target.extendStack();
@@ -0,0 +1,31 @@
/*
* 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.
*/
/**
* Implementation of variable modifier injector specified by
* {@link org.spongepowered.asm.mixin.injection.ModifyVariable
* &#64;ModifyVariable}
*/
package org.spongepowered.asm.mixin.injection.modify;
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Injectors are class postprocessors which search for annotated methods merged
* by mixins and perform weaving operations as requested.
*/
package org.spongepowered.asm.mixin.injection;
@@ -71,41 +71,41 @@ import com.google.common.primitives.Longs;
* <dt>ordinal</dt>
* <dd>The ordinal position of the constant opcode to match. The default value
* is <b>-1</b> which supresses ordinal matching</dd>
* <dt><em>named argument</em> nullValue</dt>
* <dt><i>named argument:</i> nullValue</dt>
* <dd>To match <tt>null</tt> literals in the method body, set this to
* <tt>true</tt></dd>
* <dt><em>named argument</em> intValue</dt>
* <dt><i>named argument:</i> intValue</dt>
* <dd>To match <tt>int</tt> literals in the method body. See also the
* <em>expandZeroConditions</em> argument below for concerns when matching
* conditional zeroes.</dd>
* <dt><em>named argument</em> floatValue</dt>
* <dt><i>named argument:</i> floatValue</dt>
* <dd>To match <tt>float</tt> literals in the method body.</dd>
* <dt><em>named argument</em> longValue</dt>
* <dt><i>named argument:</i> longValue</dt>
* <dd>To match <tt>long</tt> literals in the method body.</dd>
* <dt><em>named argument</em> doubleValue</dt>
* <dt><i>named argument:</i> doubleValue</dt>
* <dd>To match <tt>double</tt> literals in the method body.</dd>
* <dt><em>named argument</em> stringValue</dt>
* <dt><i>named argument:</i> stringValue</dt>
* <dd>To match {@link String} literals in the method body.</dd>
* <dt><em>named argument</em> classValue</dt>
* <dt><i>named argument:</i> classValue</dt>
* <dd>To match {@link Class} literals in the method body.</dd>
* <dt><em>named argument</em> log</dt>
* <dt><i>named argument:</i> log</dt>
* <dd>Enable debug logging when searching for matching opcodes.</dd>
* <dt><em>named argument</em> expandZeroConditions</dt>
* <dt><i>named argument:</i> expandZeroConditions</dt>
* <dd>See the {@link Constant#expandZeroConditions} option, this argument
* should be a list of {@link Condition} names</dd>
* </dl>
*
* <p>Examples:</p>
* <blockquote><pre>
* // Find all integer constans with value 4
* <del>// Find all integer constans with value 4</del>
* &#064;At(value = "CONSTANT", args = "intValue=4")</pre>
* </blockquote>
* <blockquote><pre>
* // Find the String literal "foo"
* <del>// Find the String literal "foo"</del>
* &#064;At(value = "CONSTANT", args = "stringValue=foo"</pre>
* </blockquote>
* <blockquote><pre>
* // Find all integer constants with value 0 and expand conditionals
* <del>// Find integer constants with value 0 and expand conditionals</del>
* &#064;At(
* value = "CONSTANT",
* args = {
@@ -182,9 +182,9 @@ public class BeforeConstant extends InjectionPoint {
String strClassValue = data.get("classValue", null);
this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null;
this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args");
this.matchByType = this.validateDiscriminator(data.getMixin(), "V", empty, "in @At(\"CONSTANT\") args");
if ("V".equals(this.matchByType)) {
throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args");
throw new InvalidInjectionException(data.getMixin(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args");
}
List<Condition> conditions = new ArrayList<Condition>();
@@ -236,7 +236,7 @@ public class BeforeConstant extends InjectionPoint {
if (matchesInsn) {
this.log(" BeforeConstant found a matching constant{} at ordinal {}", this.matchByType != null ? " TYPE" : " value", ordinal);
if (this.ordinal == -1 || this.ordinal == ordinal) {
this.log(" BeforeConstant found {}", Bytecode.describeNode(insn).trim());
this.log(" BeforeConstant found {}", Bytecode.describeNode(insn, false));
nodes.add(insn);
found = true;
}
@@ -280,7 +280,7 @@ public class BeforeConstant extends InjectionPoint {
}
Object value = Bytecode.getConstant(insn);
if (value == null) {
if (value == Type.VOID_TYPE) {
this.log(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue);
return this.nullValue || Constants.OBJECT_DESC.equals(this.matchByType);
} else if (value instanceof Integer) {
@@ -49,21 +49,33 @@ import org.spongepowered.asm.util.Bytecode;
* <dl>
* <dt>target</dt>
* <dd>A {@link ITargetSelector Target Selector} which identifies the target
* field.</dd>
* field.</dd>
* <dt>opcode</dt>
* <dd>The {@link Opcodes opcode} of the field access, must be one of
* GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.</dd>
* GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.</dd>
* <dt>ordinal</dt>
* <dd>The ordinal position of the field access to match. For example if the
* field is referenced 3 times and you want to match the 3rd then you can
* specify an <em>ordinal</em> of <b>2</b> (ordinals are zero-indexed). The
* default value is <b>-1</b> which supresses ordinal matching</dd>
* field is referenced 3 times and you want to match the 3rd then you can
* specify an <em>ordinal</em> of <b>2</b> (ordinals are zero-indexed). The
* default value is <b>-1</b> which supresses ordinal matching</dd>
* <dt><i>named argument:</i> array</dt>
* <dd>For matching accesses to an array field element following a GETFIELD or
* GETSTATIC. Specify <tt>get</tt>, <tt>set</tt> or <tt>length</tt> to match
* the desired operation.</dd>
* <dt><i>named argument:</i> fuzz</dt>
* <dd>When matching array operations using <tt>array</tt> the injection point
* will by default search up to 8 instructions after the matched field insn.
* However in some cases the array operation may be further from the matched
* GETFIELD or GETSTATIC and the amount to search (the "fuzz factor" can be
* specified using this argument. Likewise to optimise the search against
* false positives, this value can be specified as a lower value if desired.
* Has no effect if <tt>array</tt> is not specified.</dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* <blockquote><code>
* &#064;At(value = "FIELD", target="field_59_z:I", opcode = Opcodes.GETFIELD)
* </pre>
* </code>
* </blockquote>
*
* <p>Matching array access:</p>
@@ -72,9 +84,10 @@ import org.spongepowered.asm.util.Bytecode;
* operation. To enable this behaviour specify the <tt>array</tt> named-argument
* with the desired operation:</p>
*
* <blockquote><pre>
* &#064;At(value = "FIELD", target="myIntArray:[I", args = "array=get")
* </pre>
* <blockquote><code>
* &#064;At(value = "FIELD", target="myIntArray:[I", opcode
* = Opcodes.GETFIELD, args = "array=get")
* </code>
* </blockquote>
*
* <p>See {@link Redirect} for information on array element redirection.</p>
@@ -64,7 +64,7 @@ public class BeforeFinalReturn extends InjectionPoint {
public BeforeFinalReturn(InjectionPointData data) {
super(data);
this.context = data.getContext();
this.context = data.getMixin();
}
@Override
@@ -35,10 +35,14 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
@@ -108,7 +112,12 @@ public class BeforeInvoke extends InjectionPoint {
/**
*
*/
protected final IMixinContext context;
protected final IInjectionPointContext context;
/**
*
*/
protected final IMixinContext mixin;
/**
* Logger reference
@@ -128,8 +137,9 @@ public class BeforeInvoke extends InjectionPoint {
this.log = data.get("log", false);
this.className = this.getClassName();
this.context = data.getContext();
this.allowPermissive = this.context.getOption(Option.REFMAP_REMAP) && this.context.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE)
&& !this.context.getReferenceMapper().isDefault();
this.mixin = data.getMixin();
this.allowPermissive = this.mixin.getOption(Option.REFMAP_REMAP) && this.mixin.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE)
&& !this.mixin.getReferenceMapper().isDefault();
}
private String getClassName() {
@@ -155,14 +165,14 @@ public class BeforeInvoke extends InjectionPoint {
*/
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
this.log("{} is searching for an injection point in method with descriptor {}", this.className, desc);
this.log("{}->{} is searching for an injection point in method with descriptor {}", this.context, this.className, desc);
boolean hasDescriptor = this.target instanceof ITargetSelectorByName && ((ITargetSelectorByName)this.target).getDesc() == null;
boolean found = this.find(desc, insns, nodes, this.target, SearchType.STRICT);
if (!found && hasDescriptor && this.allowPermissive) {
this.logger.warn("STRICT match for {} using \"{}\" in {} returned 0 results, attempting permissive search. "
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.context);
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.mixin);
found = this.find(desc, insns, nodes, this.target, SearchType.PERMISSIVE);
}
@@ -174,10 +184,10 @@ public class BeforeInvoke extends InjectionPoint {
return false;
}
ITargetSelector target = searchType == SearchType.PERMISSIVE ? selector.configure("permissive") : selector;
ITargetSelector target = (searchType == SearchType.PERMISSIVE ? selector.configure(Configure.PERMISSIVE) : selector)
.configure(Configure.SELECT_INSTRUCTION);
int ordinal = 0;
int found = 0;
int ordinal = 0, found = 0, matchCount = 0;
ListIterator<AbstractInsnNode> iter = insns.iterator();
while (iter.hasNext()) {
@@ -185,23 +195,22 @@ public class BeforeInvoke extends InjectionPoint {
if (this.matchesInsn(insn)) {
MemberInfo nodeInfo = new MemberInfo(insn);
this.log("{} is considering insn {}", this.className, nodeInfo);
this.log("{}->{} is considering {}", this.context, this.className, nodeInfo);
if (target.match(insn).isExactMatch()) {
this.log("{} > found a matching insn, checking preconditions...", this.className);
if (target.match(ElementNode.<AbstractInsnNode>of(insn)).isExactMatch()) {
this.log("{}->{} > found a matching insn, checking preconditions...", this.context, this.className);
if (++matchCount > target.getMaxMatchCount()) {
break;
}
if (this.matchesOrdinal(ordinal)) {
this.log("{} > > > found a matching insn at ordinal {}", this.className, ordinal);
this.log("{}->{} > > > found a matching insn at ordinal {}", this.context, this.className, ordinal);
if (this.addInsn(insns, nodes, insn)) {
found++;
}
if (this.ordinal == ordinal) {
break;
}
}
ordinal++;
}
}
@@ -211,7 +220,12 @@ public class BeforeInvoke extends InjectionPoint {
if (searchType == SearchType.PERMISSIVE && found > 1) {
this.logger.warn("A permissive match for {} using \"{}\" in {} matched {} instructions, this may cause unexpected behaviour. "
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.context, found);
+ "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.mixin, found);
}
if (matchCount < target.getMinMatchCount()) {
throw new SelectorConstraintException(target, String.format("%s did not match the required number of targets (required=%d, matched=%d)",
target, selector.getMinMatchCount(), matchCount));
}
return found > 0;
@@ -231,7 +245,7 @@ public class BeforeInvoke extends InjectionPoint {
}
protected boolean matchesOrdinal(int ordinal) {
this.log("{} > > comparing target ordinal {} with current ordinal {}", this.className, this.ordinal, ordinal);
this.log("{}->{} > > comparing target ordinal {} with current ordinal {}", this.context, this.className, this.ordinal, ordinal);
return this.ordinal == -1 || this.ordinal == ordinal;
}
@@ -52,7 +52,7 @@ import com.google.common.base.Strings;
* {@link org.spongepowered.asm.mixin.injection.At At}:</p>
*
* <dl>
* <dt><em>named argument</em> class (or specify using <tt>target</tt></dt>
* <dt><i>named argument:</i> class (or specify using <tt>target</tt></dt>
* <dd>The value of the NEW node to look for, the fully-qualified class name
* </dd>
* <dt>ordinal</dt>
@@ -70,16 +70,16 @@ import com.google.common.base.Strings;
*
* <p>Examples:</p>
* <blockquote><pre>
* // Find all NEW opcodes for <tt>String</tt>
* <del>// Find all NEW opcodes for <tt>String</tt></del>
* &#064;At(value = "NEW", args = "class=java/lang/String")</pre>
* </blockquote>
* <blockquote><pre>
* // Find all NEW opcodes for <tt>String</tt>
* <del>// Find all NEW opcodes for <tt>String</tt></del>
* &#064;At(value = "NEW", target = "java/lang/String"</pre>
* </blockquote>
* <blockquote><pre>
* // Find all NEW opcodes for <tt>String</tt> which are constructed using the
* // ctor which takes an array of <tt>char</tt>
* <del>// Find all NEW opcodes for <tt>String</tt> which are constructed
* // using the ctor which takes an array of <tt>char</tt></del>
* &#064;At(value = "NEW", target = "([C)Ljava/lang/String;"</pre>
* </blockquote>
*
@@ -113,7 +113,7 @@ public class BeforeNew extends InjectionPoint {
String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/'));
ITargetSelector member = TargetSelector.parseAndValidate(target, data.getContext());
if (!(member instanceof ITargetSelectorConstructor)) {
throw new InvalidInjectionPointException(data.getContext(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s",
throw new InvalidInjectionPointException(data.getMixin(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s",
target, data.getDescription());
}
ITargetSelectorConstructor targetSelector = (ITargetSelectorConstructor)member;
@@ -64,7 +64,7 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
* the method is invoked 3 times and you want to match the 3rd then you can
* specify an <em>ordinal</em> of <b>2</b> (ordinals are zero-indexed). The
* default value is <b>-1</b> which supresses ordinal matching</dd>
* <dt><em>named argument</em> ldc</dt>
* <dt><i>named argument:</i> ldc</dt>
* <dd>The value of the LDC node to look for prior to the method invocation
* </dd>
* </dl>
@@ -122,7 +122,7 @@ public class BeforeStringInvoke extends BeforeInvoke {
if (insn instanceof LdcInsnNode) {
LdcInsnNode node = (LdcInsnNode) insn;
if (node.cst instanceof String && this.ldcValue.equals(node.cst)) {
this.log("{} > found a matching LDC with value {}", this.className, node.cst);
this.log("{}->{} > found a matching LDC with value {}", this.context, this.className, node.cst);
this.foundLdc = true;
return;
}
@@ -133,7 +133,7 @@ public class BeforeStringInvoke extends BeforeInvoke {
@Override
protected boolean matchesOrdinal(int ordinal) {
this.log("{} > > found LDC \"{}\" = {}", this.className, this.ldcValue, this.foundLdc);
this.log("{}->{} > > found LDC \"{}\" = {}", this.context, this.className, this.ldcValue, this.foundLdc);
return this.foundLdc && super.matchesOrdinal(ordinal);
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
/**
* Built-in {@link org.spongepowered.asm.mixin.injection.InjectionPoint
* injection point} classes.
*/
package org.spongepowered.asm.mixin.injection.points;
@@ -0,0 +1,754 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.util.Handles;
import com.google.common.base.Strings;
/**
* Wrapper for all node types supported by {@link ITargetSelector target
* selectors} ({@link FieldNode}, {@link MethodNode}, {@link FieldInsnNode},
* {@link MethodInsnNode} and {@link InvokeDynamicInsnNode}) which allows access
* to common properties of things which are basically "arbitrary node with
* owner, name and descriptor"
*
* @param <TNode> node type
*/
public abstract class ElementNode<TNode> {
/**
* Element node type, returned by <tt>getType</tt> so consumers don't need
* to do instanceof checks, and allows switching on element type in a more
* expressive way
*/
public static enum NodeType {
/**
* None or unknown type
*/
UNDEFINED(false, false, false),
/**
* A method node
*/
METHOD(true, false, false),
/**
* A field node
*/
FIELD(false, true, false),
/**
* An invoke instruction
*/
METHOD_INSN(false, false, true),
/**
* A get or put field instruction
*/
FIELD_INSN(false, false, true),
/**
* An INVOKEDYNAMIC instruction
*/
INVOKEDYNAMIC_INSN(false, false, true);
/**
* Whether this node holds a method, implies that calling <tt>getMethod
* </tt> will return a value
*/
public final boolean hasMethod;
/**
* Whether this node holds a field, implies that calling <tt>getField
* </tt> will return a value
*/
public final boolean hasField;
/**
* Whether this node holds an insn, implies that calling <tt>getInsn
* </tt> will return a value
*/
public final boolean hasInsn;
private NodeType(boolean isMethod, boolean isField, boolean isInsn) {
this.hasMethod = isMethod;
this.hasField = isField;
this.hasInsn = isInsn;
}
}
/**
* ElementNode for MethodNode
*/
static class ElementNodeMethod extends ElementNode<MethodNode> {
private final ClassNode owner;
private final MethodNode method;
ElementNodeMethod(ClassNode owner, MethodNode method) {
this.owner = owner;
this.method = method;
}
@Override
public NodeType getType() {
return NodeType.METHOD;
}
@Override
public MethodNode getMethod() {
return this.method;
}
@Override
public String getOwner() {
return this.owner != null ? this.owner.name : null;
}
@Override
public String getName() {
return this.method.name;
}
@Override
public String getDesc() {
return this.method.desc;
}
@Override
public String getSignature() {
return this.method.signature;
}
@Override
public MethodNode get() {
return this.method;
}
@Override
public boolean equals(Object obj) {
return this.method.equals(obj);
}
@Override
public int hashCode() {
return this.method.hashCode();
}
}
/**
* ElementNode for FieldNode
*/
static class ElementNodeField extends ElementNode<FieldNode> {
private final ClassNode owner;
private final FieldNode field;
ElementNodeField(ClassNode owner, FieldNode field) {
this.owner = owner;
this.field = field;
}
@Override
public NodeType getType() {
return NodeType.FIELD;
}
@Override
public boolean isField() {
return true;
}
@Override
public FieldNode getField() {
return this.field;
}
@Override
public String getOwner() {
return this.owner != null ? this.owner.name : null;
}
@Override
public String getName() {
return this.field.name;
}
@Override
public String getDesc() {
return this.field.desc;
}
@Override
public String getSignature() {
return this.field.signature;
}
@Override
public FieldNode get() {
return this.field;
}
@Override
public boolean equals(Object obj) {
return this.field.equals(obj);
}
@Override
public int hashCode() {
return this.field.hashCode();
}
}
/**
* ElementNode for MethodInsnNode
*/
static class ElementNodeMethodInsn extends ElementNode<MethodInsnNode> {
private MethodInsnNode insn;
ElementNodeMethodInsn(MethodInsnNode method) {
this.insn = method;
}
@Override
public NodeType getType() {
return NodeType.METHOD_INSN;
}
@Override
public AbstractInsnNode getInsn() {
return this.insn;
}
@Override
public String getOwner() {
return this.insn.owner;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getDesc() {
return this.insn.desc;
}
@Override
public String getSignature() {
return null;
}
@Override
public MethodInsnNode get() {
return this.insn;
}
@Override
public boolean equals(Object obj) {
return this.insn.equals(obj);
}
@Override
public int hashCode() {
return this.insn.hashCode();
}
}
/**
* ElementNode for InvokeDynamicInsnNode
*/
static class ElementNodeInvokeDynamicInsn extends ElementNode<InvokeDynamicInsnNode> {
private InvokeDynamicInsnNode insn;
private Type samMethodType;
private Handle implMethod;
private Type instantiatedMethodType;
ElementNodeInvokeDynamicInsn(InvokeDynamicInsnNode invokeDynamic) {
this.insn = invokeDynamic;
if (invokeDynamic.bsmArgs != null && invokeDynamic.bsmArgs.length > 1) {
Object samMethodType = invokeDynamic.bsmArgs[0];
Object implMethod = invokeDynamic.bsmArgs[1];
Object instantiatedMethodType = invokeDynamic.bsmArgs[2];
if (samMethodType instanceof Type && implMethod instanceof Handle && instantiatedMethodType instanceof Type) {
this.samMethodType = (Type)samMethodType;
this.implMethod = (Handle)implMethod;
this.instantiatedMethodType = (Type)instantiatedMethodType;
}
}
}
@Override
public NodeType getType() {
return NodeType.INVOKEDYNAMIC_INSN;
}
@Override
public boolean isField() {
return this.implMethod != null && Handles.isField(this.implMethod);
}
@Override
public AbstractInsnNode getInsn() {
return this.insn;
}
@Override
public String getOwner() {
return this.implMethod != null ? this.implMethod.getOwner() : this.insn.name;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getSyntheticName() {
return this.implMethod != null ? this.implMethod.getName() : this.insn.name;
}
@Override
public String getDesc() {
return this.implMethod != null ? this.implMethod.getDesc() : this.insn.desc;
}
@Override
public String getDelegateDesc() {
return this.samMethodType != null ? this.samMethodType.getDescriptor() : this.getDesc();
}
@Override
public String getImplDesc() {
return this.instantiatedMethodType != null ? this.instantiatedMethodType.getDescriptor() : this.getDesc();
}
@Override
public String getSignature() {
return null;
}
@Override
public InvokeDynamicInsnNode get() {
return this.insn;
}
@Override
public boolean equals(Object obj) {
return this.insn.equals(obj);
}
@Override
public int hashCode() {
return this.insn.hashCode();
}
}
/**
* ElementNode for FieldInsnNode
*/
static class ElementNodeFieldInsn extends ElementNode<FieldInsnNode> {
private FieldInsnNode insn;
ElementNodeFieldInsn(FieldInsnNode field) {
this.insn = field;
}
@Override
public NodeType getType() {
return NodeType.FIELD_INSN;
}
@Override
public boolean isField() {
return true;
}
@Override
public AbstractInsnNode getInsn() {
return this.insn;
}
@Override
public String getOwner() {
return this.insn.owner;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getDesc() {
return this.insn.desc;
}
@Override
public String getSignature() {
return null;
}
@Override
public FieldInsnNode get() {
return this.insn;
}
@Override
public boolean equals(Object obj) {
return this.insn.equals(obj);
}
@Override
public int hashCode() {
return this.insn.hashCode();
}
}
/**
* Wrapper iterator for method insns
*/
static class ElementNodeIterator implements Iterator<ElementNode<AbstractInsnNode>> {
private final Iterator<AbstractInsnNode> iter;
private final boolean filterDynamic;
ElementNodeIterator(Iterator<AbstractInsnNode> iter, boolean filterDynamic) {
this.iter = iter;
this.filterDynamic = filterDynamic;
}
@Override
public boolean hasNext() {
return this.iter.hasNext();
}
@Override
public ElementNode<AbstractInsnNode> next() {
AbstractInsnNode elem = this.iter.next();
return !this.filterDynamic || (elem != null && elem.getOpcode() == Opcodes.INVOKEDYNAMIC) ? ElementNode.of(elem) : null;
}
}
/**
* Wrapper for InsnList which returns node iterator
*/
static class ElementNodeIterable implements Iterable<ElementNode<AbstractInsnNode>> {
private final Iterable<AbstractInsnNode> iterable;
private final boolean filterDynamic;
public ElementNodeIterable(Iterable<AbstractInsnNode> iterable, boolean filterDynamic) {
this.iterable = iterable;
this.filterDynamic = filterDynamic;
}
@Override
public Iterator<ElementNode<AbstractInsnNode>> iterator() {
return new ElementNodeIterator(this.iterable.iterator(), this.filterDynamic);
}
}
/**
* Get whether this element is a field type and the descriptor is a bare
* type descriptor without arguments. Otherwise assumes the descriptor is a
* method descriptor.
*/
public boolean isField() {
return false;
}
/**
* Get the type of this ElementNode, the return value can be used to
* determine which accessor ({@link #getMethod}, {@link #getField}
*/
public abstract NodeType getType();
/**
* Get the {@link MethodNode} if this member is a method, otherwise returns
* <tt>null</tt>
*/
public MethodNode getMethod() {
return null;
}
/**
* Get the {@link FieldNode} if this member is a field, otherwise returns
* <tt>null</tt>
*/
public FieldNode getField() {
return null;
}
/**
* Get the {@link AbstractInsnNode instruction} if this member is an insn,
* otherwise returns <tt>null</tt>
*/
public AbstractInsnNode getInsn() {
return null;
}
/**
* Get the element owner's name, if this element has an owner, otherwise
* returns <tt>null</tt>
*/
public abstract String getOwner();
/**
* Get the element name
*/
public abstract String getName();
/**
* Get the synthetic element name. For INVOKEDYNAMIC elements this is the
* real name of the lambda method implementing the delegate.
*/
public String getSyntheticName() {
return this.getName();
}
/**
* Get the element descriptor. For INVOKEDYNAMIC this is the full descriptor
* of the lambda (including prepended captures).
*/
public abstract String getDesc();
/**
* For INVOKEDYNAMIC elements, returns original descriptor of the delegate.
*/
public String getDelegateDesc() {
return this.getDesc();
}
/**
* For INVOKEDYNAMIC elements, returns specialised descriptor of the
* delegate (lambda descriptor without prepended captures), can be the same
* as the delegate descriptor or more specialised.
*/
public String getImplDesc() {
return this.getDesc();
}
/**
* Get the element signature, can be <tt>null</tt>
*/
public abstract String getSignature();
/**
* Returns the node with horrible duck typing
*/
public abstract TNode get();
@Override
public String toString() {
String desc = Strings.nullToEmpty(this.getDesc());
if (!desc.isEmpty() && this.isField()) {
desc = ":" + desc;
}
String owner = Strings.nullToEmpty(this.getOwner());
if (!owner.isEmpty()) {
owner = "L" + owner + ";";
}
return String.format("%s%s%s", owner, Strings.nullToEmpty(this.getName()), desc);
}
/**
* Create an ElementNode wrapper for the supplied method node
*
* @param owner class which owns the method or <tt>null</tt>
* @param method Method node to wrap
* @return ElementNode
*/
public static ElementNode<MethodNode> of(ClassNode owner, MethodNode method) {
return new ElementNodeMethod(owner, method);
}
/**
* Create an ElementNode wrapper for the supplied field node
*
* @param owner class which owns the field or <tt>null</tt>
* @param field Field node to wrap
* @return ElementNode
*/
public static ElementNode<FieldNode> of(ClassNode owner, FieldNode field) {
return new ElementNodeField(owner, field);
}
/**
* Create an ElementNode wrapper for the supplied node object
*
* @param owner class which owns the node or <tt>null</tt>
* @param node Node to wrap
* @param <TNode> Node type
* @return ElementNode
* @throws IllegalArgumentException if the supplied argument is not a
* {@link MethodNode} or {@link FieldNode}
*/
@SuppressWarnings("unchecked")
public static <TNode> ElementNode<TNode> of(ClassNode owner, TNode node) {
if (node instanceof ElementNode) {
return (ElementNode<TNode>)node;
} else if (node instanceof MethodNode) {
return (ElementNode<TNode>)new ElementNodeMethod(owner, (MethodNode)node);
} else if (node instanceof FieldNode) {
return (ElementNode<TNode>)new ElementNodeField(owner, (FieldNode)node);
} else if (node instanceof MethodInsnNode) {
return (ElementNode<TNode>)new ElementNodeMethodInsn((MethodInsnNode)node);
} else if (node instanceof InvokeDynamicInsnNode) {
return (ElementNode<TNode>)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node);
} else if (node instanceof FieldInsnNode) {
return (ElementNode<TNode>)new ElementNodeFieldInsn((FieldInsnNode)node);
}
throw new IllegalArgumentException("Could not create ElementNode for unknown node type: " + node.getClass().getName());
}
/**
* Create an ElementNode wrapper for the supplied node object
*
* @param node Node to wrap
* @param <TNode> Node type
* @return ElementNode
* @throws IllegalArgumentException if the supplied argument is not a
* {@link MethodNode} or {@link FieldNode}
*/
@SuppressWarnings("unchecked")
public static <TNode extends AbstractInsnNode> ElementNode<TNode> of(TNode node) {
if (node instanceof MethodInsnNode) {
return (ElementNode<TNode>)new ElementNodeMethodInsn((MethodInsnNode)node);
} else if (node instanceof InvokeDynamicInsnNode) {
return (ElementNode<TNode>)new ElementNodeInvokeDynamicInsn((InvokeDynamicInsnNode)node);
} else if (node instanceof FieldInsnNode) {
return (ElementNode<TNode>)new ElementNodeFieldInsn((FieldInsnNode)node);
}
return null;
}
/**
* Convert the supplied list of nodes to a list of wrapped ElementNodes
*
* @param owner Owner of the supplied nodes, can be <tt>null</tt>
* @param list List of nodes
* @param <TNode> Node type
* @return List of wrapped nodes
*/
public static <TNode> List<ElementNode<TNode>> listOf(ClassNode owner, List<TNode> list) {
List<ElementNode<TNode>> nodes = new ArrayList<ElementNode<TNode>>();
for (TNode node : list) {
nodes.add(ElementNode.<TNode>of(owner, node));
}
return nodes;
}
/**
* Get a list of wrapped ElementNodes for the fields of the supplied owner
* class
*
* @param owner Class to get fields, must not be <tt>null</tt>
* @return List of wrapped nodes
*/
public static List<ElementNode<FieldNode>> fieldList(ClassNode owner) {
List<ElementNode<FieldNode>> fields = new ArrayList<ElementNode<FieldNode>>();
for (FieldNode field : owner.fields) {
fields.add(new ElementNodeField(owner, field));
}
return fields;
}
/**
* Get a list of wrapped ElementNodes for the methods of the supplied owner
* class
*
* @param owner Class to get methods, must not be <tt>null</tt>
* @return List of wrapped nodes
*/
public static List<ElementNode<MethodNode>> methodList(ClassNode owner) {
List<ElementNode<MethodNode>> methods = new ArrayList<ElementNode<MethodNode>>();
for (MethodNode method : owner.methods) {
methods.add(new ElementNodeMethod(owner, method));
}
return methods;
}
/**
* Get a wrapped version of the supplied insn list which returns element
* nodes for each (supported) instruction (FieldInsnNode, MethodInsnNode and
* InvokeDynamicInsnNode).
*
* @param insns Insn list to wrap
* @return Wrapper for insn list
*/
public static Iterable<ElementNode<AbstractInsnNode>> insnList(InsnList insns) {
return new ElementNodeIterable(insns, false);
}
/**
* Get a wrapped version of the supplied insn list which returns element
* nodes for every INVOKEDYNAMIC instruction only
*
* @param insns Insn list to wrap
* @return Wrapper for insn list
*/
public static Iterable<ElementNode<AbstractInsnNode>> dynamicInsnList(InsnList insns) {
return new ElementNodeIterable(insns, true);
}
}
@@ -0,0 +1,87 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Context passed to a {@link ITargetSelector Target Selector} in order to
* support context-sensitive behaviour for the selector. For example obtaining
* the name of the source mixin, or the element containing the selector itself.
*/
public interface ISelectorContext {
/**
* Get the parent (outer/containing) context. Can be null if this is a root
* element such as an injector method, in which case the parent is the mixin
* instead.
*/
public abstract ISelectorContext getParent();
/**
* Get the mixin containing this selector.
*/
public abstract IMixinContext getMixin();
/**
* Get the root method upon which this selector is operating, usually the
* injector method
*/
public abstract Object getMethod();
/**
* Get the root annotation for the selector, for example the injector or
* accessor annotation
*/
public abstract IAnnotationHandle getAnnotation();
/**
* Get the annotation for this selector, for example the &#064;At annotation
*/
public abstract IAnnotationHandle getSelectorAnnotation();
/**
* Get the coordinate for this selector. This is the local coordinate of the
* selector without any parent parts. Parent parts are prepended by
* consumers during the resolve process.
*
* @param leaf True if getting the coordinate when this element is a leaf,
* false if getting the coordinate when it is a parent
*/
public abstract String getSelectorCoordinate(boolean leaf);
/**
* Remap a reference in the context of this selector, usually via the local
* refmap of the mixin configuration but can be overridden as needed, for
* example to provide selector-local remap behaviour.
*
* @param reference Reference to remap
* @return Remapped reference or original reference if not remapped, must
* not return null!
*/
public abstract String remap(String reference);
}
@@ -24,10 +24,9 @@
*/
package org.spongepowered.asm.mixin.injection.selectors;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.spongepowered.asm.mixin.injection.Desc;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.ElementNode;
/**
* Target Selectors are used to identify target members in a class, with the
@@ -40,13 +39,137 @@ import org.spongepowered.asm.util.asm.ElementNode;
* <p><b>Explicit</b> Target Selectors are handled internally using
* {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the
* supported variants and examples.</p>
*
* <blockquote><code>
* <del>// An example explicit target selector</del><br />
* Lfully/qualified/OwnerClass;methodName*(III)V
* </code></blockquote>
*
* <h3>Pattern Target Selectors (Regex Selectors)</h3>
*
* <p><b>Pattern</b> Target Selectors are handled internally using
* {@link MemberMatcher}, see the javadoc for {@link MemberMatcher} for the
* supported variants and examples. Pattern Selectors always end with a forward
* slash character.</p>
*
* <blockquote><code>
* <del>// Matches candidates ending with "Bar" and which take a single int
* <br /></del>
* /bar$/ desc=/^\\(I\\)/<br />
* <br />
* <del>// The same example but with "name" explicitly specified (optional)
* <br /></del>
* name=/bar$/ desc=/^\\(I\\)/<br />
* <br />
* <del>// Matches candidates whose name contains "Entity"</del><br />
* /Entity/
* </code></blockquote>
*
* <h3>Dynamic Target Selectors</h3>
*
* <p><b>Dynamic</b> Target Selectors can be built-in or user-supplied types
* with their own specialised syntax or behaviour.</p>
*
* <h4>Built-in dynamic selectors:</h4>
*
* <ul>
* <li>{@link DynamicSelectorDesc &#64;Desc Selector}: Selector which uses
* descriptors defined in {@link Desc &#64;Desc} annotations</li>
* </ul>
*
* <p>Dynamic selectors are specified in the following format, and can be
* recognised by the fact that the selector string starts with "<tt>&#64;</tt>":
* </p>
*
* <blockquote><pre>
* <del>// Built-in dynamic selector without argument string</del>
* &#064;SelectorId
*
* <del>// Built-in dynamic selector with empty argument string</del>
* &#064;SelectorId()
*
* <del>// Built-in dynamic selector with argument</del>
* &#064;SelectorId(custom,argument,string,in,any,format)
*
* <del>// User-provided dynamic selector with argument. Note that
* // user-provided dynamic selectors are namespaced to avoid conflicts.</del>
* &#064;Namespace:SelectorId(some arguments)</pre>
* </blockquote>
*
* <p>The exact format of the argument string is specified by the dynamic
* selector itself, consult the documentation for the dynamic selector you are
* using for details on the required format.</p>
*
*/
public interface ITargetSelector {
/**
* Available selector reconfigurations
*/
public enum Configure {
/**
* Configure this selector for matching members in a class. Usually used
* to set defaults for match limits based on role.
*/
SELECT_MEMBER(0),
/**
* Configure this selector for matching field and method instructions in
* a method body. Usually used to set defaults for match limits.
*/
SELECT_INSTRUCTION(0),
/**
* Where supported, changes the owner selection to the specified value.
*/
MOVE(1),
/**
* Where supported, changes the owner selection to match all owners,
* retaining other properties.
*/
ORPHAN(0),
/**
* Where supported, changes the descriptor to the specified value.
*/
TRANSFORM(1),
/**
* Where supported, changes the descriptor to match all target
* descriptors, retaining other properties
*/
PERMISSIVE(0),
/**
* Where supported, removes the min and max limits for the selector,
* allowing it to return as many or as few matches as required.
*/
CLEAR_LIMITS(0);
private int requiredArgs;
private Configure(int requiredArgs) {
this.requiredArgs = requiredArgs;
}
public void checkArgs(String... args) throws IllegalArgumentException {
int argc = args == null ? 0 : args.length;
if (argc < this.requiredArgs) {
throw new IllegalArgumentException("Insufficient arguments for " + this.name() + " mutation. Required " + this.requiredArgs
+ " but received " + argc);
}
}
}
/**
* 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.
* the subject in order to match against the child subject.
*
* <p>Can return null</p>
*/
public abstract ITargetSelector next();
@@ -55,17 +178,22 @@ public interface ITargetSelector {
* supplied arguments. Results from this method should be idempotent in
* terms of the configuration of the returned object, but do not have to
* necessarily return the same object if the callee already matches the
* supplied configuration, though this is generally the case.
* supplied configuration, or if the requested mutation is not supported by
* the selector, though this is generally the case.
*
* <p>In other words, calling <tt>configure("foo")</tt> when this object is
* <i>already</i> configured according to "foo" may simply return this
* object, or might return an identically-configured copy.</p>
* <p>In other words, calling <tt>configure(Configure.ORPHAN)</tt> when this
* object is <i>already</i> an orphan or does not support orphaning, may
* simply return this object, or might return an identically-configured
* copy.</p>
*
* <p>Must not return null, defaults to returning unmodified selector.</p>
*
* @param request Requested operation
* @param args Configuration arguments
* @return Configured selector, may return this selector if the specified
* condition is already satisfied
*/
public abstract ITargetSelector configure(String... args);
public abstract ITargetSelector configure(Configure request, String... args);
/**
* Perform basic sanity-check validation of the selector, checks that the
@@ -86,12 +214,17 @@ public interface ITargetSelector {
* @param context Context to attach to
* @return Attached selector
*/
public abstract ITargetSelector attach(IMixinContext context) throws InvalidSelectorException;
public abstract ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException;
/**
* Number of candidates which this selector should match
* Minimum number of candidates this selector must match
*/
public abstract int getMatchCount();
public abstract int getMinMatchCount();
/**
* Maximum number of candidates this selector can match
*/
public abstract int getMaxMatchCount();
/**
* Test whether this selector matches the supplied element node
@@ -101,13 +234,5 @@ public interface ITargetSelector {
* @return true if this selector can match the supplied field
*/
public abstract <TNode> MatchResult match(ElementNode<TNode> node);
/**
* Test whether this selector matches the supplied instruction node
*
* @param insn instruction node to test
* @return true if this selector can match the supplied instruction
*/
public abstract MatchResult match(AbstractInsnNode insn);
}
@@ -44,43 +44,6 @@ public interface ITargetSelectorByName extends ITargetSelector {
*/
public abstract String getDesc();
/**
* Get whether this reference is fully qualified
*
* @return true if all components of this reference are non-null
*/
public abstract boolean isFullyQualified();
/**
* Get whether this target selector is definitely a field, the output of
* this method is undefined if {@link #isFullyQualified} returns false.
*
* @return true if this is definitely a field
*/
public abstract boolean isField();
/**
* Get whether this member represents a constructor
*
* @return true if member name is <tt>&lt;init&gt;</tt>
*/
public abstract boolean isConstructor();
/**
* Get whether this selector represents a class initialiser
*
* @return true if member name is <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isClassInitialiser();
/**
* Get whether this selector represents a constructor or class initialiser
*
* @return true if member name is <tt>&lt;init&gt;</tt> or
* <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isInitialiser();
/**
* Get a representation of this selector as a complete descriptor
*/
@@ -0,0 +1,78 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Decoration interface for dynamic target selectors
*/
public interface ITargetSelectorDynamic extends ITargetSelector {
/**
* Decoration for subclasses which indicates id used for a specific selector
* when specified, for example <tt>@MyNamespace:MySelector(argshere)</tt>
* would specify "MySelector"
*/
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.TYPE)
public @interface SelectorId {
/**
* Namespace for this code. Final selectors will be specified as
* <tt>&lt;namespace&gt;:&lt;id&gt;</tt> in order to avoid overlaps
* between consumer-provided selectors. If left blank defaults to the
* namespace specified in the configuration.
*/
public String namespace() default "";
/**
* The string code used to specify the selector selector strings,
* prefixed with namespace from the annotation or from the declaring
* configuration.
*/
public String value();
}
/**
* Decoration for subclasses which indicates an annotation type from which
* the selector can be parsed.
*/
@Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.TYPE)
public @interface SelectorAnnotation {
/**
* Annotation type for the selector
*/
public Class<? extends Annotation> value();
}
}
@@ -33,7 +33,44 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
* service
*/
public interface ITargetSelectorRemappable extends ITargetSelectorByName {
/**
* Get whether this reference is fully qualified
*
* @return true if all components of this reference are non-null
*/
public abstract boolean isFullyQualified();
/**
* Get whether this target selector is definitely a field, the output of
* this method is undefined if {@link #isFullyQualified} returns false.
*
* @return true if this is definitely a field
*/
public abstract boolean isField();
/**
* Get whether this member represents a constructor
*
* @return true if member name is <tt>&lt;init&gt;</tt>
*/
public abstract boolean isConstructor();
/**
* Get whether this selector represents a class initialiser
*
* @return true if member name is <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isClassInitialiser();
/**
* Get whether this selector represents a constructor or class initialiser
*
* @return true if member name is <tt>&lt;init&gt;</tt> or
* <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isInitialiser();
/**
* Returns this selector as a {@link MappingField} or
* {@link MappingMethod}
@@ -0,0 +1,139 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors;
/**
* Since the contract of {@link TargetSelector#parse} prohibits returing <tt>
* null</tt>, instances of this selector are returned when supplied arguments
* are unparseable in order to throw exceptions only during validation.
*/
public class InvalidSelector implements ITargetSelector {
/**
* The original input string, used in error messages
*/
private String input;
/**
* The cause of the parser failure, emitted from {@link #validate}
*/
private Throwable cause;
public InvalidSelector(Throwable cause) {
this(cause, null);
}
public InvalidSelector(String input) {
this(null, input);
}
public InvalidSelector(Throwable cause, String input) {
this.input = input;
this.cause = cause;
}
@Override
public String toString() {
if (this.cause != null) {
return String.format("%s: %s", this.cause.getClass().getName(), this.cause.getMessage());
}
return this.input;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #next()
*/
@Override
public ITargetSelector next() {
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #configure(ITargetSelector.Configure, java.lang.String[])
*/
@Override
public ITargetSelector configure(Configure request, String... args) {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #validate()
*/
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.cause instanceof InvalidSelectorException) {
throw (InvalidSelectorException)this.cause;
}
String message = "Error parsing target selector";
if (this.input != null) {
message += ", the input was in an unexpected format: " + this.input;
}
if (this.cause != null) {
throw new InvalidSelectorException(message, this.cause);
}
throw new InvalidSelectorException(message);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #attach(ISelectorContext)
*/
@Override
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMinMatchCount()
*/
@Override
public int getMinMatchCount() {
return 0;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMaxMatchCount()
*/
@Override
public int getMaxMatchCount() {
return 0;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #match(org.spongepowered.asm.util.asm.ElementNode)
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
this.validate();
return MatchResult.NONE;
}
}
@@ -0,0 +1,257 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* A {@link ITargetSelector Target Selector} which matches an element of
* candidate members using a regular expression. This selector is not remappable
* and is not suitable for use in obfuscated environments.
*
* <p>Regular expressions for this selector should be enclosed in <tt>/</tt> as
* a delimiter character, and <tt>\</tt> characters must be escaped per normal
* Java conventions (eg. use <tt>\\s</tt> instead of <tt>\s</tt> since the
* backslash must be escaped). Forward slash (<tt>/</tt>) characters in the
* regex must be escaped as well to avoid being consumed as ending delimiters.
* </p>
*
* <p>By default the regex match is performed against the <tt>name</tt> of the
* candidate, to specify matching against <tt>owner</tt> or <tt>desc</tt>, each
* pattern should be prefixed with <tt>owner=</tt> or <tt>desc=</tt> <b>outside
* the delimiting <tt>/</tt></b>.
*
* <p>Some examples:</p>
* <blockquote><pre>
* <del>// Matches candidates starting with "foo"</del>
* /^foo/
*
* <del>// Matches candidates ending with "Bar" and which take a single int
*</del> /bar$/ desc=/^\\(I\\)/
*
* <del>// The same example but with "name" explicitly specified (optional)
*</del> name=/bar$/ desc=/^\\(I\\)/
*
* <del>// Matches candidates whose name contains "Entity"</del>
* /Entity/
*
* <del>// Matches candidates whose owner contains "/google/", note the
* // escaping of the forward slash symbols</del>
* owner=/\\/google\\//</pre>
* </blockquote>
*
* <p>The <tt>owner</tt>, <tt>name</tt> and <tt>desc</tt> expressions can be
* provided in any order.</p>
*/
public final class MemberMatcher implements ITargetSelector {
/**
* Regex selector, searches for targets using supplied regular expression
*/
private static final Pattern PATTERN = Pattern.compile("((owner|name|desc)\\s*=\\s*)?/(.*?)(?<!\\\\)/");
/**
* Names of the positional source elements, just used for error messages
*/
private static final String[] PATTERN_SOURCE_NAMES = { "owner", "name", "desc" };
// Positional source elements
private static final int SOURCE_OWNER = 0;
private static final int SOURCE_NAME = 1;
private static final int SOURCE_DESC = 2;
/**
* Positional patterns. The match sources are packed into 3-element arrays
* just to make the iteration for matching simpler
*/
private final Pattern[] patterns;
/**
* Stored exception during parse. The contract of parse prohibits us from
* emitting (intentional) exceptions. Any exceptions are stored here so they
* can be emitted in {@link #validate}.
*/
private final Exception parseException;
/**
* Input string, stored just so we can emit it along with the exception
* message if {@link #validate} needs to throw a parse exception
*/
private final String input;
private MemberMatcher(Pattern[] patterns, Exception parseException, String input) {
this.patterns = patterns;
this.parseException = parseException;
this.input = input;
}
/**
* Parse a MemberMatcher from the supplied input string.
*
* @param input Raw input string
* @param context selector context
* @return parsed MemberMatcher
*/
public static MemberMatcher parse(final String input, ISelectorContext context) {
Matcher matcher = MemberMatcher.PATTERN.matcher(input);
Pattern[] patterns = new Pattern[3];
Exception parseException = null;
while (matcher.find()) {
Pattern pattern;
try {
pattern = Pattern.compile(matcher.group(3));
} catch (PatternSyntaxException ex) {
parseException = ex;
pattern = Pattern.compile(".*");
ex.printStackTrace();
}
int patternId = "owner".equals(matcher.group(2)) ? MemberMatcher.SOURCE_OWNER : "desc".equals(matcher.group(2))
? MemberMatcher.SOURCE_DESC : MemberMatcher.SOURCE_NAME;
if (patterns[patternId] != null) {
parseException = new InvalidSelectorException("Pattern for '" + MemberMatcher.PATTERN_SOURCE_NAMES[patternId]
+ "' specified multiple times: Old=/" + patterns[patternId].pattern() + "/ New=/" + pattern.pattern() + "/");
}
patterns[patternId] = pattern;
}
return new MemberMatcher(patterns, parseException, input);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #validate()
*/
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.parseException != null) {
if (this.parseException instanceof InvalidSelectorException) {
throw (InvalidSelectorException)this.parseException;
}
throw new InvalidSelectorException("Error parsing regex selector", this.parseException);
}
boolean validPattern = false;
for (Pattern pattern : this.patterns) {
validPattern |= pattern != null;
}
if (!validPattern) {
throw new InvalidSelectorException("Error parsing regex selector, the input was in an unexpected format: " + this.input);
}
return this;
}
@Override
public String toString() {
return this.input;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #next()
*/
@Override
public ITargetSelector next() {
return this; // Regex matcher flows into targets
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #configure(java.lang.String[])
*/
@Override
public ITargetSelector configure(Configure request, String... args) {
request.checkArgs(args);
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #attach(org.spongepowered.asm.mixin.injection.selectors
* .ISelectorContext)
*/
@Override
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMinMatchCount()
*/
@Override
public int getMinMatchCount() {
return 0;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #getMaxMatchCount()
*/
@Override
public int getMaxMatchCount() {
return Integer.MAX_VALUE;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #match(org.spongepowered.asm.util.asm.ElementNode)
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc());
}
private MatchResult matches(String... args) {
MatchResult result = MatchResult.NONE;
// boolean exactOnly = true;
for (int i = 0; i < this.patterns.length; i++) {
if (this.patterns[i] == null || args[i] == null) {
continue;
}
if (this.patterns[i].matcher(args[i]).find()) {
// String pattern = this.patterns[i].pattern();
// if (pattern.startsWith("^") && pattern.endsWith("$") && exactOnly) {
result = MatchResult.EXACT_MATCH;
// } else {
// result = MatchResult.EXACT_MATCH;
// exactOnly = false;
// }
} else {
result = MatchResult.NONE;
}
}
return result;
}
}
@@ -24,14 +24,37 @@
*/
package org.spongepowered.asm.mixin.injection.selectors;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import javax.tools.Diagnostic.Kind;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.util.asm.ElementNode;
import org.spongepowered.asm.mixin.throwables.MixinError;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.asm.util.logging.MessageRouter;
import com.google.common.base.Strings;
/**
* Utility class for parsing selectors
@@ -48,14 +71,14 @@ public final class TargetSelector {
/**
* Any exact match returned by the query
*/
public final TNode exactMatch;
public final ElementNode<TNode> exactMatch;
/**
* All candidates returned by the query
*/
public final List<TNode> candidates;
public final List<ElementNode<TNode>> candidates;
Result(TNode exactMatch, List<TNode> candidates) {
Result(ElementNode<TNode> exactMatch, List<ElementNode<TNode>> candidates) {
this.exactMatch = exactMatch;
this.candidates = candidates;
}
@@ -75,27 +98,190 @@ public final class TargetSelector {
public TNode getSingleResult(boolean strict) {
int resultCount = this.candidates.size();
if (this.exactMatch != null) {
return this.exactMatch;
return this.exactMatch.get();
}
if (resultCount == 1 || !strict) {
return this.candidates.get(0);
return this.candidates.get(0).get();
}
throw new IllegalStateException((resultCount == 0 ? "No" : "Multiple") + " candidates were found");
}
}
/**
* A dynamic selector registration entry
*/
static class DynamicSelectorEntry {
final String namespace;
final String id;
final Class<? extends ITargetSelectorDynamic> type;
final Class<? extends Annotation> annotation;
final Method mdParseString, mdParseAnnotation;
DynamicSelectorEntry(String namespace, String id, Class<? extends ITargetSelectorDynamic> type) throws NoSuchMethodException {
this.namespace = namespace;
this.id = id;
this.type = type;
this.mdParseString = type.getDeclaredMethod("parse", String.class, ISelectorContext.class);
if (!Modifier.isStatic(this.mdParseString.getModifiers())) {
throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static");
}
if (!ITargetSelectorDynamic.class.isAssignableFrom(this.mdParseString.getReturnType())) {
throw new MixinError("parse(String) method for dynamic target selector [" + this.type.getName()
+ "] must return an ITargetSelectorDynamic subtype");
}
Class<? extends Annotation> annotation = null;
Method mdParseAnnotation = null;
SelectorAnnotation selectorAnnotation = type.<SelectorAnnotation>getAnnotation(SelectorAnnotation.class);
if (selectorAnnotation != null) {
annotation = selectorAnnotation.value();
mdParseAnnotation = type.getDeclaredMethod("parse", IAnnotationHandle.class, ISelectorContext.class);
if (!Modifier.isStatic(mdParseAnnotation.getModifiers())) {
throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static");
}
if (!ITargetSelectorDynamic.class.isAssignableFrom(mdParseAnnotation.getReturnType())) {
throw new MixinError("parse(Annotation) method for dynamic target selector [" + this.type.getName()
+ "] must return an ITargetSelectorDynamic subtype");
}
}
this.annotation = annotation;
this.mdParseAnnotation = mdParseAnnotation;
}
String getCode() {
return (this.namespace != null ? this.namespace + ":" : "") + this.id;
}
ITargetSelectorDynamic parse(String input, ISelectorContext context) throws ReflectiveOperationException {
return this.parse(input, context, this.mdParseString);
}
ITargetSelectorDynamic parse(IAnnotationHandle input, ISelectorContext context) throws ReflectiveOperationException {
return this.parse(input, context, this.mdParseAnnotation);
}
ITargetSelectorDynamic parse(Object input, ISelectorContext context, Method parseMethod) throws ReflectiveOperationException {
try {
return (ITargetSelectorDynamic)parseMethod.invoke(null, input, context);
} catch (InvocationTargetException itex) {
Throwable cause = itex.getCause();
if (cause instanceof MixinException) {
throw (MixinException)cause;
}
Throwable ex = cause != null ? cause : itex;
throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex);
}
}
}
/**
* Regex for dynamic selector ids
*/
private static final String DYNAMIC_SELECTOR_ID = "[a-z]+(:[a-z]+)?";
/**
* Pattern for matching dynamic selectors
*/
private static final Pattern PATTERN_DYNAMIC = Pattern.compile("(?i)^\\x40(" + TargetSelector.DYNAMIC_SELECTOR_ID + ")(\\((.*)\\))?$");
/**
* Registered dynamic selectors
*/
private static Map<String, DynamicSelectorEntry> dynamicSelectors = new LinkedHashMap<String, DynamicSelectorEntry>();
static {
TargetSelector.registerBuiltIn(DynamicSelectorDesc.class);
}
private TargetSelector() {
}
/**
* Parse a target selector from a string and perform validation
* Register a dynamic target selector class. The supplied class must be
* decorated with an {@link SelectorId} annotation for registration to
* succeed.
*
* @param string String to parse target selector from
* @param type ITargetSelectorDynamic to register
* @param namespace namespace for SelectorId
*/
public static void register(Class<? extends ITargetSelectorDynamic> type, String namespace) {
SelectorId selectorId = type.<SelectorId>getAnnotation(SelectorId.class);
if (selectorId == null) {
throw new IllegalArgumentException("Dynamic target selector class " + type + " is not annotated with @SelectorId");
}
String annotationNamespace = selectorId.namespace();
if (!Strings.isNullOrEmpty(annotationNamespace)) {
namespace = annotationNamespace;
}
if (Strings.isNullOrEmpty(namespace)) {
throw new IllegalArgumentException("Dynamic target selector class " + type
+ " has no namespace. Please specify namespace in SelectorId annotation or declaring configuration");
}
DynamicSelectorEntry entry;
try {
entry = new DynamicSelectorEntry(namespace.toLowerCase(Locale.ROOT), selectorId.value().toLowerCase(Locale.ROOT), type);
} catch (NoSuchMethodException ex) {
throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method");
}
String code = entry.getCode();
if (!Pattern.matches(TargetSelector.DYNAMIC_SELECTOR_ID, code)) {
throw new IllegalArgumentException("Dynamic target selector class " + type
+ " has an invalid id. Only alpha characters can be used in selector ids and namespaces");
}
DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(code);
if (existing != null) { // && !existing.type.equals(type)) {
MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)",
code, type.getName(), existing.type.getName()));
} else {
MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s",
code, type.getName()));
}
TargetSelector.dynamicSelectors.put(code, entry);
}
/**
* Register a built-in target selector class. Skips validation and
* namespacing checks
*
* @param type ITargetSelectorDynamic to register
*/
private static void registerBuiltIn(Class<? extends ITargetSelectorDynamic> type) {
SelectorId selectorId = type.<SelectorId>getAnnotation(SelectorId.class);
DynamicSelectorEntry entry;
try {
entry = new DynamicSelectorEntry(null, selectorId.value().toLowerCase(Locale.ROOT), type);
} catch (NoSuchMethodException ex) {
throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method");
}
TargetSelector.dynamicSelectors.put(entry.id, entry);
TargetSelector.dynamicSelectors.put("mixin:" + entry.id, entry);
}
/**
* Parse a target selector from the supplied annotation and perform
* validation
*
* @param annotation Annotation to parse target selector from
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parseAndValidate(String string) throws InvalidMemberDescriptorException {
return TargetSelector.parse(string, null, null).validate();
public static ITargetSelector parseAndValidate(IAnnotationHandle annotation, ISelectorContext context) throws InvalidSelectorException {
return TargetSelector.parse(annotation, context).validate();
}
/**
@@ -105,18 +291,96 @@ public final class TargetSelector {
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parseAndValidate(String string, IMixinContext context) throws InvalidMemberDescriptorException {
return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()).validate();
public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidSelectorException {
return TargetSelector.parse(string, context).validate();
}
/**
* Parse a target selector from a string
* Parse a collection of target selector representations (strings,
* annotations, class literals) into selectors.
*
* @param string String to parse target selector from
* @param selectors Selectors to parse
* @param context Selection context
* @return parsed collection of selectors, uses LinkedHashSet to preserve
* parse ordering
*/
public static Set<ITargetSelector> parseAndValidate(Iterable<?> selectors, ISelectorContext context) throws InvalidSelectorException {
Set<ITargetSelector> parsed = TargetSelector.parse(selectors, context, new LinkedHashSet<ITargetSelector>());
for (ITargetSelector selector : parsed) {
selector.validate();
}
return parsed;
}
/**
* Parse a collection of target selector representations (strings,
* annotations, class literals) into selectors.
*
* @param selectors Selectors to parse
* @param context Selection context
* @return parsed collection of selectors, uses LinkedHashSet to preserve
* parse ordering
*/
public static Set<ITargetSelector> parse(Iterable<?> selectors, ISelectorContext context) {
return TargetSelector.parse(selectors, context, new LinkedHashSet<ITargetSelector>());
}
/**
* Parse a collection of target selector representations (strings,
* annotations, class literals) into selectors and store them in the
* provided collection.
*
* @param selectors Selectors to parse
* @param context Selection context
* @param parsed Collection to add parsed selectors to, initialised as a
* LinkedHashSet if null
* @return the same collection passed in via the <tt>parsed</tt> parameter,
* for convenience
*/
public static Set<ITargetSelector> parse(Iterable<?> selectors, ISelectorContext context, Set<ITargetSelector> parsed) {
if (parsed == null) {
parsed = new LinkedHashSet<ITargetSelector>();
}
if (selectors != null) {
for (Object selector : selectors) {
if (selector instanceof IAnnotationHandle) {
parsed.add(TargetSelector.parse((IAnnotationHandle)selector, context));
} else if (selector instanceof AnnotationNode) {
parsed.add(TargetSelector.parse(Annotations.handleOf(selector), context));
} else if (selector instanceof String) {
parsed.add(TargetSelector.parse((String)selector, context));
} else if (selector instanceof Class) {
String desc = Type.getType((Class<?>)selector).getDescriptor();
parsed.add(TargetSelector.parse(desc, context));
} else if (selector != null) {
parsed.add(TargetSelector.parse(selector.toString(), context));
}
}
}
return parsed;
}
/**
* Parse a target selector from the supplied annotation
*
* @param annotation String to parse target selector from
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parse(String string) {
return TargetSelector.parse(string, null, null);
public static ITargetSelector parse(IAnnotationHandle annotation, ISelectorContext context) {
for (DynamicSelectorEntry entry : TargetSelector.dynamicSelectors.values()) {
if (entry.annotation != null && Annotations.getDesc(entry.annotation).equals(annotation.getDesc())) {
try {
return entry.parse(annotation, context);
} catch (ReflectiveOperationException ex) {
return new InvalidSelector(ex.getCause());
} catch (Exception ex) {
return new InvalidSelector(ex);
}
}
}
return new InvalidSelector(new InvalidSelectorException("Dynamic selector for annotation " + annotation + " is not registered."));
}
/**
@@ -126,8 +390,42 @@ public final class TargetSelector {
* @param context Context to use for reference mapping
* @return parsed target selector
*/
public static ITargetSelector parse(String string, IMixinContext context) {
return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef());
public static ITargetSelector parse(String string, ISelectorContext context) {
string = string.trim();
// Ending with slash indicates a regex target, no other type of target
// selector can end (legally) with a forward slash
if (string.endsWith("/")) {
MemberMatcher regexMatcher = MemberMatcher.parse(string, context);
if (regexMatcher != null) {
return regexMatcher;
}
}
// Starting with @ indicates a dynamic target. Parse as a regular
// MemberInfo if the selector does not start with @
if (!string.startsWith("@")) {
return MemberInfo.parse(string, context);
}
Matcher dynamic = TargetSelector.PATTERN_DYNAMIC.matcher(string);
if (!dynamic.matches()) {
return new InvalidSelector(new InvalidSelectorException("Dynamic selector was in an unrecognised format. Parsing selector: " + string));
}
String selectorId = dynamic.group(1).toLowerCase(Locale.ROOT);
if (!TargetSelector.dynamicSelectors.containsKey(selectorId)) {
return new InvalidSelector(new InvalidSelectorException("Dynamic selector with id '@" + dynamic.group(1)
+ "' is not registered. Parsing selector: " + string));
}
try {
return TargetSelector.dynamicSelectors.get(selectorId).parse(Strings.nullToEmpty(dynamic.group(4)).trim(), context);
} catch (ReflectiveOperationException ex) {
return new InvalidSelector(ex.getCause(), string);
} catch (Exception ex) {
return new InvalidSelector(ex);
}
}
/**
@@ -141,7 +439,7 @@ public final class TargetSelector {
* @param context Mixin context
* @return remapped name or original name
*/
public static String parseName(String name, IMixinContext context) {
public static String parseName(String name, ISelectorContext context) {
ITargetSelector selector = TargetSelector.parse(name, context);
if (!(selector instanceof ITargetSelectorByName)) {
return name;
@@ -150,38 +448,34 @@ public final class TargetSelector {
return mappedName != null ? mappedName : name;
}
private static ITargetSelector parse(String input, IReferenceMapper refMapper, String mixinClass) {
return MemberInfo.parse(input, refMapper, mixinClass);
}
/**
* Run query on supplied target nodes
*
* @param target Target selector
* @param selector Target selector
* @param nodes Node collection to enumerate
* @param <TNode> Node type
* @return query result
*/
public static <TNode> Result<TNode> run(ITargetSelector target, List<ElementNode<TNode>> nodes) {
List<TNode> candidates = new ArrayList<TNode>();
TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates);
public static <TNode> Result<TNode> run(ITargetSelector selector, Iterable<ElementNode<TNode>> nodes) {
List<ElementNode<TNode>> candidates = new ArrayList<ElementNode<TNode>>();
ElementNode<TNode> exactMatch = TargetSelector.runSelector(selector, nodes, candidates);
return new Result<TNode>(exactMatch, candidates);
}
/**
* Run query on supplied target nodes
*
* @param targets Target selector
* @param selector Target selector
* @param nodes Node collection to enumerate
* @param <TNode> Node type
* @return query result
*/
public static <TNode> Result<TNode> run(Iterable<ITargetSelector> targets, List<ElementNode<TNode>> nodes) {
TNode exactMatch = null;
List<TNode> candidates = new ArrayList<TNode>();
public static <TNode> Result<TNode> run(Iterable<ITargetSelector> selector, Iterable<ElementNode<TNode>> nodes) {
ElementNode<TNode> exactMatch = null;
List<ElementNode<TNode>> candidates = new ArrayList<ElementNode<TNode>>();
for (ITargetSelector target : targets) {
TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates);
for (ITargetSelector target : selector) {
ElementNode<TNode> selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates);
if (exactMatch == null) {
exactMatch = selectorExactMatch;
}
@@ -190,20 +484,32 @@ public final class TargetSelector {
return new Result<TNode>(exactMatch, candidates);
}
private static <TNode> TNode runSelector(ITargetSelector target, List<ElementNode<TNode>> nodes, List<TNode> candidates) {
TNode exactMatch = null;
for (ElementNode<TNode> element : nodes) {
MatchResult match = target.match(element);
private static <TNode> ElementNode<TNode> runSelector(ITargetSelector selector, Iterable<ElementNode<TNode>> nodes,
List<ElementNode<TNode>> candidates) {
int matchCount = 0;
ElementNode<TNode> exactMatch = null;
for (Iterator<ElementNode<TNode>> iterator = nodes.iterator(); iterator.hasNext();) {
ElementNode<TNode> element = iterator.next();
MatchResult match = selector.match(element);
if (match.isMatch()) {
TNode node = element.get();
if (!candidates.contains(node)) {
candidates.add(node);
matchCount++;
if (matchCount > selector.getMaxMatchCount()) {
break;
}
if (!candidates.contains(element)) {
candidates.add(element);
}
if (exactMatch == null && match.isExactMatch()) {
exactMatch = node;
exactMatch = element;
}
}
}
if (matchCount < selector.getMinMatchCount()) {
throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)",
selector, selector.getMinMatchCount(), matchCount));
}
return exactMatch;
}
@@ -0,0 +1,426 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors.dynamic;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.Desc;
import org.spongepowered.asm.mixin.injection.Descriptors;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.Quantifier;
import org.spongepowered.asm.util.asm.IAnnotatedElement;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
/**
* Utility class which contains the logic for resolving descriptors
* ({@link Desc} annotations) starting from an element and recursing up the tree
* of parent elements looking for a matching descriptor
*/
public final class DescriptorResolver {
/**
* Resolution result
*/
static final class Descriptor implements IResolvedDescriptor {
/**
* The set of coordinates which were searched, stored here so they can
* be included in error messages if resolution fails
*/
private final Set<String> searched;
/**
* The resolved descriptor
*/
private final IAnnotationHandle desc;
/**
* Selector context
*/
private final ISelectorContext context;
Descriptor(Set<String> searched, IAnnotationHandle desc, ISelectorContext context) {
this.searched = searched;
this.desc = desc;
this.context = context;
}
/**
* True if the resolution process was successful
*/
@Override
public boolean isResolved() {
return this.desc != null;
}
/**
* Get information about the resolution of this descriptor, for
* inclusion in error messages when isResolved is false
*
*/
@Override
public String getResolutionInfo() {
if (this.searched == null) {
return "";
}
return String.format("Searched coordinates [ \"%s\" ]", Joiner.on("\", \"").join(this.searched));
}
/**
* Gets the resolved descriptor annotation if successful, otherwise
* returns null
*/
@Override
public IAnnotationHandle getAnnotation() {
return this.desc;
}
@Override
public String getId() {
return this.desc != null ? this.desc.<String>getValue("id", "") : "";
}
@Override
public Type getOwner() {
if (this.desc == null) {
return Type.VOID_TYPE;
}
Type ownerClass = this.desc.getTypeValue("owner");
if (ownerClass != Type.VOID_TYPE) {
return ownerClass;
}
return this.context != null ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass;
}
@Override
public String getName() {
if (this.desc == null) {
return "";
}
String value = this.desc.<String>getValue("value", "");
if (!value.isEmpty()) {
return value;
}
return this.desc.<String>getValue("name", "");
}
@Override
public Type[] getArgs() {
if (this.desc == null) {
return new Type[0];
}
List<Type> args = this.desc.getTypeList("args");
return args.toArray(new Type[args.size()]);
}
@Override
public Type getReturnType() {
if (this.desc == null) {
return Type.VOID_TYPE;
}
return this.desc.getTypeValue("ret");
}
@Override
public Quantifier getMatches() {
if (this.desc == null) {
return Quantifier.DEFAULT;
}
int min = Math.max(0, this.desc != null ? this.desc.<Integer>getValue("min", 0) : 0);
Integer max = this.desc != null ? this.desc.<Integer>getValue("max", null) : null;
return new Quantifier(min, max != null ? (max > 0 ? max : Integer.MAX_VALUE) : -1);
}
@Override
public List<IAnnotationHandle> getNext() {
return this.desc != null ? this.desc.getAnnotationList("next") : Collections.<IAnnotationHandle>emptyList();
}
}
/**
* Observer for the resolution process, used to support printing resolution
* path during debug or collecting resolution info for inclusion in error
* messages
*/
interface IResolverObserver {
/**
* Called when the resolver visits a coordinate on the specified member
*
* @param coordinate coordinate being visited
* @param element element being visited
* @param detail diagnostic detail
*/
public abstract void visit(String coordinate, Object element, String detail);
/**
* Get all of the searched coordinates, for inclusion in error messages
*/
public abstract Set<String> getSearched();
/**
* Called after resolution completes
*/
public abstract void postResolve();
}
/**
* Basic resolver observer which just collects searched coordinates
*/
static class ResolverObserverBasic implements IResolverObserver {
private final Set<String> searched = new LinkedHashSet<String>();
@Override
public void visit(String coordinate, Object element, String detail) {
this.searched.add(coordinate);
}
@Override
public Set<String> getSearched() {
return this.searched;
}
@Override
public void postResolve() {
}
}
/**
* Debug resolver observer which prints resolution debug info after
* resolution is complete
*/
static class ResolverObserverDebug extends ResolverObserverBasic {
private final PrettyPrinter printer = new PrettyPrinter();
ResolverObserverDebug(ISelectorContext context) {
this.printer.add("Searching for implicit descriptor").add(context).hr().table();
this.printer.tr("Context Coordinate:", context.getSelectorCoordinate(true) + " (" + context.getSelectorCoordinate(false) + ")");
this.printer.tr("Selector Annotation:", context.getSelectorAnnotation());
this.printer.tr("Root Annotation:", context.getAnnotation());
this.printer.tr("Method:", context.getMethod()).hr();
this.printer.table("Search Coordinate", "Search Element", "Detail").th().hr();
}
@Override
public void visit(String coordinate, Object element, String detail) {
super.visit(coordinate, element, detail);
this.printer.tr(coordinate, element, detail);
}
@Override
public void postResolve() {
this.printer.print();
}
}
/**
* Special ID used to instruct the resolver to print its progress.
*/
public static String PRINT_ID = "?";
// No
private DescriptorResolver() {
}
public static IResolvedDescriptor resolve(IAnnotationHandle desc, ISelectorContext context) {
return new Descriptor(Collections.emptySet(), desc, context);
}
/**
* Resolve the specified descriptor id starting at the specified context
*
* @param id Id to resolve, can be empty if resolving by coordinate
* @param context Selector context, usually from the source annotation
* @return Resolution result
*/
public static IResolvedDescriptor resolve(String id, ISelectorContext context) {
IResolverObserver observer = new ResolverObserverBasic();
if (!Strings.isNullOrEmpty(id)) {
if (DescriptorResolver.PRINT_ID.equals(id)) {
observer = new ResolverObserverDebug(context);
id = "";
} else {
observer.visit(id, "", "");
}
}
IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true));
observer.postResolve();
return new Descriptor(observer.getSearched(), desc, context);
}
/**
* Recursive function which checks an element and then recurses to parent
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate) {
IAnnotationHandle annotation = Annotations.handleOf(context.getSelectorAnnotation());
observer.visit(coordinate, annotation, annotation.toString() + ".desc");
// First check if there's a "desc" value on the current annotation
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, annotation.getAnnotationList("desc"));
if (resolved != null) {
return resolved;
}
// Next check with the current coordinates on the owning method
resolved = DescriptorResolver.resolve(id, context, observer, coordinate, context.getMethod(), "method");
if (resolved != null) {
return resolved;
}
ISelectorContext root = DescriptorResolver.getRoot(context);
String rootCoordinate = root.getSelectorCoordinate(false);
String mixinCoordinate = (root != context || !coordinate.contains(".")) && !rootCoordinate.equals(coordinate)
? rootCoordinate + "." + coordinate : coordinate;
// Next check with the current coordinates on the mixin
resolved = DescriptorResolver.resolve(id, context, observer, mixinCoordinate, context.getMixin(), "mixin");
if (resolved != null) {
return resolved;
}
// Otherwise compute the parent coordinates and then recurse into the parent
ISelectorContext parent = context.getParent();
if (parent != null) {
String parentCoordinate = parent.getSelectorCoordinate(false) + "." + coordinate;
return DescriptorResolver.resolve(id, parent, observer, parentCoordinate);
}
// If all else fails, return failure
return null;
}
/**
* Attempt to resolve on an element
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate, Object element,
String detail) {
observer.visit(coordinate, element, detail);
IAnnotationHandle descriptors = DescriptorResolver.getVisibleAnnotation(element, Descriptors.class);
if (descriptors != null) {
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptors.getAnnotationList("value"));
if (resolved != null) {
return resolved;
}
}
IAnnotationHandle descriptor = DescriptorResolver.getVisibleAnnotation(element, Desc.class);
if (descriptor != null) {
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptor);
if (resolved != null) {
return resolved;
}
}
return null;
}
/**
* Attempt resolution using annotations from a particular element
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate,
List<IAnnotationHandle> availableDescriptors) {
if (availableDescriptors != null) {
for (IAnnotationHandle desc : availableDescriptors) {
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, desc);
if (resolved != null) {
return resolved;
}
}
}
return null;
}
/**
* Attempt resolution using an actual annotation
*/
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate,
IAnnotationHandle desc) {
if (desc != null) {
String descriptorId = desc.getValue("id", coordinate);
boolean implicit = Strings.isNullOrEmpty(id);
if ((implicit && descriptorId.equalsIgnoreCase(coordinate)) || (!implicit && descriptorId.equalsIgnoreCase(id))) {
return desc;
}
}
return null;
}
/**
* Utility function, gets an annotation handle from the candidate elements
* we are able to process
*
* @param element Element to fetch annotations for
* @param annotationClass Annotation we're searching for
* @return Annotation handle or null if the source is null
* @throws IllegalStateException if element is of an unsupported type
*/
private static IAnnotationHandle getVisibleAnnotation(Object element, Class<? extends Annotation> annotationClass) {
if (element instanceof MethodNode) {
return Annotations.handleOf(Annotations.getVisible((MethodNode)element, annotationClass));
} else if (element instanceof ClassNode) {
return Annotations.handleOf(Annotations.getVisible((ClassNode)element, annotationClass));
} else if (element instanceof MixinTargetContext) {
return Annotations.handleOf(Annotations.getVisible(((MixinTargetContext)element).getClassNode(), annotationClass));
} else if (element instanceof IAnnotatedElement) {
IAnnotationHandle annotation = ((IAnnotatedElement)element).getAnnotation(annotationClass);
return annotation != null && annotation.exists() ? annotation : null;
} else if (element == null) {
return null;
}
throw new IllegalStateException("Cannot read visible annotations from element with unknown type: " + element.getClass().getName());
}
private static ISelectorContext getRoot(ISelectorContext context) {
ISelectorContext parent = context.getParent();
while (parent != null) {
context = parent;
parent = context.getParent();
}
return context;
}
}
@@ -0,0 +1,521 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors.dynamic;
import java.util.List;
import org.objectweb.asm.Type;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Desc;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.MatchResult;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Quantifier;
import org.spongepowered.asm.util.SignaturePrinter;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Strings;
/**
* A {@link ITargetSelector Target Selector} which matches candidates using
* descriptors contained in {@link Desc &#064;Desc} annotations. The descriptor
* annotations may be local, or may be applied to the method or even the owning
* mixin using user-specified ids, or implicit coordinates based on the relative
* location of the consumer. eg. an &#064;At annotation and the &#064;Desc
* annotation itself, which might be on a parent element for convenience.
*
* <p>See {@link Desc &#064;Desc} for the specific syntax of descriptor
* annotations.</p>
*
* <h3>Local Descriptors</h3>
*
* <p>Some annotations can use {@link Desc &#064;Desc} selectors directly,
* namely {@link At &#064;At} (specified in {@link At#desc &#064;At.desc}) and
* all <b>Injector</b> annotations (specified in <tt>target</tt> - for example
* {@link Inject#target &#064;Inject.target}). In these cases it is not
* necessary to specify an {@link Desc#id id} for the descriptor since the usage
* is inferred from context.</p>
*
* <h3>Resolved Descriptors</h3>
*
* <p>Descriptors can also be placed as annotations on the mixin method or the
* mixin class, thus allowing descriptors to be re-used by multiple consumers.
* For example where several injectors target the same method, the descriptor
* can be placed on the mixin itself and consumed by id. In this situation it is
* necessary to specify an {@link Desc#id id} for the descriptor and specify the
* chosen id as a selector string:</p>
*
* <blockquote><code>&#064;Mixin(TargetClass.class)<br />
* &#064;Desc(id = "<ins>foo</ins>", value = "getFoo", args = { int.class })
* <br />
* abstract class MyMixin {<br />
* <br />
* &nbsp; &nbsp; &#064;Inject(target = "<ins>&#064;Desc(foo)</ins>", at =
* &#064;At("RETURN"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }<br />
* <br />
* }</code></blockquote>
*
* <p>Note that the id string can be anything you wish, but is matched
* case-insensitively and must be non-empty, so feel free to be as descriptive
* as you wish.</p>
*
* <h4>Implicit coordinates</h4>
*
* <p>As an alternative to specifying an <em>explicit</em> descriptor id for
* descriptors, it is also possible to use implicit coordinates generated using
* the location of the consumer. To do so, use the selector <tt>"&#064;Desc"
* </tt> with no arguments and give the descriptor an {@link Desc#id id} which
* corresponds to the coordinate of the consumer:</p>
*
* <p>In this example, the coordinate of the {@link At &#064;At} annotation,
* <tt>"at"</tt> is used as the descriptor id.</p>
*
* <blockquote><code>
* &nbsp; &nbsp; &#064;Desc(id = "<ins>at</ins>",
* value = "theMethodName", args = { String.class }, ret = boolean.class)<br />
* &nbsp; &nbsp; &#064;Inject(method = "targetMethod()V", at =
* &#064;At(value = "INVOKE" target = "<ins>&#064;Desc</ins>"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }
* </code></blockquote>
*
* <p>As the resolver widens its search it adds new components to the start of
* the implicit coordinate which match the element, separated by dots. For
* example {@link At &#064;At} annotations inside a {@link Slice &#064;Slice}
* will first resolve as (local coordinate) <tt>from</tt>, followed by
* <tt>slice.from</tt>, and finally <tt>handlerMethodName.slice.from</tt>. This
* allows implicit coordinates to be used up to the mixin level as in the first
* example.</p>
*
* <blockquote><code>&#064;Mixin(TargetClass.class)<br />
* &#064;Desc(id = "<ins>myHandlerMethod.at</ins>", value = "theMethodName",
* args = { String.class }, ret = boolean.class)<br />
* &#064;Desc(id = "<ins>myHandlerMethod.method</ins>", value = "getFoo", args =
* { int.class })<br />
* abstract class MyMixin {<br />
* <br />
* &nbsp; &nbsp; &#064;Inject(method = "<ins>@Desc</ins>", at = &#064;At(value =
* "INVOKE" target = "<ins>&#064;Desc</ins>"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }
* </code></blockquote>
*
* <p>To view the coordinates used to resolve the descriptor for a particular
* element, use the special id "?" in the selector:</p>
*
* <blockquote><code>
* &nbsp; &nbsp; &#064;Inject(method = "&#064;Desc", at = &#064;At(value =
* "INVOKE" target = "<ins>&#064;Desc(?)</ins>"))
* <br />
* &nbsp; &nbsp; void myHandler(int arg, CallbackInfo ci) {
* </code></blockquote>
*
* <p>This will cause the resolver to pretty-print the considered coordinates
* and elements into the console:</p>
*
* <blockquote><pre>/*****************************************************&#47;
*&#47;* Coordinate Search Element Detail *&#47;
*&#47;*****************************************************&#47;
*&#47;* at &#64;At &#64;At.desc *&#47;
*&#47;* at myHandler method *&#47;
*&#47;* myhandler.at mixins.json:MyMixin mixin *&#47;
*&#47;* myhandler.at &#64;Redirect &#64;Redirect.desc *&#47;
*&#47;* myhandler.at myhandler method *&#47;
*&#47;*****************************************************&#47;</pre>
*</blockquote>
*
* <p>Don't worry that some combinations of coordinate and element are not
* possible (for example there is no member <tt>desc</tt> on <tt>&#64;At</tt>).
* The resolver doesn't know that and scans each visited element for members it
* supports.</p>
*/
@SelectorId("Desc")
@SelectorAnnotation(Desc.class)
public class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelectorByName {
/**
* Next selector
*/
final class Next extends DynamicSelectorDesc {
private final int index;
Next(int index, IResolvedDescriptor next) {
super(null, null, next.getOwner(), next.getName(), next.getArgs(), next.getReturnType(), next.getMatches(), null);
this.index = index;
}
@Override
public ITargetSelector next() {
return DynamicSelectorDesc.this.next(this.index + 1);
}
}
/**
* Parser/resolver error mesage, only stored if the descriptor is invalid so
* we can emit it when {@link #validate} is called
*/
private final InvalidSelectorException parseException;
/**
* Resolved id
*/
private final String id;
/**
* The owner specified in the resolved {@link Desc} annotation, or null if
* resolution failed
*/
private final Type owner;
/**
* The name specified in the resolved {@link Desc} annotation, or null if
* resolution failed
*/
private final String name;
/**
* The arguments specified in the resolved {@link Desc} annotation, or null
* if resolution failed
*/
private final Type[] args;
/**
* The return type specified in the resolved {@link Desc} annotation, or
* null if resolution failed
*/
private final Type returnType;
/**
* Method descriptor, used for matching against methods. Computed from
* argument types and return type
*/
private final String methodDesc;
/**
* Required matches
*/
private final Quantifier matches;
/**
* Annotation for next, parsed on demand
*/
private final List<IAnnotationHandle> next;
private DynamicSelectorDesc(IResolvedDescriptor desc) {
this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches(),
desc.getNext());
}
private DynamicSelectorDesc(DynamicSelectorDesc desc, Quantifier quantifier) {
this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier, desc.next);
}
private DynamicSelectorDesc(DynamicSelectorDesc desc, Type owner) {
this(desc.parseException, desc.id, owner, desc.name, desc.args, desc.returnType, desc.matches, desc.next);
}
private DynamicSelectorDesc(InvalidSelectorException ex) {
this(ex, null, null, null, null, null, Quantifier.NONE, null);
}
protected DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches,
List<IAnnotationHandle> then) {
this.parseException = ex;
this.id = id;
this.owner = owner;
this.name = Strings.emptyToNull(name);
this.args = args;
this.returnType = returnType;
this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null;
this.matches = matches;
this.next = then;
}
/**
* Parse a descriptor selector from the supplied input. The input is treated
* as a descriptor id to be resolved, or if empty uses implicit coordinates
* from the selection context
*
* @param input ID string, can be empty
* @param context Selector context
* @return parsed selector
*/
public static DynamicSelectorDesc parse(String input, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context);
if (!descriptor.isResolved()) {
String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : "";
return new DynamicSelectorDesc(new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra));
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Convert the supplied annotation into a selector instance
*
* @param context Selector context
* @param desc Annotation to parse
* @return selector
*/
public static DynamicSelectorDesc parse(IAnnotationHandle desc, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context);
if (!descriptor.isResolved()) {
return new DynamicSelectorDesc(new InvalidSelectorException("Invalid descriptor"));
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Resolve a descriptor selector from the supplied context only, implicit
* coordinates are used.
*
* @param context Selector context
* @return parsed selector
*/
public static DynamicSelectorDesc resolve(ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context);
if (!descriptor.isResolved()) {
return null;
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Convert the supplied annotation into a selector instance
*
* @param desc Annotation to parse
* @param context Selector context
* @return selector
*/
public static DynamicSelectorDesc of(IAnnotationHandle desc, ISelectorContext context) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context);
if (!descriptor.isResolved()) {
return null;
}
return DynamicSelectorDesc.of(descriptor);
}
/**
* Convert the supplied annotation into a selector instance
*
* @param desc Resolved descriptor
* @return selector
*/
public static DynamicSelectorDesc of(IResolvedDescriptor desc) {
return new DynamicSelectorDesc(desc);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("@Desc(");
boolean started = false;
if (!Strings.isNullOrEmpty(this.id)) {
sb.append("id = \"").append(this.id).append("\"");
started = true;
}
if (this.owner != Type.VOID_TYPE) {
if (started) {
sb.append(", ");
}
sb.append("owner = ").append(SignaturePrinter.getTypeName(this.owner, false, false)).append(".class");
started = true;
}
if (started) {
sb.append(", ");
}
if (this.name != null) {
sb.append("value = \"").append(this.name).append("\"");
}
if (this.args.length > 0) {
sb.append(", args = { ");
for (int i = 0; i < this.args.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(SignaturePrinter.getTypeName(this.args[i], false, false)).append(".class");
}
sb.append(" }");
}
if (this.returnType != Type.VOID_TYPE) {
sb.append(", ret = ").append(SignaturePrinter.getTypeName(this.returnType, false, false)).append(".class");
}
sb.append(")");
return sb.toString();
}
public String getId() {
return this.id;
}
@Override
public String getOwner() {
return this.owner.getInternalName();
}
@Override
public String getName() {
return this.name;
}
public Type[] getArgs() {
return this.args;
}
public Type getReturnType() {
return this.returnType;
}
@Override
public String getDesc() {
return this.methodDesc;
}
@Override
public String toDescriptor() {
return new SignaturePrinter(this).setFullyQualified(true).toDescriptor();
}
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.parseException != null) {
throw this.parseException;
}
return this;
}
@Override
public ITargetSelector next() {
return this.next(0);
}
protected ITargetSelector next(int index) {
if (index >= 0 && index < this.next.size()) {
IAnnotationHandle nextAnnotation = this.next.get(index);
IResolvedDescriptor descriptor = DescriptorResolver.resolve(nextAnnotation, null);
return new Next(index, descriptor);
}
return null;
}
@Override
public ITargetSelector configure(Configure request, String... args) {
request.checkArgs(args);
switch (request) {
case SELECT_MEMBER:
if (this.matches.isDefault()) {
return new DynamicSelectorDesc(this, Quantifier.SINGLE);
}
break;
case SELECT_INSTRUCTION:
if (this.matches.isDefault()) {
return new DynamicSelectorDesc(this, Quantifier.ANY);
}
break;
case MOVE:
return new DynamicSelectorDesc(this, Type.getObjectType(args[0]));
case CLEAR_LIMITS:
if (this.getMinMatchCount() != 0 || this.getMaxMatchCount() < Integer.MAX_VALUE) {
return new DynamicSelectorDesc(this, Quantifier.ANY);
}
break;
default:
break;
}
return this;
}
@Override
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
return this;
}
@Override
public int getMinMatchCount() {
return this.matches.getClampedMin();
}
@Override
public int getMaxMatchCount() {
return this.matches.getClampedMax();
}
@Override
public MatchResult matches(String owner, String name, String desc) {
return this.matches(owner, name, desc, this.methodDesc);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #match(org.spongepowered.asm.util.asm.ElementNode)
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
if (node == null) {
return MatchResult.NONE;
} else if (node.isField()) {
return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.returnType.getInternalName());
} else {
return this.matches(node.getOwner(), node.getName(), node.getDesc(), this.methodDesc);
}
}
private MatchResult matches(String owner, String name, String desc, String compareWithDesc) {
if (!compareWithDesc.equals(desc)) {
return MatchResult.NONE;
} else if (this.owner != Type.VOID_TYPE && !this.owner.getInternalName().equals(owner)) {
return MatchResult.NONE;
} else if (this.name != null && this.name.equals(name)) {
return MatchResult.EXACT_MATCH;
} else if (this.name != null && this.name.equalsIgnoreCase(name)) {
return MatchResult.MATCH;
} else if (this.name == null) {
return MatchResult.EXACT_MATCH;
}
return MatchResult.NONE;
}
}
@@ -0,0 +1,94 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors.dynamic;
import java.util.List;
import org.objectweb.asm.Type;
import org.spongepowered.asm.util.Quantifier;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* A resolved descriptor, or rather the result of resolving a descriptor. If the
* descriptor was not resolved then {@link #isResolved} returns <tt>false</tt>.
*/
public interface IResolvedDescriptor {
/**
* Get whether the descriptor was successfully resolved
*/
public abstract boolean isResolved();
/**
* Get the resolved descriptor, or null if the descriptor was not resolved
*/
public abstract IAnnotationHandle getAnnotation();
/**
* Get information about the resolution process (eg. visited implicit
* coordinates) as a human-readable string for inclusion in error messages.
*/
public abstract String getResolutionInfo();
/**
* Get the ID of the resolved descriptor, should match the query
*/
public abstract String getId();
/**
* Get the owner from the resolved descriptor, returns <tt>void</tt> if the
* descriptor was not resolved.
*/
public abstract Type getOwner();
/**
* Get the name from the resolved descriptor, returns an empty string if the
* descriptor was not resolved.
*/
public abstract String getName();
/**
* Get the arguments from the resolved descriptor, returns an empty array if
* the descriptor was not resolved.
*/
public abstract Type[] getArgs();
/**
* Get the return type from the resolved descriptor, returns <tt>void</tt>
* if the descriptor was not resolved.
*/
public abstract Type getReturnType();
/**
* Get the specified matches values from the resolved descriptor.
*/
public abstract Quantifier getMatches();
/**
* Get the values specified for next, if any
*/
public abstract List<IAnnotationHandle> getNext();
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Dynamic target selectors provide custom logic for selecting injector targets.
*/
package org.spongepowered.asm.mixin.injection.selectors.dynamic;
@@ -0,0 +1,31 @@
/*
* 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.
*/
/**
* Target selectors are consumed by injectors and injection points when
* identifying target members in a class or inside a method, see {@link
* org.spongepowered.asm.mixin.injection.selectors.ITargetSelector}.
*/
package org.spongepowered.asm.mixin.injection.selectors;
@@ -0,0 +1,51 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors.throwables;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
/**
* Exception to be thrown when a {@link ITargetSelector target selector}
* {@link ITargetSelector#getMinMatchCount min} or
* {@link ITargetSelector#getMaxMatchCount max} constraint is not met when
* running the selector
*/
public class SelectorConstraintException extends SelectorException {
private static final long serialVersionUID = 1L;
public SelectorConstraintException(ITargetSelector selector, String message) {
super(selector, message);
}
public SelectorConstraintException(ITargetSelector selector, Throwable cause) {
super(selector, cause);
}
public SelectorConstraintException(ITargetSelector selector, String message, Throwable cause) {
super(selector, message, cause);
}
}
@@ -0,0 +1,59 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.selectors.throwables;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.throwables.MixinException;
/**
* Exception to be thrown for error conditions raised by {@link ITargetSelector
* target selectors}
*/
public class SelectorException extends MixinException {
private static final long serialVersionUID = 1L;
private final ITargetSelector selector;
public SelectorException(ITargetSelector selector, String message) {
super(message);
this.selector = selector;
}
public SelectorException(ITargetSelector selector, Throwable cause) {
super(cause);
this.selector = selector;
}
public SelectorException(ITargetSelector selector, String message, Throwable cause) {
super(message, cause);
this.selector = selector;
}
public ITargetSelector getSelector() {
return this.selector;
}
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Exceptions for selectors.
*/
package org.spongepowered.asm.mixin.injection.selectors.throwables;
@@ -30,8 +30,14 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.tools.Diagnostic.Kind;
@@ -50,9 +56,13 @@ import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.code.InjectorTarget;
import org.spongepowered.asm.mixin.injection.code.MethodSlice;
import org.spongepowered.asm.mixin.injection.code.MethodSlices;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException;
import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorException;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
@@ -66,7 +76,6 @@ import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
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.ElementNode;
import org.spongepowered.asm.util.asm.MethodNodeEx;
import org.spongepowered.asm.util.logging.MessageRouter;
@@ -117,19 +126,19 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
final Class<? extends Annotation> annotationType;
final Class<? extends InjectionInfo> type;
final Class<? extends InjectionInfo> injectorType;
final Constructor<? extends InjectionInfo> ctor;
final String simpleName;
final String annotationDesc;
final String prefix;
InjectorEntry(Class<? extends Annotation> annotationType, Class<? extends InjectionInfo> type) throws NoSuchMethodException {
this.annotationType = annotationType;
this.type = type;
this.injectorType = type;
this.ctor = type.getDeclaredConstructor(MixinTargetContext.class, MethodNode.class, AnnotationNode.class);
this.simpleName = annotationType.getSimpleName() + ";";
this.annotationDesc = Type.getDescriptor(annotationType);
HandlerPrefix handlerPrefix = type.<HandlerPrefix>getAnnotation(HandlerPrefix.class);
this.prefix = handlerPrefix != null ? handlerPrefix.value() : InjectionInfo.DEFAULT_PREFIX;
@@ -144,13 +153,40 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
throw (MixinException)cause;
}
Throwable ex = cause != null ? cause : itex;
throw new MixinError("Error initialising injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex);
throw new MixinError("Error initialising injector metaclass [" + this.injectorType + "] for annotation " + annotation.desc, ex);
} catch (ReflectiveOperationException ex) {
throw new MixinError("Failed to instantiate injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex);
throw new MixinError("Failed to instantiate injector metaclass [" + this.injectorType + "] for annotation " + annotation.desc, ex);
}
}
}
/**
* Selected target, paired with the selector which identified it
*/
static class SelectedTarget {
private final ITargetSelector root;
final ITargetSelector selector;
final MethodNode method;
SelectedTarget(ITargetSelector root, ITargetSelector selector, MethodNode method) {
this.root = root;
this.selector = selector;
this.method = method;
}
SelectedTarget(ITargetSelector selector, MethodNode method) {
this(null, selector, method);
}
ITargetSelector getRoot() {
return this.root != null ? this.root : this.selector;
}
}
/**
* Default conform prefix for handler methods
*/
@@ -183,10 +219,15 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
*/
protected final boolean isStatic;
/**
* Target selector(s)
*/
protected final Set<ITargetSelector> selectors = new LinkedHashSet<ITargetSelector>();
/**
* Target method(s)
*/
protected final Deque<MethodNode> targets = new ArrayDeque<MethodNode>();
protected final List<SelectedTarget> targets = new ArrayList<SelectedTarget>();
/**
* Method slice descriptors parsed from the annotation
@@ -285,25 +326,30 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
List<AnnotationNode> injectionPoints = this.readInjectionPoints();
this.parseRequirements();
this.findMethods(this.parseTargets());
this.parseSelectors();
this.findTargets();
this.parseInjectionPoints(injectionPoints);
this.injector = this.parseInjector(this.annotation);
}
protected Set<ITargetSelector> parseTargets() {
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",
protected void parseSelectors() {
Set<ITargetSelector> selectors = new LinkedHashSet<ITargetSelector>();
TargetSelector.parse(Annotations.<String>getValue(this.annotation, "method", false), this, selectors);
TargetSelector.parse(Annotations.<AnnotationNode>getValue(this.annotation, "target", false), this, selectors);
// Raise an error if we have no selectors
if (selectors.size() == 0) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets",
this.annotationType, this.methodName));
}
Set<ITargetSelector> selectors = new LinkedHashSet<ITargetSelector>();
for (String method : methods) {
// Validate and attach the parsed selectors
for (ITargetSelector selector : selectors) {
try {
selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin));
this.selectors.add(selector.validate().attach(this));
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s",
this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus()));
throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: %s. %s",
this.annotationType, this.methodName, ex.getMessage(), 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",
@@ -314,7 +360,6 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
ex.getMessage()));
}
}
return selectors;
}
protected List<AnnotationNode> readInjectionPoints() {
@@ -369,11 +414,26 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
*/
public void prepare() {
this.targetNodes.clear();
for (MethodNode targetMethod : this.targets) {
Target target = this.mixin.getTargetMethod(targetMethod);
InjectorTarget injectorTarget = new InjectorTarget(this, target);
this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints));
injectorTarget.dispose();
for (SelectedTarget targetMethod : this.targets) {
Target target = this.mixin.getTargetMethod(targetMethod.method);
InjectorTarget injectorTarget = new InjectorTarget(this, target, targetMethod.selector);
try {
this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints));
} catch (SelectorException ex) {
throw new InvalidInjectionException(this, String.format("Injection validation failed: %s on %s: %s. %s%s",
this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()));
} finally {
injectorTarget.dispose();
}
}
}
/**
* Perform pre-injection checks and tasks
*/
public void preInject() {
for (Entry<Target, List<InjectionNode>> entry : this.targetNodes.entrySet()) {
this.injector.preInject(entry.getKey(), entry.getValue());
}
}
@@ -435,12 +495,12 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
/**
* Get methods being injected into
* Get number of methods being injected into
*
* @return methods being injected into
* @return count of methods being injected into
*/
public Collection<MethodNode> getTargets() {
return this.targets;
public int getTargetCount() {
return this.targets.size();
}
/**
@@ -519,44 +579,68 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
/**
* Finds methods in the target class which match searchFor
*
* @param selectors members to search for
* Find methods in the target class which match the parsed selectors
*/
private void findMethods(Set<ITargetSelector> selectors) {
protected void findTargets() {
this.targets.clear();
this.findRootTargets();
this.validateTargets();
}
/**
* Evaluate the root selectors parsed from this injector, find the root
* targets and store them in the {@link #targets} collection.
*/
private void findRootTargets() {
// When remapping refmap is enabled this implies we are in a development
// environment. In certain circumstances including the descriptor for
// the method may actually fail, so we will do a second pass without the
// descriptor if this happens.
int passes = this.mixin.getOption(Option.REFMAP_REMAP) ? 2 : 1;
for (ITargetSelector selector : selectors) {
int matchCount = selector.getMatchCount();
for (int count = 0, pass = 0; pass < passes && count < 1; pass++) {
for (ITargetSelector selector : this.selectors) {
selector = selector.configure(Configure.SELECT_MEMBER);
int matchCount = 0;
int maxCount = selector.getMaxMatchCount();
// Second pass ignores descriptor
ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE);
int selectorPasses = (permissiveSelector == selector) ? 1 : passes;
scan: for (int pass = 0; pass < selectorPasses && matchCount < 1; pass++) {
ITargetSelector passSelector = pass == 0 ? selector : permissiveSelector;
for (MethodNode target : this.classNode.methods) {
if (selector.match(ElementNode.of(this.classNode, target)).isExactMatch()) {
if (passSelector.match(ElementNode.of(this.classNode, target)).isExactMatch()) {
matchCount++;
boolean isMixinMethod = Annotations.getVisible(target, MixinMerged.class) != null;
if (matchCount > 1 && (Bytecode.isStatic(target) != this.isStatic || target == this.method || isMixinMethod)) {
continue;
if (maxCount <= 1 || ((this.isStatic || !Bytecode.isStatic(target)) && target != this.method && !isMixinMethod)) {
this.checkTarget(target);
this.targets.add(new SelectedTarget(passSelector, target));
}
this.checkTarget(target);
this.targets.add(target);
count++;
if (count >= matchCount) {
break;
if (matchCount >= maxCount) {
break scan;
}
}
}
// Second pass ignores descriptor
selector = selector.configure("permissive");
}
if (matchCount < selector.getMinMatchCount()) {
throw new InvalidInjectionException(this, new SelectorConstraintException(selector, String.format(
"Injection validation failed: %s for %s on %s did not match the required number of targets (required=%d, matched=%d). %s%s",
selector, this.annotationType, this.methodName, selector.getMinMatchCount(), matchCount,
this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())));
}
}
}
/**
* Post-search validation that some targets were found, we can fail-fast if
* no targets were actually identified
*/
protected void validateTargets() {
this.targetCount = this.targets.size();
if (this.targetCount > 0) {
return;
@@ -565,17 +649,17 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
if ((this.mixin.getOption(Option.DEBUG_INJECTORS) && this.expectedCallbackCount > 0)) {
throw new InvalidInjectionException(this,
String.format("Injection validation failed: %s annotation on %s could not find any targets matching %s in %s. %s%s",
this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
this.annotationType, this.methodName, InjectionInfo.namesOf(this.selectors), this.mixin.getTarget(),
this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()));
} else if (this.requiredCallbackCount > 0) {
throw new InvalidInjectionException(this,
String.format("Critical injection failure: %s annotation on %s could not find any targets matching %s in %s. %s%s",
this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
this.annotationType, this.methodName, InjectionInfo.namesOf(this.selectors), this.mixin.getTarget(),
this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()));
}
}
private void checkTarget(MethodNode target) {
protected void checkTarget(MethodNode target) {
AnnotationNode merged = Annotations.getVisible(target, MixinMerged.class);
if (merged == null) {
return;
@@ -602,7 +686,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
return description.length() > 0 ? String.format(" Method is @Dynamic(%s).", description) : "";
}
/**
* Parse an injector from the specified method (if an injector annotation is
* present). If no injector annotation is present then <tt>null</tt> is
@@ -620,7 +704,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
for (InjectorEntry injector : InjectionInfo.registry.values()) {
if (annotation.desc.endsWith(injector.simpleName)) {
if (annotation.desc.equals(injector.annotationDesc)) {
return injector.create(mixin, method, annotation);
}
}
@@ -660,7 +744,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
for (InjectorEntry injector : InjectionInfo.registry.values()) {
if (annotation.desc.endsWith(injector.simpleName)) {
if (annotation.desc.endsWith(injector.annotationDesc)) {
return injector.prefix;
}
}
@@ -669,7 +753,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
static String describeInjector(IMixinContext mixin, AnnotationNode annotation, MethodNode method) {
return String.format("%s->@%s::%s%s", mixin.toString(), Bytecode.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc);
return String.format("%s->@%s::%s%s", mixin.toString(), Annotations.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc);
}
/**
@@ -694,7 +778,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
return sb.toString();
}
/**
* Register an injector info class. The supplied class must be decorated
* with an {@link AnnotationType} annotation for registration purposes.
@@ -713,16 +797,16 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
} catch (NoSuchMethodException ex) {
throw new MixinError("InjectionInfo class " + type.getName() + " is missing a valid constructor");
}
InjectorEntry existing = InjectionInfo.registry.get(entry.simpleName);
InjectorEntry existing = InjectionInfo.registry.get(entry.annotationDesc);
if (existing != null) { // && !existing.type.equals(type)) {
MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding InjectionInfo for @%s with %s (previously %s)",
annotationType.value().getSimpleName(), type.getName(), existing.type.getName()));
annotationType.value().getSimpleName(), type.getName(), existing.injectorType.getName()));
} else {
MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new injector for @%s with %s",
annotationType.value().getSimpleName(), type.getName()));
}
InjectionInfo.registry.put(entry.simpleName, entry);
InjectionInfo.registry.put(entry.annotationDesc, entry);
ArrayList<Class<? extends Annotation>> annotations = new ArrayList<Class<? extends Annotation>>();
for (InjectorEntry injector : InjectionInfo.registry.values()) {
@@ -206,7 +206,7 @@ public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
*/
@Override
public String toString() {
return String.format("InjectionNode[%s]", Bytecode.describeNode(this.currentTarget).replaceAll("\\s+", " "));
return String.format("InjectionNode[%s]", Bytecode.describeNode(this.currentTarget, false));
}
}
@@ -0,0 +1,95 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.struct;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Specialised SelectorAnnotationContext for injection points
*/
public class InjectionPointAnnotationContext extends SelectorAnnotationContext implements IInjectionPointContext {
/**
* Parent context
*/
private IInjectionPointContext parentContext;
public InjectionPointAnnotationContext(IInjectionPointContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) {
super(parent, selectorAnnotation, selectorCoordinate);
this.parentContext = parent;
}
public InjectionPointAnnotationContext(IInjectionPointContext parent, AnnotationNode selectorAnnotation, String selectorCoordinate) {
super(parent, Annotations.handleOf(selectorAnnotation), selectorCoordinate);
this.parentContext = parent;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.util.IMessageSink
* #addMessage(java.lang.String, java.lang.Object[])
*/
@Override
public void addMessage(String format, Object... args) {
this.parentContext.addMessage(format, args);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.struct
* .SelectorAnnotationContext#getMethod()
*/
@Override
public MethodNode getMethod() {
return this.parentContext.getMethod();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.IInjectionPointContext
* #getAnnotationNode()
*/
@Override
public AnnotationNode getAnnotationNode() {
return this.parentContext.getAnnotationNode();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.struct
* .SelectorAnnotationContext#getAnnotation()
*/
@Override
public IAnnotationHandle getAnnotation() {
return this.parentContext.getAnnotation();
}
@Override
public String toString() {
return String.format("%s->%s(%s)", this.parentContext, this.getSelectorAnnotation(),
this.getSelectorCoordinate(false));
}
}
@@ -39,10 +39,15 @@ import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.TargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Annotations.Handle;
import org.spongepowered.asm.util.IMessageSink;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
@@ -174,10 +179,17 @@ public class InjectionPointData {
}
/**
* Get the context
* Get the injection point context
*/
public IMixinContext getContext() {
return this.context.getContext();
public IInjectionPointContext getContext() {
return this.context;
}
/**
* Get the mixin context
*/
public IMixinContext getMixin() {
return this.context.getMixin();
}
/**
@@ -198,7 +210,7 @@ public class InjectionPointData {
* Get the root annotation (eg. {@link Inject})
*/
public AnnotationNode getParent() {
return this.context.getAnnotation();
return this.context.getAnnotationNode();
}
/**
@@ -258,9 +270,9 @@ public class InjectionPointData {
*/
public ITargetSelector get(String key) {
try {
return TargetSelector.parseAndValidate(this.get(key, ""), this.getContext());
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s",
return TargetSelector.parseAndValidate(this.get(key, ""), this.context);
} catch (InvalidSelectorException ex) {
throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").%s \"%s\" on %s",
this.at, key, this.target, this.getDescription());
}
}
@@ -270,9 +282,19 @@ public class InjectionPointData {
*/
public ITargetSelector getTarget() {
try {
return TargetSelector.parseAndValidate(this.target, this.getContext());
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").target descriptor \"%s\" on %s",
if (Strings.isNullOrEmpty(this.target)) {
IAnnotationHandle selectorAnnotation = this.context.getSelectorAnnotation();
AnnotationNode desc = Annotations.<AnnotationNode>getValue(((Handle)selectorAnnotation).getNode(), "desc");
if (desc != null) {
String id = Annotations.<String>getValue(desc, "id", "at");
if ("at".equalsIgnoreCase(id)) {
return DynamicSelectorDesc.of(Annotations.handleOf(desc), this.context);
}
}
}
return TargetSelector.parseAndValidate(this.target, this.context);
} catch (InvalidSelectorException ex) {
throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed validating @At(\"%s\").target \"%s\" on %s",
this.at, this.target, this.getDescription());
}
}
@@ -281,7 +303,7 @@ public class InjectionPointData {
* Get a description of this injector for use in error messages
*/
public String getDescription() {
return InjectionInfo.describeInjector(this.getContext(), this.getParent(), this.getMethod());
return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotationNode(), this.context.getMethod());
}
/**
@@ -340,7 +362,7 @@ public class InjectionPointData {
}
private static Pattern createPattern() {
return Pattern.compile(String.format("^([^:]+):?(%s)?$", Joiner.on('|').join(Selector.values())));
return Pattern.compile(String.format("^(.+?)(:(%s))?$", Joiner.on('|').join(Selector.values())));
}
/**
@@ -359,7 +381,7 @@ public class InjectionPointData {
}
private static Selector parseSelector(Matcher matcher) {
return matcher.matches() && matcher.group(2) != null ? Selector.valueOf(matcher.group(2)) : Selector.DEFAULT;
return matcher.matches() && matcher.group(3) != null ? Selector.valueOf(matcher.group(3)) : Selector.DEFAULT;
}
private static int parseInt(String string, int defaultValue) {
@@ -264,7 +264,8 @@ public class InjectorGroupInfo {
int min = this.getMinRequired();
int max = this.getMaxAllowed();
if (total < min) {
throw new InjectionValidationException(this, String.format("expected %d invocation(s) but only %d succeeded", min, total));
String only = total > 0 ? "only " : "";
throw new InjectionValidationException(this, String.format("expected %d invocation(s) but %s%d succeeded", min, only, total));
} else if (total > max) {
throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total));
}
@@ -32,17 +32,25 @@ import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
public class InvalidMemberDescriptorException extends InvalidSelectorException {
private static final long serialVersionUID = 1L;
private final String input;
public InvalidMemberDescriptorException(String message) {
public InvalidMemberDescriptorException(String input, String message) {
super(message);
this.input = input;
}
public InvalidMemberDescriptorException(Throwable cause) {
public InvalidMemberDescriptorException(String input, Throwable cause) {
super(cause);
this.input = input;
}
public InvalidMemberDescriptorException(String message, Throwable cause) {
public InvalidMemberDescriptorException(String input, String message, Throwable cause) {
super(message, cause);
this.input = input;
}
public String getInput() {
return this.input;
}
}
@@ -28,69 +28,200 @@ import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.selectors.ElementNode;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.MatchResult;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.obfuscation.mapping.IMapping;
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.Quantifier;
import org.spongepowered.asm.util.SignaturePrinter;
import org.spongepowered.asm.util.asm.ElementNode;
import org.spongepowered.asm.util.asm.ASM;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
/**
* <p>Target selector, also used as a general-purpose information bundle about a
* member (method or field) parsed from a String token in another annotation,
* this is used where target members need to be specified as Strings in order to
* parse the String representation to something useful. See
* {@link ITargetSelector} for other supported selector types.</p>
* <p>Struct which defines an <b>Explcit Target selector</b>, See
* {@link ITargetSelector} for other supported selector types. This struct is
* also used as a general-purpose information bundle about a member (method or
* field) parsed from a String token in another annotation, this is used where
* target members need to be specified as Strings in order to parse the String
* representation to something useful.</p>
*
* <p>Some examples:</p>
* <blockquote><pre>
* // references a method or field called func_1234_a, if there are multiple
* // members with the same signature, matches the first occurrence
* func_1234_a
*
* // references a method or field called func_1234_a, if there are multiple
* // members with the same signature, matches all occurrences
* func_1234_a*
*
* // references a method called func_1234_a which takes 3 ints and returns
* // a bool
* func_1234_a(III)Z
*
* // references a field called field_5678_z which is a String
* field_5678_z:Ljava/lang/String;
*
* // references a ctor which takes a single String argument
* &lt;init&gt;(Ljava/lang/String;)V
*
* // references a method called func_1234_a in class foo.bar.Baz
* Lfoo/bar/Baz;func_1234_a
*
* // references a field called field_5678_z in class com.example.Dave
* Lcom/example/Dave;field_5678_z
*
* // references a method called func_1234_a in class foo.bar.Baz which takes
* // three doubles and returns void
* Lfoo/bar/Baz;func_1234_a(DDD)V
*
* // alternate syntax for the same
* foo.bar.Baz.func_1234_a(DDD)V</pre>
* </blockquote>
* <p>In general a <tt>MemberInfo</tt> consists of 4 parts, <span class="ownr">
* owner</span>, <span class="name">name</span>, <span class="quan">quantifier
* </span> and <span class="desc">descriptor</span>, all of which are optional:
* </p>
*
* <table class="selectorTable">
* <thead>
* <tr>
* <th>&nbsp;</th>
* <th class="ownr">Owner</th>
* <th class="name">Name</th>
* <th class="quan">Quantifier</th>
* <th>&nbsp;</th>
* <th class="desc">Descriptor</th>
* <th>Resulting selector string</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td class="th">Method</td>
* <td class="ownr">Lfully/qualified/OwnerClass;</td>
* <td class="name">methodName</td>
* <td class="quan">{1,3}</td>
* <td>&nbsp;</td>
* <td class="desc">(III)V</td>
* <td><span class="ownr">Lfully/qualified/OwnerClass;</span><span
* class="name">methodName</span><span class="quan">{1,3}</span><span
* class="desc">(III)V</span></td>
* </tr>
* <tr>
* <td class="th">Field</td>
* <td class="ownr">Lfully/qualified/OwnerClass;</td>
* <td class="name">fieldName</td>
* <td class="quan">*</td>
* <td>:</td>
* <td class="desc">Ljava/lang/String;</td>
* <td><span class="ownr">Lfully/qualified/OwnerClass;</span><span
* class="name">fieldName</span><span class="quan">*</span>:<span
* class="desc">Ljava/lang/String;</span></td>
* </tr>
* </tbody>
* </table>
*
* <p>Any part of the selector can be omitted, though they must appear in the
* correct order. Some examples:</p>
*
* <blockquote><code>
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with the same signature, matches the first occurrence<br /></del>
* <span class="name">func_1234_a</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches all occurrences</del><br />
* <span class="name">func_1234_a</span><span class="quan">*</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches all occurrences, matching less than 1
* <br />
* // occurrence is an error condition</del><br />
* <span class="name">func_1234_a</span><span class="quan">+</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches up to 3 occurrences</del><br />
* <span class="name">func_1234_a</span><span class="quan">{,3}</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches exactly 3 occurrences, matching fewer
* <br />
* // than 3 occurrences is an error condition</del><br />
* <span class="name">func_1234_a</span><span class="quan">{3}</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches at least 3 occurrences, matching fewer
* <br />
* // than 3 occurrences is an error condition</del><br />
* <span class="name">func_1234_a</span><span class="quan">{3,}</span><br />
* <br />
* <del>// selects all members of any type and descriptor</del><br />
* <span class="quan">*</span><br />
* <br />
* <del>// selects the first member of any type and descriptor</del><br />
* <span class="quan">{1}</span><br />
* <br />
* <del>// selects all methods which take 3 ints and return a bool</del><br />
* <span class="quan">*</span><span class="desc">(III)Z</span><br />
* <br />
* <del>// selects the first 2 methods which take a bool and return void</del>
* <br />
* <span class="quan">{2}</span><span class="desc">(Z)V</span><br />
* <br />
* <del>// selects a method called func_1234_a which takes 3 ints and returns a
* bool</del><br />
* <span class="name">func_1234_a</span><span class="desc">(III)Z</span><br />
* <br />
* <del>// selects a field called field_5678_z which is a String</del><br />
* <span class="name">field_5678_z</span>:<span class="desc">Ljava/lang/String;
* </span><br />
* <br />
* <del>// selects a ctor which takes a single String argument</del><br />
* <span class="name">&lt;init&gt;</span><span
* class="desc">(Ljava/lang/String;)V</span><br />
* <br />
* <del>// selects a method called func_1234_a in class foo.bar.Baz</del><br />
* <span class="ownr">Lfoo/bar/Baz;</span><span class="name">func_1234_a</span>
* <br />
* <br />
* <del>// selects a field called field_5678_z in class com.example.Dave</del>
* <br />
* <span class="ownr">Lcom/example/Dave;</span><span class="name">field_5678_z
* </span><br />
* <br />
* <del>// selects a field called field_5678_z in class com.example.Dave<br />
* // which is of type String</del><br />
* <span class="ownr">Lcom/example/Dave;</span><span
* class="name">field_5678_z</span>:<span class="desc">Ljava/lang/String;
* </span><br />
* <br />
* <del>// selects a method called func_1234_a in class foo.bar.Baz which<br />
* // takes three doubles and returns void</del><br />
* <span class="ownr">Lfoo/bar/Baz;</span><span
* class="name">func_1234_a</span><span class="desc">(DDD)V</span><br />
* <br />
* <del>// alternate syntax for the same</del><br />
* <span class="ownr">foo.bar.Baz</span>.<span
* class="name">func_1234_a</span><span class="desc">(DDD)V</span>
* </code></blockquote>
*
* <h4>Notes</h4>
*
* <ul>
* <li>All whitespace in the selector string is stripped before the selector
* is parsed.</li>
* <li><span class="quan">Quantifiers</span> for selectors can be used as a
* form of early validation (prior to injector <tt>require</tt> directives)
* that an injection point has matched a required number of targets or to
* limit the number of matches it can return.</li>
* <li>The syntax for <span class="quan">quantifiers</span> is based on the
* syntax for <a href="https://www.regular-expressions.info/refrepeat.html"
* target="_top">quantifiers in regular expressions</a>, though more
* limited. In particular:
* <ul>
* <li><b>No quantifer</b> is equivalent to the regex <tt>?</tt>
* quantifier, in that undecorated selectors can match <tt>{0,1}</tt>,
* this is for backward compatibility reasons. Likewise <tt>?</tt> is
* not supported since it's implied. To require exactly one match use
* <tt>{1}</tt>.</li>
* <li>The quantifiers <tt>*</tt> and <tt>+</tt> work the same as their
* regex counterparts.</li>
* </ul>
* </li>
* </ul>
*/
public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelectorConstructor {
/**
* Separator for elements in the path
*/
private static final String ARROW = "->";
/**
* Member owner in internal form but without L;, can be null
*/
@@ -107,9 +238,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
private final String desc;
/**
* True to match all matching members, not just the first
* Required matches
*/
private final boolean matchAll;
private final Quantifier matches;
/**
* Force this member to report as a field
@@ -119,17 +250,21 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
/**
* The actual String value passed into the {@link #parse} method
*/
private final String unparsed;
private final String input;
/**
* The actual String value passed into the {@link #parse} method
*/
private final String tail;
/**
* ctor
*
* @param name Member name, must not be null
* @param matchAll true if this info should match all matching references,
* or only the first
* @param matches Quantifier specifying the number of matches required
*/
public MemberInfo(String name, boolean matchAll) {
this(name, null, null, matchAll);
public MemberInfo(String name, Quantifier matches) {
this(name, null, null, matches, null, null);
}
/**
@@ -138,11 +273,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form
* without L;
* @param matchAll true if this info should match all matching references,
* or only the first
* @param matches Quantifier specifying the number of matches required
*/
public MemberInfo(String name, String owner, boolean matchAll) {
this(name, owner, null, matchAll);
public MemberInfo(String name, String owner, Quantifier matches) {
this(name, owner, null, matches, null, null);
}
/**
@@ -154,7 +288,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* @param desc Member descriptor, can be null
*/
public MemberInfo(String name, String owner, String desc) {
this(name, owner, desc, false);
this(name, owner, desc, Quantifier.DEFAULT, null, null);
}
/**
@@ -164,10 +298,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* @param owner Member owner, can be null otherwise must be in internal form
* without L;
* @param desc Member descriptor, can be null
* @param matchAll True to match all matching members, not just the first
* @param matches Quantifier specifying the number of matches required
*/
public MemberInfo(String name, String owner, String desc, boolean matchAll) {
this(name, owner, desc, matchAll, null);
public MemberInfo(String name, String owner, String desc, Quantifier matches) {
this(name, owner, desc, matches, null, null);
}
/**
@@ -177,9 +311,22 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* @param owner Member owner, can be null otherwise must be in internal form
* without L;
* @param desc Member descriptor, can be null
* @param matchAll True to match all matching members, not just the first
* @param matches Quantifier specifying the number of matches required
*/
public MemberInfo(String name, String owner, String desc, boolean matchAll, String unparsed) {
public MemberInfo(String name, String owner, String desc, Quantifier matches, String tail) {
this(name, owner, desc, matches, tail, null);
}
/**
* ctor
*
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form
* without L;
* @param desc Member descriptor, can be null
* @param matches Quantifier specifying the number of matches required
*/
public MemberInfo(String name, String owner, String desc, Quantifier matches, String tail, String input) {
if (owner != null && owner.contains(".")) {
throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format");
}
@@ -187,9 +334,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
this.owner = owner;
this.name = name;
this.desc = desc;
this.matchAll = matchAll;
this.matches = matches;
this.forceField = false;
this.unparsed = unparsed;
this.tail = tail;
this.input = input;
}
/**
@@ -199,9 +347,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* @param insn instruction node to copy values from
*/
public MemberInfo(AbstractInsnNode insn) {
this.matchAll = false;
this.matches = Quantifier.DEFAULT;
this.forceField = false;
this.unparsed = null;
this.input = null;
this.tail = null;
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodNode = (MethodInsnNode) insn;
@@ -227,9 +376,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
this.owner = mapping.getOwner();
this.name = mapping.getSimpleName();
this.desc = mapping.getDesc();
this.matchAll = false;
this.matches = Quantifier.SINGLE;
this.forceField = mapping.getType() == IMapping.Type.FIELD;
this.unparsed = null;
this.tail = null;
this.input = null;
}
/**
@@ -241,9 +391,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
this.owner = setOwner ? method.getOwner() : remapped.owner;
this.name = method.getSimpleName();
this.desc = method.getDesc();
this.matchAll = remapped.matchAll;
this.matches = remapped.matches;
this.forceField = false;
this.unparsed = null;
this.tail = null;
this.input = null;
}
/**
@@ -256,14 +407,15 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
this.owner = owner;
this.name = original.name;
this.desc = original.desc;
this.matchAll = original.matchAll;
this.matches = original.matches;
this.forceField = original.forceField;
this.unparsed = null;
this.tail = original.tail;
this.input = null;
}
@Override
public ITargetSelector next() {
return null; // Not supported yet
return Strings.isNullOrEmpty(this.tail) ? null : MemberInfo.parse(this.tail, null);
}
@Override
@@ -282,8 +434,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
}
@Override
public int getMatchCount() {
return this.matchAll ? Integer.MAX_VALUE : 1;
public int getMinMatchCount() {
return this.matches.getClampedMin();
}
@Override
public int getMaxMatchCount() {
return this.matches.getClampedMax();
}
/* (non-Javadoc)
@@ -293,12 +450,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
public String toString() {
String owner = this.owner != null ? "L" + this.owner + ";" : "";
String name = this.name != null ? this.name : "";
String qualifier = this.matchAll ? "*" : "";
String quantifier = this.matches.toString();
String desc = this.desc != null ? this.desc : "";
String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : "");
return owner + name + qualifier + separator + desc;
String tail = this.tail != null ? " " + MemberInfo.ARROW + " " + this.tail : "";
return owner + name + quantifier + separator + desc + tail;
}
/**
* Return this MemberInfo as an SRG mapping
*
@@ -335,7 +493,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
*/
@Override
public String toCtorType() {
if (this.unparsed == null) {
if (this.input == null) {
return null;
}
@@ -352,7 +510,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
return this.name;
}
return this.desc != null ? this.desc : this.unparsed;
return this.desc != null ? this.desc : this.input;
}
/**
@@ -471,52 +629,74 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
*
* @return fluent
*
* @throws InvalidMemberDescriptorException if any validation check fails
* @throws InvalidSelectorException if any validation check fails
*/
@Override
public MemberInfo validate() throws InvalidMemberDescriptorException {
public MemberInfo validate() throws InvalidSelectorException {
// Parse emits a match count of 0 if the quantifier is incorrectly specified
if (this.getMaxMatchCount() == 0) {
throw new InvalidMemberDescriptorException(this.input, "Malformed quantifier in selector: " + this.input);
}
// Extremely naive class name validation, just to spot really egregious errors
if (this.owner != null) {
if (!this.owner.matches("(?i)^[\\w\\p{Sc}/]+$")) {
throw new InvalidMemberDescriptorException("Invalid owner: " + this.owner);
throw new InvalidMemberDescriptorException(this.input, "Invalid owner: " + this.owner);
}
// We can't detect this situation 100% reliably, but we can take a
// decent stab at it in order to detect really obvious cases where
// the user types a dot instead of a semicolon
if (this.unparsed != null && this.unparsed.lastIndexOf('.') > 0 && this.owner.startsWith("L")) {
throw new InvalidMemberDescriptorException("Malformed owner: " + this.owner + " If you are seeing this message unexpectedly and the"
+ " owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + "; to suppress this error");
if (this.input != null && this.input.lastIndexOf('.') > 0 && this.owner.startsWith("L")) {
throw new InvalidMemberDescriptorException(this.input, "Malformed owner: " + this.owner + " If you are seeing this message"
+ "unexpectedly and the owner appears to be correct, replace the owner descriptor with formal type L" + this.owner
+ "; to suppress this error");
}
}
// Also naive validation, we're looking for stupid errors here
if (this.name != null && !this.name.matches("(?i)^<?[\\w\\p{Sc}]+>?$")) {
throw new InvalidMemberDescriptorException("Invalid name: " + this.name);
throw new InvalidMemberDescriptorException(this.input, "Invalid name: " + this.name);
}
if (this.desc != null) {
if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[*[\\w\\p{Sc}/;]+$")) {
throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc);
throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc);
}
if (this.isField()) {
if (!this.desc.equals(Type.getType(this.desc).getDescriptor())) {
throw new InvalidMemberDescriptorException("Invalid field type in descriptor: " + this.desc);
throw new InvalidMemberDescriptorException(this.input, "Invalid field type in descriptor: " + this.desc);
}
} else {
try {
Type.getArgumentTypes(this.desc);
// getArgumentTypes can choke on some invalid descriptors
Type[] argTypes = Type.getArgumentTypes(this.desc);
// getInternalName is a useful litmus test for improperly-formatted types which parse out of
// the descriptor correctly but are actually invalid, for example unterminated class names.
// However it doesn't support primitive types properly in ASM versions before 6 so don't run
// the test unless running ASM 6 or later
if (ASM.isAtLeastVersion(6)) {
for (Type argType : argTypes) {
argType.getInternalName();
}
}
} catch (Exception ex) {
throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc);
throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc);
}
String retString = this.desc.substring(this.desc.indexOf(')') + 1);
try {
Type retType = Type.getType(retString);
int sort = retType.getSort();
if (sort >= Type.ARRAY) {
retType.getInternalName(); // sanity check
}
if (!retString.equals(retType.getDescriptor())) {
throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc);
throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: "
+ this.desc);
}
} catch (Exception ex) {
throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc);
throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: "
+ this.desc);
}
}
}
@@ -530,23 +710,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
*/
@Override
public <TNode> MatchResult match(ElementNode<TNode> node) {
return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc());
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #matches(org.objectweb.asm.tree.AbstractInsnNode)
*/
@Override
public MatchResult match(AbstractInsnNode insn) {
if (insn instanceof MethodInsnNode) {
MethodInsnNode method = (MethodInsnNode)insn;
return this.matches(method.owner, method.name, method.desc);
} else if (insn instanceof FieldInsnNode) {
FieldInsnNode field = (FieldInsnNode)insn;
return this.matches(field.owner, field.name, field.desc);
}
return MatchResult.NONE;
return node == null ? MatchResult.NONE : this.matches(node.getOwner(), node.getName(), node.getDesc());
}
/* (non-Javadoc)
@@ -583,46 +747,68 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
}
ITargetSelectorByName other = (ITargetSelectorByName)obj;
boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField : other.isField();
boolean otherMatchAll = other.getMatchCount() == Integer.MAX_VALUE;
boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField
: other instanceof ITargetSelectorRemappable ? ((ITargetSelectorRemappable)other).isField() : false;
return this.matchAll == otherMatchAll && this.forceField == otherForceField
return this.compareMatches(other) && this.forceField == otherForceField
&& Objects.equal(this.owner, other.getOwner())
&& Objects.equal(this.name, other.getName())
&& Objects.equal(this.desc, other.getDesc());
}
/**
* Compare local match count with match count of other selector
*/
private boolean compareMatches(ITargetSelectorByName other) {
if (other instanceof MemberInfo) {
return ((MemberInfo)other).matches.equals(this.matches);
}
return this.getMinMatchCount() == other.getMinMatchCount() && this.getMaxMatchCount() == other.getMaxMatchCount();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Objects.hashCode(this.matchAll, this.owner, this.name, this.desc);
return Objects.hashCode(this.matches, this.owner, this.name, this.desc);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector
* #configure(java.lang.String[])
* #mutate(java.lang.String[])
*/
@Override
public ITargetSelector configure(String... args) {
ITargetSelectorRemappable configured = this;
for (String arg : args) {
if (arg == null) {
continue;
}
if (arg.startsWith("move:")) {
configured = configured.move(Strings.emptyToNull(arg.substring(5)));
} else if (arg.startsWith("transform:")) {
configured = configured.transform(Strings.emptyToNull(arg.substring(10)));
} else if ("permissive".equals(arg)) {
configured = configured.transform(null);
} else if ("orphan".equals(arg)) {
configured = configured.move(null);
}
public ITargetSelector configure(Configure request, String... args) {
request.checkArgs(args);
switch (request) {
case SELECT_MEMBER:
if (this.matches.isDefault()) {
return new MemberInfo(this.name, this.owner, this.desc, Quantifier.SINGLE, this.tail);
}
break;
case SELECT_INSTRUCTION:
if (this.matches.isDefault()) {
return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY, this.tail);
}
break;
case MOVE:
return this.move(Strings.emptyToNull(args[0]));
case ORPHAN:
return this.move(null);
case TRANSFORM:
return this.transform(Strings.emptyToNull(args[0]));
case PERMISSIVE:
return this.transform(null);
case CLEAR_LIMITS:
if (this.matches.getMin() != 0 || this.matches.getMax() < Integer.MAX_VALUE) {
return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY, this.tail);
}
break;
default:
break;
}
return configured;
return this;
}
/* (non-Javadoc)
@@ -630,8 +816,8 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* #attach(org.spongepowered.asm.mixin.refmap.IMixinContext)
*/
@Override
public ITargetSelector attach(IMixinContext context) throws InvalidSelectorException {
if (this.owner != null && !this.owner.equals(context.getTargetClassRef())) {
public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException {
if (this.owner != null && !this.owner.equals(context.getMixin().getTargetClassRef())) {
throw new TargetNotSupportedException(this.owner);
}
return this;
@@ -660,7 +846,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
if ((newDesc == null && this.desc == null) || (newDesc != null && newDesc.equals(this.desc))) {
return this;
}
return new MemberInfo(this.name, this.owner, newDesc, this.matchAll);
return new MemberInfo(this.name, this.owner, newDesc, this.matches);
}
/**
@@ -679,17 +865,23 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
* Parse a MemberInfo from a string
*
* @param input String to parse MemberInfo from
* @param refMapper Reference mapper to use
* @param className Class context to use for remapping
* @param context Selector context for this parse request
* @return parsed MemberInfo
*/
public static MemberInfo parse(String input, IReferenceMapper refMapper, String className) {
public static MemberInfo parse(final String input, final ISelectorContext context) {
String desc = null;
String owner = null;
String name = Strings.nullToEmpty(input).replaceAll("\\s", "");
String tail = null;
int arrowPos = name.indexOf(MemberInfo.ARROW);
if (arrowPos > -1) {
tail = name.substring(arrowPos + 2);
name = name.substring(0, arrowPos);
}
if (refMapper != null) {
name = refMapper.remap(className, name);
if (context != null) {
name = context.remap(name);
}
int lastDotPos = name.lastIndexOf('.');
@@ -717,16 +909,40 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
name = "";
}
boolean matchAll = name.endsWith("*");
if (matchAll) {
// Use default quantifier with negative max value. Used to indicate that
// an explicit quantifier was not parsed from the selector string, this
// allows us to provide backward-compatible behaviour for injection
// points vs. selecting target members which have different default
// semantics when omitting the quantifier. This is handled by consumers
// calling configure() with SELECT_MEMBER or SELECT_INSTRUCTION to
// promote the default case to a concrete case.
Quantifier quantifier = Quantifier.DEFAULT;
if (name.endsWith("*")) {
quantifier = Quantifier.ANY;
name = name.substring(0, name.length() - 1);
} else if (name.endsWith("+")) {
quantifier = Quantifier.PLUS;
name = name.substring(0, name.length() - 1);
} else if (name.endsWith("}")) {
quantifier = Quantifier.NONE; // Assume invalid until quantifier is parsed
int bracePos = name.indexOf("{");
if (bracePos >= 0) {
try {
quantifier = Quantifier.parse(name.substring(bracePos, name.length()));
name = name.substring(0, bracePos);
} catch (Exception ex) {
// Handled later in validate since matchCount will be 0
}
}
} else if (name.indexOf("{") >= 0) {
quantifier = Quantifier.NONE; // Probably incomplete quantifier
}
if (name.isEmpty()) {
name = null;
}
return new MemberInfo(name, owner, desc, matchAll, input);
return new MemberInfo(name, owner, desc, quantifier, tail, input);
}
/**
@@ -70,7 +70,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo {
Type returnType = Type.getReturnType(this.method.desc);
for (AnnotationNode at : ats) {
this.injectionPoints.add(new BeforeConstant(this.getContext(), at, returnType.getDescriptor()));
this.injectionPoints.add(new BeforeConstant(this.getMixin(), at, returnType.getDescriptor()));
}
}
@@ -0,0 +1,131 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Narrowed context for selectors in annotations which are themselves inside
* a parent annotation, for example &#064;At annotations within a parent
* &#064;Inject annotation.
*/
public class SelectorAnnotationContext implements ISelectorContext {
/**
* The selector context of the parent, eg. the &#064;Inject context
*/
private final ISelectorContext parent;
/**
* The annotation for this selector
*/
private final IAnnotationHandle selectorAnnotation;
/**
* The coordinate for this selector
*/
private final String selectorCoordinate;
/**
* Create a specialised context for a child annotation
*
* @param parent Parent selector context, eg. context of the outer element
* such as &#064;Inject
* @param selectorAnnotation Annotation for this selector, eg. &#064;At
* @param selectorCoordinate Coordinate for this selector
*/
public SelectorAnnotationContext(ISelectorContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) {
this.parent = parent;
this.selectorAnnotation = selectorAnnotation;
this.selectorCoordinate = selectorCoordinate;
}
/**
* Get the parent of this selector, must not return null
*
* @return parent context
*/
@Override
public ISelectorContext getParent() {
return this.parent;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #getMixin()
*/
@Override
public IMixinContext getMixin() {
return this.parent.getMixin();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #getMethod()
*/
@Override
public Object getMethod() {
return this.parent.getMethod();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #getAnnotation()
*/
@Override
public IAnnotationHandle getAnnotation() {
return this.parent.getAnnotation();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #getSelectorAnnotation()
*/
@Override
public IAnnotationHandle getSelectorAnnotation() {
return this.selectorAnnotation;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #getSelectorCoordinate()
*/
@Override
public String getSelectorCoordinate(boolean leaf) {
return this.selectorCoordinate;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #remap(java.lang.String)
*/
@Override
public String remap(String reference) {
return this.parent.remap(reference);
}
}
@@ -28,7 +28,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
@@ -45,6 +44,7 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Bytecode.DelegateInitialiser;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.Locals.SyntheticLocalVariableNode;
/**
* Information about the current injection target, mainly just convenience
@@ -751,13 +751,7 @@ public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
* @param desc local variable type
*/
public void addLocalVariable(int index, String name, String desc) {
if (this.start == null) {
this.start = new LabelNode(new Label());
this.end = new LabelNode(new Label());
this.insns.insert(this.start);
this.insns.add(this.end);
}
this.addLocalVariable(index, name, desc, this.start, this.end);
this.addLocalVariable(index, name, desc, null, null);
}
/**
@@ -766,14 +760,50 @@ public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
* @param index local variable index
* @param name local variable name
* @param desc local variable type
* @param start start of range
* @param end end of range
* @param from start of range
* @param to end of range
*/
private void addLocalVariable(int index, String name, String desc, LabelNode start, LabelNode end) {
public void addLocalVariable(int index, String name, String desc, LabelNode from, LabelNode to) {
if (from == null) {
from = this.getStartLabel();
}
if (to == null) {
to = this.getEndLabel();
}
if (this.method.localVariables == null) {
this.method.localVariables = new ArrayList<LocalVariableNode>();
}
this.method.localVariables.add(new LocalVariableNode(name, desc, null, start, end, index));
for (Iterator<LocalVariableNode> iter = this.method.localVariables.iterator(); iter.hasNext();) {
LocalVariableNode local = iter.next();
if (local != null && local.index == index && from == local.start && to == local.end) {
iter.remove();
}
}
this.method.localVariables.add(new SyntheticLocalVariableNode(name, desc, null, from, to, index));
}
/**
* Get a label which marks the very start of the method
*/
private LabelNode getStartLabel() {
if (this.start == null) {
this.insns.insert(this.start = new LabelNode());
}
return this.start;
}
/**
* Get a label which marks the very end of the method
*/
private LabelNode getEndLabel() {
if (this.end == null) {
this.insns.add(this.end = new LabelNode());
}
return this.end;
}
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Internal data bundles used by injectors during application.
*/
package org.spongepowered.asm.mixin.injection.struct;
@@ -50,12 +50,12 @@ public class InvalidInjectionException extends InvalidMixinException {
}
public InvalidInjectionException(InjectionInfo info, String message) {
super(info.getContext(), message);
super(info.getMixin(), message);
this.info = info;
}
public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) {
super(info.getContext(), message, activityContext);
super(info.getMixin(), message, activityContext);
this.info = info;
}
@@ -70,12 +70,12 @@ public class InvalidInjectionException extends InvalidMixinException {
}
public InvalidInjectionException(InjectionInfo info, Throwable cause) {
super(info.getContext(), cause);
super(info.getMixin(), cause);
this.info = info;
}
public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) {
super(info.getContext(), cause, activityContext);
super(info.getMixin(), cause, activityContext);
this.info = info;
}
@@ -90,12 +90,12 @@ public class InvalidInjectionException extends InvalidMixinException {
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) {
super(info.getContext(), message, cause);
super(info.getMixin(), message, cause);
this.info = info;
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) {
super(info.getContext(), message, cause, activityContext);
super(info.getMixin(), message, cause, activityContext);
this.info = info;
}
@@ -40,7 +40,7 @@ public class InvalidSliceException extends InvalidInjectionException {
}
public InvalidSliceException(ISliceContext owner, String message) {
super(owner.getContext(), message);
super(owner.getMixin(), message);
}
public InvalidSliceException(IMixinContext context, Throwable cause) {
@@ -48,7 +48,7 @@ public class InvalidSliceException extends InvalidInjectionException {
}
public InvalidSliceException(ISliceContext owner, Throwable cause) {
super(owner.getContext(), cause);
super(owner.getMixin(), cause);
}
public InvalidSliceException(IMixinContext context, String message, Throwable cause) {
@@ -56,7 +56,7 @@ public class InvalidSliceException extends InvalidInjectionException {
}
public InvalidSliceException(ISliceContext owner, String message, Throwable cause) {
super(owner.getContext(), message, cause);
super(owner.getMixin(), message, cause);
}
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Throwable classes (errors and exceptions) for injectors.
*/
package org.spongepowered.asm.mixin.injection.throwables;
@@ -0,0 +1,34 @@
/*
* 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.
*/
/**
* Primary interaction points (
* {@link org.spongepowered.asm.mixin.Mixin &#64;Mixin} and
* {@link org.spongepowered.asm.mixin.MixinEnvironment &#64;MixinEnvironment})
* and annotations (eg&#46;
* {@link org.spongepowered.asm.mixin.Mixin &#64;Mixin},
* {@link org.spongepowered.asm.mixin.Shadow &#64;Shadow}) for mixin consumers.
*/
package org.spongepowered.asm.mixin;
@@ -24,10 +24,8 @@
*/
package org.spongepowered.asm.mixin.refmap;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
/**
@@ -87,14 +85,4 @@ public interface IMixinContext {
*/
public abstract int getPriority();
/**
* Obtain a {@link Target} method handle for a method in the target, this is
* used by consumers to manipulate the bytecode in a target method in a
* controlled manner.
*
* @param method method node to wrap
* @return target method
*/
public abstract Target getTargetMethod(MethodNode method);
}
@@ -243,7 +243,7 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable {
* @param writer Writer to write to
*/
public void write(Appendable writer) {
new GsonBuilder().setPrettyPrinting().create().toJson(this, writer);
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(this, writer);
}
/**
@@ -150,9 +150,9 @@ public final class RemappingReferenceMapper implements IClassReferenceMapper, IR
// To handle propagation, find super/itf-class (for IRemapper)
// but pass the requested class in the MemberInfo
MemberInfo info = MemberInfo.parse(remapped, null, null);
MemberInfo info = MemberInfo.parse(remapped, null);
if (info.getName() == null && info.getDesc() == null) {
return info.getOwner() != null ? new MemberInfo(remapper.map(info.getOwner()), null, null).toString() : info.toString();
return info.getOwner() != null ? new MemberInfo(remapper.map(info.getOwner()), null).toString() : info.toString();
} else if (info.isField()) {
remapped = new MemberInfo(
remapper.mapFieldName(info.getOwner(), info.getName(), info.getDesc()),
@@ -0,0 +1,31 @@
/*
* 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.
*/
/**
* Refmaps are data bundles which map string references to obfuscated
* counterparts at runtime, see {@link
* org.spongepowered.asm.mixin.refmap.ReferenceMapper}.
*/
package org.spongepowered.asm.mixin.refmap;
@@ -24,24 +24,26 @@
*/
package org.spongepowered.asm.mixin.struct;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Locale;
import javax.tools.Diagnostic.Kind;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.asm.util.logging.MessageRouter;
/**
* Data bundle for an annotated method in a mixin
*/
public class AnnotatedMethodInfo implements IInjectionPointContext {
/**
* Log more things
*/
protected static final Logger logger = LogManager.getLogger("mixin");
/**
* Mixin context
*/
@@ -62,6 +64,24 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
this.method = method;
this.annotation = annotation;
}
@Override
public String remap(String reference) {
if (this.context != null) {
IReferenceMapper referenceMapper = this.context.getReferenceMapper();
return referenceMapper != null ? referenceMapper.remap(this.context.getClassRef(), reference) : reference;
}
return reference;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext
* #getParent()
*/
@Override
public ISelectorContext getParent() {
return null;
}
/**
* Get the mixin target context for this annotated method
@@ -69,7 +89,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
* @return the target context
*/
@Override
public final IMixinContext getContext() {
public final IMixinContext getMixin() {
return this.context;
}
@@ -82,16 +102,52 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
public final MethodNode getMethod() {
return this.method;
}
/**
* Get the annotation which this InjectionInfo was created from
*
* @return The annotation which this InjectionInfo was created from
* Get the original name of the method, if available
*/
public String getMethodName() {
return this.method.name;
}
/**
* Get the primary annotation which makes this method special
*/
@Override
public final AnnotationNode getAnnotation() {
public AnnotationNode getAnnotationNode() {
return this.annotation;
}
/**
* Get the primary annotation which makes this method special
*
* @return The primary method annotation
*/
@Override
public final IAnnotationHandle getAnnotation() {
return Annotations.handleOf(this.annotation);
}
/**
* Get the annotation context for selectors operating in the context of this
* method.
*
* @return The selector context annotation
*/
@Override
public IAnnotationHandle getSelectorAnnotation() {
return Annotations.handleOf(this.annotation);
}
/**
* Get the selector coordinate for this method
*
* @return The selector context annotation
*/
@Override
public String getSelectorCoordinate(boolean leaf) {
return leaf ? "method" : this.getMethodName().toLowerCase(Locale.ROOT);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.IInjectionPointContext
@@ -100,7 +156,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
@Override
public void addMessage(String format, Object... args) {
if (this.context.getOption(Option.DEBUG_VERBOSE)) {
AnnotatedMethodInfo.logger.warn(String.format(format, args));
MessageRouter.getMessager().printMessage(Kind.WARNING, String.format(format, args));
}
}
@@ -29,12 +29,13 @@ import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Handles;
/**
* Reference to a field or method that also includes invocation instructions.
*
* <p>To instances are defined to be equal if they both refer to the same method
* and have the same invocation instructions.</p>
* <p>Two instances are defined to be equal if they both refer to the same
* member and have the same invocation instructions.</p>
*/
public abstract class MemberRef {
@@ -209,26 +210,12 @@ public abstract class MemberRef {
@Override
public boolean isField() {
switch (this.handle.getTag()) {
case Opcodes.H_INVOKEVIRTUAL:
case Opcodes.H_INVOKESTATIC:
case Opcodes.H_INVOKEINTERFACE:
case Opcodes.H_INVOKESPECIAL:
case Opcodes.H_NEWINVOKESPECIAL:
return false;
case Opcodes.H_GETFIELD:
case Opcodes.H_GETSTATIC:
case Opcodes.H_PUTFIELD:
case Opcodes.H_PUTSTATIC:
return true;
default:
throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
}
return Handles.isField(this.handle);
}
@Override
public int getOpcode() {
int opcode = MemberRef.opcodeFromTag(this.handle.getTag());
int opcode = Handles.opcodeFromTag(this.handle.getTag());
if (opcode == 0) {
throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
}
@@ -237,12 +224,11 @@ public abstract class MemberRef {
@Override
public void setOpcode(int opcode) {
int tag = MemberRef.tagFromOpcode(opcode);
int tag = Handles.tagFromOpcode(opcode);
if (tag == 0) {
throw new MixinTransformerError("Invalid opcode " + Bytecode.getOpcodeName(opcode) + " for method handle " + this.handle + ".");
}
boolean itf = tag == Opcodes.H_INVOKEINTERFACE;
this.handle = new org.objectweb.asm.Handle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), itf);
this.setHandle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), this.handle.isInterface());
}
@Override
@@ -252,8 +238,7 @@ public abstract class MemberRef {
@Override
public void setOwner(String owner) {
boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE;
this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), itf);
this.setHandle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), this.handle.isInterface());
}
@Override
@@ -263,8 +248,7 @@ public abstract class MemberRef {
@Override
public void setName(String name) {
boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE;
this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), itf);
this.setHandle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), this.handle.isInterface());
}
@Override
@@ -274,23 +258,14 @@ public abstract class MemberRef {
@Override
public void setDesc(String desc) {
boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE;
this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, itf);
this.setHandle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, this.handle.isInterface());
}
public void setHandle(int tag, String owner, String name, String desc, boolean isInterface) {
this.handle = new org.objectweb.asm.Handle(tag, owner, name, desc, isInterface);
}
}
private static final int[] H_OPCODES = {
0, // invalid
Opcodes.GETFIELD, // H_GETFIELD
Opcodes.GETSTATIC, // H_GETSTATIC
Opcodes.PUTFIELD, // H_PUTFIELD
Opcodes.PUTSTATIC, // H_PUTSTATIC
Opcodes.INVOKEVIRTUAL, // H_INVOKEVIRTUAL
Opcodes.INVOKESTATIC, // H_INVOKESTATIC
Opcodes.INVOKESPECIAL, // H_INVOKESPECIAL
Opcodes.INVOKESPECIAL, // H_NEWINVOKESPECIAL
Opcodes.INVOKEINTERFACE // H_INVOKEINTERFACE
};
/**
* Whether this member is a field.
@@ -357,8 +332,8 @@ public abstract class MemberRef {
@Override
public String toString() {
String name = Bytecode.getOpcodeName(this.getOpcode());
return String.format("%s for %s.%s%s%s", name, this.getOwner(), this.getName(), this.isField() ? ":" : "", this.getDesc());
return String.format("%s for %s.%s%s%s", Bytecode.getOpcodeName(this.getOpcode()), this.getOwner(), this.getName(), this.isField() ? ":" : "",
this.getDesc());
}
@Override
@@ -379,17 +354,4 @@ public abstract class MemberRef {
return this.toString().hashCode();
}
static int opcodeFromTag(int tag) {
return (tag >= 0 && tag < MemberRef.H_OPCODES.length) ? MemberRef.H_OPCODES[tag] : 0;
}
static int tagFromOpcode(int opcode) {
for (int tag = 1; tag < MemberRef.H_OPCODES.length; tag++) {
if (MemberRef.H_OPCODES[tag] == opcode) {
return tag;
}
}
return 0;
}
}
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff. Show more