Merge branch 'initphase'

Conflicts:
	src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
	src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java
This commit is contained in:
Mumfrey committed 2016-06-21 15:27:40 +01:00
commit a3b98d8a15
163 files changed
+15949 -3149

No files matched your search

@@ -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.launch;
import net.minecraft.launchwrapper.Launch;
/**
* Abstractions for working with {@link Launch#blackboard}
*/
public final class Blackboard {
/**
* Blackboard keys
*/
public static final class Keys {
public static final String TWEAKCLASSES = "TweakClasses";
public static final String TWEAKS = "Tweaks";
public static final String INIT = "mixin.initialised";
public static final String AGENTS = "mixin.agents";
public static final String CONFIGS = "mixin.configs";
public static final String TRANSFORMER = "mixin.transformer";
public static final String FML_LOAD_CORE_MOD = "mixin.launch.fml.loadcoremodmethod";
public static final String FML_GET_REPARSEABLE_COREMODS = "mixin.launch.fml.reparseablecoremodsmethod";
public static final String FML_CORE_MOD_MANAGER = "mixin.launch.fml.coremodmanagerclass";
public static final String FML_GET_IGNORED_MODS = "mixin.launch.fml.ignoredmodsmethod";
private Keys() {}
}
private Blackboard() {}
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return (T)Launch.blackboard.get(key);
}
public static void put(String key, Object value) {
Launch.blackboard.put(key, value);
}
@SuppressWarnings("unchecked")
public static <T> T get(String key, T defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? (T)value : defaultValue;
}
public static String getString(String key, String defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? value.toString() : defaultValue;
}
}
@@ -26,13 +26,15 @@ package org.spongepowered.asm.launch;
import java.util.List;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.platform.MixinPlatformManager;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Bootstaps the mixin subsystem. This class acts as a bridge between the mixin
* subsystem and the tweaker or coremod which is boostrapping it. Without this
@@ -60,13 +62,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.4.5";
/**
* Blackboard key where the subsystem version will be stored to indicate
* successful bootstrap
*/
public static final String INIT_KEY = "mixin.initialised";
public static final String VERSION = "0.5.11";
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
@@ -82,7 +78,7 @@ public abstract class MixinBootstrap {
// These are Klass local, with luck this shouldn't be a problem
private static boolean initialised = false;
private static boolean injectStateTweaker = true;
private static boolean initState = true;
// Static initialiser, add classloader exclusions as early as possible
static {
@@ -94,6 +90,8 @@ public abstract class MixinBootstrap {
// Only needed in dev, in production this would be handled by the tweaker
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.LAUNCH_PACKAGE);
}
private static MixinPlatformManager platformManager = new MixinPlatformManager();
private MixinBootstrap() {}
@@ -104,22 +102,29 @@ public abstract class MixinBootstrap {
Launch.classLoader.registerTransformer(MixinBootstrap.TRANSFORMER_PROXY_CLASS);
}
/**
* Get the platform manager
*/
public static MixinPlatformManager getPlatform() {
return MixinBootstrap.platformManager;
}
/**
* Initialise the mixin subsystem
*/
public static void init() {
if (!MixinBootstrap.preInit()) {
if (!MixinBootstrap.start()) {
return;
}
MixinBootstrap.register();
MixinBootstrap.doInit(null);
}
/**
* Phase 1 of mixin initialisation
*/
static boolean preInit() {
Object registeredVersion = Launch.blackboard.get(MixinBootstrap.INIT_KEY);
static boolean start() {
Object registeredVersion = Blackboard.get(Blackboard.Keys.INIT);
if (registeredVersion != null) {
if (!registeredVersion.equals(MixinBootstrap.VERSION)) {
throw new MixinInitialisationError("Mixin subsystem version " + registeredVersion
@@ -129,15 +134,21 @@ public abstract class MixinBootstrap {
return false;
}
Launch.blackboard.put(MixinBootstrap.INIT_KEY, MixinBootstrap.VERSION);
Blackboard.put(Blackboard.Keys.INIT, MixinBootstrap.VERSION);
if (!MixinBootstrap.initialised) {
MixinBootstrap.initialised = true;
String command = System.getProperty("sun.java.command");
if (command != null && command.contains("GradleStart")) {
System.setProperty("mixin.env.disableRefMap", "true");
}
if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") > 132) {
MixinBootstrap.logger.error("Initialising mixin subsystem after game pre-init phase! Some mixins may be skipped.");
MixinEnvironment.init(Phase.DEFAULT);
MixinBootstrap.injectStateTweaker = false;
MixinBootstrap.getPlatform().prepare(null);
MixinBootstrap.initState = false;
} else {
MixinEnvironment.init(Phase.PREINIT);
}
@@ -149,26 +160,37 @@ public abstract class MixinBootstrap {
}
/**
* Phase 2 of mixin initialisation, register the state tweaker
* Phase 2 of mixin initialisation, initialise the phases
*/
static void register() {
static void doInit(List<String> args) {
if (!MixinBootstrap.initialised) {
throw new IllegalStateException("MixinBootstrap.register() called before MixinBootstrap.preInit()");
throw new IllegalStateException("MixinBootstrap.doInit() called before MixinBootstrap.preInit()");
}
if (MixinBootstrap.injectStateTweaker) {
MixinBootstrap.getPlatform().getPhaseProviderClasses();
// for (String platformProviderClass : MixinBootstrap.getPlatform().getPhaseProviderClasses()) {
// System.err.printf("Registering %s\n", platformProviderClass);
// MixinEnvironment.registerPhaseProvider(platformProviderClass);
// }
if (MixinBootstrap.initState) {
MixinBootstrap.getPlatform().prepare(args);
if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") < 4) {
MixinBootstrap.logger.warn("MixinBootstrap.register() called during a tweak constructor. Expect CoModificationException in 5.. 4..");
MixinBootstrap.logger.warn("MixinBootstrap.doInit() called during a tweak constructor. Expect CoModificationException in 5.. 4..");
}
@SuppressWarnings("unchecked")
List<String> tweakClasses = (List<String>)Launch.blackboard.get("TweakClasses");
List<String> tweakClasses = Blackboard.<List<String>>get(Blackboard.Keys.TWEAKCLASSES);
if (tweakClasses != null) {
tweakClasses.add(MixinEnvironment.class.getName() + "$EnvironmentStateTweaker");
}
}
}
static void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader);
}
private static int findInStackTrace(String className, String methodName) {
Thread currentThread = Thread.currentThread();
@@ -185,4 +207,5 @@ public abstract class MixinBootstrap {
return 0;
}
}
@@ -24,7 +24,9 @@
*/
package org.spongepowered.asm.launch;
/**
* Error raised when mixin subsystem initialisation fails
*/
public class MixinInitialisationError extends Error {
private static final long serialVersionUID = 1L;
@@ -25,23 +25,11 @@
package org.spongepowered.asm.launch;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
/**
* TweakClass for running mixins in production. Being a tweaker ensures that we
* get injected into the AppClassLoader but does mean that we will need to
@@ -49,84 +37,20 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
*/
public class MixinTweaker implements ITweaker {
private static final String MFATT_TWEAKER = "TweakClass";
private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main";
/**
* Make with the logging already
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Tweak containers
*/
private final Map<URI, MixinTweakContainer> containers = new LinkedHashMap<URI, MixinTweakContainer>();
/**
* Tracks whether {@link #acceptOptions} was called yet, if true, causes new
* launch agents to be <tt>prepare</tt>d immediately
*/
private boolean prepared = false;
/**
* Hello world
*/
public MixinTweaker() {
MixinBootstrap.preInit();
// Add agents for the tweak container
URI uri = null;
try {
uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
if (uri != null) {
this.addContainer(uri);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
MixinBootstrap.start();
}
public final void addContainer(URI uri) {
if (this.containers.containsKey(uri)) {
return;
}
MixinTweaker.logger.debug("Adding mixin launch agents for container {}", uri);
MixinTweakContainer container = new MixinTweakContainer(uri);
this.containers.put(uri, container);
if (this.prepared) {
container.prepare();
}
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#acceptOptions(java.util.List,
* java.io.File, java.io.File, java.lang.String)
*/
@Override
public final void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
MixinBootstrap.register();
this.prepared = true;
for (MixinTweakContainer container : this.containers.values()) {
container.prepare();
}
this.parseArgs(args);
}
/**
* Read and parse command-line arguments
*
* @param args command-line arguments
*/
private void parseArgs(List<String> args) {
boolean captureNext = false;
for (String arg : args) {
if (captureNext) {
MixinTweaker.addConfig(arg);
}
captureNext = "--mixin".equals(arg);
}
MixinBootstrap.doInit(args);
}
/* (non-Javadoc)
@@ -135,42 +59,7 @@ public class MixinTweaker implements ITweaker {
*/
@Override
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
this.scanClasspath();
MixinTweaker.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size());
for (MixinTweakContainer container : this.containers.values()) {
try {
container.injectIntoClassLoader(classLoader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Scan the classpath for mixin containers (containers which declare the
* mixin tweaker in their manifest) and add agents for them
*/
private void scanClasspath() {
for (URL url : Launch.classLoader.getSources()) {
try {
URI uri = url.toURI();
if (this.containers.containsKey(uri)) {
continue;
}
MixinTweaker.logger.debug("Scanning {} for mixin tweaker", uri);
if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) {
continue;
}
MainAttributes attributes = MainAttributes.of(uri);
String tweaker = attributes.get(MixinTweaker.MFATT_TWEAKER);
if (MixinTweaker.class.getName().equals(tweaker)) {
MixinTweaker.logger.debug("{} contains a mixin tweaker, adding agents", uri);
this.addContainer(uri);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
MixinBootstrap.injectIntoClassLoader(classLoader);
}
/* (non-Javadoc)
@@ -178,14 +67,7 @@ public class MixinTweaker implements ITweaker {
*/
@Override
public String getLaunchTarget() {
for (MixinTweakContainer container : this.containers.values()) {
String mainClass = container.getLaunchTarget();
if (mainClass != null) {
return mainClass;
}
}
return MixinTweaker.DEFAULT_MAIN_CLASS;
return MixinBootstrap.getPlatform().getLaunchTarget();
}
/* (non-Javadoc)
@@ -195,52 +77,5 @@ public class MixinTweaker implements ITweaker {
public String[] getLaunchArguments() {
return new String[]{};
}
/**
* Add a config from a jar manifest source or the command line. Supports
* config declarations in the form <tt>filename.json</tt> or alternatively
* <tt>filename.json&#064;PHASE</tt> where <tt>PHASE</tt> is a
* case-sensitive string token representing an environment phase.
*
* @param config config resource name, does not require a leading /
*/
static void addConfig(String config) {
if (config.endsWith(".json")) {
MixinTweaker.logger.debug("Registering mixin config: {}", config);
MixinEnvironment.getDefaultEnvironment().addConfiguration(config);
} else if (config.contains(".json@")) {
int pos = config.indexOf(".json@");
String phaseName = config.substring(pos + 6);
config = config.substring(0, pos + 5);
Phase phase = Phase.forName(phaseName);
if (phase != null) {
MixinTweaker.logger.debug("Registering mixin config: {}", config);
MixinEnvironment.getEnvironment(phase).addConfiguration(config);
}
}
}
/**
* Add a token provider class from a jar manifest source. Supports either
* bare class names in the form <tt>blah.package.ClassName</tt> or
* alternatively <tt>blah.package.ClassName&#064;PHASE</tt> where
* <tt>PHASE</tt> is a case-sensitive string token representing an
* environment phase name.
*
* @param provider provider class name, optionally suffixed with &#064;PHASE
*/
static void addTokenProvider(String provider) {
if (provider.contains("@")) {
String[] parts = provider.split("@", 2);
Phase phase = Phase.forName(parts[1]);
if (phase != null) {
MixinTweaker.logger.debug("Registering token provider class: {}", parts[0]);
MixinEnvironment.getEnvironment(phase).registerTokenProviderClass(parts[0]);
}
return;
}
MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass(provider);
}
}
@@ -22,21 +22,26 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Base interface for launch agents. Launch agents are environment-specific
* launch handlers which are used by the {@link MixinTweaker mixin tweaker} to
* perform launch tasks required by that environment without having to fill the
* tweaker itself with a bunch of environment-specific cruft.
* Base interface for platform agents. Platform agents are environment-specific
* handlers which are used by the Mixin subsystem to perform platform-specific
* tasks required by different environments without having to litter the Mixin
* codebase with a bunch of environment-specific cruft.
*
* <p>Agents handle mixin environment launch tasks on a per-container basis,
* <p>Platform Agents handle mixin environment tasks on a per-container basis,
* with each container in the environment being assigned one of each available
* type of agent to handle those tasks on behalf of the container.</p>
*/
interface IMixinLaunchAgent {
public interface IMixinPlatformAgent {
/**
* Get the phase provider for this agent
*/
public abstract String getPhaseProvider();
/**
* Called during pre-initialisation, after all tweakers and tweak containers
@@ -44,6 +49,13 @@ interface IMixinLaunchAgent {
*/
public abstract void prepare();
/**
* Called from <tt>injectIntoClassLoader</tt> in the parent tweaker but <b>
* only called on the primary tweak container</b>. This is useful if the
* agent needs to perform some environment-specific setup just once.
*/
public abstract void initPrimaryContainer();
/**
* Called from <tt>injectIntoClassLoader</tt> in the parent tweaker
*
@@ -56,4 +68,5 @@ interface IMixinLaunchAgent {
* custom target is available.
*/
public abstract String getLaunchTarget();
}
@@ -22,7 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.io.IOException;
@@ -22,46 +22,51 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.Blackboard;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* A collection of {@link IMixinLaunchAgent launch agents)
* A collection of {@link IMixinPlatformAgent} platform agents)
*/
public class MixinTweakContainer {
public class MixinContainer {
public static final List<String> agentClasses = new ArrayList<String>();
static {
Launch.blackboard.put("mixin.agents", MixinTweakContainer.agentClasses);
MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentFML");
MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentDefault");
Blackboard.put(Blackboard.Keys.AGENTS, MixinContainer.agentClasses);
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentFML");
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentDefault");
}
private final Logger logger = LogManager.getLogger("mixin");
private final URI uri;
private final List<IMixinLaunchAgent> agents = new ArrayList<IMixinLaunchAgent>();
private final List<IMixinPlatformAgent> agents = new ArrayList<IMixinPlatformAgent>();
public MixinTweakContainer(URI uri) {
public MixinContainer(MixinPlatformManager manager, URI uri) {
this.uri = uri;
for (String agentClass : MixinTweakContainer.agentClasses) {
for (String agentClass : MixinContainer.agentClasses) {
try {
@SuppressWarnings("unchecked")
Class<IMixinLaunchAgent> clazz = (Class<IMixinLaunchAgent>)Class.forName(agentClass);
Constructor<IMixinLaunchAgent> ctor = clazz.getDeclaredConstructor(URI.class);
IMixinLaunchAgent agent = ctor.newInstance(uri);
Class<IMixinPlatformAgent> clazz = (Class<IMixinPlatformAgent>)Class.forName(agentClass);
Constructor<IMixinPlatformAgent> ctor = clazz.getDeclaredConstructor(MixinPlatformManager.class, URI.class);
IMixinPlatformAgent agent = ctor.newInstance(manager, uri);
this.agents.add(agent);
} catch (Exception ex) {
ex.printStackTrace();
this.logger.catching(ex);
}
}
}
@@ -73,26 +78,44 @@ public class MixinTweakContainer {
return this.uri;
}
public Collection<String> getPhaseProviders() {
List<String> phaseProviders = new ArrayList<String>();
for (IMixinPlatformAgent agent : this.agents) {
String phaseProvider = agent.getPhaseProvider();
if (phaseProvider != null) {
phaseProviders.add(phaseProvider);
}
}
return phaseProviders;
}
/**
*
*/
public void prepare() {
for (IMixinLaunchAgent agent : this.agents) {
for (IMixinPlatformAgent agent : this.agents) {
agent.prepare();
}
}
public void initPrimaryContainer() {
for (IMixinPlatformAgent agent : this.agents) {
this.logger.debug("Processing launch tasks for {}", agent);
agent.initPrimaryContainer();
}
}
/**
* @param classLoader
*/
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
for (IMixinLaunchAgent agent : this.agents) {
for (IMixinPlatformAgent agent : this.agents) {
agent.injectIntoClassLoader(classLoader);
}
}
public String getLaunchTarget() {
for (IMixinLaunchAgent agent : this.agents) {
for (IMixinPlatformAgent agent : this.agents) {
String launchTarget = agent.getLaunchTarget();
if (launchTarget != null) {
return launchTarget;
@@ -22,17 +22,26 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.net.URI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Launch agent base class
* Platform agent base class
*/
public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent {
public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent {
/**
* Logger
*/
protected static final Logger logger = LogManager.getLogger("mixin");
protected final MixinPlatformManager manager;
/**
* URI to the container
*/
@@ -49,11 +58,12 @@ public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent {
protected final MainAttributes attributes;
/**
* Create a new launch agent for the specified URI
* Create a new platform agent for the specified URI
*
* @param uri
*/
public MixinLaunchAgentAbstract(URI uri) {
public MixinPlatformAgentAbstract(MixinPlatformManager manager, URI uri) {
this.manager = manager;
this.uri = uri;
this.container = this.uri != null ? new File(this.uri) : null;
this.attributes = MainAttributes.of(uri);
@@ -61,7 +71,12 @@ public abstract class MixinLaunchAgentAbstract implements IMixinLaunchAgent {
@Override
public String toString() {
return String.format("LaunchAgent[%s:%s]", this.getClass().getSimpleName(), this.uri);
return String.format("PlatformAgent[%s:%s]", this.getClass().getSimpleName(), this.uri);
}
@Override
public String getPhaseProvider() {
return null;
}
}
@@ -22,42 +22,50 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.net.URI;
import org.spongepowered.asm.util.Constants.ManifestAttributes;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Default launch agent, handles the <tt>MixinConfigs</tt> manifest key
* Default platform agent, handles the mixin manifest keys such as
* <tt>MixinConfigs</tt> and <tt>MixinTokenProviders</tt>.
*/
public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract {
protected static final String MFATT_MIXINCONFIGS = "MixinConfigs";
protected static final String MFATT_TOKENPROVIDERS = "MixinTokenProviders";
protected static final String MFATT_MAINCLASS = "Main-Class";
public MixinLaunchAgentDefault(URI uri) {
super(uri);
public MixinPlatformAgentDefault(MixinPlatformManager manager, URI uri) {
super(manager, uri);
}
@Override
public void prepare() {
String mixinConfigs = this.attributes.get(MixinLaunchAgentDefault.MFATT_MIXINCONFIGS);
@SuppressWarnings("deprecation")
String compatibilityLevel = this.attributes.get(ManifestAttributes.COMPATIBILITY);
if (compatibilityLevel != null) {
this.manager.setCompatibilityLevel(compatibilityLevel);
}
String mixinConfigs = this.attributes.get(ManifestAttributes.MIXINCONFIGS);
if (mixinConfigs != null) {
for (String config : mixinConfigs.split(",")) {
MixinTweaker.addConfig(config.trim());
this.manager.addConfig(config.trim());
}
}
String tokenProviders = this.attributes.get(MixinLaunchAgentDefault.MFATT_TOKENPROVIDERS);
String tokenProviders = this.attributes.get(ManifestAttributes.TOKENPROVIDERS);
if (tokenProviders != null) {
for (String provider : tokenProviders.split(",")) {
MixinTweaker.addTokenProvider(provider.trim());
this.manager.addTokenProvider(provider.trim());
}
}
}
@Override
public void initPrimaryContainer() {
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
@@ -65,7 +73,7 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
@Override
public String getLaunchTarget() {
return this.attributes.get(MixinLaunchAgentDefault.MFATT_MAINCLASS);
return this.attributes.get(ManifestAttributes.MAINCLASS);
}
}
@@ -22,28 +22,46 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.launch;
package org.spongepowered.asm.launch.platform;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
//import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.logging.log4j.Level;
import org.spongepowered.asm.launch.Blackboard;
import org.spongepowered.asm.mixin.MixinEnvironment;
//import org.spongepowered.asm.mixin.environment.IPhaseProvider;
//import org.spongepowered.asm.mixin.environment.PhaseDefinition;
//import org.spongepowered.asm.mixin.environment.phase.OnLogMessage;
import org.spongepowered.asm.mixin.extensibility.IRemapper;
//import com.google.common.collect.ImmutableList;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Launch agent for use under FML.
* Platform agent for use under FML.
*
* <p>When FML is present we scan containers for the manifest entries which are
* inhibited by the tweaker, in particular the <tt>FMLCorePlugin</tt> and
* <tt>FMLCorePluginContainsFMLMod</tt> entries. This is required because FML
* performs no further processing of containers if they contain a tweaker!</p>
*/
public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract {
private static final String LOAD_CORE_MOD_METHOD = "loadCoreMod";
private static final String GET_REPARSEABLE_COREMODS_METHOD = "getReparseableCoremods";
private static final String CORE_MOD_MANAGER_CLASS = "net.minecraftforge.fml.relauncher.CoreModManager";
private static final String GET_IGNORED_MODS_METHOD = "getIgnoredMods";
private static final String FML_REMAPPER_ADAPTER_CLASS = "org.spongepowered.asm.bridge.RemapperAdapterFML";
private static final String MFATT_FORCELOADASMOD = "ForceLoadAsMod";
private static final String MFATT_FMLCOREPLUGIN = "FMLCorePlugin";
@@ -72,8 +90,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
/**
* @param uri
*/
public MixinLaunchAgentFML(URI uri) {
super(uri);
public MixinPlatformAgentFML(MixinPlatformManager manager, URI uri) {
super(manager, uri);
this.fileName = this.container.getName();
this.coreModWrapper = this.initFMLCoreMod();
}
@@ -83,17 +101,16 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private ITweaker initFMLCoreMod() {
try {
this.clCoreModManager = MixinLaunchAgentFML.getCoreModManagerClass();
this.clCoreModManager = MixinPlatformAgentFML.getCoreModManagerClass();
if ("true".equalsIgnoreCase(this.attributes.get(MixinLaunchAgentFML.MFATT_FORCELOADASMOD))) {
if ("true".equalsIgnoreCase(this.attributes.get(MixinPlatformAgentFML.MFATT_FORCELOADASMOD))) {
this.loadAsMod();
}
return this.injectCorePlugin();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
return null;
}
/**
@@ -109,15 +126,12 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private void loadAsMod() {
try {
Method mdGetLoadedCoremods = this.clCoreModManager.getDeclaredMethod("getLoadedCoremods");
@SuppressWarnings("unchecked")
List<String> loadedCoremods = (List<String>)mdGetLoadedCoremods.invoke(null);
loadedCoremods.remove(this.fileName);
MixinPlatformAgentFML.getIgnoredMods(this.clCoreModManager).remove(this.fileName);
} catch (Exception ex) {
ex.printStackTrace();
MixinPlatformAgentAbstract.logger.catching(ex);
}
if (this.attributes.get(MixinLaunchAgentFML.MFATT_COREMODCONTAINSMOD) != null) {
if (this.attributes.get(MixinPlatformAgentFML.MFATT_COREMODCONTAINSMOD) != null) {
this.addReparseableJar();
}
}
@@ -128,7 +142,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private void addReparseableJar() {
try {
Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod("getReparseableCoremods");
Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod(Blackboard.getString(
Blackboard.Keys.FML_GET_REPARSEABLE_COREMODS, MixinPlatformAgentFML.GET_REPARSEABLE_COREMODS_METHOD));
@SuppressWarnings("unchecked")
List<String> reparsedCoremods = (List<String>)mdGetReparsedCoremods.invoke(null);
if (!reparsedCoremods.contains(this.fileName)) {
@@ -140,12 +155,13 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
}
private ITweaker injectCorePlugin() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String coreModName = this.attributes.get(MixinLaunchAgentFML.MFATT_FMLCOREPLUGIN);
String coreModName = this.attributes.get(MixinPlatformAgentFML.MFATT_FMLCOREPLUGIN);
if (coreModName == null) {
return null;
}
Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod("loadCoreMod", LaunchClassLoader.class, String.class, File.class);
Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod(Blackboard.getString(
Blackboard.Keys.FML_LOAD_CORE_MOD, MixinPlatformAgentFML.LOAD_CORE_MOD_METHOD), LaunchClassLoader.class, String.class, File.class);
mdLoadCoreMod.setAccessible(true);
ITweaker wrapper = (ITweaker)mdLoadCoreMod.invoke(null, Launch.classLoader, coreModName, this.container);
if (wrapper == null) {
@@ -154,16 +170,44 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
return wrapper;
}
@Override
public String getPhaseProvider() {
return MixinPlatformAgentFML.class.getName() + "$PhaseProvider";
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinLaunchAgent#prepare()
* @see org.spongepowered.asm.launch.IMixinPlatformAgent#prepare()
*/
@Override
public void prepare() {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinPlatformAgent
* #initPrimaryContainer()
*/
@Override
public void initPrimaryContainer() {
if (this.clCoreModManager != null) {
// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFML.class.getName() + "$PhaseProvider");
this.injectRemapper();
}
}
private void injectRemapper() {
try {
Class<?> clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFML.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader);
Method mdCreate = clFmlRemapperAdapter.getDeclaredMethod("create");
IRemapper remapper = (IRemapper)mdCreate.invoke(null);
MixinEnvironment.getDefaultEnvironment().getRemappers().add(remapper);
} catch (Exception ex) {
MixinPlatformAgentAbstract.logger.debug("Failed instancing FML remapper adapter, things will probably go horribly for notch-obf'd mods!");
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinLaunchAgent
* @see org.spongepowered.asm.launch.IMixinPlatformAgent
* #injectIntoClassLoader(net.minecraft.launchwrapper.LaunchClassLoader)
*/
@Override
@@ -174,13 +218,13 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinLaunchAgent#getLaunchTarget()
* @see org.spongepowered.asm.launch.IMixinPlatformAgent#getLaunchTarget()
*/
@Override
public String getLaunchTarget() {
return null;
}
/**
* Performs a naive check which attempts to discover whether we are pre or
* post FML's main injection. If we are <i>pre</i>, then we must <b>not</b>
@@ -193,9 +237,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*
* @return true if FML was already injected
*/
@SuppressWarnings("unchecked")
protected final boolean isFMLInjected() {
for (String tweaker : (List<String>)Launch.blackboard.get("TweakClasses")) {
for (String tweaker : Blackboard.<List<String>>get(Blackboard.Keys.TWEAKCLASSES)) {
if (tweaker.endsWith("FMLDeobfTweaker")) {
return true;
}
@@ -209,10 +252,31 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
*/
private static Class<?> getCoreModManagerClass() throws ClassNotFoundException {
try {
return Class.forName("net.minecraftforge.fml.relauncher.CoreModManager");
return Class.forName(Blackboard.getString(
Blackboard.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS));
} catch (ClassNotFoundException ex) {
return Class.forName("cpw.mods.fml.relauncher.CoreModManager");
}
}
@SuppressWarnings("unchecked")
private static List<String> getIgnoredMods(Class<?> clCoreModManager) throws IllegalAccessException, InvocationTargetException {
Method mdGetIgnoredMods = null;
try {
mdGetIgnoredMods = clCoreModManager.getDeclaredMethod(Blackboard.getString(
Blackboard.Keys.FML_GET_IGNORED_MODS, MixinPlatformAgentFML.GET_IGNORED_MODS_METHOD));
} catch (NoSuchMethodException ex1) {
try {
// Legacy name
mdGetIgnoredMods = clCoreModManager.getDeclaredMethod("getLoadedCoremods");
} catch (NoSuchMethodException ex2) {
MixinPlatformAgentAbstract.logger.catching(Level.DEBUG, ex2);
return Collections.<String>emptyList();
}
}
return (List<String>)mdGetIgnoredMods.invoke(null);
}
}
@@ -0,0 +1,287 @@
/*
* 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.launch.platform;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
//import org.spongepowered.asm.launch.MixinBootstrap.Delegate;
import org.spongepowered.asm.launch.MixinTweaker;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.Mixins;
//import com.google.common.collect.ImmutableList;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Handler for platform-specific behaviour required in different mixin
* environments.
*/
public class MixinPlatformManager {
private static final String MFATT_TWEAKER = "TweakClass";
private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main";
/**
* Make with the logging already
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Bootstrap delegate
*/
// private final Delegate delegate;
/**
* Tweak containers
*/
private final Map<URI, MixinContainer> containers = new LinkedHashMap<URI, MixinContainer>();
/**
* Container for this tweaker
*/
private MixinContainer primaryContainer;
/**
* Tracks whether {@link #acceptOptions} was called yet, if true, causes new
* agents to be <tt>prepare</tt>d immediately
*/
private boolean prepared = false;
/**
* Tracks whether {@link #injectIntoClassLoader} was called yet
*/
private boolean injected;
public MixinPlatformManager() { //Delegate delegate) {
// this.delegate = delegate;
// Add agents for the tweak container
URI uri = null;
try {
uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
if (uri != null) {
this.primaryContainer = this.addContainer(uri);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
public Collection<String> getPhaseProviderClasses() {
Collection<String> phaseProviders = this.primaryContainer.getPhaseProviders();
if (phaseProviders != null) {
return Collections.<String>unmodifiableCollection(phaseProviders);
}
return Collections.<String>emptyList();
}
public final MixinContainer addContainer(URI uri) {
MixinContainer existingContainer = this.containers.get(uri);
if (existingContainer != null) {
return existingContainer;
}
MixinPlatformManager.logger.debug("Adding mixin platform agents for container {}", uri);
MixinContainer container = new MixinContainer(this, uri);
this.containers.put(uri, container);
if (this.prepared) {
container.prepare();
}
return container;
}
public final void prepare(List<String> args) {
this.prepared = true;
for (MixinContainer container : this.containers.values()) {
container.prepare();
}
if (args != null) {
this.parseArgs(args);
} else {
String argv = System.getProperty("sun.java.command");
if (argv != null) {
this.parseArgs(Arrays.asList(argv.split(" ")));
}
}
}
/**
* Read and parse command-line arguments
*
* @param args command-line arguments
*/
private void parseArgs(List<String> args) {
boolean captureNext = false;
for (String arg : args) {
if (captureNext) {
this.addConfig(arg);
}
captureNext = "--mixin".equals(arg);
}
}
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
if (this.injected) {
return;
}
this.injected = true;
if (this.primaryContainer != null) {
this.primaryContainer.initPrimaryContainer();
}
this.scanClasspath();
MixinPlatformManager.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size());
for (MixinContainer container : this.containers.values()) {
try {
container.injectIntoClassLoader(classLoader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Scan the classpath for mixin containers (containers which declare the
* mixin tweaker in their manifest) and add agents for them
*/
private void scanClasspath() {
for (URL url : Launch.classLoader.getSources()) {
try {
URI uri = url.toURI();
if (this.containers.containsKey(uri)) {
continue;
}
MixinPlatformManager.logger.debug("Scanning {} for mixin tweaker", uri);
if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) {
continue;
}
MainAttributes attributes = MainAttributes.of(uri);
String tweaker = attributes.get(MixinPlatformManager.MFATT_TWEAKER);
if (MixinTweaker.class.getName().equals(tweaker)) {
MixinPlatformManager.logger.debug("{} contains a mixin tweaker, adding agents", uri);
this.addContainer(uri);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public String getLaunchTarget() {
for (MixinContainer container : this.containers.values()) {
String mainClass = container.getLaunchTarget();
if (mainClass != null) {
return mainClass;
}
}
return MixinPlatformManager.DEFAULT_MAIN_CLASS;
}
/**
* Set the desired compatibility level as a string, used by agents to set
* compatibility level from jar manifest
*
* @param level compatibility level as a string
*/
@SuppressWarnings("deprecation")
final void setCompatibilityLevel(String level) {
try {
CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase());
MixinPlatformManager.logger.debug("Setting mixin compatibility level: {}", value);
MixinEnvironment.setCompatibilityLevel(value);
} catch (IllegalArgumentException ex) {
MixinPlatformManager.logger.warn("Invalid compatibility level specified: {}", level);
}
}
/**
* Add a config from a jar manifest source or the command line. Supports
* config declarations in the form <tt>filename.json</tt> or alternatively
* <tt>filename.json&#064;PHASE</tt> where <tt>PHASE</tt> is a
* case-sensitive string token representing an environment phase.
*
* @param config config resource name, does not require a leading /
*/
@SuppressWarnings("deprecation")
final void addConfig(String config) {
if (config.endsWith(".json")) {
MixinPlatformManager.logger.debug("Registering mixin config: {}", config);
Mixins.addConfiguration(config);
} else if (config.contains(".json@")) {
int pos = config.indexOf(".json@");
String phaseName = config.substring(pos + 6);
config = config.substring(0, pos + 5);
Phase phase = Phase.forName(phaseName);
if (phase != null) {
MixinPlatformManager.logger.warn("Setting config phase via manifest is deprecated: {}. Specify target in config instead", config);
MixinPlatformManager.logger.debug("Registering mixin config: {}", config);
MixinEnvironment.getEnvironment(phase).addConfiguration(config);
}
}
}
/**
* Add a token provider class from a jar manifest source. Supports either
* bare class names in the form <tt>blah.package.ClassName</tt> or
* alternatively <tt>blah.package.ClassName&#064;PHASE</tt> where
* <tt>PHASE</tt> is a case-sensitive string token representing an
* environment phase name.
*
* @param provider provider class name, optionally suffixed with &#064;PHASE
*/
final void addTokenProvider(String provider) {
if (provider.contains("@")) {
String[] parts = provider.split("@", 2);
Phase phase = Phase.forName(parts[1]);
if (phase != null) {
MixinPlatformManager.logger.debug("Registering token provider class: {}", parts[0]);
MixinEnvironment.getEnvironment(phase).registerTokenProviderClass(parts[0]);
}
return;
}
MixinEnvironment.getDefaultEnvironment().registerTokenProviderClass(provider);
}
}
@@ -0,0 +1,64 @@
/*
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Anotation used to decorate items you might wish to examine after mixin
* application.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Debug {
/**
* Only applicable for classes, use this to decorate mixins that you wish
* to export even if <tt>mixin.debug.export</tt> is not enabled. This is
* useful if you wish to export only the target of the mixin you are working
* on without enabling export globally.
*
* <p>Note that if <tt>mixin.debug.export</tt> is <b>not</b> <tt>true</tt>
* then the decompiler is <em>not</em> initialised (even if present on the
* classpath) and thus you must set <tt>mixin.debug.export.decompile</tt> to
* <tt>true</tt> in order to have force-exported classes decompiled.</p>
*
* @return whether to export the decorated target class
*/
public boolean export() default false;
/**
* Print the method bytecode to the console after mixin application. This
* setting is only used if the <tt>mixin.debug.verbose</tt> option is
* enabled.
*
* @return whether to print the class or method to the console.
*/
public boolean print() default false;
}
@@ -0,0 +1,62 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
* This annotation has two uses:
*
* <ul>
* <li>
* On an {@link Shadow} field, it can be used to raise an error-level log
* message if any write occurrences appear in the mixin bytecode. This can
* be used in place of declaring the field as actually <tt>final</tt>. This
* is required since it is normally desirable to remove the <tt>final</tt>
* modifier from shadow fields to avoid unwanted field initialisers. If
* {@link Option#DEBUG_VERIFY} is <tt>true</tt>, then an
* {@link InvalidMixinException} is thrown.
* </li>
* <li>
* On an {@link Inject injector} or {@link Overwrite overwritten} method,
* it is equivalent to setting the priority of the containing mixin to
* {@link Integer#MAX_VALUE} but applies only to the annotated method. This
* allows methods to mark themselves as effectively final, preventing their
* replacement by later mixins with higher priority.
* </li>
* </ul>
*/
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Final {
}
@@ -53,4 +53,12 @@ public @interface Interface {
*/
public String prefix();
/**
* If set to <tt>true</tt>, all methods implementing this interface are
* treated as if they were individually decorated with {@link Unique}
*
* @return true to mark all implementing methods as unique
*/
public boolean unique() default false;
}
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation allows fine-tuning of the overwrite policy for a
* soft-implemented interface member method.
@@ -25,23 +25,36 @@
package org.spongepowered.asm.mixin;
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.helpers.Booleans;
import org.spongepowered.asm.launch.Blackboard;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.obfuscation.RemapperChain;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.JavaVersion;
import org.spongepowered.asm.util.PrettyPrinter;
import com.google.common.collect.ImmutableList;
@@ -53,12 +66,11 @@ import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* The mixin environment manages global state information for the mixin
* subsystem.
*/
public class MixinEnvironment implements ITokenProvider {
public final class MixinEnvironment implements ITokenProvider {
/**
* Environment phase, deliberately not implemented as an enum
@@ -76,16 +88,22 @@ public class MixinEnvironment implements ITokenProvider {
*/
public static final Phase PREINIT = new Phase(0, "PREINIT");
/**
* "Initialisation" phase, after FML's deobf transformer has loaded
*/
public static final Phase INIT = new Phase(1, "INIT");
/**
* "Default" phase, during runtime
*/
public static final Phase DEFAULT = new Phase(1, "DEFAULT");
public static final Phase DEFAULT = new Phase(2, "DEFAULT");
/**
* All phases
*/
static final List<Phase> phases = ImmutableList.of(
Phase.PREINIT,
Phase.INIT,
Phase.DEFAULT
);
@@ -175,11 +193,10 @@ public class MixinEnvironment implements ITokenProvider {
protected abstract boolean detect();
@SuppressWarnings("unchecked")
protected final String getSideName() {
// Using this method first prevents us from accidentally loading FML classes
// too early when using the tweaker in dev
for (ITweaker tweaker : (List<ITweaker>)Launch.blackboard.get("Tweaks")) {
for (ITweaker tweaker : Blackboard.<List<ITweaker>>get(Blackboard.Keys.TWEAKS)) {
if (tweaker.getClass().getName().endsWith(".common.launcher.FMLServerTweaker")) {
return "SERVER";
} else if (tweaker.getClass().getName().endsWith(".common.launcher.FMLTweaker")) {
@@ -197,7 +214,7 @@ public class MixinEnvironment implements ITokenProvider {
return name;
}
name = this.getSideName("com.mumfrey.liteloader.core.LiteLoader", "getEnvironmentType");
name = this.getSideName("com.mumfrey.liteloader.launch.LiteLoaderTweaker", "getEnvironmentType");
if (name != null) {
return name;
}
@@ -246,10 +263,22 @@ public class MixinEnvironment implements ITokenProvider {
* <dt>?</dt><dd>Matches exactly one character</dd>
* </dl>
*/
DEBUG_EXPORT_FILTER(Option.DEBUG_EXPORT, "filter"),
DEBUG_EXPORT_FILTER(Option.DEBUG_EXPORT, "filter", false),
/**
* Run the CheckClassAdapter on all classes after mixins are applied
* Allow fernflower to be disabled even if it is found on the classpath
*/
DEBUG_EXPORT_DECOMPILE(Option.DEBUG_EXPORT, "decompile") {
@Override
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), super.getBooleanValue());
}
},
/**
* Run the CheckClassAdapter on all classes after mixins are applied,
* also enables stricter checks on mixins for use at dev-time, promotes
* some warning-level messages to exceptions
*/
DEBUG_VERIFY(Option.DEBUG_ALL, "verify"),
@@ -259,6 +288,44 @@ public class MixinEnvironment implements ITokenProvider {
*/
DEBUG_VERBOSE(Option.DEBUG_ALL, "verbose"),
/**
* Elevates failed injections to an error condition, see
* {@link Inject#expect} for details
*/
DEBUG_INJECTORS(Option.DEBUG_ALL, "countInjections"),
/**
* Enable strict checks
*/
DEBUG_STRICT(Option.DEBUG_ALL, "strict") {
@Override
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), false);
}
},
/**
* If false (default), {@link Unique} public methods merely raise a
* warning when encountered and are not merged into the target. If true,
* an exception is thrown instead
*/
DEBUG_UNIQUE(Option.DEBUG_STRICT, "unique"),
/**
* Enable strict checking for mixin targets
*/
DEBUG_TARGETS(Option.DEBUG_STRICT, "targets"),
/**
* Disable the injector handler remapper
*/
DEBUG_DISABLE_HANDLER_REMAP(Option.DEBUG_ALL, "disableHandlerRename") {
@Override
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), super.getBooleanValue());
}
},
/**
* Dumps the bytecode for the target class to disk when mixin
* application fails
@@ -279,8 +346,38 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Ignore all constraints on mixin annotations, output warnings instead
*/
IGNORE_CONSTRAINTS("ignoreConstraints");
IGNORE_CONSTRAINTS("ignoreConstraints"),
/**
* Enables the hot-swap agent
*/
HOT_SWAP("hotSwap"),
/**
* Parent for environment settings
*/
ENVIRONMENT("env") {
@Override
boolean getBooleanValue() {
return false;
}
},
/**
* Force refmap obf type when required
*/
OBFUSCATION_TYPE(Option.ENVIRONMENT, "obf"),
/**
* Disable refmap when required
*/
DISABLE_REFMAP(Option.ENVIRONMENT, "disableRefMap"),
/**
* Default compatibility level to operate at
*/
DEFAULT_COMPATIBILITY_LEVEL(Option.ENVIRONMENT, "compatLevel");
/**
* Prefix for mixin options
*/
@@ -296,14 +393,38 @@ public class MixinEnvironment implements ITokenProvider {
* Java property name
*/
final String property;
/**
* Whether this property is boolean or not
*/
final boolean flag;
/**
* Number of parents
*/
final int depth;
private Option(String property) {
this(null, property);
this(null, property, true);
}
private Option(String property, boolean flag) {
this(null, property, flag);
}
private Option(Option parent, String property) {
this(parent, property, true);
}
private Option(Option parent, String property, boolean flag) {
this.parent = parent;
this.property = (parent != null ? parent.property : Option.PREFIX) + "." + property;
this.flag = flag;
int depth = 0;
for (; parent != null; depth++) {
parent = parent.parent;
}
this.depth = depth;
}
Option getParent() {
@@ -314,6 +435,11 @@ public class MixinEnvironment implements ITokenProvider {
return this.property;
}
@Override
public String toString() {
return this.flag ? String.valueOf(this.getBooleanValue()) : this.getStringValue();
}
boolean getBooleanValue() {
return Booleans.parseBoolean(System.getProperty(this.property), false)
|| (this.parent != null && this.parent.getBooleanValue());
@@ -322,6 +448,93 @@ public class MixinEnvironment implements ITokenProvider {
String getStringValue() {
return (this.parent == null || this.parent.getBooleanValue()) ? System.getProperty(this.property) : null;
}
@SuppressWarnings("unchecked")
<E extends Enum<E>> E getEnumValue(E defaultValue) {
String value = System.getProperty(this.property, defaultValue.name());
try {
return (E) Enum.valueOf(defaultValue.getClass(), value);
} catch (IllegalArgumentException ex) {
return defaultValue;
}
}
}
/**
* Operational compatibility level for the mixin subsystem
*/
public static enum CompatibilityLevel {
JAVA_6(6, Opcodes.V1_6, false),
JAVA_7(7, Opcodes.V1_7, false) {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.7;
}
},
JAVA_8(8, Opcodes.V1_8, true) {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.8;
}
};
private final int ver;
private final int classVersion;
private final boolean supportsMethodsInInterfaces;
private CompatibilityLevel maxCompatibleLevel;
private CompatibilityLevel(int ver, int classVersion, boolean resolveMethodsInInterfaces) {
this.ver = ver;
this.classVersion = classVersion;
this.supportsMethodsInInterfaces = resolveMethodsInInterfaces;
}
@SuppressWarnings("unused")
private void setMaxCompatibleLevel(CompatibilityLevel maxCompatibleLevel) {
this.maxCompatibleLevel = maxCompatibleLevel;
}
boolean isSupported() {
return true;
}
public int classVersion() {
return this.classVersion;
}
public boolean supportsMethodsInInterfaces() {
return this.supportsMethodsInInterfaces;
}
public boolean isAtLeast(CompatibilityLevel level) {
return this.ver >= level.ver;
}
public boolean canElevateTo(CompatibilityLevel level) {
if (level == null || this.maxCompatibleLevel == null) {
return true;
}
return level.ver <= this.maxCompatibleLevel.ver;
}
public boolean canSupport(CompatibilityLevel level) {
if (level == null) {
return true;
}
return level.canElevateTo(this);
}
}
/**
@@ -336,6 +549,7 @@ public class MixinEnvironment implements ITokenProvider {
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader);
}
@Override
@@ -392,6 +606,39 @@ public class MixinEnvironment implements ITokenProvider {
}
/**
* Temporary
*/
static class MixinLogger {
static MixinAppender appender = new MixinAppender("MixinLogger", null, null);
public MixinLogger() {
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
appender.start();
log.addAppender(appender);
}
/**
* Temporary
*/
static class MixinAppender extends AbstractAppender {
protected MixinAppender(String name, Filter filter, Layout<? extends Serializable> layout) {
super(name, filter, layout);
}
@Override
public void append(LogEvent event) {
if (event.getLevel() == Level.DEBUG && "Validating minecraft".equals(event.getMessage().getFormat())) {
// transition to INIT
MixinEnvironment.gotoPhase(Phase.INIT);
}
}
}
}
/**
* Known re-entrant transformers, other re-entrant transformers will
* detected automatically
@@ -403,10 +650,6 @@ public class MixinEnvironment implements ITokenProvider {
"cpw.mods.fml.common.asm.transformers.TerminalTransformer"
);
// Blackboard keys
private static final String CONFIGS_KEY = "mixin.configs";
private static final String TRANSFORMER_KEY = "mixin.transformer";
/**
* Currently active environment
*/
@@ -418,6 +661,11 @@ public class MixinEnvironment implements ITokenProvider {
*/
private static Phase currentPhase = Phase.NOT_INITIALISED;
/**
* Current compatibility level
*/
private static CompatibilityLevel compatibility = Option.DEFAULT_COMPATIBILITY_LEVEL.<CompatibilityLevel>getEnumValue(CompatibilityLevel.JAVA_6);
/**
* Show debug header info on first environment construction
*/
@@ -426,7 +674,7 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Logger
*/
private final Logger logger = LogManager.getLogger("mixin");
private static final Logger logger = LogManager.getLogger("mixin");
/**
* The phase for this environment
@@ -443,10 +691,7 @@ public class MixinEnvironment implements ITokenProvider {
*/
private final boolean[] options;
/**
* Error handlers for environment
*/
private final Set<String> errorHandlers = new LinkedHashSet<String>();
// private final Map<String, MixinConfig> configs;
/**
* List of token provider classes
@@ -462,6 +707,11 @@ public class MixinEnvironment implements ITokenProvider {
* Internal tokens defined by this environment
*/
private final Map<String, Integer> internalTokens = new HashMap<String, Integer>();
/**
* Remappers for this environment
*/
private final RemapperChain remappers = new RemapperChain();
/**
* Detected side
@@ -481,19 +731,24 @@ public class MixinEnvironment implements ITokenProvider {
*/
private IClassNameTransformer nameTransformer;
/**
* Obfuscation context (refmap key to use in this environment)
*/
private String obfuscationContext = null;
MixinEnvironment(Phase phase) {
this.phase = phase;
this.configsKey = MixinEnvironment.CONFIGS_KEY + "." + this.phase.name.toLowerCase();
this.configsKey = Blackboard.Keys.CONFIGS + "." + this.phase.name.toLowerCase();
// Sanity check
Object version = Launch.blackboard.get(MixinBootstrap.INIT_KEY);
Object version = this.getVersion();
if (version == null || !MixinBootstrap.VERSION.equals(version)) {
throw new RuntimeException("Environment conflict, mismatched versions or you didn't call MixinBootstrap.init()");
throw new MixinException("Environment conflict, mismatched versions or you didn't call MixinBootstrap.init()");
}
// Also sanity check
if (this.getClass().getClassLoader() != Launch.class.getClassLoader()) {
throw new RuntimeException("Attempted to init the mixin environment in the wrong classloader");
throw new MixinException("Attempted to init the mixin environment in the wrong classloader");
}
this.options = new boolean[Option.values().length];
@@ -510,17 +765,22 @@ public class MixinEnvironment implements ITokenProvider {
private void printHeader(Object version) {
Side side = this.getSide();
String codeSource = this.getCodeSource();
this.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
if (this.getOption(Option.DEBUG_VERBOSE)) {
PrettyPrinter printer = new PrettyPrinter(32);
printer.add("SpongePowered MIXIN (Verbose debugging enabled)").centre().hr();
printer.add("%25s : %s", "Code source", codeSource);
printer.add("%25s : %s", "Internal Version", version).hr();
printer.kv("Code source", codeSource);
printer.kv("Internal Version", version);
printer.kv("Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr();
for (Option option : Option.values()) {
printer.add("%25s : %s%s", option.property, option.parent == null ? "" : " - ", this.getOption(option));
StringBuilder indent = new StringBuilder();
for (int i = 0; i < option.depth; i++) {
indent.append("- ");
}
printer.kv(option.property, "%s<%s>", indent, option);
}
printer.hr().add("%25s : %s", "Detected Side", side);
printer.hr().kv("Detected Side", side);
printer.print(System.err);
}
}
@@ -546,10 +806,11 @@ public class MixinEnvironment implements ITokenProvider {
* Get mixin configurations from the blackboard
*
* @return list of registered mixin configs
* @deprecated no replacement
*/
@Deprecated
public List<String> getMixinConfigs() {
@SuppressWarnings("unchecked")
List<String> mixinConfigs = (List<String>) Launch.blackboard.get(this.configsKey);
List<String> mixinConfigs = Blackboard.<List<String>>get(this.configsKey);
if (mixinConfigs == null) {
mixinConfigs = new ArrayList<String>();
Launch.blackboard.put(this.configsKey, mixinConfigs);
@@ -562,23 +823,32 @@ public class MixinEnvironment implements ITokenProvider {
*
* @param config Name of configuration resource to add
* @return fluent interface
* @deprecated use Mixins::addConfiguration instead
*/
@Deprecated
public MixinEnvironment addConfiguration(String config) {
MixinEnvironment.logger.warn("MixinEnvironment::addConfiguration is deprecated and will be removed. Use Mixins::addConfiguration instead!");
Mixins.addConfiguration(config, this);
return this;
}
void registerConfig(String config) {
List<String> configs = this.getMixinConfigs();
if (!configs.contains(config)) {
configs.add(config);
}
return this;
}
/**
* Add a new error handler class to this environment
*
* @param handlerName Handler class to add
* @return fluent interface
* @deprecated use Mixins::registerErrorHandlerClass
*/
@Deprecated
public MixinEnvironment registerErrorHandlerClass(String handlerName) {
this.errorHandlers.add(handlerName);
Mixins.registerErrorHandlerClass(handlerName);
return this;
}
@@ -597,7 +867,7 @@ public class MixinEnvironment implements ITokenProvider {
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
this.logger.error("Error instantiating " + providerName, th);
MixinEnvironment.logger.error("Error instantiating " + providerName, th);
}
}
return this;
@@ -613,7 +883,7 @@ public class MixinEnvironment implements ITokenProvider {
if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) {
String providerName = provider.getClass().getName();
TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this);
this.logger.info("Adding new token provider {} to {}", providerName, this);
MixinEnvironment.logger.info("Adding new token provider {} to {}", providerName, this);
this.tokenProviders.add(wrapper);
this.tokenProviderClasses.add(providerName);
Collections.sort(this.tokenProviders);
@@ -647,9 +917,11 @@ public class MixinEnvironment implements ITokenProvider {
* Get all registered error handlers for this environment
*
* @return set of error handler class names
* @deprecated use Mixins::getErrorHandlerClasses
*/
@Deprecated
public Set<String> getErrorHandlerClasses() {
return Collections.<String>unmodifiableSet(this.errorHandlers);
return Mixins.getErrorHandlerClasses();
}
/**
@@ -658,7 +930,7 @@ public class MixinEnvironment implements ITokenProvider {
* @return active mixin transformer instance
*/
public Object getActiveTransformer() {
return Launch.blackboard.get(MixinEnvironment.TRANSFORMER_KEY);
return Blackboard.get(Blackboard.Keys.TRANSFORMER);
}
/**
@@ -668,7 +940,7 @@ public class MixinEnvironment implements ITokenProvider {
*/
public void setActiveTransformer(IClassTransformer transformer) {
if (transformer != null) {
Launch.blackboard.put(MixinEnvironment.TRANSFORMER_KEY, transformer);
Blackboard.put(Blackboard.Keys.TRANSFORMER, transformer);
}
}
@@ -709,7 +981,7 @@ public class MixinEnvironment implements ITokenProvider {
* @return current version
*/
public String getVersion() {
return (String)Launch.blackboard.get(MixinBootstrap.INIT_KEY);
return Blackboard.<String>get(Blackboard.Keys.INIT);
}
/**
@@ -742,6 +1014,40 @@ public class MixinEnvironment implements ITokenProvider {
return option.getStringValue();
}
/**
* Set the obfuscation context
*
* @param context
*/
public void setObfuscationContext(String context) {
this.obfuscationContext = context;
}
/**
* Get the current obfuscation context
*/
public String getObfuscationContext() {
return this.obfuscationContext;
}
/**
* Get the current obfuscation context
*/
public String getRefmapObfuscationContext() {
String overrideObfuscationType = Option.OBFUSCATION_TYPE.getStringValue();
if (overrideObfuscationType != null) {
return overrideObfuscationType;
}
return this.obfuscationContext;
}
/**
* Get the remapper chain for this environment
*/
public RemapperChain getRemappers() {
return this.remappers;
}
/**
* Invoke a mixin environment audit process
*/
@@ -804,7 +1110,7 @@ public class MixinEnvironment implements ITokenProvider {
* list just once per environment and cache the result.
*/
private void buildTransformerDelegationList() {
this.logger.debug("Rebuilding transformer delegation list:");
MixinEnvironment.logger.debug("Rebuilding transformer delegation list:");
this.transformers = new ArrayList<IClassTransformer>();
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
String transformerName = transformer.getClass().getName();
@@ -815,19 +1121,20 @@ public class MixinEnvironment implements ITokenProvider {
break;
}
}
if (include && !transformerName.contains(MixinTransformer.class.getName())) {
this.logger.debug(" Adding: {}", transformerName);
boolean ignoreTransformer = transformer.getClass().getAnnotation(Resource.class) != null;
if (include && !ignoreTransformer && !transformerName.contains(MixinTransformer.class.getName())) {
MixinEnvironment.logger.debug(" Adding: {}", transformerName);
this.transformers.add(transformer);
} else {
this.logger.debug(" Excluding: {}", transformerName);
MixinEnvironment.logger.debug(" Excluding: {}", transformerName);
}
}
this.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
if (transformer instanceof IClassNameTransformer) {
this.logger.debug("Found name transformer: {}", transformer.getClass().getName());
MixinEnvironment.logger.debug("Found name transformer: {}", transformer.getClass().getName());
this.nameTransformer = (IClassNameTransformer) transformer;
}
}
@@ -861,6 +1168,9 @@ public class MixinEnvironment implements ITokenProvider {
if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) {
MixinEnvironment.currentPhase = phase;
MixinEnvironment.getEnvironment(phase);
@SuppressWarnings("unused")
MixinLogger logSpy = new MixinLogger();
}
}
@@ -899,6 +1209,37 @@ public class MixinEnvironment implements ITokenProvider {
return MixinEnvironment.currentEnvironment;
}
/**
* Get the current compatibility level
*/
public static CompatibilityLevel getCompatibilityLevel() {
return MixinEnvironment.compatibility;
}
/**
* Set desired compatibility level for the entire environment
*
* @param level Level to set, ignored if less than the current level
* @throws IllegalArgumentException if the specified level is not supported
* @deprecated set compatibility level in configuration
*/
@Deprecated
public static void setCompatibilityLevel(CompatibilityLevel level) throws IllegalArgumentException {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
if (!"org.spongepowered.asm.mixin.transformer.MixinConfig".equals(stackTrace[2].getClassName())) {
MixinEnvironment.logger.warn("MixinEnvironment::setCompatibilityLevel is deprecated and will be removed. Set level via config instead!");
}
if (level != MixinEnvironment.compatibility && level.isAtLeast(MixinEnvironment.compatibility)) {
if (!level.isSupported()) {
throw new IllegalArgumentException("The requested compatibility level " + level + " could not be set. Level is not supported");
}
MixinEnvironment.compatibility = level;
MixinEnvironment.logger.info("Compatibility level set to {}", level);
}
}
/**
* Internal callback
*
@@ -913,6 +1254,12 @@ public class MixinEnvironment implements ITokenProvider {
MixinBootstrap.addProxy();
}
if (phase == Phase.DEFAULT) {
// remove appender
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
log.removeAppender(MixinLogger.appender);
}
MixinEnvironment.currentPhase = phase;
MixinEnvironment.currentEnvironment = MixinEnvironment.getEnvironment(MixinEnvironment.getCurrentPhase());
}
@@ -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;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.Blackboard;
import org.spongepowered.asm.mixin.transformer.Config;
import net.minecraft.launchwrapper.Launch;
/**
* Entry point for registering global mixin resources. Compatibility with
* pre-0.6 versions is maintained via the methods on {@link MixinEnvironment}
* delegating to the methods here.
*/
public final class Mixins {
/**
* Logger
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Blackboard key storing mixin configs which are pending
*/
private static final String CONFIGS_KEY = Blackboard.Keys.CONFIGS + ".queue";
/**
* Error handlers for environment
*/
private static final Set<String> errorHandlers = new LinkedHashSet<String>();
private Mixins() {}
public static void addConfigurations(String... configFiles) {
MixinEnvironment fallback = MixinEnvironment.getDefaultEnvironment();
for (String configFile : configFiles) {
Mixins.createConfiguration(configFile, fallback);
}
}
/**
* Add a mixin configuration resource
*
* @param configFile path to configuration resource
*/
public static void addConfiguration(String configFile) {
Mixins.createConfiguration(configFile, MixinEnvironment.getDefaultEnvironment());
}
@Deprecated
static void addConfiguration(String configFile, MixinEnvironment fallback) {
Mixins.createConfiguration(configFile, fallback);
}
@SuppressWarnings("deprecation")
private static void createConfiguration(String configFile, MixinEnvironment fallback) {
Config config = null;
try {
config = Config.create(configFile, fallback);
} catch (Exception ex) {
Mixins.logger.error("Error encountered reading mixin config " + configFile + ": " + ex.getClass().getName() + " " + ex.getMessage(), ex);
}
Mixins.registerConfiguration(config);
}
private static void registerConfiguration(Config config) {
if (config == null) {
return;
}
MixinEnvironment env = config.getEnvironment();
if (env != null) {
env.registerConfig(config.getName());
}
Mixins.getConfigs().add(config);
}
/**
* Get current pending configs set, only configs which have yet to be
* consumed are present in this set
*/
public static Set<Config> getConfigs() {
Set<Config> mixinConfigs = Blackboard.<Set<Config>>get(Mixins.CONFIGS_KEY);
if (mixinConfigs == null) {
mixinConfigs = new LinkedHashSet<Config>();
Launch.blackboard.put(Mixins.CONFIGS_KEY, mixinConfigs);
}
return mixinConfigs;
}
/**
* Register a gloabl error handler class
*
* @param handlerName Fully qualified class name
*/
public static void registerErrorHandlerClass(String handlerName) {
if (handlerName != null) {
Mixins.errorHandlers.add(handlerName);
}
}
/**
* Get current error handlers
*/
public static Set<String> getErrorHandlerClasses() {
return Collections.<String>unmodifiableSet(Mixins.errorHandlers);
}
}
@@ -0,0 +1,40 @@
/*
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use in conjunction with {@link Final} to indicate that whilst a field is
* final in the target class, mutation within the mixin is intentional.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mutable {
}
@@ -29,7 +29,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.transformer.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
* Used to indicate a Mixin class member which is acting as a placeholder for a
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Decorator for methods which override a method in a supermixin which the
* containing mixin does not directly extend
@@ -0,0 +1,72 @@
/*
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation, when applied to a member method or field in a mixin,
* indicates that the member <b>should never</b> overwrite a matching membver in
* the target class. This indicates that the member differs from the normal
* "overlay-like" behaviour of mixins in general, and should only ever be
* <em>added</em> to the target. For public fields, the annotation has no
* effect.
*
* <p>Typical usage of this annotation would be to decorate a utility method in
* a mixin, or mark an interface-implementing method which must not overwrite a
* target if it exists (consider appropriate use of {@link Intrinsic} in these
* situations).</p>
*
* <p>Because of the mixed usage, this annotation has different implications for
* methods with differing visibility:</p>
*
* <dl>
* <dt>public methods</dt>
* <dd>public methods marked with this annotation are <b>discarded</b> if a
* matching target exists. A <tt>warning</tt>-level message is generated.</dd>
* <dt>private and protected methods</dt>
* <dd>non-public methods are <b>renamed</b> if a matching target method is
* found, this allows utility methods to be safely assigned meaningful names
* in code, but renamed if a conflict occurs when a mixin is applied.</dd>
* </dl>
*
* <p><strong>Notes</strong></p>
*
* <ul>
* <li>To mark all methods in a mixin as unique, apply the annotation to the
* mixin itself</li>
* <li>Uniqueness can be defined on a per-interface basis by using an
* {@link Implements} annotation with <tt>unique</tt> set to <tt>true</tt>
* </li>
* </ul>
*/
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Unique {
}
@@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.extensibility;
import org.spongepowered.asm.mixin.MixinEnvironment;
/**
* Provides a token value into the attached environment
*/
@@ -26,6 +26,8 @@ package org.spongepowered.asm.mixin.extensibility;
import java.util.Set;
import org.spongepowered.asm.mixin.MixinEnvironment;
/**
* Interface for loaded mixin configurations
*/
@@ -35,6 +37,13 @@ public interface IMixinConfig {
* Default priority for mixin configs and mixins
*/
public static final int DEFAULT_PRIORITY = 1000;
/**
* Get the parent environment of this config
*
* @return the parent environment
*/
public abstract MixinEnvironment getEnvironment();
/**
* Get the name of the file from which this configuration object was
@@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.extensibility;
import org.apache.logging.log4j.Level;
/**
* Interface for objects which want to perform custom behaviour when fatal mixin
* errors occur. For example displaying a user-friendly error message
@@ -52,8 +51,9 @@ public interface IMixinErrorHandler {
WARN(Level.WARN),
/**
* Throw a {@link org.spongepowered.asm.mixin.MixinApplyError} to halt
* further processing if possible
* Throw a
* {@link org.spongepowered.asm.mixin.throwables.MixinApplyError} to
* halt further processing if possible
*/
ERROR(Level.FATAL);
@@ -64,6 +64,33 @@ public interface IMixinErrorHandler {
}
}
/**
* Called when an error occurs whilst initialising a mixin config. This
* allows the plugin to display more user-friendly error messages if
* required.
*
* <p>By default, when a critical error occurs the mixin processor will
* raise a warning if the config is not marked as "required" and will throw
* an {@link Error} if it is. This behaviour can be altered by returning
* different values from this method.</p>
*
* <p>The original throwable which was caught is passed in via the <code>
* th</code> parameter and the default action is passed in to the <code>
* action</code> parameter. A plugin can choose to output a friendly message
* but leave the original behaviour intact (by returning <code>null</code>
* or returning <code>action</code> directly. Alternatively it may throw a
* different exception or error, or can reduce the severity of the error by
* returning a different {@link ErrorAction}.</p>
*
* @param config Config being prepared when the error occurred
* @param th Throwable which was caught
* @param mixin Mixin which was being applied at the time of the error
* @param action Default action
* @return null to perform the default action (or return action) or new
* action to take
*/
public abstract ErrorAction onPrepareError(IMixinConfig config, Throwable th, IMixinInfo mixin, ErrorAction action);
/**
* Called when an error occurs applying a mixin. This allows
* the plugin to display more user-friendly error messages if required.
@@ -88,6 +115,6 @@ public interface IMixinErrorHandler {
* @return null to perform the default action (or return action) or new
* action to take
*/
public abstract ErrorAction onError(String targetClassName, Throwable th, IMixinInfo mixin, ErrorAction action);
public abstract ErrorAction onApplyError(String targetClassName, Throwable th, IMixinInfo mixin, ErrorAction action);
}
@@ -29,6 +29,9 @@ import java.util.List;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
/**
* Interface for MixinInfo, used in extensibility API
*/
public interface IMixinInfo {
/**
@@ -102,4 +105,5 @@ public interface IMixinInfo {
* @return the phase
*/
public abstract Phase getPhase();
}
@@ -0,0 +1,84 @@
/*
* 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.extensibility;
/**
* Interface for remap chain participants
*/
public interface IRemapper {
/**
* Map method name to the new name. Subclasses can override.
*
* @param owner owner of the method.
* @param name name of the method.
* @param desc descriptor of the method.
* @return new name of the method
*/
public abstract String mapMethodName(String owner, String name, String desc);
/**
* Map field name to the new name. Subclasses can override.
*
* @param owner owner of the field.
* @param name name of the field
* @param desc descriptor of the field
* @return new name of the field.
*/
public abstract String mapFieldName(String owner, String name, String desc);
/**
* Map type name to the new name. Subclasses can override.
*
* @param typeName Class name to convert
* @return new name for the class
*/
public abstract String map(String typeName);
/**
* Convert a mapped type name back to the original obfuscated name
*
* @param typeName Class name to convert
* @return old name for the class
*/
public abstract String unmap(String typeName);
/**
* Convert a descriptor to remapped form
*
* @param desc descriptor to convert
* @return new descriptor
*/
public abstract String mapDesc(String desc);
/**
* Convert a descriptor back to the original obfuscated form
*
* @param desc descriptor to convert
* @return old descriptor
*/
public abstract String unmapDesc(String desc);
}
@@ -27,7 +27,6 @@ package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Indicates that a local capture injector should coerce top-level primitive
* types to covariant types.
@@ -0,0 +1,111 @@
/*
* 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.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Annotation for specifying the injection point for an {@link ModifyConstant}
* injector. Leaving all values unset causes the injection point to match all
* constants with the same type as the {@link ModifyConstant} handler's return
* type.
*
* <p>To match a specific constant, specify the appropriate value for the
* appropriate argument. Specifying values of different types will cause an
* error to be raised by the injector.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Constant {
/**
* Causes this injector to match ACONST_NULL (null object) literals
*
* @return true to match <tt>null</tt>
*/
public boolean nullValue() default false;
/**
* Specify an integer constant to match, includes byte and short values
*
* @return integer value to match
*/
public int intValue() default 0;
/**
* Specify a float constant to match
*
* @return float value to match
*/
public float floatValue() default 0.0F;
/**
* Specify a long constant to match
*
* @return long value to match
*/
public long longValue() default 0L;
/**
* Specify a double constant to match
*
* @return double value to match
*/
public double doubleValue() default 0.0;
/**
* Specify a String constant to match
*
* @return string value to match
*/
public String stringValue() default "";
/**
* Specify a type literal to match
*
* @return type literal to match
*/
public Class<?> classValue() default Object.class;
/**
* Ordinal offset. Many InjectionPoints will return every opcode matching
* their criteria, specifying <em>ordinal</em> allows a particular opcode to
* be identified from the returned list. The default value of -1 does not
* alter the behaviour and returns all matching opcodes. Specifying a value
* of 0 or higher returns <em>only</em> the requested opcode (if one exists:
* for example specifying an ordinal of 4 when only 2 opcodes are matched by
* the InjectionPoint is not going to work particularly well!)
*
* @return ordinal value for supported InjectionPoint types
*/
public int ordinal() default -1;
/**
* @return true to enable verbose debug logging for this injection point
*/
public boolean log() default false;
}
@@ -0,0 +1,65 @@
/*
* 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.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation can be used on any injector callback to define a value for
* total required injections across multiple callbacks. Much like
* {@link Inject#require()} it can be used to treat an injection failure as a
* critical error, however the <tt>require</tt> value specified applies to all
* injectors in the group. This can be used, for example, for 'surrogate'
* injectors where multiple injectors exist but only one is expected to succeed.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface Group {
/**
* The name of the injector group, any string
*
* @return group name
*/
public String name() default "";
/**
* Minimum required injections for this injector group
*
* @return required min value
*/
public int min() default -1;
/**
* Maximum allowed injections for this injector group
*
* @return allowed max value
*/
public int max() default -1;
}
@@ -29,8 +29,12 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject a callback (or
@@ -41,6 +45,15 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Retention(RetentionPolicy.RUNTIME)
public @interface Inject {
/**
* The identifier for this injector, can be retrieved via the
* {@link CallbackInfo#getId} accessor. If not specified, the ID defaults to
* the target method name.
*
* @return the injector id to use
*/
public String id() default "";
/**
* String representation of a
* {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo
@@ -111,7 +124,6 @@ public @interface Inject {
*/
public LocalCapture locals() default LocalCapture.NO_CAPTURE;
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link Inject} methods since it is
@@ -128,4 +140,47 @@ public @interface Inject {
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -0,0 +1,262 @@
/*
* 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.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.ASMHelper;
/**
* Used to keep track of instruction nodes in a {@link Target} method which are
* targetted by various types of injector. This collection is populated during
* the first injector pass and allows injectors to keep track of their targets
* even when the target method is being manipulated by other injectors.
*/
public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
/**
* Never gonna give you up
*/
private static final long serialVersionUID = 1L;
/**
* A node targetted by one or more injectors. Using this wrapper allows
* injectors to be aware of when their target node is removed or replace by
* another injector. It also allows injectors to decorate certain nodes with
* custom metadata to allow arbitration between injectors to take place.
*/
public static class InjectionNode implements Comparable<InjectionNode> {
/**
* The original node targetted
*/
private final AbstractInsnNode originalTarget;
/**
* Initially set to the {@link #originalTarget}, if an injector removes
* or replaces this node then points to the current target. Can be null
* if the node is removed.
*/
private AbstractInsnNode currentTarget;
/**
* Injector decorations on this node
*/
private Map<Object, Object> decorations;
/**
* Create a new node wrapper for the specified target node
*
* @param node target node
*/
public InjectionNode(AbstractInsnNode node) {
this.currentTarget = this.originalTarget = node;
}
/**
* Get the original target of this node
*/
public AbstractInsnNode getOriginalTarget() {
return this.originalTarget;
}
/**
* Get the current target of this node, can be null if the node was
* replaced
*/
public AbstractInsnNode getCurrentTarget() {
return this.currentTarget;
}
/**
* Replace this node with the specified target
*
* @param target new node
*/
public InjectionNode replace(AbstractInsnNode target) {
this.currentTarget = target;
return this;
}
/**
* Remove the node
*/
public InjectionNode remove() {
this.currentTarget = null;
return this;
}
/**
* Checks whether the original or current target of this node match the
* specified node
*
* @param node node to check
* @return true if the supplied node matches either of this node's
* internal identities
*/
public boolean matches(AbstractInsnNode node) {
return this.originalTarget == node || this.currentTarget == node;
}
/**
* Get whether this node has been replaced
*/
public boolean isReplaced() {
return this.originalTarget != this.currentTarget;
}
/**
* Get whether this node has been removed
*/
public boolean isRemoved() {
return this.currentTarget == null;
}
/**
* Decorate this node with arbitrary metadata for injector arbitration
*
* @param key meta key
* @param value meta value
*/
public <K, V> InjectionNode decorate(K key, V value) {
if (this.decorations == null) {
this.decorations = new HashMap<Object, Object>();
}
this.decorations.put(key, value);
return this;
}
/**
* Get whether this node is decorated with the specified key
*
* @param key meta key
* @return true if the specified decoration exists
*/
public <K> boolean hasDecoration(K key) {
return this.decorations != null && this.decorations.get(key) != null;
}
/**
* Get the specified decoration
*
* @param key meta key
* @return decoration value or null if absent
*/
@SuppressWarnings("unchecked")
public <K, V> V getDecoration(K key) {
return (V) (this.decorations == null ? null : this.decorations.get(key));
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(InjectionNode other) {
return other == null ? Integer.MAX_VALUE : this.hashCode() - other.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("InjectionNode[%s]", ASMHelper.getNodeDescriptionForDebug(this.currentTarget));
}
}
/**
* Add a tracked node to this collection if it does not already exist
*
* @param node Instruction node to add
* @return wrapper for the specified node
*/
public InjectionNode add(AbstractInsnNode node) {
InjectionNode injectionNode = this.get(node);
if (injectionNode == null) {
injectionNode = new InjectionNode(node);
this.add(injectionNode);
}
return injectionNode;
}
/**
* Get a tracked node from this collection if it already exists, returns
* null if the node is not tracked
*
* @param node instruction node
* @return wrapper node or null if not tracked
*/
public InjectionNode get(AbstractInsnNode node) {
for (InjectionNode injectionNode : this) {
if (injectionNode.matches(node)) {
return injectionNode;
}
}
return null;
}
/**
* Get whether this collection contains a mapping for the specified insn
*
* @param node instruction node to check
* @return true if a wrapper exists for the node
*/
public boolean contains(AbstractInsnNode node) {
return this.get(node) != null;
}
/**
* Replace the specified node with the new node, does not update the wrapper
* if no wrapper exists for <tt>oldNode</tt>
*
* @param oldNode node being replaced
* @param newNode node to replace with
*/
public void replace(AbstractInsnNode oldNode, AbstractInsnNode newNode) {
InjectionNode injectionNode = this.get(oldNode);
if (injectionNode != null) {
injectionNode.replace(newNode);
}
}
/**
* Mark the specified node as removed, does not update the wrapper if no
* wrapper exists
*
* @param node node being removed
*/
public void remove(AbstractInsnNode node) {
InjectionNode injectionNode = this.get(node);
if (injectionNode != null) {
injectionNode.remove();
}
}
}
@@ -24,6 +24,7 @@
*/
package org.spongepowered.asm.mixin.injection;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
@@ -31,9 +32,14 @@ import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal;
import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.points.AfterInvoke;
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
import org.spongepowered.asm.mixin.injection.points.BeforeInvoke;
@@ -43,6 +49,7 @@ import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke;
import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint;
import org.spongepowered.asm.mixin.injection.points.MethodHead;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
@@ -143,12 +150,12 @@ public abstract class InjectionPoint {
super(points);
}
@SuppressWarnings("unchecked")
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
boolean found = false;
@SuppressWarnings({ "unchecked", "rawtypes" })
ArrayList<AbstractInsnNode>[] allNodes = new ArrayList[this.components.length];
ArrayList<AbstractInsnNode>[] allNodes = (ArrayList<AbstractInsnNode>[]) Array.newInstance(ArrayList.class, this.components.length);
for (int i = 0; i < this.components.length; i++) {
allNodes[i] = new ArrayList<AbstractInsnNode>();
@@ -308,12 +315,15 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param at {@link At} annotation to parse information from
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, At at) {
return InjectionPoint.parse(mixin, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, At at) {
List<String> args = Arrays.asList(at.args());
return InjectionPoint.parse(mixin, method, parent, at.value(), at.shift(), at.by(), args, at.target(), at.ordinal(), at.opcode());
}
/**
@@ -322,11 +332,13 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param node {@link At} annotation to parse information from
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, AnnotationNode node) {
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, AnnotationNode node) {
String at = ASMHelper.<String>getAnnotationValue(node, "value");
List<String> args = ASMHelper.<List<String>>getAnnotationValue(node, "args");
String target = ASMHelper.<String>getAnnotationValue(node, "target", "");
@@ -339,7 +351,7 @@ public abstract class InjectionPoint {
args = ImmutableList.<String>of();
}
return InjectionPoint.parse(mixin, at, shift, by, args, target, ordinal, opcode);
return InjectionPoint.parse(mixin, method, parent, at, shift, by, args, target, ordinal, opcode);
}
/**
@@ -348,6 +360,8 @@ public abstract class InjectionPoint {
*
* @param mixin Data for the mixin containing the annotation, used to obtain
* the refmap, amongst other things
* @param method The annotated handler method
* @param parent The parent annotation which owns this {@link At} annotation
* @param at Injection point specifier
* @param shift Shift type to apply
* @param by Amount of shift to apply for the BY shift type
@@ -358,9 +372,9 @@ public abstract class InjectionPoint {
* @return InjectionPoint parsed from the supplied data or null if parsing
* failed
*/
public static InjectionPoint parse(MixinTargetContext mixin, String at, At.Shift shift, int by,
public static InjectionPoint parse(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, At.Shift shift, int by,
List<String> args, String target, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode);
InjectionPointData data = new InjectionPointData(mixin, method, parent, at, args, target, ordinal, opcode);
InjectionPoint point = null;
if (BeforeFieldAccess.CODE.equals(at)) {
@@ -379,6 +393,12 @@ public abstract class InjectionPoint {
point = new MethodHead(data);
} else if (AfterInvoke.CODE.equals(at)) {
point = new AfterInvoke(data);
} else if (BeforeLoadLocal.CODE.equals(at)) {
LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent);
point = new BeforeLoadLocal(mixin, Type.getReturnType(method.desc), discriminator, data);
} else if (AfterStoreLocal.CODE.equals(at)) {
LocalVariableDiscriminator discriminator = LocalVariableDiscriminator.parse(parent);
point = new AfterStoreLocal(mixin, Type.getReturnType(method.desc), discriminator, data);
} else if (at.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) {
try {
@SuppressWarnings("unchecked") Class<? extends InjectionPoint> cls = (Class<? extends InjectionPoint>) Class.forName(at);
@@ -0,0 +1,274 @@
/*
* 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.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information store for injector groups
*/
public class InjectorGroupInfo {
/**
* Storage for injector groups
*/
public static final class Map extends HashMap<String, InjectorGroupInfo> {
private static final long serialVersionUID = 1L;
private static final InjectorGroupInfo NO_GROUP = new InjectorGroupInfo("NONE", true);
@Override
public InjectorGroupInfo get(Object key) {
return this.forName(key.toString());
}
/**
* Get group for the specified name, creates the group in this map if
* it does not already exist
*
* @param name Name of group to fetch
* @return Existing group or new group if none was previously declared
*/
public InjectorGroupInfo forName(String name) {
InjectorGroupInfo value = super.get(name);
if (value == null) {
value = new InjectorGroupInfo(name);
this.put(name, value);
}
return value;
}
/**
* Parse a group from the specified method, use the default group name
* if no group name is specified on the annotation
*
* @param method (Possibly) annotated method
* @param defaultGroup Default group name to use
* @return Group or NO_GROUP if no group
*/
public InjectorGroupInfo parseGroup(MethodNode method, String defaultGroup) {
return this.parseGroup(ASMHelper.getInvisibleAnnotation(method, Group.class), defaultGroup);
}
/**
* Parse a group from the specified annotation, use the default group
* name if no group name is specified on the annotation
*
* @param annotation Annotation or null
* @param defaultGroup Default group name to use
* @return Group or NO_GROUP if no group
*/
public InjectorGroupInfo parseGroup(AnnotationNode annotation, String defaultGroup) {
if (annotation == null) {
return InjectorGroupInfo.Map.NO_GROUP;
}
String name = ASMHelper.<String>getAnnotationValue(annotation, "name");
if (name == null || name.isEmpty()) {
name = defaultGroup;
}
InjectorGroupInfo groupInfo = this.forName(name);
Integer min = ASMHelper.<Integer>getAnnotationValue(annotation, "min");
if (min != null && min.intValue() != -1) {
groupInfo.setMinRequired(min.intValue());
}
Integer max = ASMHelper.<Integer>getAnnotationValue(annotation, "max");
if (max != null && max.intValue() != -1) {
groupInfo.setMaxAllowed(max.intValue());
}
return groupInfo;
}
/**
* Validate all groups in this collection
*
* @throws InjectionValidationException if validation fails
*/
public void validateAll() throws InjectionValidationException {
for (InjectorGroupInfo group : this.values()) {
group.validate();
}
}
}
/**
* Group name
*/
private final String name;
/**
* Members of this group
*/
private final List<InjectionInfo> members = new ArrayList<InjectionInfo>();
/**
* True if this is the default group
*/
private final boolean isDefault;
/**
* Number of callbacks we require injected across this group
*/
private int minCallbackCount = -1;
/**
* Maximum number of callbacks allowed across this group
*/
private int maxCallbackCount = Integer.MAX_VALUE;
public InjectorGroupInfo(String name) {
this(name, false);
}
InjectorGroupInfo(String name, boolean flag) {
this.name = name;
this.isDefault = flag;
}
@Override
public String toString() {
return String.format("@Group(name=%s, min=%d, max=%d)", this.getName(), this.getMinRequired(), this.getMaxAllowed());
}
public boolean isDefault() {
return this.isDefault;
}
public String getName() {
return this.name;
}
public int getMinRequired() {
return Math.max(this.minCallbackCount, 1);
}
public int getMaxAllowed() {
return Math.min(this.maxCallbackCount, Integer.MAX_VALUE);
}
/**
* Get all members of this group as a read-only collection
*
* @return read-only view of group members
*/
public Collection<InjectionInfo> getMembers() {
return Collections.unmodifiableCollection(this.members);
}
/**
* Set the required minimum value for this group. Since this is normally
* done on the first {@link Group} annotation it is considered a
* warning-level event if a later annotation sets a different value. The
* highest value specified on all annotations is always used.
*
* @param min new value for min required
*/
public void setMinRequired(int min) {
if (min < 1) {
throw new IllegalArgumentException("Cannot set zero or negative value for injector group min count. Attempted to set min="
+ min + " on " + this);
}
if (this.minCallbackCount > 0 && this.minCallbackCount != min) {
LogManager.getLogger("mixin").warn("Conflicting min value '{}' on @Group({}), previously specified {}", min, this.name,
this.minCallbackCount);
}
this.minCallbackCount = Math.max(this.minCallbackCount, min);
}
/**
* Set the required minimum value for this group. Since this is normally
* done on the first {@link Group} annotation it is considered a
* warning-level event if a later annotation sets a different value. The
* highest value specified on all annotations is always used.
*
* @param max new value for max allowed
*/
public void setMaxAllowed(int max) {
if (max < 1) {
throw new IllegalArgumentException("Cannot set zero or negative value for injector group max count. Attempted to set max="
+ max + " on " + this);
}
if (this.maxCallbackCount < Integer.MAX_VALUE && this.maxCallbackCount != max) {
LogManager.getLogger("mixin").warn("Conflicting max value '{}' on @Group({}), previously specified {}", max, this.name,
this.maxCallbackCount);
}
this.maxCallbackCount = Math.min(this.maxCallbackCount, max);
}
/**
* Add a new member to this group
*
* @param member injector to add
* @return fluent interface
*/
public InjectorGroupInfo add(InjectionInfo member) {
this.members.add(member);
return this;
}
/**
* Validate all members in this group
*
* @return fluent interface
* @throws InjectionValidationException if validation fails
*/
public InjectorGroupInfo validate() throws InjectionValidationException {
if (this.members.size() == 0) {
// I have no idea how we got here, but it's not an error :/
return this;
}
int total = 0;
for (InjectionInfo member : this.members) {
total += member.getInjectedCallbackCount();
}
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));
} else if (total > max) {
throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total));
}
return this;
}
}
@@ -29,6 +29,11 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
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}.
@@ -86,4 +91,47 @@ public @interface ModifyArg {
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -0,0 +1,135 @@
/*
* 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.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* Specifies that this mixin method should inject a constant modifier callback
* to itself in the target method(s) identified by {@link #method} at the
* specified LDC (or specialised const opcode) instruction in order to adjust
* the constant value returned.
*
* <p><tt>ModifyConstant</tt> callbacks should always take one argument of the
* appropriate constant type and return the same type. For example a
* <tt>ModifyConstant </tt> for a local of type {@link String} should have the
* signature:</p>
*
* <code>private String methodName(String variable) { ...</code>
*
* <p>The callback receives the original value of the constant, and should
* return the new value.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ModifyConstant {
/**
* String representation of a
* {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo
* MemberInfo} which identifies the target method.
*
* @return method to inject into
*/
public String method();
/**
* Discriminator for the constant to match (injection point), if not
* specified then all constants matching the annotated handler's return type
* are matched
*
* @return the constant discriminator
*/
public Constant constant() default @Constant;
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link ModifyConstant} methods since it is
* anticipated that in general the target of a {@link ModifyConstant}
* annotation will be an obfuscated method in the target class. However
* since it is possible to also apply mixins to non-obfuscated targets (or
* non- obfuscated methods in obfuscated targets, such as methods added by
* Forge) it may be necessary to suppress the compiler error which would
* otherwise be generated. Setting this value to <em>false</em> will cause
* the annotation processor to skip this annotation when attempting to build
* the obfuscation table for the mixin.
*
* @return True to instruct the annotation processor to search for
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -0,0 +1,198 @@
/*
* 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.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
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}.
*
* <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>
*
* <code>private String methodName(String variable) { ...</code>
*
* <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>.
*
* <p>In <em>explicit</em> mode, the variable to capture can be specified by
* specifying values for the discriminator arguments {@link #ordinal},
* {@link #index} and {@link #name}. The injector uses the discriminators in
* order to attempt to locate the variable to capture. If no local variable
* matches any discriminators, the capture fails.</p>
*
* <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>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ModifyVariable {
/**
* String representation of a
* {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo
* MemberInfo} which identifies the target method.
*
* @return target method
*/
public String method();
/**
* An {@link At} annotation which describes the {@link InjectionPoint} in
* the target method. The specified {@link InjectionPoint} <i>must only</i>
* return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances
* and an exception will be thrown if this is not the case.
*
* @return {@link At} which identifies the target method invocation
*/
public At at();
/**
* When creating a {@link ModifyVariable} callback, you may wish to first
* inspect the local variable table in the target method at the injection
* point. Set this value to <tt>true</tt> to print the local variable table
* and perform no injection.
*
* @return true to print the LVT to the console
*/
public boolean print() default false;
/**
* Gets the local variable ordinal by type. For example, if there are 3
* {@link String} arguments in the local variable table, ordinal 0 specifies
* the first, 1 specifies the second, etc. Use <tt>ordinal</tt> when the
* index within the LVT is known. Takes precedence over {@link #index}.
*
* @return variable ordinal
*/
public int ordinal() default -1;
/**
* Gets the absolute index of the local variable within the local variable
* table to capture. The local variable at the specified index must be of
* the same type as the capture. Takes precedence over {@link #name}.
*
* @return argument index to modify or -1 for automatic
*/
public int index() default -1;
/**
* Gets the name of the variable to capture. Only used if the variable
* cannot be located via {@link #ordinal} or {@link #index}.
*
* @return possible names to capture, only useful when the LVT in the target
* method is known to be complete.
*/
public String[] name() default {};
/**
* Under normal circumstances the injector will consider all local variables
* including method arguments and all other local variables. This involves
* reading (and possibly generating) the local variable table for the method
* which can have mixed results. Set this value to <tt>true</tt> to <i>only
* </i> consider method arguments.
*
* @return true if this injector should only consider method arguments and
* not all locals.
*/
public boolean argsOnly() default false;
/**
* By default, the annotation processor will attempt to locate an
* obfuscation mapping for all {@link ModifyVariable} methods since it is
* anticipated that in general the target of a {@link ModifyVariable}
* annotation will be an obfuscated method in the target class. However
* since it is possible to also apply mixins to non-obfuscated targets (or
* non- obfuscated methods in obfuscated targets, such as methods added by
* Forge) it may be necessary to suppress the compiler error which would
* otherwise be generated. Setting this value to <em>false</em> will cause
* the annotation processor to skip this annotation when attempting to build
* the obfuscation table for the mixin.
*
* @return True to instruct the annotation processor to search for
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -29,9 +29,16 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
/**
* <p>Specifies that this mixin method should redirect the specified
* {@link #method} call to the method decorated with this annotation.</p>
* method call or field access to the method decorated with this annotation.</p>
*
* <h4>Method Redirect Mode</h4>
*
* <p>The handler method signature must match the hooked method precisely
* <b>but</b> prepended with an arg of the owning object's type to accept the
@@ -68,6 +75,42 @@ import java.lang.annotation.Target;
* <pre>public boolean barProxy(Foo someObject, int abc, int def,
* int someInt, String someString)</pre>
* </blockquote>
*
* <h4>Field Access Redirect Mode</h4>
*
* <p>The handler method signature varies depending on whether the redirector is
* handling a field <b>write</b> (<tt>PUTFIELD</tt>, <tt>PUTSTATIC</tt>) or a
* field <b>read</b> (<tt>GETFIELD</tt>, <tt>GETSTATIC</tt>).</p>
*
* <table width="100%">
* <tr>
* <th>Operation (OPCODE)</th>
* <th>Handler signature</th>
* </tr>
* <tr>
* <td>Read static field (<tt>GETSTATIC</tt>)</td>
* <td><code>private <b>FieldType</b> getFieldValue()</code></td>
* </tr>
* <tr>
* <td>Read instance field (<tt>GETFIELD</tt>)</td>
* <td><code>private <b>FieldType</b> getFieldValue(<b>OwnerType</b>
* owner)</code></td>
* </tr>
* <tr>
* <td>Write static field (<tt>PUTSTATIC</tt>)</td>
* <td><code>private void setFieldValue(<b>FieldType</b> value)</code></td>
* </tr>
* <tr>
* <td>Write instance field (<tt>PUTFIELD</tt>)</td>
* <td><code>private void getFieldValue(<b>OwnerType</b>
* owner, <b>FieldType</b> value)</code></td>
* </tr>
* </table>
*
* <p>It is also possible to capture the arguments of the target method in
* addition to the arguments being passed to the method call (for example in
* the code above this would be the <em>someInt</em> and <em>someString</em>
* arguments) by appending the arguments to the method signature.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -108,4 +151,47 @@ public @interface Redirect {
* obfuscation mappings for this annotation
*/
public boolean remap() default true;
/**
* In general, injectors are intended to "fail soft" in that a failure to
* locate the injection point in the target method is not considered an
* error condition. Another transformer may have changed the method
* structure or any number of reasons may cause an injection to fail. This
* also makes it possible to define several injections to achieve the same
* task given <em>expected</em> mutation of the target class and the
* injectors which fail are simply ignored.
*
* <p>However, this behaviour is not always desirable. For example, if your
* application depends on a particular injection succeeding you may wish to
* detect the injection failure as an error condition. This argument is thus
* provided to allow you to stipulate a <b>minimum</b> number of successful
* injections for this callback handler. If the number of injections
* specified is not achieved then an {@link InjectionError} is thrown at
* application time. Use this option with care.</p>
*
* @return Minimum required number of injected callbacks, default specified
* by the containing config
*/
public int require() default -1;
/**
* Like {@link #require()} but only enabled if the
* {@link Option#DEBUG_INJECTORS mixin.debug.countInjections} option is set
* to <tt>true</tt> and defaults to 1. Use this option during debugging to
* perform simple checking of your injectors. Causes the injector to throw
* a {@link InvalidInjectionException} if the expected number of injections
* is not realised.
*
* @return Minimum number of <em>expected</em> callbacks, default 1
*/
public int expect() default 1;
/**
* Returns constraints which must be validated for this injector to
* succeed. See {@link Constraint} for details of constraint formats.
*
* @return Constraints for this annotation
*/
public String constraints() default "";
}
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to decorate surrogate injector methods. See
* {@link Inject#locals()} for information.
@@ -25,6 +25,8 @@
package org.spongepowered.asm.mixin.injection.callback;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.util.Constants;
/**
* CallbackInfo instances are passed to callbacks in order to provide
@@ -34,9 +36,6 @@ import org.spongepowered.asm.lib.Type;
*/
public class CallbackInfo implements Cancellable {
protected static final String STRING = "Ljava/lang/String;";
protected static final String OBJECT = "Ljava/lang/Object;";
/**
* Method name being injected into, this is useful if a single callback is
* injecting into multiple methods.
@@ -65,11 +64,13 @@ public class CallbackInfo implements Cancellable {
}
/**
* Get the method name where this callback originated
* Get the ID of the injector which defined this callback. This defaults to
* the method name but can be overridden by specifying the {@link Inject#id}
* parameter on the injector
*
* @return the name of the calling method
* @return the injector ID
*/
public String getName() {
public String getId() {
return this.name;
}
@@ -118,15 +119,15 @@ public class CallbackInfo implements Cancellable {
return CallbackInfo.getConstructorDescriptor();
}
if (returnType.getSort() == Type.OBJECT) {
return String.format("(%sZ%s)V", CallbackInfo.STRING, CallbackInfo.OBJECT);
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
return String.format("(%sZ%s)V", Constants.STRING, Constants.OBJECT);
}
return String.format("(%sZ%s)V", CallbackInfo.STRING, returnType.getDescriptor());
return String.format("(%sZ%s)V", Constants.STRING, returnType.getDescriptor());
}
static String getConstructorDescriptor() {
return String.format("(%sZ)V", CallbackInfo.STRING);
return String.format("(%sZ)V", Constants.STRING);
}
static String getIsCancelledMethodName() {
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin.injection.callback;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.util.Constants;
/**
* For callbacks with a non-void return type, a CallbackInfoReturnable is passed
@@ -124,7 +125,7 @@ public class CallbackInfoReturnable<R> extends CallbackInfo {
// CHECKSTYLE:ON
static String getReturnAccessor(Type returnType) {
if (returnType.getSort() == Type.OBJECT) {
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
return "getReturnValue";
}
@@ -132,8 +133,8 @@ public class CallbackInfoReturnable<R> extends CallbackInfo {
}
static String getReturnDescriptor(Type returnType) {
if (returnType.getSort() == Type.OBJECT) {
return String.format("()%s", CallbackInfo.OBJECT);
if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) {
return String.format("()%s", Constants.OBJECT);
}
return String.format("()%s", returnType.getDescriptor());
@@ -27,26 +27,27 @@ package org.spongepowered.asm.mixin.injection.callback;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.*;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.InjectionError;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.points.BeforeReturn;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
import com.google.common.base.Strings;
/**
* This class is responsible for generating the bytecode for injected callbacks
*/
@@ -148,10 +149,10 @@ public class CallbackInjector extends Injector {
*/
private boolean captureArgs = true;
Callback(MethodNode handler, Target target, final AbstractInsnNode node, final LocalVariableNode[] locals, boolean captureLocals) {
Callback(MethodNode handler, Target target, final InjectionNode node, final LocalVariableNode[] locals, boolean captureLocals) {
this.handler = handler;
this.target = target;
this.node = node;
this.node = node.getCurrentTarget();
this.locals = locals;
this.localTypes = locals != null ? new Type[locals.length] : null;
this.frameSize = ASMHelper.getFirstNonArgLocalIndex(target.arguments, !CallbackInjector.this.isStatic());
@@ -260,7 +261,7 @@ public class CallbackInjector extends Injector {
return false; // No @Coerce specified, types must match
}
boolean canCoerce = CallbackInjector.canCoerce(inTypes[arg], myTypes[arg]);
boolean canCoerce = Injector.canCoerce(inTypes[arg], myTypes[arg]);
if (!canCoerce) {
return false; // Can't coerce source type to local type, give up
}
@@ -277,8 +278,6 @@ public class CallbackInjector extends Injector {
}
}
private final Logger logger = LogManager.getLogger("mixin");
/**
* True if cancellable
*/
@@ -289,6 +288,11 @@ public class CallbackInjector extends Injector {
*/
private final LocalCapture localCapture;
/**
* ID to return from callbackinfo
*/
private final String identifier;
/**
* Make a new CallbackInjector with the supplied args
*
@@ -297,10 +301,11 @@ public class CallbackInjector extends Injector {
* be cancellable
* @param localCapture Local variable capture behaviour
*/
public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture) {
public CallbackInjector(InjectionInfo info, boolean cancellable, LocalCapture localCapture, String identifier) {
super(info);
this.cancellable = cancellable;
this.localCapture = localCapture;
this.identifier = identifier;
}
/* (non-Javadoc)
@@ -310,15 +315,17 @@ public class CallbackInjector extends Injector {
*/
@Override
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
super.sanityCheck(target, injectionPoints);
if (ASMHelper.methodIsStatic(target.method) != this.isStatic) {
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this.methodNode.name);
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this);
}
if (Constants.INIT.equals(target.method.name)) {
if (Constants.CTOR.equals(target.method.name)) {
for (InjectionPoint injectionPoint : injectionPoints) {
if (!injectionPoint.getClass().equals(BeforeReturn.class)) {
throw new InvalidInjectionException(this.info, "Found injection point type " + injectionPoint.getClass().getSimpleName()
+ " targetting a ctor in " + this.classNode.name + ". Only RETURN allowed for a ctor target");
+ " targetting a ctor in " + this + ". Only RETURN allowed for a ctor target");
}
}
}
@@ -330,11 +337,11 @@ public class CallbackInjector extends Injector {
* org.objectweb.asm.tree.AbstractInsnNode)
*/
@Override
protected void inject(Target target, AbstractInsnNode node) {
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);
locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget());
}
this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals()));
@@ -357,7 +364,7 @@ public class CallbackInjector extends Injector {
MethodNode callbackMethod = this.methodNode;
if (!callback.checkDescriptor(this.methodNode.desc)) {
if (this.info.getTargets().size() != 0) {
if (this.info.getTargets().size() > 1) {
return; // Look for a match in other targets before failing
}
@@ -367,24 +374,24 @@ public class CallbackInjector extends Injector {
// signature for the current locals. This allows silent failover
// if changes to the local variable table are EXPECTED for some
// reason.
MethodNode handler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (handler != null && ASMHelper.getVisibleAnnotation(handler, Surrogate.class) != null) {
MethodNode surrogateHandler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (surrogateHandler != null && ASMHelper.getVisibleAnnotation(surrogateHandler, Surrogate.class) != null) {
// Found a matching method, use it
callbackMethod = handler;
callbackMethod = surrogateHandler;
} else {
// No matching method, generate a message to bitch about it
String message = this.generateBadLVTMessage(callback);
switch (this.localCapture) {
case CAPTURE_FAILEXCEPTION:
this.logger.error("Injection error: {}", message);
Injector.logger.error("Injection error: {}", message);
callbackMethod = this.generateErrorMethod(callback, "org/spongepowered/asm/mixin/injection/InjectionError", message);
break;
case CAPTURE_FAILSOFT:
this.logger.warn("Injection warning: {}", message);
Injector.logger.warn("Injection warning: {}", message);
return;
default:
this.logger.error("Critical injection failure: {}", message);
Injector.logger.error("Critical injection failure: {}", message);
throw new InjectionError(message);
}
}
@@ -397,20 +404,29 @@ public class CallbackInjector extends Injector {
if (callback.checkDescriptor(returnableSig)) {
// Switching out CallbackInfo for CallbackInfoReturnable
// worked, so notify the user that they done derped
throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: CallbackInfoReturnable is required!");
throw new InvalidInjectionException(this.info, "Invalid descriptor on " + this.info + "! CallbackInfoReturnable is required!");
}
throw new InvalidInjectionException(this.info, "Invalid descriptor on callback: expected " + callback.getDescriptor()
+ " but found " + this.methodNode.desc);
MethodNode surrogateHandler = ASMHelper.findMethod(this.classNode, this.methodNode.name, callback.getDescriptor());
if (surrogateHandler != null && ASMHelper.getVisibleAnnotation(surrogateHandler, Surrogate.class) != null) {
// Found a matching surrogate method, use it
callbackMethod = surrogateHandler;
} else {
throw new InvalidInjectionException(this.info, "Invalid descriptor on " + this.info + "! Expected " + callback.getDescriptor()
+ " but found " + this.methodNode.desc);
}
}
}
this.createCallbackInfo(callback);
this.dupReturnValue(callback);
if (this.cancellable) {
this.createCallbackInfo(callback, true);
}
this.invokeCallback(callback, callbackMethod);
this.injectCancellationCode(callback);
callback.inject();
this.info.getTargets().clear();
this.info.notifyInjected(callback.target);
}
/**
@@ -422,9 +438,9 @@ public class CallbackInjector extends Injector {
private String generateBadLVTMessage(final Callback callback) {
int position = callback.target.method.instructions.indexOf(callback.node);
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
List<String> found = CallbackInjector.summariseLocals(callback.localTypes, callback.frameSize);
String message = String.format("LVT in %s::%s has incompatible changes at opcode %d in callback %s%s.\nExpected: %s\n Found:%s",
this.classNode.name, callback.target.method.name, position, this.methodNode.name, this.methodNode.desc, expected, found);
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), callback.frameSize);
String message = 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);
return message;
}
@@ -444,7 +460,7 @@ public class CallbackInjector extends Injector {
insns.add(new TypeInsnNode(Opcodes.NEW, errorClass));
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new LdcInsnNode(message));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, Constants.INIT, "(Ljava/lang/String;)V", false));
insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, errorClass, Constants.CTOR, "(Ljava/lang/String;)V", false));
insns.add(new InsnNode(Opcodes.ATHROW));
return method;
}
@@ -461,12 +477,12 @@ public class CallbackInjector extends Injector {
handlerSig.setModifiers(this.methodNode);
PrettyPrinter printer = new PrettyPrinter();
printer.add("%20s : %s", "Target Class", this.classNode.name.replace('/', '.'));
printer.add("%20s : %s", "Target Method", methodSig);
printer.add("%20s : %d", "Target Max LOCALS", callback.target.getMaxLocals());
printer.add("%20s : %d", "Initial Frame Size", callback.frameSize);
printer.add("%20s : %s", "Callback Name", this.methodNode.name);
printer.add("%20s : %s %s", "Instruction", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode()));
printer.kv("Target Class", this.classNode.name.replace('/', '.'));
printer.kv("Target Method", methodSig);
printer.kv("Target Max LOCALS", callback.target.getMaxLocals());
printer.kv("Initial Frame Size", callback.frameSize);
printer.kv("Callback Name", this.methodNode.name);
printer.kv("Instruction", "%s %s", callback.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(callback.node.getOpcode()));
printer.hr();
if (callback.locals.length > callback.frameSize) {
printer.add(" %s %20s %s", "LOCAL", "TYPE", "NAME");
@@ -489,15 +505,27 @@ public class CallbackInjector extends Injector {
/**
* @param callback callback handle
* @param store store the callback info in a local variable
*/
private void createCallbackInfo(final Callback callback) {
this.dupReturnValue(callback);
callback.add(new TypeInsnNode(Opcodes.NEW, callback.target.callbackInfoClass), true, false);
private void createCallbackInfo(final Callback callback, boolean store) {
callback.add(new TypeInsnNode(Opcodes.NEW, callback.target.callbackInfoClass), true, !store);
callback.add(new InsnNode(Opcodes.DUP), true, true);
this.invokeCallbackInfoCtor(callback);
callback.add(new VarInsnNode(Opcodes.ASTORE, callback.marshallVar));
this.invokeCallbackInfoCtor(callback, store);
if (store) {
callback.add(new VarInsnNode(Opcodes.ASTORE, callback.marshallVar));
}
}
/**
* @param callback callback handle
*/
private void loadOrCreateCallbackInfo(final Callback callback) {
if (this.cancellable) {
callback.add(new VarInsnNode(Opcodes.ALOAD, callback.marshallVar), false, true);
} else {
this.createCallbackInfo(callback, false);
}
}
/**
@@ -519,18 +547,20 @@ public class CallbackInjector extends Injector {
/**
* @param callback callback handle
* @param store true if storing in a local, false if this is happening at an
* invoke
*/
protected void invokeCallbackInfoCtor(final Callback callback) {
callback.add(new LdcInsnNode(callback.target.method.name), true, false);
callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, false);
protected void invokeCallbackInfoCtor(final Callback callback, boolean store) {
callback.add(new LdcInsnNode(this.getIdentifier(callback)), true, !store);
callback.add(new InsnNode(this.cancellable ? Opcodes.ICONST_1 : Opcodes.ICONST_0), true, !store);
if (callback.isAtReturn) {
callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar));
callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ILOAD), callback.marshallVar), true, !store);
callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
callback.target.callbackInfoClass, Constants.INIT, CallbackInfo.getConstructorDescriptor(callback.target.returnType), false));
callback.target.callbackInfoClass, Constants.CTOR, CallbackInfo.getConstructorDescriptor(callback.target.returnType), false));
} else {
callback.add(new MethodInsnNode(Opcodes.INVOKESPECIAL,
callback.target.callbackInfoClass, Constants.INIT, CallbackInfo.getConstructorDescriptor(), false));
callback.target.callbackInfoClass, Constants.CTOR, CallbackInfo.getConstructorDescriptor(), false));
}
}
@@ -540,7 +570,7 @@ public class CallbackInjector extends Injector {
private void invokeCallback(final Callback callback, final MethodNode callbackMethod) {
// Push "this" onto the stack if the callback is not static
if (!this.isStatic) {
callback.add(new VarInsnNode(Opcodes.ALOAD, 0));
callback.add(new VarInsnNode(Opcodes.ALOAD, 0), false, true);
}
// Push the target method's parameters onto the stack
@@ -549,7 +579,7 @@ public class CallbackInjector extends Injector {
}
// Push the callback info onto the stack
callback.add(new VarInsnNode(Opcodes.ALOAD, callback.marshallVar), false, true);
this.loadOrCreateCallbackInfo(callback);
// (Maybe) push the locals onto the stack
if (callback.canCaptureLocals) {
@@ -557,7 +587,19 @@ public class CallbackInjector extends Injector {
}
// Call the callback!
this.invokeMethod(callback, callbackMethod);
this.invokeHandler(callback, callbackMethod);
}
/**
* Get the identifier to use for the specified callback. If an id was
* specified by the end user on the annotation then use the value specified,
* otherwise defaults to the target method name.
*
* @param callback Callback being injected
* @return Identifier to use
*/
private String getIdentifier(Callback callback) {
return Strings.isNullOrEmpty(this.identifier) ? callback.target.method.name : this.identifier;
}
/**
@@ -631,21 +673,5 @@ public class CallbackInjector extends Injector {
}
return list;
}
public static boolean canCoerce(Type from, Type to) {
return CallbackInjector.canCoerce(from.getDescriptor(), to.getDescriptor());
}
public static boolean canCoerce(String from, String to) {
if (from.length() > 1 || to.length() > 1) {
return false;
}
return CallbackInjector.canCoerce(from.charAt(0), to.charAt(0));
}
public static boolean canCoerce(char from, char to) {
return to == 'I' && "IBSCZ".indexOf(from) > -1;
}
}
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Interface for things which can be cancelled
*/
@@ -24,6 +24,10 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Exception thrown when a consumer attemtps to call <tt>cancel()</tt> on a
* callback not marked as <tt>cancellable</tt>.
*/
public class CancellationException extends RuntimeException {
private static final long serialVersionUID = 1L;
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.injection.callback;
/**
* Specifies the behaviour for capturing local variables at an injection point.
*
@@ -30,6 +30,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
@@ -37,19 +39,26 @@ import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Joiner;
/**
* Base class for bytecode injectors
*/
public abstract class Injector {
/**
* Log more things
*/
protected static final Logger logger = LogManager.getLogger("mixin");
/**
* Injection info
*/
@@ -64,6 +73,16 @@ public abstract class Injector {
* Callback method
*/
protected final MethodNode methodNode;
/**
* Arguments of the handler method
*/
protected final Type[] methodArgs;
/**
* Return type of the handler method
*/
protected final Type returnType;
/**
* True if the callback method is static
@@ -89,20 +108,46 @@ public abstract class Injector {
private Injector(ClassNode classNode, MethodNode methodNode) {
this.classNode = classNode;
this.methodNode = methodNode;
this.methodArgs = Type.getArgumentTypes(this.methodNode.desc);
this.returnType = Type.getReturnType(this.methodNode.desc);
this.isStatic = ASMHelper.methodIsStatic(this.methodNode);
}
@Override
public String toString() {
return String.format("%s::%s", this.classNode.name, this.methodNode.name);
}
/**
* Inject into the specified method at the specified injection points
* ...
*
* @param target Target method to inject into
* @param injectionPoints InjectionPoint instances which will identify
* target insns in the target method
* @return discovered injection points
*/
public final void injectInto(Target target, List<InjectionPoint> injectionPoints) {
public final List<InjectionNode> find(Target target, List<InjectionPoint> injectionPoints) {
this.sanityCheck(target, injectionPoints);
List<InjectionNode> myNodes = new ArrayList<InjectionNode>();
for (AbstractInsnNode node : this.findTargetNodes(target.method, injectionPoints)) {
this.addTargetNode(target, myNodes, node);
}
return myNodes;
}
protected void addTargetNode(Target target, List<InjectionNode> myNodes, AbstractInsnNode node) {
myNodes.add(target.injectionNodes.add(node));
}
public final void inject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
if (node.isRemoved()) {
if (this.info.getContext().getEnvironment().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target);
}
continue;
}
this.inject(target, node);
}
}
@@ -125,7 +170,7 @@ public abstract class Injector {
for (InjectionPoint injectionPoint : injectionPoints) {
nodes.clear();
if (injectionPoint.find(into.desc, insns, nodes)) {
if (this.findTargetNodes(into, injectionPoint, insns, nodes)) {
targetNodes.addAll(nodes);
}
}
@@ -134,28 +179,63 @@ public abstract class Injector {
return targetNodes;
}
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
// stub for subclasses
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
return injectionPoint.find(into.desc, insns, nodes);
}
protected abstract void inject(Target target, AbstractInsnNode node);
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
if (target.classNode != this.classNode) {
throw new InvalidInjectionException(this.info, "Target class does not match injector class in " + this);
}
}
protected abstract void inject(Target target, InjectionNode node);
/**
* Invoke the handler method
*
* @param insns Instruction list to inject into
* @return injected insn node
*/
protected void invokeHandler(InsnList insns) {
this.invokeMethod(insns, this.methodNode);
protected AbstractInsnNode invokeHandler(InsnList insns) {
return this.invokeHandler(insns, this.methodNode);
}
protected void invokeMethod(InsnList insns, MethodNode methodNode) {
boolean isPrivate = (methodNode.access & Opcodes.ACC_PRIVATE) != 0;
/**
* Invoke a handler method
*
* @param insns Instruction list to inject into
* @param handler Actual method to invoke (may be different if using a
* surrogate)
* @return injected insn node
*/
protected AbstractInsnNode invokeHandler(InsnList insns, MethodNode handler) {
boolean isPrivate = (handler.access & Opcodes.ACC_PRIVATE) != 0;
int invokeOpcode = this.isStatic ? Opcodes.INVOKESTATIC : isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL;
insns.add(new MethodInsnNode(invokeOpcode, this.classNode.name, methodNode.name, methodNode.desc, false));
MethodInsnNode insn = new MethodInsnNode(invokeOpcode, this.classNode.name, handler.name, handler.desc, false);
insns.add(insn);
this.info.addCallbackInvocation(handler);
return insn;
}
protected static String printArgs(Type[] args) {
return "(" + Joiner.on("").join(args) + ")";
}
public static boolean canCoerce(Type from, Type to) {
return Injector.canCoerce(from.getDescriptor(), to.getDescriptor());
}
public static boolean canCoerce(String from, String to) {
if (from.length() > 1 || to.length() > 1) {
return false;
}
return Injector.canCoerce(from.charAt(0), to.charAt(0));
}
public static boolean canCoerce(char from, char to) {
return to == 'I' && "IBSCZ".indexOf(from) > -1;
}
}
@@ -32,27 +32,18 @@ import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
/**
* Base class for injectors which inject at method invokes
*/
public abstract class InvokeInjector extends Injector {
/**
* Arguments of the handler method
*/
protected final Type[] methodArgs;
/**
* Return type of the handler method
*/
protected final Type returnType;
protected final String annotationType;
/**
@@ -61,8 +52,6 @@ public abstract class InvokeInjector extends Injector {
*/
public InvokeInjector(InjectionInfo info, String annotationType) {
super(info);
this.methodArgs = Type.getArgumentTypes(this.methodNode.desc);
this.returnType = Type.getReturnType(this.methodNode.desc);
this.annotationType = annotationType;
}
@@ -73,8 +62,18 @@ public abstract class InvokeInjector extends Injector {
*/
@Override
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
super.sanityCheck(target, injectionPoints);
this.checkTarget(target);
}
/**
* Sanity checks on target
*
* @param target target
*/
protected void checkTarget(Target target) {
if (target.isStatic != this.isStatic) {
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this.methodNode.name);
throw new InvalidInjectionException(this.info, "'static' modifier of callback method does not match target in " + this);
}
}
@@ -84,13 +83,13 @@ public abstract class InvokeInjector extends Injector {
* org.objectweb.asm.tree.AbstractInsnNode)
*/
@Override
protected void inject(Target target, AbstractInsnNode node) {
if (!(node instanceof MethodInsnNode)) {
throw new InvalidInjectionException(this.info, this.annotationType + " annotation is targetting a non-method insn in " + target
+ " in " + this.classNode.name);
protected void inject(Target target, InjectionNode node) {
if (!(node.getCurrentTarget() instanceof MethodInsnNode)) {
throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting a non-method insn in " + target
+ " in " + this);
}
this.inject(target, (MethodInsnNode)node);
this.injectAtInvoke(target, node);
}
/**
@@ -99,15 +98,16 @@ public abstract class InvokeInjector extends Injector {
* @param target Target to inject into
* @param node Discovered instruction node
*/
protected abstract void inject(Target target, MethodInsnNode node);
protected abstract void injectAtInvoke(Target target, InjectionNode node);
/**
* @param args handler arguments
* @param insns InsnList to inject insns into
* @param argMap Mapping of args to local variables
* @return injected insn node
*/
protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) {
this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) {
return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
}
/**
@@ -116,13 +116,14 @@ public abstract class InvokeInjector extends Injector {
* @param argMap Mapping of args to local variables
* @param startArg Starting arg to consume
* @param endArg Ending arg to consume
* @return injected insn node
*/
protected void invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) {
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) {
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
this.pushArgs(args, insns, argMap, startArg, endArg);
this.invokeHandler(insns);
return this.invokeHandler(insns);
}
/**
@@ -31,10 +31,11 @@ import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
/**
* A bytecode injector which allows a single argument of a chosen method call to
@@ -76,18 +77,30 @@ public class ModifyArgInjector extends InvokeInjector {
if (this.singleArgMode) {
if (!this.methodArgs[0].equals(this.returnType)) {
throw new InvalidInjectionException(this.info, "@ModifyArg return type must match the parameter type."
throw new InvalidInjectionException(this.info, "@ModifyArg return type on " + this + " must match the parameter type."
+ " ARG=" + this.methodArgs[0] + " RETURN=" + this.returnType);
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.invoke.InvokeInjector
* #checkTarget(org.spongepowered.asm.mixin.injection.struct.Target)
*/
@Override
protected void checkTarget(Target target) {
if (!this.isStatic && target.isStatic) {
throw new InvalidInjectionException(this.info, "non-static callback method " + this + " targets a static method which is not supported");
}
}
/**
* Do the injection
*/
@Override
protected void inject(Target target, MethodInsnNode node) {
Type[] args = Type.getArgumentTypes(node.desc);
protected void injectAtInvoke(Target target, InjectionNode node) {
MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget();
Type[] args = Type.getArgumentTypes(methodNode.desc);
int argIndex = this.findArgIndex(target, args);
InsnList insns = new InsnList();
int extraLocals = 0;
@@ -98,7 +111,7 @@ public class ModifyArgInjector extends InvokeInjector {
extraLocals = this.injectMultiArgHandler(target, args, argIndex, insns);
}
target.insns.insertBefore(node, insns);
target.insns.insertBefore(methodNode, insns);
target.addToLocals(extraLocals);
target.addToStack(2 - (extraLocals - 1));
}
@@ -110,7 +123,7 @@ public class ModifyArgInjector extends InvokeInjector {
int[] argMap = this.storeArgs(target, args, insns, argIndex);
this.invokeHandlerWithArgs(args, insns, argMap, argIndex, argIndex + 1);
this.pushArgs(args, insns, argMap, argIndex + 1, args.length);
return (target.getCurrentMaxLocals() - argMap[argMap.length - 1]) + 1 + args[args.length - 1].getSize();
return (argMap[argMap.length - 1] - target.getMaxLocals()) + args[args.length - 1].getSize();
}
/**
@@ -118,7 +131,7 @@ public class ModifyArgInjector extends InvokeInjector {
*/
private int injectMultiArgHandler(Target target, Type[] args, int argIndex, InsnList insns) {
if (!Arrays.equals(args, this.methodArgs)) {
throw new InvalidInjectionException(this.info, "@ModifyArg method targets a method with an invalid signature "
throw new InvalidInjectionException(this.info, "@ModifyArg method " + this + " targets a method with an invalid signature "
+ Injector.printArgs(args) + ", expected " + Injector.printArgs(this.methodArgs));
}
@@ -126,14 +139,14 @@ public class ModifyArgInjector extends InvokeInjector {
this.pushArgs(args, insns, argMap, 0, argIndex);
this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
this.pushArgs(args, insns, argMap, argIndex + 1, args.length);
return (target.getCurrentMaxLocals() - argMap[argMap.length - 1]) + 1 + args[args.length - 1].getSize();
return (argMap[argMap.length - 1] - target.getMaxLocals()) + args[args.length - 1].getSize();
}
protected int findArgIndex(Target target, Type[] args) {
if (this.index > -1) {
if (this.index >= args.length || !args[this.index].equals(this.returnType)) {
throw new InvalidInjectionException(this.info, "Specified index " + this.index + " for @ModifyArg is invalid for args "
+ Injector.printArgs(args) + ", expected " + this.returnType);
+ Injector.printArgs(args) + ", expected " + this.returnType + " on " + this);
}
return this.index;
}
@@ -147,8 +160,7 @@ public class ModifyArgInjector extends InvokeInjector {
if (argIndex != -1) {
throw new InvalidInjectionException(this.info, "Found duplicate args with index [" + argIndex + ", " + arg + "] matching type "
+ this.returnType + " for @ModifyArg target " + target + " in " + this.classNode.name
+ ". Please specify index of desired arg.");
+ this.returnType + " for @ModifyArg target " + target + " in " + this + ". Please specify index of desired arg.");
}
argIndex = arg;
@@ -156,7 +168,7 @@ public class ModifyArgInjector extends InvokeInjector {
if (argIndex == -1) {
throw new InvalidInjectionException(this.info, "Could not find arg matching type " + this.returnType + " for @ModifyArg target "
+ target + " in " + this.classNode.name);
+ target + " in " + this);
}
return argIndex;
@@ -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.invoke;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
/**
* A bytecode injector which allows a specific
*/
public class ModifyConstantInjector extends RedirectInjector {
/**
* @param info Injection info
*/
public ModifyConstantInjector(InjectionInfo info) {
super(info, "@ModifyConstant");
}
@Override
protected void inject(Target target, InjectionNode node) {
if (!this.preInject(node)) {
return;
}
if (node.isReplaced()) {
throw new UnsupportedOperationException("Target failure for " + this.info);
}
if (ASMHelper.isConstant(node.getCurrentTarget())) {
this.injectConstantModifier(target, node);
return;
}
throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in "
+ target + " in " + this);
}
private void injectConstantModifier(Target target, InjectionNode node) {
final AbstractInsnNode constNode = node.getCurrentTarget();
final Type constantType = ASMHelper.getConstantType(constNode);
final InsnList before = new InsnList();
final InsnList after = new InsnList();
AbstractInsnNode invoke = this.invokeConstantHandler(constNode, constantType, target, before, after);
target.wrapNode(constNode, invoke, before, after);
}
private AbstractInsnNode invokeConstantHandler(AbstractInsnNode targetNode, Type constantType, Target target, InsnList before, InsnList after) {
final String handlerDesc = ASMHelper.generateDescriptor(constantType, constantType);
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
if (!this.isStatic) {
before.add(new VarInsnNode(Opcodes.ALOAD, 0));
target.addToStack(1);
}
if (withArgs) {
this.pushArgs(target.arguments, after, target.argIndices, 0, target.arguments.length);
target.addToStack(ASMHelper.getArgsSize(target.arguments));
}
return this.invokeHandler(after);
}
}
@@ -24,25 +24,36 @@
*/
package org.spongepowered.asm.mixin.injection.invoke;
import java.util.List;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.InsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.ObjectArrays;
import com.google.common.primitives.Ints;
/**
* <p>A bytecode injector which allows a method call to be redirected to the
* annotated handler method. 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 on. For
* example when hooking the following call:</p>
* <p>A bytecode injector which allows a method call or field access to be
* redirected to the annotated handler 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 on. For example when hooking the following
* call:</p>
*
* <blockquote><pre>
* int abc = 0;
@@ -62,27 +73,125 @@ import com.google.common.primitives.Ints;
* <p>For obvious reasons this does not apply for static methods, for static
* methods it is sufficient that the signature simply match the hooked method.
* </p>
*
* <p>For field redirections, see the details in {@link Redirect} for the
* required signature of the handler method.</p>
*/
public class RedirectInjector extends InvokeInjector {
/**
* Meta decoration object for redirector target nodes
*/
class Meta {
public static final String KEY = "redirector";
final int priority;
final boolean isFinal;
final String name;
final String desc;
public Meta(int priority, boolean isFinal, String name, String desc) {
this.priority = priority;
this.isFinal = isFinal;
this.name = name;
this.desc = desc;
}
RedirectInjector getOwner() {
return RedirectInjector.this;
}
}
protected Meta meta;
/**
* @param info Injection info
*/
public RedirectInjector(InjectionInfo info) {
super(info, "@Redirect");
this(info, "@Redirect");
}
protected RedirectInjector(InjectionInfo info, String annotationType) {
super(info, annotationType);
int priority = info.getContext().getPriority();
boolean isFinal = ASMHelper.getVisibleAnnotation(this.methodNode, Final.class) != null;
this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc);
}
@Override
protected void addTargetNode(Target target, List<InjectionNode> myNodes, AbstractInsnNode insn) {
InjectionNode node = target.injectionNodes.get(insn);
if (node != null ) {
Meta other = node.getDecoration(Meta.KEY);
if (other != null && other.getOwner() != this) {
if (other.priority >= this.meta.priority) {
Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}",
this.annotationType, this.info, this.meta.priority, other.name, other.priority);
return;
} else if (other.isFinal) {
throw new InvalidInjectionException(this.info, this.annotationType + " conflict: " + this
+ " failed because target was already remapped by " + other.name);
}
}
}
myNodes.add(target.injectionNodes.add(insn).decorate(Meta.KEY, this.meta));
}
@Override
protected void inject(Target target, InjectionNode node) {
if (!this.preInject(node)) {
return;
}
if (node.isReplaced()) {
throw new UnsupportedOperationException("Redirector target failure for " + this.info);
}
if (node.getCurrentTarget() instanceof MethodInsnNode) {
this.injectAtInvoke(target, node);
return;
}
if (node.getCurrentTarget() instanceof FieldInsnNode) {
this.injectAtFieldAccess(target, node);
return;
}
throw new InvalidInjectionException(this.info, this.annotationType + " annotation on is targetting an invalid insn in "
+ target + " in " + this);
}
protected boolean preInject(InjectionNode node) {
Meta other = node.getDecoration(Meta.KEY);
if (other.getOwner() != this) {
Injector.logger.warn("{} conflict. Skipping {} with priority {}, already redirected by {} with priority {}",
this.annotationType, this.info, this.meta.priority, other.name, other.priority);
return false;
}
return true;
}
/**
* Do the injection
* Redirect a method invocation
*/
@Override
protected void inject(Target target, MethodInsnNode node) {
protected void injectAtInvoke(Target target, InjectionNode node) {
final MethodInsnNode methodNode = (MethodInsnNode)node.getCurrentTarget();
final boolean targetIsStatic = methodNode.getOpcode() == Opcodes.INVOKESTATIC;
final Type ownerType = Type.getType("L" + methodNode.owner + ";");
final Type returnType = Type.getReturnType(methodNode.desc);
final Type[] args = Type.getArgumentTypes(methodNode.desc);
final Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args);
boolean injectTargetParams = false;
boolean targetIsStatic = node.getOpcode() == Opcodes.INVOKESTATIC;
Type ownerType = Type.getType("L" + node.owner + ";");
Type returnType = Type.getReturnType(node.desc);
Type[] args = Type.getArgumentTypes(node.desc);
Type[] stackVars = targetIsStatic ? args : ObjectArrays.concat(ownerType, args);
String desc = Injector.printArgs(stackVars) + returnType;
if (!desc.equals(this.methodNode.desc)) {
@@ -90,23 +199,125 @@ public class RedirectInjector extends InvokeInjector {
if (alternateDesc.equals(this.methodNode.desc)) {
injectTargetParams = true;
} else {
throw new InvalidInjectionException(this.info, "@Redirect handler method has an invalid signature "
+ ", expected " + desc + " found " + this.methodNode.desc);
throw new InvalidInjectionException(this.info, this.annotationType + " handler method " + this
+ " has an invalid signature, expected " + desc + " found " + this.methodNode.desc);
}
}
InsnList insns = new InsnList();
int extraLocals = ASMHelper.getArgsSize(stackVars) + 1;
int extraStack = 1; // Normally only need 1 extra stack pos to store target ref
int[] argMap = this.storeArgs(target, stackVars, insns, 0);
if (injectTargetParams) {
extraLocals += ASMHelper.getArgsSize(target.arguments);
int argSize = ASMHelper.getArgsSize(target.arguments);
extraLocals += argSize;
extraStack += argSize;
argMap = Ints.concat(argMap, target.argIndices);
}
this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
target.insns.insertBefore(node, insns);
target.insns.remove(node);
AbstractInsnNode insn = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
target.replaceNode(methodNode, insn, insns);
target.addToLocals(extraLocals);
target.addToStack(1);
target.addToStack(extraStack);
}
/**
* Redirect a field get or set operation
*/
private void injectAtFieldAccess(Target target, InjectionNode node) {
final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget();
final int opCode = fieldNode.getOpcode();
final boolean staticField = opCode == Opcodes.GETSTATIC || opCode == Opcodes.PUTSTATIC;
final Type ownerType = Type.getType("L" + fieldNode.owner + ";");
final Type fieldType = Type.getType(fieldNode.desc);
AbstractInsnNode invoke = null;
InsnList insns = new InsnList();
if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) {
invoke = this.injectAtGetField(insns, target, fieldNode, staticField, ownerType, fieldType);
} else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) {
invoke = this.injectAtPutField(insns, target, fieldNode, staticField, ownerType, fieldType);
} else {
throw new InvalidInjectionException(this.info, "Unspported opcode " + opCode + " on FieldInsnNode for " + this.info);
}
target.replaceNode(fieldNode, invoke, insns);
}
/**
* Inject opcodes to redirect a field getter. The injection will vary based
* on the staticness of the field and the handler thus there are four
* possible scenarios based on the possible combinations of static on the
* handler and the field itself.
*/
private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
final String handlerDesc = staticField ? ASMHelper.generateDescriptor(fieldType) : ASMHelper.generateDescriptor(fieldType, owner);
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
if (!staticField) {
insns.add(new InsnNode(Opcodes.SWAP));
}
}
if (withArgs) {
this.pushArgs(target.arguments, insns, target.argIndices, 0, target.arguments.length);
target.addToStack(ASMHelper.getArgsSize(target.arguments));
}
target.addToStack(this.isStatic ? 0 : 1);
return this.invokeHandler(insns);
}
/**
* Inject opcodes to redirect a field setter. The injection will vary based
* on the staticness of the field and the handler thus there are four
* possible scenarios based on the possible combinations of static on the
* handler and the field itself.
*/
private AbstractInsnNode injectAtPutField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
String handlerDesc = staticField ? ASMHelper.generateDescriptor(null, fieldType) : ASMHelper.generateDescriptor(null, owner, fieldType);
boolean withArgs = this.checkDescriptor(handlerDesc, target, "setter");
if (!this.isStatic) {
if (staticField) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
} else {
int marshallVar = target.allocateLocals(fieldType.getSize());
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ISTORE), marshallVar));
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ILOAD), marshallVar));
}
}
if (withArgs) {
this.pushArgs(target.arguments, insns, target.argIndices, 0, target.arguments.length);
target.addToStack(ASMHelper.getArgsSize(target.arguments));
}
target.addToStack(!this.isStatic && !staticField ? 1 : 0);
return this.invokeHandler(insns);
}
/**
* Check that the handler descriptor matches the calculated descriptor for
* the field access being redirected.
*/
protected boolean checkDescriptor(String desc, Target target, String type) {
if (this.methodNode.desc.equals(desc)) {
return false;
}
int pos = desc.indexOf(')');
String alternateDesc = String.format("%s%s%s", desc.substring(0, pos), Joiner.on("").join(target.arguments), desc.substring(pos));
if (this.methodNode.desc.equals(alternateDesc)) {
return true;
}
throw new InvalidInjectionException(this.info, this.annotationType + " method " + type + " " + this
+ " has an invalid signature. Expected " + desc + " but found " + this.methodNode.desc);
}
}
@@ -0,0 +1,81 @@
/*
* 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.modify;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
* injector which searches for STORE operations which match the local variables
* described by the injector's defined discriminators.</p>
*
* <p>This allows you consumers to specify an injection immediately after a
* local variable is written in a method. Specify an <tt>ordinal</tt> of <tt>n
* </tt> to match the <em>n + 1<sup>th</sup></em> access of the variable in
* question.</p>
*
* <dl>
* <dt>ordinal</dt>
* <dd>The ordinal position of the STORE opcode for the matching local
* variable to search for, if not specified then the injection point returns
* <em>all </em> opcodes for which the parent annotation's discriminators
* match. The default value is <b>-1</b> which supresses ordinal checking.
* </dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;ModifyVariable(
* method = "md",
* ordinal = 1,
* at = &#064;At(
* value = "STORE",
* ordinal = 0
* )
* )</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("STORE")</pre>
* </blockquote>
*
* <p><b>Important Note:</b> Unlike other standard injection points, this class
* matches the insn immediately <b>after</b> the matching point.</p>
*/
public class AfterStoreLocal extends BeforeLoadLocal {
@SuppressWarnings("hiding")
public static final String CODE = "STORE";
public AfterStoreLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator local, InjectionPointData data) {
super(mixin, returnType, local, data, Opcodes.ISTORE, true);
}
}
@@ -0,0 +1,212 @@
/*
* 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.modify;
import java.util.Collection;
import java.util.ListIterator;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.ContextualInjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* <p>This injection point is a companion for the {@link ModifyVariable}
* injector which searches for LOAD operations which match the local variables
* described by the injector's defined discriminators.</p>
*
* <p>This allows you consumers to specify an injection immediately before a
* local variable is accessed in a method. Specify an <tt>ordinal</tt> of <tt>n
* </tt> to match the <em>n + 1<sup>th</sup></em> access of the variable in
* question.</p>
*
* <dl>
* <dt>ordinal</dt>
* <dd>The ordinal position of the LOAD opcode for the matching local variable
* to search for, if not specified then the injection point returns <em>all
* </em> opcodes for which the parent annotation's discriminators match. The
* default value is <b>-1</b> which supresses ordinal checking.</dd>
* </dl>
*
* <p>Example:</p>
* <blockquote><pre>
* &#064;ModifyVariable(
* method = "md",
* ordinal = 1,
* at = &#064;At(
* value = "LOAD",
* ordinal = 0
* )
* )</pre>
* </blockquote>
* <p>Note that if <em>value</em> is the only parameter specified, it can be
* omitted:</p>
* <blockquote><pre>
* &#064;At("LOAD")</pre>
* </blockquote>
*/
public class BeforeLoadLocal extends ContextualInjectionPoint {
/**
* Keeps track of state within {@link #find}
*/
static class SearchState {
/**
* The target ordinal from the injection point
*/
private final int targetOrdinal;
/**
* The current ordinal
*/
private int ordinal = 0;
/**
* Flag to defer a {@link check} to the next opcode, to honour the after
* semantics of {@link AfterStoreLocal}.
*/
private boolean pendingCheck = false;
/**
* True if one or more opcodes was matched
*/
private boolean found = false;
/**
* Var node, captured for when deferring processing to the next opcode
*/
private VarInsnNode varNode;
SearchState(int targetOrdinal) {
this.targetOrdinal = targetOrdinal;
}
boolean success() {
return this.found;
}
boolean isPendingCheck() {
return this.pendingCheck;
}
void setPendingCheck() {
this.pendingCheck = true;
}
void register(VarInsnNode node) {
this.varNode = node;
}
void check(Collection<AbstractInsnNode> nodes, AbstractInsnNode insn, int local) {
this.pendingCheck = false;
if (local != this.varNode.var) {
return;
}
if (this.targetOrdinal == -1 || this.targetOrdinal == this.ordinal) {
nodes.add(insn);
this.found = true;
}
this.ordinal++;
this.varNode = null;
}
}
public static final String CODE = "LOAD";
/**
* Return type of the handler, also the type of the local variable we're
* interested in
*/
private final Type returnType;
/**
* Discriminator, parsed from parent annotation
*/
private final LocalVariableDiscriminator discriminator;
/**
* Target opcode, inflected from return type
*/
private final int opcode;
/**
* Target ordinal
*/
private final int ordinal;
/**
* True if this injection point should capture the opcode after a matching
* opcode, used by {@link AfterStoreLocal}.
*/
private boolean opcodeAfter;
public BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data) {
this(mixin, returnType, discriminator, data, Opcodes.ILOAD, false);
}
protected BeforeLoadLocal(MixinTargetContext mixin, Type returnType, LocalVariableDiscriminator discriminator, InjectionPointData data,
int opcode, boolean opcodeAfter) {
super(mixin);
this.returnType = returnType;
this.discriminator = discriminator;
this.opcode = data.getOpcode(returnType.getOpcode(opcode));
this.ordinal = data.getOrdinal();
this.opcodeAfter = opcodeAfter;
}
@Override
boolean find(Target target, Collection<AbstractInsnNode> nodes) {
SearchState state = new SearchState(this.ordinal);
ListIterator<AbstractInsnNode> iter = target.method.instructions.iterator();
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (state.isPendingCheck()) {
int local = this.discriminator.findLocal(this.returnType, this.discriminator.isArgsOnly(), target, insn);
state.check(nodes, insn, local);
} else if (insn instanceof VarInsnNode && insn.getOpcode() == this.opcode && (this.ordinal == -1 || !state.success())) {
state.register((VarInsnNode)insn);
if (this.opcodeAfter) {
state.setPendingCheck();
} else {
int local = this.discriminator.findLocal(this.returnType, this.discriminator.isArgsOnly(), target, insn);
state.check(nodes, insn, local);
}
}
}
return state.success();
}
}
@@ -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.modify;
import org.spongepowered.asm.mixin.throwables.MixinException;
/**
* Thrown when an <em>implicit</em> discriminator (no args) fails to identify
* a unique candidate.
*/
public class InvalidImplicitDiscriminatorException extends MixinException {
private static final long serialVersionUID = 1L;
public InvalidImplicitDiscriminatorException(String message) {
super(message);
}
public InvalidImplicitDiscriminatorException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,348 @@
/*
* 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.modify;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.LocalVariableNode;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* Encapsulates logic for identifying a local variable in a target method using
* 3 criteria: <em>ordinal</em>, <em>index</em> and <em>name</em>. This is used
* by the {@link ModifyVariableInjector} and its associated injection points.
*/
public class LocalVariableDiscriminator {
/**
* Discriminator context information, wraps all relevant information about
* a target location for use when performing discrimination
*/
public static class Context implements org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable {
/**
* Information about a local variable in the LVT, used during
* discrimination
*/
public class Local {
/**
* Ordinal value of this local variable type
*/
int ord = 0;
/**
* Local variable name
*/
String name;
/**
* Local variable type
*/
Type type;
public Local(String name, Type type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type);
}
}
/**
* Target method for this context
*/
final Target target;
/**
* The return type of the handler in question, also the type of the
* local variable that we care about
*/
final Type returnType;
/**
* Injection point
*/
final AbstractInsnNode node;
/**
* Base argument index, for static methods this is 0, for instance
* methods this is 1
*/
final int baseArgIndex;
/**
* Enumerated locals in this context
*/
final Local[] locals;
/**
* True if the handler (and target) are static
*/
private final boolean isStatic;
public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
this.isStatic = ASMHelper.methodIsStatic(target.method);
this.returnType = returnType;
this.target = target;
this.node = node;
this.baseArgIndex = this.isStatic ? 0 : 1;
this.locals = this.initLocals(target, argsOnly, node);
this.initOrdinals();
}
private Local[] initLocals(Target target, boolean argsOnly, AbstractInsnNode node) {
if (!argsOnly) {
LocalVariableNode[] locals = Locals.getLocalsAt(target.classNode, target.method, node);
if (locals != null) {
Local[] lvt = new Local[locals.length];
for (int l = 0; l < locals.length; l++) {
if (locals[l] != null) {
lvt[l] = new Local(locals[l].name, Type.getType(locals[l].desc));
}
}
return lvt;
}
}
Local[] lvt = new Local[this.baseArgIndex + target.arguments.length];
if (!this.isStatic) {
lvt[0] = new Local("this", Type.getType(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);
}
return lvt;
}
private void initOrdinals() {
Map<Type, Integer> ordinalMap = new HashMap<Type, Integer>();
for (int l = 0; l < this.locals.length; l++) {
Integer ordinal = Integer.valueOf(0);
if (this.locals[l] != null) {
ordinal = ordinalMap.get(this.locals[l].type);
ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1));
this.locals[l].ord = ordinal.intValue();
}
}
}
@Override
public void print(PrettyPrinter printer) {
printer.add("%5s %7s %30s %-50s %s", "INDEX", "ORDINAL", "TYPE", "NAME", "CANDIDATE");
for (int l = this.baseArgIndex; l < this.locals.length; l++) {
Local local = this.locals[l];
if (local != null) {
Type localType = local.type;
String localName = local.name;
int ordinal = local.ord;
String candidate = this.returnType.equals(localType) ? "YES" : "-";
printer.add("[%3d] [%3d] %30s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate);
} else if (l > 0) {
Local prevLocal = this.locals[l - 1];
boolean isTop = prevLocal != null && prevLocal.type != null && prevLocal.type.getSize() > 1;
printer.add("[%3d] %30s", l, isTop ? "<top>" : "-");
}
}
}
}
/**
* True to consider only method args
*/
private final boolean argsOnly;
/**
* Ordinal of the target variable or -1 to fail over to {@link index}
*/
private final int ordinal;
/**
* Ordinal of the target variable or -1 to fail over to {@link names}
*/
private final int index;
/**
* Candidate names for the local variable, if empty fails over to matching
* single local by type
*/
private final Set<String> names;
/**
* @param argsOnly
* @param ordinal target variable ordinal
* @param index target variable index
* @param names target variable names
*/
public LocalVariableDiscriminator(boolean argsOnly, int ordinal, int index, Set<String> names) {
this.argsOnly = argsOnly;
this.ordinal = ordinal;
this.index = index;
this.names = Collections.<String>unmodifiableSet(names);
}
/**
* True if this discriminator will examine only the target method args and
* won't consider the rest of the LVT at the target location
*/
public boolean isArgsOnly() {
return this.argsOnly;
}
/**
* Get the local variable ordinal (nth variable of type)
*/
public int getOrdinal() {
return this.ordinal;
}
/**
* Get the local variable absolute index
*/
public int getIndex() {
return this.index;
}
/**
* Get valid names for consideration
*/
public Set<String> getNames() {
return this.names;
}
/**
* Returns true if names is not empty
*/
public boolean hasNames() {
return !this.names.isEmpty();
}
/**
* If the user specifies no values for <tt>ordinal</tt>, <tt>index</tt> or
* <tt>names</tt> then we are considered to be operating in "implicit mode"
* where only a single local variable of the specified type is expected to
* exist.
*
* @param context Target context
* @return true if operating in implicit mode
*/
protected boolean isImplicit(final Context context) {
return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty();
}
public int findLocal(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
try {
return this.findLocal(new Context(returnType, argsOnly, target, node));
} catch (InvalidImplicitDiscriminatorException ex) {
return -1;
}
}
public int findLocal(Context context) {
if (this.isImplicit(context)) {
return this.findImplicitLocal(context);
}
return this.findExplicitLocal(context);
}
private int findImplicitLocal(final Context context) {
int found = 0;
int count = 0;
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(context.returnType)) {
continue;
}
count++;
found = index;
}
if (count == 1) {
return found;
}
throw new InvalidImplicitDiscriminatorException("Found " + count + " candidate variables but exactly 1 is required.");
}
private int findExplicitLocal(final Context context) {
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
if (local == null || !local.type.equals(context.returnType)) {
continue;
}
if (this.ordinal > -1) {
if (this.ordinal == local.ord) {
return index;
}
continue;
}
if (this.index >= context.baseArgIndex) {
if (this.index == index) {
return index;
}
continue;
}
if (this.names.contains(local.name)) {
return index;
}
}
return -1;
}
public static LocalVariableDiscriminator parse(AnnotationNode annotation) {
boolean argsOnly = ASMHelper.<Boolean>getAnnotationValue(annotation, "argsOnly", Boolean.FALSE).booleanValue();
int ordinal = ASMHelper.<Integer>getAnnotationValue(annotation, "ordinal", -1);
int index = ASMHelper.<Integer>getAnnotationValue(annotation, "index", -1);
Set<String> names = new HashSet<String>();
List<String> namesList = ASMHelper.<List<String>>getAnnotationValue(annotation, "name", (List<String>)null);
if (namesList != null) {
names.addAll(namesList);
}
return new LocalVariableDiscriminator(argsOnly, ordinal, index, names);
}
}
@@ -0,0 +1,209 @@
/*
* 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.modify;
import java.util.Collection;
import java.util.List;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* A bytecode injector which allows a single local variable in the target method
* to be captured and altered. See also {@link LocalVariableDiscriminator} and
* {@link ModifyVariable}.
*/
public class ModifyVariableInjector extends Injector {
/**
* Target context information
*/
static class Context extends LocalVariableDiscriminator.Context {
/**
* Instructions to inject
*/
final InsnList insns = new InsnList();
public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
super(returnType, argsOnly, target, node);
}
}
/**
* Specialised injection point which uses a target-aware search pattern
*/
abstract static class ContextualInjectionPoint extends InjectionPoint {
protected final MixinTargetContext mixin;
ContextualInjectionPoint(MixinTargetContext mixin) {
this.mixin = mixin;
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
throw new InvalidInjectionException(this.mixin, "STORE injection point must be used in conjunction with @ModifyVariable");
}
abstract boolean find(Target target, Collection<AbstractInsnNode> nodes);
}
/**
* Print LVT
*/
private final boolean print;
/**
* True to consider only method args
*/
private final LocalVariableDiscriminator discriminator;
/**
* @param info Injection info
* @param print
*/
public ModifyVariableInjector(InjectionInfo info, boolean print, LocalVariableDiscriminator discriminator) {
super(info);
this.print = print;
this.discriminator = discriminator;
}
@Override
protected boolean findTargetNodes(MethodNode into, InjectionPoint injectionPoint, InsnList insns, Collection<AbstractInsnNode> nodes) {
if (injectionPoint instanceof ContextualInjectionPoint) {
return ((ContextualInjectionPoint)injectionPoint).find(this.info.getContext().getTargetMethod(into), nodes);
}
return injectionPoint.find(into.desc, insns, nodes);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.callback.BytecodeInjector
* #sanityCheck(org.spongepowered.asm.mixin.injection.callback.Target,
* java.util.List)
*/
@Override
protected void sanityCheck(Target target, List<InjectionPoint> injectionPoints) {
super.sanityCheck(target, injectionPoints);
if (target.isStatic != this.isStatic) {
throw new InvalidInjectionException(this.info, "'static' of variable modifier method does not match target in " + this);
}
int ordinal = this.discriminator.getOrdinal();
if (ordinal < -1) {
throw new InvalidInjectionException(this.info, "Invalid ordinal " + ordinal + " specified in " + this);
}
if (this.discriminator.getIndex() == 0 && !this.isStatic) {
throw new InvalidInjectionException(this.info, "Invalid index 0 specified in non-static variable modifier " + this);
}
}
/**
* Do the injection
*/
@Override
protected void inject(Target target, InjectionNode node) {
if (node.isReplaced()) {
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());
if (this.print) {
this.printLocals(context);
}
try {
int local = this.discriminator.findLocal(context);
if (local > -1) {
this.inject(context, local);
}
} catch (InvalidImplicitDiscriminatorException ex) {
throw new InvalidInjectionException(this.info, "Implicit variable modifier injection failed in " + this, ex);
}
target.insns.insertBefore(context.node, context.insns);
target.addToStack(this.isStatic ? 1 : 2);
}
/**
* Pretty-print local variable information to stderr
*/
private void printLocals(final Context context) {
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, this.returnType, this.methodArgs, new String[] { "var" });
handlerSig.setModifiers(this.methodNode);
new PrettyPrinter()
.kvWidth(20)
.kv("Target Class", this.classNode.name.replace('/', '.'))
.kv("Target Method", context.target.method.name)
.kv("Callback Name", this.methodNode.name)
.kv("Capture Type", SignaturePrinter.getTypeName(this.returnType, false))
.kv("Instruction", "%s %s", context.node.getClass().getSimpleName(), ASMHelper.getOpcodeName(context.node.getOpcode())).hr()
.kv("Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)")
.kv("Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal())
.kv("Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex())
.kv("Match name(s)", this.discriminator.hasNames() ? this.discriminator.getNames() : "any")
.kv("Args only", this.discriminator.isArgsOnly()).hr()
.add(context)
.print(System.err);
}
/**
* Perform the injection
*
* @param context target context
* @param local local variable to capture
*/
private void inject(final Context context, final int local) {
if (!this.isStatic) {
context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local));
this.invokeHandler(context.insns);
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local));
}
}
@@ -35,7 +35,6 @@ import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
/**
* <p>This injection point searches for INVOKEVIRTUAL, INVOKESTATIC and
* INVOKESPECIAL opcodes matching its arguments and returns a list of insns
@@ -71,9 +71,9 @@ public class BeforeInvoke extends InjectionPoint {
protected final MemberInfo target;
/**
* This strategy can be used to identify a particular invokation if the same
* This strategy can be used to identify a particular invocation if the same
* method is invoked at multiple points, if this value is -1 then the
* strategy returns <em>all</em> invokations of the method.
* strategy returns <em>all</em> invocations of the method.
*/
protected final int ordinal;
@@ -26,12 +26,16 @@ package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information about a callback to inject, usually specified by {@link Inject}
*/
public class CallbackInjectionInfo extends InjectionInfo {
protected CallbackInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
@@ -39,10 +43,12 @@ public class CallbackInjectionInfo extends InjectionInfo {
}
@Override
protected Injector initInjector(AnnotationNode injectAnnotation) {
protected Injector parseInjector(AnnotationNode injectAnnotation) {
boolean cancellable = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "cancellable", false);
LocalCapture locals = ASMHelper.<LocalCapture>getAnnotationValue(injectAnnotation, "locals", LocalCapture.class, LocalCapture.NO_CAPTURE);
String identifier = ASMHelper.<String>getAnnotationValue(injectAnnotation, "id", "");
return new CallbackInjector(this, cancellable, locals);
return new CallbackInjector(this, cancellable, locals, identifier);
}
}
@@ -28,24 +28,34 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.InjectorGroupInfo;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.transformer.InvalidMixinException;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
/**
* Contructs information about an injection from an {@link Inject} annotation
* and allows the injection to be processed.
@@ -68,8 +78,7 @@ public abstract class InjectionInfo {
* Mixin data
*/
protected final MixinTargetContext mixin;
/**
* Annotated method is static
*/
@@ -86,16 +95,41 @@ public abstract class InjectionInfo {
*/
protected final List<InjectionPoint> injectionPoints = new ArrayList<InjectionPoint>();
/**
* Map of lists of nodes enumerated by calling {@link #prepare}
*/
protected final Map<Target, List<InjectionNode>> targetNodes = new LinkedHashMap<Target, List<InjectionNode>>();
/**
* Bytecode injector
*/
protected Injector injector;
/**
* Injection group
*/
protected InjectorGroupInfo group;
/**
* Methods injected by injectors
*/
private final List<MethodNode> injectedMethods = new ArrayList<MethodNode>(0);
/**
* Number of callbacks we expect to inject into targets
*/
private int expectedCallbackCount = 1;
/**
* Number of callbacks we require injected
*/
private int requiredCallbackCount = 0;
/**
* Actual number of injected callbacks
*/
private int injectedCallbackCount = 0;
/**
* ctor
*
@@ -104,10 +138,10 @@ public abstract class InjectionInfo {
* @param annotation Annotation to parse
*/
protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
this.annotation = annotation;
this.method = method;
this.mixin = mixin;
this.classNode = mixin.getTargetClass();
this.method = method;
this.annotation = annotation;
this.classNode = mixin.getTargetClassNode();
this.isStatic = ASMHelper.methodIsStatic(method);
this.readAnnotation();
}
@@ -115,55 +149,78 @@ public abstract class InjectionInfo {
/**
* Parse the info from the supplied annotation
*/
@SuppressWarnings("unchecked")
protected void readAnnotation() {
if (this.annotation == null) {
return;
}
String type = "@" + this.annotation.desc.substring(this.annotation.desc.lastIndexOf('/') + 1, this.annotation.desc.length() - 1);
String type = "@" + ASMHelper.getSimpleName(this.annotation);
List<AnnotationNode> injectionPoints = this.readInjectionPoints(type);
this.findMethods(this.parseTarget(type), type);
this.parseInjectionPoints(injectionPoints);
this.parseRequirements();
this.injector = this.parseInjector(this.annotation);
}
protected MemberInfo parseTarget(String type) {
String method = ASMHelper.<String>getAnnotationValue(this.annotation, "method");
if (method == null) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing method name");
}
List<AnnotationNode> ats = null;
try {
MemberInfo targetMember = MemberInfo.parseAndValidate(method, this.mixin);
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '"
+ targetMember.owner + "', which is not supported");
}
return targetMember;
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + ", has invalid target descriptor: \""
+ method + "\"");
}
}
@SuppressWarnings("unchecked")
protected List<AnnotationNode> readInjectionPoints(String type) {
Object atValue = ASMHelper.getAnnotationValue(this.annotation, "at");
if (atValue instanceof List) {
ats = (List<AnnotationNode>)atValue;
return (List<AnnotationNode>)atValue;
} else if (atValue instanceof AnnotationNode) {
ats = new ArrayList<AnnotationNode>();
List<AnnotationNode> ats = new ArrayList<AnnotationNode>();
ats.add((AnnotationNode)atValue);
} else {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
return ats;
}
MemberInfo targetMember = MemberInfo.parse(method, this.mixin);
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '"
+ targetMember.owner + "', which is not supported");
}
this.findMethods(targetMember);
if (this.targets.size() == 0) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + targetMember.name + "'");
}
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
}
protected void parseInjectionPoints(List<AnnotationNode> ats) {
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, at);
InjectionPoint injectionPoint = InjectionPoint.parse(this.mixin, this.method, this.annotation, at);
if (injectionPoint != null) {
this.injectionPoints.add(injectionPoint);
}
}
}
protected void parseRequirements() {
this.group = this.mixin.getInjectorGroups().parseGroup(this.method, this.mixin.getDefaultInjectorGroup()).add(this);
this.injector = this.initInjector(this.annotation);
Integer expect = ASMHelper.<Integer>getAnnotationValue(this.annotation, "expect");
if (expect != null) {
this.expectedCallbackCount = expect.intValue();
}
Integer require = ASMHelper.<Integer>getAnnotationValue(this.annotation, "require");
if (require != null && require.intValue() > -1) {
this.requiredCallbackCount = require.intValue();
} else if (this.group.isDefault()) {
this.requiredCallbackCount = this.mixin.getDefaultRequiredInjections();
}
}
// stub
protected abstract Injector initInjector(AnnotationNode injectAnnotation);
protected abstract Injector parseInjector(AnnotationNode injectAnnotation);
/**
* Get whether there is enough valid information in this info to actually
@@ -176,13 +233,24 @@ public abstract class InjectionInfo {
}
/**
* Perform the injection
* Discover injection points
*/
public void prepare() {
this.targetNodes.clear();
for (MethodNode targetMethod : this.targets) {
Target target = this.mixin.getTargetMethod(targetMethod);
this.targetNodes.put(target, this.injector.find(target, this.injectionPoints));
}
}
/**
* Perform injections
*/
public void inject() {
while (this.targets.size() > 0) {
Target target = this.mixin.getTargetMethod(this.targets.removeFirst());
this.injector.injectInto(target, this.injectionPoints);
for (Entry<Target, List<InjectionNode>> entry : this.targetNodes.entrySet()) {
this.injector.inject(entry.getKey(), entry.getValue());
}
this.targets.clear();
}
/**
@@ -192,6 +260,30 @@ public abstract class InjectionInfo {
for (MethodNode method : this.injectedMethods) {
this.classNode.methods.add(method);
}
if ((MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) {
throw new InvalidInjectionException(this,
String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded",
this.getDescription(), this.method.name, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount));
} else if (this.injectedCallbackCount < this.requiredCallbackCount) {
throw new InjectionError(
String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded",
this.getDescription(), this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount));
}
}
public void notifyInjected(Target target) {
// this.targets.remove(target.method);
}
protected String getDescription() {
return "Callback method";
}
@Override
public String toString() {
return InjectionInfo.describeInjector(this.mixin, this.annotation, this.method);
}
/**
@@ -238,6 +330,15 @@ public abstract class InjectionInfo {
public Collection<MethodNode> getTargets() {
return this.targets;
}
/**
* Get the injected callback count
*
* @return the injected callback count
*/
public int getInjectedCallbackCount() {
return this.injectedCallbackCount;
}
/**
* Inject a method into the target class
@@ -254,41 +355,66 @@ public abstract class InjectionInfo {
return method;
}
/**
* Notify method, called by injector when adding a callback into a target
*
* @param handler callback handler being invoked
*/
public void addCallbackInvocation(MethodNode handler) {
this.injectedCallbackCount++;
}
/**
* Finds methods in the target class which match searchFor
*
* @param searchFor member info to search for
* @param type annotation type
*/
private void findMethods(MemberInfo searchFor) {
private void findMethods(MemberInfo searchFor, String type) {
this.targets.clear();
int ordinal = 0;
for (MethodNode target : this.classNode.methods) {
if (searchFor.matches(target.name, target.desc, ordinal)) {
if (searchFor.matchAll && ASMHelper.methodIsStatic(target) != this.isStatic) {
boolean isMixinMethod = ASMHelper.getVisibleAnnotation(target, MixinMerged.class) != null;
if (searchFor.matchAll && (ASMHelper.methodIsStatic(target) != this.isStatic || target == this.method || isMixinMethod)) {
continue;
}
AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class);
if (merged != null) {
throw new InvalidInjectionException(this, "Cannot inject into a mixin method");
}
this.checkTarget(target);
this.targets.add(target);
ordinal++;
}
}
if (this.targets.size() == 0) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " could not find '" + searchFor.name + "'");
}
}
private void checkTarget(MethodNode target) {
AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class);
if (merged == null) {
return;
}
String owner = ASMHelper.<String>getAnnotationValue(merged, "mixin");
int priority = ASMHelper.<Integer>getAnnotationValue(merged, "priority");
if (priority >= this.mixin.getPriority() && !owner.equals(this.mixin.getClassName())) {
throw new InvalidInjectionException(this, this + " cannot inject into " + this.classNode.name + "::" + target.name + target.desc
+ " merged by " + owner + " with priority " + priority);
}
if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) {
throw new InvalidInjectionException(this, this + " cannot inject into @Final method " + this.classNode.name + "::" + target.name
+ target.desc + " merged by " + owner);
}
}
@SuppressWarnings("unchecked")
public static InjectionInfo parse(MixinTargetContext mixin, MethodNode method) {
AnnotationNode annotation = null;
try {
annotation = ASMHelper.getSingleVisibleAnnotation(method, Inject.class, ModifyArg.class, Redirect.class);
} catch (IllegalArgumentException ex) {
throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": "
+ ex.getMessage());
}
AnnotationNode annotation = InjectionInfo.getInjectorAnnotation(mixin, method);
if (annotation == null) {
return null;
@@ -300,8 +426,50 @@ public abstract class InjectionInfo {
return new ModifyArgInjectionInfo(mixin, method, annotation);
} else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) {
return new RedirectInjectionInfo(mixin, method, annotation);
} else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) {
return new ModifyVariableInjectionInfo(mixin, method, annotation);
} else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) {
return new ModifyConstantInjectionInfo(mixin, method, annotation);
}
return null;
}
@SuppressWarnings("unchecked")
public static AnnotationNode getInjectorAnnotation(MixinTargetContext mixin, MethodNode method) {
AnnotationNode annotation = null;
try {
annotation = ASMHelper.getSingleVisibleAnnotation(method,
Inject.class,
ModifyArg.class,
Redirect.class,
ModifyVariable.class,
ModifyConstant.class
);
} catch (IllegalArgumentException ex) {
throw new InvalidMixinException(mixin, "Error parsing annotations on " + method.name + " in " + mixin.getClassName() + ": "
+ ex.getMessage());
}
return annotation;
}
public static String getInjectorPrefix(AnnotationNode annotation) {
if (annotation != null) {
if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) {
return "modify";
} else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) {
return "redirect";
} else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) {
return "localvar";
} else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) {
return "constant";
}
}
return "handler";
}
static String describeInjector(MixinTargetContext mixin, AnnotationNode annotation, MethodNode method) {
return String.format("%s->@%s::%s%s", mixin.toString(), ASMHelper.getSimpleName(annotation), method.name, method.desc);
}
}
@@ -28,8 +28,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.spongepowered.asm.mixin.transformer.IReferenceMapperContext;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* Data read from an {@link org.spongepowered.asm.mixin.injection.At} annotation
@@ -45,8 +48,23 @@ public class InjectionPointData {
/**
* Mixin
*/
private final IReferenceMapperContext mixin;
private final MixinTargetContext mixin;
/**
* Injector callback
*/
private MethodNode method;
/**
* Parent annotation
*/
private AnnotationNode parent;
/**
* At arg
*/
private String at;
/**
* Target
*/
@@ -62,8 +80,12 @@ public class InjectionPointData {
*/
private final int opcode;
public InjectionPointData(IReferenceMapperContext mixin, List<String> args, String target, int ordinal, int opcode) {
public InjectionPointData(MixinTargetContext mixin, MethodNode method, AnnotationNode parent, String at, List<String> args, String target,
int ordinal, int opcode) {
this.mixin = mixin;
this.method = method;
this.parent = parent;
this.at = at;
this.target = target;
this.ordinal = Math.max(-1, ordinal);
this.opcode = opcode;
@@ -76,6 +98,9 @@ public class InjectionPointData {
}
private void parseArgs(List<String> args) {
if (args == null) {
return;
}
for (String arg : args) {
if (arg != null) {
int eqPos = arg.indexOf('=');
@@ -87,6 +112,18 @@ public class InjectionPointData {
}
}
}
public MixinTargetContext getMixin() {
return this.mixin;
}
public MethodNode getMethod() {
return this.method;
}
public AnnotationNode getParent() {
return this.parent;
}
public String get(String key, String defaultValue) {
String value = this.args.get(key);
@@ -102,7 +139,12 @@ public class InjectionPointData {
}
public MemberInfo get(String key) {
return MemberInfo.parse(this.get(key, ""), this.mixin);
try {
return MemberInfo.parseAndValidate(this.get(key, ""), this.mixin);
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s",
this.at, key, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method));
}
}
private int parseInt(String string, int defaultValue) {
@@ -122,7 +164,12 @@ public class InjectionPointData {
}
public MemberInfo getTarget() {
return MemberInfo.parse(this.target, this.mixin);
try {
return MemberInfo.parseAndValidate(this.target, this.mixin);
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\") descriptor \"%s\" on %s",
this.at, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method));
}
}
public int getOrdinal() {
@@ -0,0 +1,48 @@
/*
* 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.throwables.MixinException;
/**
* Thrown when a {@link MemberInfo} fails basic syntax validation
*/
public class InvalidMemberDescriptorException extends MixinException {
private static final long serialVersionUID = 1L;
public InvalidMemberDescriptorException(String message) {
super(message);
}
public InvalidMemberDescriptorException(Throwable cause) {
super(cause);
}
public InvalidMemberDescriptorException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -24,15 +24,16 @@
*/
package org.spongepowered.asm.mixin.injection.struct;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.transformer.IReferenceMapperContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.obfuscation.SrgMethod;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* <p>Information bundle about a member (method or field) parsed from a String
* token in another annotation, this is used where target members need to be
@@ -164,31 +165,42 @@ public class MemberInfo {
}
/**
* Initialise a MemberInfo using the supplied MethodData object
* Initialise a MemberInfo using the supplied SrgMethod object
*
* @param methodData MethodData object to copy values from
* @param srgMethod SrgMethod object to copy values from
*/
private MemberInfo(MethodData methodData) {
int slashPos = methodData.name.lastIndexOf('/');
this.owner = methodData.name.substring(0, slashPos);
this.name = methodData.name.substring(slashPos + 1);
this.desc = methodData.sig;
public MemberInfo(SrgMethod srgMethod) {
this.owner = srgMethod.getOwner();
this.name = srgMethod.getSimpleName();
this.desc = srgMethod.getDesc();
this.matchAll = false;
}
/**
* Initialise a remapped MemberInfo using the supplied MethodData object
* Initialise a remapped MemberInfo using the supplied SrgMethod object
*
* @param methodData MethodData object to copy values from
* @param srgMethod SrgMethod object to copy values from
*/
private MemberInfo(MemberInfo remapped, MethodData methodData, boolean setOwner) {
int slashPos = methodData.name.lastIndexOf('/');
this.owner = setOwner ? methodData.name.substring(0, slashPos) : remapped.owner;
this.name = methodData.name.substring(slashPos + 1);
this.desc = remapped.desc;
this.matchAll = false;
private MemberInfo(MemberInfo remapped, SrgMethod srgMethod, boolean setOwner) {
this.owner = setOwner ? srgMethod.getOwner() : remapped.owner;
this.name = srgMethod.getSimpleName();
this.desc = srgMethod.getDesc();
this.matchAll = remapped.matchAll;
}
/**
* Initialise a remapped MemberInfo with a new name
*
* @param original Original MemberInfo
* @param owner new owner
*/
private MemberInfo(MemberInfo original, String owner) {
this.owner = owner;
this.name = original.name;
this.desc = original.desc;
this.matchAll = original.matchAll;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@@ -209,7 +221,7 @@ public class MemberInfo {
*/
public String toSrg() {
if (!this.isFullyQualified()) {
throw new RuntimeException("Cannot convert unqalified reference to SRG mapping");
throw new MixinException("Cannot convert unqualified reference to SRG mapping");
}
if (this.desc.startsWith("(")) {
@@ -227,16 +239,16 @@ public class MemberInfo {
return new SignaturePrinter(this).setFullyQualified(true).toDescriptor();
}
public MethodData asMethodData() {
public SrgMethod asSrgMethod() {
if (!this.isFullyQualified()) {
throw new RuntimeException("Cannot convert unqalified reference to MethodData");
throw new MixinException("Cannot convert unqualified reference to SrgMethod");
}
if (this.isField()) {
throw new RuntimeException("Cannot convert a non-method reference to MethodData");
throw new MixinException("Cannot convert a non-method reference to SrgMethod");
}
return new MethodData(this.owner + "/" + this.name, this.desc);
return new SrgMethod(this.owner + "/" + this.name, this.desc);
}
/**
@@ -257,6 +269,64 @@ public class MemberInfo {
public boolean isField() {
return this.desc != null && !this.desc.startsWith("(");
}
/**
* Perform ultra-simple validation of the descriptor, checks that the parts
* of the descriptor are basically sane.
*
* @return fluent
*
* @throws InvalidMemberDescriptorException if any validation check fails
*/
public MemberInfo validate() throws InvalidMemberDescriptorException {
// 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);
}
try {
if (!this.owner.equals(Type.getType(this.owner).getDescriptor())) {
throw new InvalidMemberDescriptorException("Invalid owner type specified: " + this.owner);
}
} catch (Exception ex) {
throw new InvalidMemberDescriptorException("Invalid owner type specified: " + this.owner);
}
}
// 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);
}
if (this.desc != null) {
if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[?[\\w\\p{Sc}/;]+$")) {
throw new InvalidMemberDescriptorException("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);
}
} else {
try {
Type.getArgumentTypes(this.desc);
} catch (Exception ex) {
throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc);
}
String retString = this.desc.substring(this.desc.indexOf(')') + 1);
try {
Type retType = Type.getType(retString);
if (!retString.equals(retType.getDescriptor())) {
throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc);
}
} catch (Exception ex) {
throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc);
}
}
}
return this;
}
/**
* Test whether this MemberInfo matches the supplied values. Null values are
@@ -327,15 +397,48 @@ public class MemberInfo {
&& (ordinal == 0 || this.matchAll);
}
/**
* Create a new version of this member with a different owner
*
* @param newOwner New owner for this member
*/
public MemberInfo move(String newOwner) {
if (newOwner.equals(this.owner)) {
return this;
}
return new MemberInfo(this, newOwner);
}
/**
* Create a remapped version of this member using the supplied method data
*
* @param methodData Method data to use
* @param srgMethod SRG method data to use
* @param setOwner True to set the owner as well as the name
* @return New MethodInfo with remapped values
*/
public MemberInfo remapUsing(MethodData methodData, boolean setOwner) {
return new MemberInfo(this, methodData, setOwner);
public MemberInfo remapUsing(SrgMethod srgMethod, boolean setOwner) {
return new MemberInfo(this, srgMethod, setOwner);
}
/**
* Parse a MemberInfo from a string and perform validation
*
* @param string String to parse MemberInfo from
* @return parsed MemberInfo
*/
public static MemberInfo parseAndValidate(String string) throws InvalidMemberDescriptorException {
return MemberInfo.parse(string, null, null).validate();
}
/**
* Parse a MemberInfo from a string and perform validation
*
* @param string String to parse MemberInfo from
* @param context Context to use for reference mapping
* @return parsed MemberInfo
*/
public static MemberInfo parseAndValidate(String string, IReferenceMapperContext context) throws InvalidMemberDescriptorException {
return MemberInfo.parse(string, context.getReferenceMapper(), context.getClassRef()).validate();
}
/**
@@ -367,10 +470,12 @@ public class MemberInfo {
* @param mixinClass Mixin class to use for remapping
* @return parsed MemberInfo
*/
public static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) {
private static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) {
String desc = null;
String owner = null;
name = name.replaceAll("\\s", "");
if (refMapper != null) {
name = refMapper.remap(mixinClass, name);
}
@@ -414,7 +519,7 @@ public class MemberInfo {
return new MemberInfo(name, owner, desc, false);
}
public static MemberInfo fromSrgMethod(MethodData methodData) {
return new MemberInfo(methodData);
public static MemberInfo fromSrgMethod(SrgMethod srgMethod) {
return new MemberInfo(srgMethod);
}
}
@@ -26,11 +26,15 @@ package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.ModifyArgInjector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information about a {@link ModifyArg} injector
*/
public class ModifyArgInjectionInfo extends InjectionInfo {
public ModifyArgInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
@@ -38,9 +42,15 @@ public class ModifyArgInjectionInfo extends InjectionInfo {
}
@Override
protected Injector initInjector(AnnotationNode injectAnnotation) {
protected Injector parseInjector(AnnotationNode injectAnnotation) {
int index = ASMHelper.<Integer>getAnnotationValue(injectAnnotation, "index", -1);
return new ModifyArgInjector(this, index);
}
@Override
protected String getDescription() {
return "Argument modifier method";
}
}
@@ -0,0 +1,222 @@
/*
* 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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.ModifyConstantInjector;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
/**
* Information about a constant modifier injector
*/
public class ModifyConstantInjectionInfo extends InjectionInfo {
/**
* Special injection point which is defined by an {@link Constant}
* annotation.
*/
static class BeforeConstant extends InjectionPoint {
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Ordinal of the target insn
*/
private final int ordinal;
private final boolean nullValue;
private final Integer intValue;
private final Float floatValue;
private final Long longValue;
private final Double doubleValue;
private final String stringValue;
private final Type typeValue;
private final String matchByType;
private final boolean log;
public BeforeConstant(InjectionInfo info, AnnotationNode node, String returnType) {
Boolean empty = ASMHelper.<Boolean>getAnnotationValue(node, "nullValue", (Boolean)null);
this.ordinal = ASMHelper.<Integer>getAnnotationValue(node, "ordinal", Integer.valueOf(-1));
this.nullValue = empty != null ? empty.booleanValue() : false;;
this.intValue = ASMHelper.<Integer>getAnnotationValue(node, "intValue", (Integer)null);
this.floatValue = ASMHelper.<Float>getAnnotationValue(node, "floatValue", (Float)null);
this.longValue = ASMHelper.<Long>getAnnotationValue(node, "longValue", (Long)null);
this.doubleValue = ASMHelper.<Double>getAnnotationValue(node, "doubleValue", (Double)null);
this.stringValue = ASMHelper.<String>getAnnotationValue(node, "stringValue", (String)null);
this.typeValue = ASMHelper.<Type>getAnnotationValue(node, "classValue", (Type)null);
int c = BeforeConstant.count(empty, this.intValue, this.floatValue, this.longValue, this.doubleValue, this.stringValue, this.typeValue);
if (c == 1) {
returnType = null;
} else if (c > 1) {
throw new InvalidInjectionException(info, "Conflicting constant discriminators specified on @Constant annotation for " + info);
}
this.matchByType = returnType;
this.log = ASMHelper.<Boolean>getAnnotationValue(node, "log", Boolean.FALSE).booleanValue();
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
boolean found = false;
if (this.log) {
BeforeConstant.logger.info("BeforeConstant is searching for an constants in method with descriptor {}", desc);
}
ListIterator<AbstractInsnNode> iter = insns.iterator();
for (int ordinal = 0; iter.hasNext();) {
AbstractInsnNode insn = iter.next();
boolean matchesInsn = this.matchesInsn(insn);
if (matchesInsn) {
if (this.log) {
String byType = this.matchByType != null ? " TYPE" : " value";
BeforeConstant.logger.info(" BeforeConstant found a matching constant{} at ordinal {}", byType, ordinal);
}
if (this.ordinal == -1 || this.ordinal == ordinal) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found {}", ASMHelper.getNodeDescriptionForDebug(insn).trim());
}
nodes.add(insn);
found = true;
}
ordinal++;
}
}
return found;
}
private boolean matchesInsn(AbstractInsnNode insn) {
if (!ASMHelper.isConstant(insn)) {
return false;
}
Object value = ASMHelper.getConstant(insn);
if (value == null) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue);
}
return this.nullValue || Constants.OBJECT.equals(this.matchByType);
} else if (value instanceof Integer) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found INTEGER constant: value = {}, intValue = {}", value, this.intValue);
}
return value.equals(this.intValue) || "I".equals(this.matchByType);
} else if (value instanceof Float) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found FLOAT constant: value = {}, floatValue = {}", value, this.floatValue);
}
return value.equals(this.floatValue) || "F".equals(this.matchByType);
} else if (value instanceof Long) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found LONG constant: value = {}, longValue = {}", value, this.longValue);
}
return value.equals(this.longValue) || "J".equals(this.matchByType);
} else if (value instanceof Double) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found DOUBLE constant: value = {}, doubleValue = {}", value, this.doubleValue);
}
return value.equals(this.doubleValue) || "D".equals(this.matchByType);
} else if (value instanceof String) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found STRING constant: value = {}, stringValue = {}", value, this.stringValue);
}
return value.equals(this.stringValue) || Constants.STRING.equals(this.matchByType);
} else if (value instanceof Type) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found CLASS constant: value = {}, typeValue = {}", value, this.typeValue);
}
return value.equals(this.typeValue) || Constants.CLASS.equals(this.matchByType);
}
return false;
}
private static int count(Object... values) {
int counter = 0;
for (Object value : values) {
if (value != null) {
counter++;
}
}
return counter;
}
}
public ModifyConstantInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
super(mixin, method, annotation);
}
@Override
protected List<AnnotationNode> readInjectionPoints(String type) {
AnnotationNode constantAnnotation = ASMHelper.<AnnotationNode>getAnnotationValue(this.annotation, "constant");
List<AnnotationNode> ats = new ArrayList<AnnotationNode>();
ats.add(constantAnnotation);
return ats;
}
@Override
protected void parseInjectionPoints(List<AnnotationNode> ats) {
Type returnType = Type.getReturnType(this.method.desc);
for (AnnotationNode at : ats) {
this.injectionPoints.add(new BeforeConstant(this, at, returnType.getDescriptor()));
}
}
@Override
protected Injector parseInjector(AnnotationNode injectAnnotation) {
return new ModifyConstantInjector(this);
}
@Override
protected String getDescription() {
return "Constant modifier method";
}
}
@@ -0,0 +1,56 @@
/*
* 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.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information about a {@link ModifyVariable} injector
*/
public class ModifyVariableInjectionInfo extends InjectionInfo {
public ModifyVariableInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
super(mixin, method, annotation);
}
@Override
protected Injector parseInjector(AnnotationNode injectAnnotation) {
boolean print = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "print", Boolean.FALSE).booleanValue();
return new ModifyVariableInjector(this, print, LocalVariableDiscriminator.parse(injectAnnotation));
}
@Override
protected String getDescription() {
return "Variable modifier method";
}
}
@@ -30,6 +30,9 @@ import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* Information about a redirector injector
*/
public class RedirectInjectionInfo extends InjectionInfo {
public RedirectInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
@@ -37,7 +40,13 @@ public class RedirectInjectionInfo extends InjectionInfo {
}
@Override
protected Injector initInjector(AnnotationNode injectAnnotation) {
protected Injector parseInjector(AnnotationNode injectAnnotation) {
return new RedirectInjector(this);
}
@Override
protected String getDescription() {
return "Redirector";
}
}
@@ -1,106 +0,0 @@
/*
* 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 java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.launchwrapper.Launch;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class ReferenceMapper implements Serializable {
private static final long serialVersionUID = 1L;
public static final String DEFAULT_RESOURCE = "mixin.refmap.json";
private final Map<String, Map<String, String>> mappings;
public ReferenceMapper() {
this(new HashMap<String, Map<String, String>>());
}
public ReferenceMapper(Map<String, Map<String, String>> mappings) {
this.mappings = mappings;
}
public String remap(String className, String reference) {
if (className == null) {
for (Map<String, String> mappings : this.mappings.values()) {
if (mappings.containsKey(reference)) {
return mappings.get(reference);
}
}
}
Map<String, String> classMappings = this.mappings.get(className);
if (classMappings == null) {
return reference;
}
String remappedReference = classMappings.get(reference);
return remappedReference != null ? remappedReference : reference;
}
public void addMapping(String className, String reference, String newReference) {
Map<String, String> classMappings = this.mappings.get(className);
if (classMappings == null) {
classMappings = new HashMap<String, String>();
this.mappings.put(className, classMappings);
}
classMappings.put(reference, newReference);
}
public void write(Appendable writer) {
new GsonBuilder().setPrettyPrinting().create().toJson(this, writer);
}
public static ReferenceMapper read(String resource) {
Reader reader = null;
try {
reader = new InputStreamReader(Launch.classLoader.getResourceAsStream(resource));
return ReferenceMapper.read(reader);
} catch (Exception ex) {
return new ReferenceMapper();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// don't really care
}
}
}
}
public static ReferenceMapper read(Reader reader) {
return new Gson().fromJson(reader, ReferenceMapper.class);
}
}
@@ -25,17 +25,21 @@
package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.InsnList;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.InjectionNodes;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.util.ASMHelper;
/**
* Information about the current injection target, mainly just convenience
* rather than passing a bunch of values around.
*/
public class Target {
public class Target implements Comparable<Target> {
public final ClassNode classNode;
/**
* Target method
@@ -67,16 +71,6 @@ public class Target {
*/
public final Type returnType;
/**
* Method's (original) MAXS
*/
private final int maxStack;
/**
* Method's original max locals
*/
private final int maxLocals;
/**
* Callback method descriptor based on this target
*/
@@ -86,13 +80,29 @@ public class Target {
* Callback info class
*/
public final String callbackInfoClass;
/**
* Nodes targetted by injectors
*/
public final InjectionNodes injectionNodes = new InjectionNodes();
/**
* Method's (original) MAXS
*/
private final int maxStack;
/**
* Method's original max locals
*/
private final int maxLocals;
/**
* Make a new Target for the supplied method
*
* @param method target method
*/
public Target(MethodNode method) {
public Target(ClassNode classNode, MethodNode method) {
this.classNode = classNode;
this.method = method;
this.insns = method.instructions;
this.isStatic = ASMHelper.methodIsStatic(method);
@@ -255,9 +265,10 @@ public class Target {
}
String descriptor = this.callbackDescriptor.substring(0, this.callbackDescriptor.indexOf(')'));
for (int l = startIndex; l < locals.length && l < (startIndex + extra); l++) {
for (int l = startIndex; l < locals.length && extra > 0; l++) {
if (locals[l] != null) {
descriptor += locals[l].getDescriptor();
extra--;
}
}
@@ -266,6 +277,79 @@ public class Target {
@Override
public String toString() {
return this.method.name + this.method.desc;
return String.format("%s::%s%s", this.classNode.name, this.method.name, this.method.desc);
}
@Override
public int compareTo(Target o) {
if (o == null) {
return Integer.MAX_VALUE;
}
return this.toString().compareTo(o.toString());
}
/**
* Replace an instruction in this target with the specified instruction and
* mark the node as replaced for other injectors
*
* @param location Instruction to replace
* @param insn Instruction to replace with
*/
public void replaceNode(AbstractInsnNode location, AbstractInsnNode insn) {
this.insns.insertBefore(location, insn);
this.insns.remove(location);
this.injectionNodes.replace(location, insn);
}
/**
* Replace an instruction in this target with the specified instructions and
* mark the node as replaced with the specified champion node from the list.
*
* @param location Instruction to replace
* @param champion Instruction which notionally replaces the original insn
* @param insns Instructions to actually insert (must contain champion)
*/
public void replaceNode(AbstractInsnNode location, AbstractInsnNode champion, InsnList insns) {
this.insns.insertBefore(location, insns);
this.insns.remove(location);
this.injectionNodes.replace(location, champion);
}
/**
* Wrap instruction in this target with the specified instructions and mark
* the node as replaced with the specified champion node from the list.
*
* @param location Instruction to replace
* @param champion Instruction which notionally replaces the original insn
* @param before Instructions to actually insert (must contain champion)
*/
public void wrapNode(AbstractInsnNode location, AbstractInsnNode champion, InsnList before, InsnList after) {
this.insns.insertBefore(location, before);
this.insns.insert(location, after);
this.injectionNodes.replace(location, champion);
}
/**
* Replace an instruction in this target with the specified instructions and
* mark the original node as removed
*
* @param location Instruction to replace
* @param insns Instructions to replace with
*/
public void replaceNode(AbstractInsnNode location, InsnList insns) {
this.insns.insertBefore(location, insns);
this.removeNode(location);
}
/**
* Remove the specified instruction from the target and mark it as removed
* for injections
*
* @param insn instruction to remove
*/
public void removeNode(AbstractInsnNode insn) {
this.insns.remove(insn);
this.injectionNodes.remove(insn);
}
}
@@ -22,8 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
package org.spongepowered.asm.mixin.injection.throwables;
/**
* Error to throw for critical injection problems
@@ -0,0 +1,47 @@
/*
* 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.throwables;
import org.spongepowered.asm.mixin.injection.InjectorGroupInfo;
/**
* Thrown when an injector group fails an injection check
*/
public class InjectionValidationException extends Exception {
private static final long serialVersionUID = 1L;
private final InjectorGroupInfo group;
public InjectionValidationException(InjectorGroupInfo group, String message) {
super(message);
this.group = group;
}
public InjectorGroupInfo getGroup() {
return this.group;
}
}
@@ -22,39 +22,54 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection;
package org.spongepowered.asm.mixin.injection.throwables;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.transformer.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
* Thrown when an injector fails a state check, for example if an injector
* handler signature is invalid, an invalid opcode is targetted, etc.
*/
public class InvalidInjectionException extends InvalidMixinException {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 2L;
private final InjectionInfo info;
public InvalidInjectionException(MixinTargetContext mixin, String message) {
super(mixin, message);
public InvalidInjectionException(IReferenceMapperContext context, String message) {
super(context, message);
this.info = null;
}
public InvalidInjectionException(InjectionInfo info, String message) {
super(info.getContext(), message);
this.info = info;
}
public InvalidInjectionException(MixinTargetContext mixin, Throwable cause) {
super(mixin, cause);
public InvalidInjectionException(IReferenceMapperContext context, Throwable cause) {
super(context, cause);
this.info = null;
}
public InvalidInjectionException(InjectionInfo info, Throwable cause) {
super(info.getContext(), cause);
this.info = info;
}
public InvalidInjectionException(MixinTargetContext mixin, String message, Throwable cause) {
super(mixin, message, cause);
public InvalidInjectionException(IReferenceMapperContext context, String message, Throwable cause) {
super(context, message, cause);
this.info = null;
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) {
super(info.getContext(), message, cause);
this.info = info;
}
public InjectionInfo getInjectionInfo() {
return this.info;
}
}
@@ -0,0 +1,53 @@
/*
* 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.throwables;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
/**
* Thrown when an injection point cannot be parsed due to invalid data
*/
public class InvalidInjectionPointException extends InvalidInjectionException {
private static final long serialVersionUID = 2L;
public InvalidInjectionPointException(IReferenceMapperContext context, String format, Object... args) {
super(context, String.format(format, args));
}
public InvalidInjectionPointException(InjectionInfo info, String format, Object... args) {
super(info, String.format(format, args));
}
public InvalidInjectionPointException(IReferenceMapperContext context, Throwable cause, String format, Object... args) {
super(context, String.format(format, args), cause);
}
public InvalidInjectionPointException(InjectionInfo info, Throwable cause, String format, Object... args) {
super(info, String.format(format, args), cause);
}
}
@@ -22,14 +22,19 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
package org.spongepowered.asm.mixin.refmap;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
/**
* Context for performing reference mapping
*/
public interface IReferenceMapperContext {
/**
* Get the mixin info
*/
public abstract IMixinInfo getMixin();
/**
* Get the internal mixin class name
@@ -0,0 +1,247 @@
/*
* 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.refmap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.launchwrapper.Launch;
/**
* Stores runtime information allowing field, method and type references which
* cannot be hard remapped by the reobfuscation process to be remapped in a
* "soft" manner at runtime. Refmaps are generated by the <em>Annotation
* Processor</em> at compile time and must be bundled with an obfuscated binary
* to allow obfuscated references in injectors and other String-defined targets
* to be remapped to the target obfsucation environment as appropriate. If the
* refmap is absent the environment is assumed to be deobfuscated (eg. dev-time)
* and injections and other transformations will fail if this is not the case.
*/
public final class ReferenceMapper implements Serializable {
private static final long serialVersionUID = 2L;
/**
* Resource to attempt to load if no source is specified explicitly
*/
public static final String DEFAULT_RESOURCE = "mixin.refmap.json";
/**
* Passthrough mapper, used as failover
*/
public static final ReferenceMapper DEFAULT_MAPPER = new ReferenceMapper(true);
/**
* "Default" mappings. The set of mappings to use as "default" is specified
* by the AP. Each entry is keyed by the owning mixin, with the value map
* containing the actual remappings for each owner
*/
private final Map<String, Map<String, String>> mappings = Maps.newHashMap();
/**
* All mapping sets, keyed by environment type, eg. "notch", "searge". The
* format of each map within this map is the same as for {@link #mappings}
*/
private final Map<String, Map<String, Map<String, String>>> data = Maps.newHashMap();
/**
* True if this refmap cannot be written. Only true for the
* {@link #DEFAULT_MAPPER}
*/
private final transient boolean readOnly;
/**
* Current remapping context, used as the key into {@link data}
*/
private transient String context = null;
/**
* Create an empty refmap
*/
public ReferenceMapper() {
this(false);
}
/**
* Create a readonly refmap, only used by {@link #DEFAULT_MAPPER}
*
* @param readOnly flag to indicate read-only
*/
private ReferenceMapper(boolean readOnly) {
this.readOnly = readOnly;
}
/**
* Get the current context
*
* @return current context key, can be null
*/
public String getContext() {
return this.context;
}
/**
* Set the current remap context, can be null
*
* @param context remap context
*/
public void setContext(String context) {
this.context = context;
}
/**
* Remap a reference for the specified owning class in the current context
*
* @param className Owner class
* @param reference Reference to remap
* @return remapped reference, returns original reference if not remapped
*/
public String remap(String className, String reference) {
return this.remapWithContext(this.context, className, reference);
}
/**
* Remap a reference for the specified owning class in the specified context
*
* @param context Remap context to use
* @param className Owner class
* @param reference Reference to remap
* @return remapped reference, returns original reference if not remapped
*/
public String remapWithContext(String context, String className, String reference) {
Map<String, Map<String, String>> mappings = this.mappings;
if (context != null) {
mappings = this.data.get(context);
if (mappings == null) {
mappings = this.mappings;
}
}
return this.remap(mappings, className, reference);
}
/**
* Remap the things
*/
private String remap(Map<String, Map<String, String>> mappings, String className, String reference) {
if (className == null) {
for (Map<String, String> mapping : mappings.values()) {
if (mapping.containsKey(reference)) {
return mapping.get(reference);
}
}
}
Map<String, String> classMappings = mappings.get(className);
if (classMappings == null) {
return reference;
}
String remappedReference = classMappings.get(reference);
return remappedReference != null ? remappedReference : reference;
}
/**
* Add a mapping to this refmap
*
* @param context Obfuscation context, can be null
* @param className Class which owns this mapping, cannot be null
* @param reference Reference to remap, cannot be null
* @param newReference Remapped value, cannot be null
*/
public void addMapping(String context, String className, String reference, String newReference) {
if (this.readOnly || reference == null || newReference == null || reference.equals(newReference)) {
return;
}
Map<String, Map<String, String>> mappings = this.mappings;
if (context != null) {
mappings = this.data.get(context);
if (mappings == null) {
mappings = Maps.newHashMap();
this.data.put(context, mappings);
}
}
Map<String, String> classMappings = mappings.get(className);
if (classMappings == null) {
classMappings = new HashMap<String, String>();
mappings.put(className, classMappings);
}
classMappings.put(reference, newReference);
}
/**
* Write this refmap out to the specified writer
*
* @param writer Writer to write to
*/
public void write(Appendable writer) {
new GsonBuilder().setPrettyPrinting().create().toJson(this, writer);
}
/**
* Read a new refmap from the specified resource
*
* @param resource Resource to read from
* @return new refmap or {@link #DEFAULT_MAPPER} if reading fails
*/
public static ReferenceMapper read(String resource) {
Reader reader = null;
try {
reader = new InputStreamReader(Launch.classLoader.getResourceAsStream(resource));
return ReferenceMapper.read(reader);
} catch (Exception ex) {
return ReferenceMapper.DEFAULT_MAPPER;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// don't really care
}
}
}
}
/**
* Read a new refmap instance from the specified reader
*
* @param reader Reader to read from
* @return new refmap
*/
public static ReferenceMapper read(Reader reader) {
try {
return new Gson().fromJson(reader, ReferenceMapper.class);
} catch (Exception ex) {
return ReferenceMapper.DEFAULT_MAPPER;
}
}
}
@@ -0,0 +1,50 @@
/*
* 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.throwables;
/**
* Exception raised when a class was loaded before mixins were able to be
* applied.
*/
public class ClassAlreadyLoadedException extends MixinException {
private static final long serialVersionUID = 1L;
public ClassAlreadyLoadedException(String message) {
super(message);
}
public ClassAlreadyLoadedException(Throwable cause) {
super(cause);
}
public ClassAlreadyLoadedException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -22,8 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin;
package org.spongepowered.asm.mixin.throwables;
/**
* Error to throw for required mixins when mixing of the mixin fails
@@ -22,28 +22,28 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.ClassNode;
package org.spongepowered.asm.mixin.throwables;
/**
* ClassNode for a MixinInfo
* Base class for all mixin processor exceptions
*/
public class MixinClassNode extends ClassNode {
private final MixinInfo mixin;
public class MixinException extends RuntimeException {
public MixinClassNode(MixinInfo mixin) {
this(Opcodes.ASM5, mixin);
private static final long serialVersionUID = 1L;
public MixinException() {
}
public MixinClassNode(int api, MixinInfo mixin) {
super(api);
this.mixin = mixin;
public MixinException(String message) {
super(message);
}
public MixinInfo getMixin() {
return this.mixin;
public MixinException(Throwable cause) {
super(cause);
}
public MixinException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,46 @@
/*
* 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.throwables;
/**
* Error to throw for required configs when initialising of the config fails
*/
public class MixinPrepareError extends Error {
private static final long serialVersionUID = 1L;
public MixinPrepareError(String message) {
super(message);
}
public MixinPrepareError(Throwable cause) {
super(cause);
}
public MixinPrepareError(String message, Throwable cause) {
super(message, cause);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
/*
* 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.transformer;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
/**
* Handle for marshalling mixin configs outside of the transformer package
*/
public class Config {
/**
* Config name, used as identity for the purposes of {@link #equals}
*/
private final String name;
/**
* Config
*/
private final MixinConfig config;
public Config(MixinConfig config) {
this.name = config.getName();
this.config = config;
}
public String getName() {
return this.name;
}
/**
* Access inner config
*/
MixinConfig get() {
return this.config;
}
/**
* Get API-level config view
*/
public IMixinConfig getConfig() {
return this.config;
}
/**
* Get environment for the config
*/
public MixinEnvironment getEnvironment() {
return this.config.getEnvironment();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.config.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return obj instanceof Config && this.name.equals(((Config)obj).name);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.name.hashCode();
}
/**
* Factory method, create a config from the specified config file and fail
* over to the specified environment if no selector is present in the config
*
* @param configFile config resource
* @param outer failover environment
* @return new config or null if invalid config version
*/
@Deprecated
public static Config create(String configFile, MixinEnvironment outer) {
return MixinConfig.create(configFile, outer);
}
/**
* Factory method, create a config from the specified config resource
*
* @param configFile config resource
* @return new config or null if invalid config version
*/
public static Config create(String configFile) {
return MixinConfig.create(configFile, MixinEnvironment.getDefaultEnvironment());
}
}
@@ -24,11 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.SortedSet;
import org.spongepowered.asm.lib.tree.ClassNode;
/**
* Mixin Transformer Module interface for pre- and post-processors
*/
@@ -37,19 +32,15 @@ public interface IMixinTransformerModule {
/**
* Called before the mixins are applied
*
* @param transformedName Target class name
* @param targetClass Target class tree
* @param mixins Mixins to be applied
* @param context Target class context
*/
public abstract void preApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins);
public abstract void preApply(TargetClassContext context);
/**
* Called after the mixins are applied
*
* @param transformedName Target class name
* @param targetClass Target class tree
* @param mixins Mixins which were applied
* @param context Target class context
*/
public abstract void postApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins);
public abstract void postApply(TargetClassContext context);
}
@@ -27,11 +27,15 @@ package org.spongepowered.asm.mixin.transformer;
import java.util.HashSet;
import java.util.Set;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
/**
@@ -56,6 +60,12 @@ public class InterfaceInfo extends TreeInfo {
*/
private final Type iface;
/**
* True if all methods implementing this interface should be treated as
* unique
*/
private final boolean unique;
/**
* Method signatures in the interface, lazy loaded
*/
@@ -68,7 +78,7 @@ public class InterfaceInfo extends TreeInfo {
* @param prefix Method prefix
* @param iface Interface to load
*/
private InterfaceInfo(MixinInfo mixin, String prefix, Type iface) {
private InterfaceInfo(MixinInfo mixin, String prefix, Type iface, boolean unique) {
if (prefix == null || prefix.length() < 2 || !prefix.endsWith("$")) {
throw new InvalidMixinException(mixin, String.format("Prefix %s for iface %s is not valid", prefix, iface.toString()));
}
@@ -76,6 +86,7 @@ public class InterfaceInfo extends TreeInfo {
this.mixin = mixin;
this.prefix = prefix;
this.iface = iface;
this.unique = unique;
}
/**
@@ -121,6 +132,15 @@ public class InterfaceInfo extends TreeInfo {
public Type getIface() {
return this.iface;
}
/**
* Get the internal name of the interface
*
* @return the internal name for the interface
*/
public String getName() {
return this.iface.getClassName();
}
/**
* Get the internal name of the interface
@@ -130,6 +150,15 @@ public class InterfaceInfo extends TreeInfo {
public String getInternalName() {
return this.iface.getInternalName();
}
/**
* Get whether all methods for this interface should be treated as unique
*
* @return true to treat all member methods as unique
*/
public boolean isUnique() {
return this.unique;
}
/**
* Processes a method node in the mixin and renames it if necessary. If the
@@ -146,20 +175,46 @@ public class InterfaceInfo extends TreeInfo {
}
if (!method.name.startsWith(this.prefix)) {
if (this.methods.contains(method.name + method.desc)) {
this.decorateUniqueMethod(method);
}
return false;
}
String realName = method.name.substring(this.prefix.length());
String signature = realName + method.desc;
if (!this.methods.contains(signature)) {
throw new InvalidMixinException(this.mixin, String.format("%s does not exist in target interface %s", realName, this.iface.toString()));
throw new InvalidMixinException(this.mixin, String.format("%s does not exist in target interface %s", realName, this.getName()));
}
if ((method.access & Opcodes.ACC_PUBLIC) == 0) {
throw new InvalidMixinException(this.mixin, String.format("%s cannot implement %s because it is not visible", realName, this.getName()));
}
ASMHelper.setVisibleAnnotation(method, MixinRenamed.class, "originalName", method.name, "isInterfaceMember", true);
this.decorateUniqueMethod(method);
method.name = realName;
return true;
}
/**
* Decorate the target method with {@link Unique} if the interface is marked
* as unique
*
* @param method method to decorate
*/
private void decorateUniqueMethod(MethodNode method) {
if (!this.unique) {
return;
}
if (ASMHelper.getVisibleAnnotation(method, Unique.class) == null) {
ASMHelper.setVisibleAnnotation(method, Unique.class);
this.mixin.getClassInfo().findMethod(method).setUnique(true);
}
}
/**
* Convert an {@link Interface} annotation node into an
* {@link InterfaceInfo}
@@ -171,11 +226,34 @@ public class InterfaceInfo extends TreeInfo {
static InterfaceInfo fromAnnotation(MixinInfo mixin, AnnotationNode node) {
String prefix = ASMHelper.<String>getAnnotationValue(node, "prefix");
Type iface = ASMHelper.<Type>getAnnotationValue(node, "iface");
Boolean unique = ASMHelper.<Boolean>getAnnotationValue(node, "unique");
if (prefix == null || iface == null) {
throw new InvalidMixinException(mixin, String.format("@Interface annotation on is missing a required parameter"));
throw new InvalidMixinException(mixin, String.format("@Interface annotation on %s is missing a required parameter", mixin));
}
return new InterfaceInfo(mixin, prefix, iface);
return new InterfaceInfo(mixin, prefix, iface, unique != null ? unique.booleanValue() : false);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InterfaceInfo that = (InterfaceInfo) o;
return this.mixin.equals(that.mixin) && this.prefix.equals(that.prefix) && this.iface.equals(that.iface);
}
@Override
public int hashCode() {
int result = this.mixin.hashCode();
result = 31 * result + this.prefix.hashCode();
result = 31 * result + this.iface.hashCode();
return result;
}
}
@@ -0,0 +1,321 @@
/*
* 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.transformer;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.util.ASMHelper;
/**
* Reference to a field or method that also includes invocation
* instructions.
*
* To instances are defined to be equal if they both refer to the same method
* and have the same invocation instructions.
*/
public abstract class MemberRef {
/**
* A static reference to a method backed by an invoke instruction
*/
public static final class Method extends MemberRef {
/**
* Method invocation instruction
*/
public final MethodInsnNode insn;
/**
* ctor
*
* @param insn Method instruction of this member reference
*/
public Method(MethodInsnNode insn) {
this.insn = insn;
}
@Override
public boolean isField() {
return false;
}
@Override
public int getOpcode() {
return this.insn.getOpcode();
}
@Override
public String getOwner() {
return this.insn.owner;
}
@Override
public void setOwner(String owner) {
this.insn.owner = owner;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getDesc() {
return this.insn.desc;
}
@Override
public void setDesc(String desc) {
this.insn.desc = desc;
}
}
/**
* A static reference to a field backed by field get/put instruction
*/
public static final class Field extends MemberRef {
/**
* Field accessor instruction
*/
public final FieldInsnNode insn;
/**
* ctor
*
* @param insn Field instruction this member reference
*/
public Field(FieldInsnNode insn) {
this.insn = insn;
}
@Override
public boolean isField() {
return true;
}
@Override
public int getOpcode() {
return this.insn.getOpcode();
}
@Override
public String getOwner() {
return this.insn.owner;
}
@Override
public void setOwner(String owner) {
this.insn.owner = owner;
}
@Override
public String getName() {
return this.insn.name;
}
@Override
public String getDesc() {
return this.insn.desc;
}
@Override
public void setDesc(String desc) {
this.insn.desc = desc;
}
}
/**
* A reference to a field or method backed by a method handle
*/
public static final class Handle extends MemberRef {
private org.spongepowered.asm.lib.Handle handle;
/**
* Creates a member reference initially referring to the member referred
* to by the method handle and the invocation instruction of the method
* handle.
*
* @param handle Initial method handle.
*/
public Handle(org.spongepowered.asm.lib.Handle handle) {
this.handle = handle;
}
/**
* Gets a method handle for the member this is object is referring to.
*
* @return Method handle representing this object
*/
public org.spongepowered.asm.lib.Handle getMethodHandle() {
return this.handle;
}
@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 + ".");
}
}
@Override
public int getOpcode() {
switch (this.handle.getTag()) {
case Opcodes.H_INVOKEVIRTUAL:
return Opcodes.INVOKEVIRTUAL;
case Opcodes.H_INVOKESTATIC:
return Opcodes.INVOKESTATIC;
case Opcodes.H_INVOKEINTERFACE:
return Opcodes.INVOKEINTERFACE;
case Opcodes.H_INVOKESPECIAL:
case Opcodes.H_NEWINVOKESPECIAL:
return Opcodes.INVOKESPECIAL;
case Opcodes.H_GETFIELD:
return Opcodes.GETFIELD;
case Opcodes.H_GETSTATIC:
return Opcodes.GETSTATIC;
case Opcodes.H_PUTFIELD:
return Opcodes.PUTFIELD;
case Opcodes.H_PUTSTATIC:
return Opcodes.PUTSTATIC;
default:
throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
}
}
@Override
public String getOwner() {
return this.handle.getOwner();
}
@Override
public void setOwner(String owner) {
this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc());
}
@Override
public String getName() {
return this.handle.getName();
}
@Override
public String getDesc() {
return this.handle.getDesc();
}
@Override
public void setDesc(String desc) {
this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
}
}
/**
* Whether this member is a field.
*
* @return If this member is a field, else it is a method
*/
public abstract boolean isField();
/**
* The opcode of the invocation.
*
* @return The opcode of the invocation
*/
public abstract int getOpcode();
/**
* The internal name for the owner of this member.
*
* @return The owners name
*/
public abstract String getOwner();
/**
* Changes the owner of this
*
* @param owner New owner
*/
public abstract void setOwner(String owner);
/**
* Name of this member.
*
* @return Name of this member.
*/
public abstract String getName();
/**
* Descriptor of this member.
*
* @return Descriptor of this member
*/
public abstract String getDesc();
/**
* Changes the descriptor of this member
*
* @param desc New descriptor of this member
*/
public abstract void setDesc(String desc);
@Override
public String toString() {
return ASMHelper.getOpcodeName(this.getOpcode()) + " for "
+ this.getOwner() + "." + this.getName() + (this.isField() ? ":" : "") + this.getDesc();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MemberRef)) {
return false;
}
MemberRef other = (MemberRef)obj;
return this.getOpcode() == other.getOpcode()
&& this.getOwner().equals(other.getOwner())
&& this.getName().equals(other.getName())
&& this.getDesc().equals(other.getDesc());
}
@Override
public int hashCode() {
return this.toString().hashCode();
}
}
@@ -0,0 +1,123 @@
/*
* 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.transformer;
import java.util.Map.Entry;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException;
/**
* Applicator for interface mixins, mainly just disables things which aren't
* supported for interface mixins
*/
public class MixinApplicatorInterface extends MixinApplicatorStandard {
/**
* ctor
*
* @param context applier context
*/
MixinApplicatorInterface(TargetClassContext context) {
super(context);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinApplicator
* #applyInterfaces(
* org.spongepowered.asm.mixin.transformer.MixinTargetContext)
*/
@Override
protected void applyInterfaces(MixinTargetContext mixin) {
for (String interfaceName : mixin.getInterfaces()) {
if (!this.targetClass.name.equals(interfaceName) && !this.targetClass.interfaces.contains(interfaceName)) {
this.targetClass.interfaces.add(interfaceName);
mixin.getTargetClassInfo().addInterface(interfaceName);
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinApplicator
* #applyFields(
* org.spongepowered.asm.mixin.transformer.MixinTargetContext)
*/
@Override
protected void applyFields(MixinTargetContext mixin) {
// shadow fields have no meaning for interfaces, just spam the dev with messages
for (Entry<FieldNode, Field> entry : mixin.getShadowFields()) {
FieldNode shadow = entry.getKey();
this.logger.error("Ignoring redundant @Shadow field {}:{} in {}", shadow.name, shadow.desc, mixin);
}
this.mergeNewFields(mixin);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinApplicator
* #applyInitialisers(
* org.spongepowered.asm.mixin.transformer.MixinTargetContext)
*/
@Override
protected void applyInitialisers(MixinTargetContext mixin) {
// disabled for interface mixins
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinApplicator
* #prepareInjections(
* org.spongepowered.asm.mixin.transformer.MixinTargetContext)
*/
@Override
protected void prepareInjections(MixinTargetContext mixin) {
// disabled for interface mixins
for (MethodNode method : this.targetClass.methods) {
try {
InjectionInfo injectInfo = InjectionInfo.parse(mixin, method);
if (injectInfo != null) {
throw new InvalidInterfaceMixinException(mixin, injectInfo + " is not supported on interface mixin method " + method.name);
}
} catch (InvalidInjectionException ex) {
String description = ex.getInjectionInfo() != null ? ex.getInjectionInfo().toString() : "Injection";
throw new InvalidInterfaceMixinException(mixin, description + " is not supported in interface mixin");
}
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinApplicator
* #applyInjections(
* org.spongepowered.asm.mixin.transformer.MixinTargetContext)
*/
@Override
protected void applyInjections(MixinTargetContext mixin) {
// Do nothing
}
}
@@ -24,12 +24,14 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.lang.annotation.Annotation;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import org.apache.logging.log4j.LogManager;
@@ -46,25 +48,65 @@ import org.spongepowered.asm.lib.tree.LabelNode;
import org.spongepowered.asm.lib.tree.LineNumberNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.ConstraintParser;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
import org.spongepowered.asm.util.ConstraintViolationException;
import org.spongepowered.asm.util.InvalidConstraintException;
import org.spongepowered.asm.util.throwables.ConstraintViolationException;
import org.spongepowered.asm.util.throwables.InvalidConstraintException;
import com.google.common.collect.ImmutableList;
/**
* Applies mixins to a target class
*/
public class MixinApplicator {
public class MixinApplicatorStandard {
/**
* Annotations which can have constraints
*/
protected static final List<Class<? extends Annotation>> CONSTRAINED_ANNOTATIONS = ImmutableList.<Class<? extends Annotation>>of(
Overwrite.class,
Inject.class,
ModifyArg.class,
Redirect.class,
ModifyVariable.class,
ModifyConstant.class
);
/**
* Passes the mixin applicator applies to each mixin
*/
enum ApplicatorPass {
/**
* Main pass, mix in methods, fields, interfaces etc
*/
MAIN,
/**
* Enumerate injectors and scan for injection points
*/
PREINJECT,
/**
* Apply injectors from previous pass
*/
INJECT
}
/**
* Internal struct for representing a range
@@ -145,7 +187,7 @@ public class MixinApplicator {
* locals are shifted so that they don't interfere with locals in the
* receiving constructor.
*/
private static final int[] INITIALISER_OPCODE_BLACKLIST = {
protected static final int[] INITIALISER_OPCODE_BLACKLIST = {
Opcodes.RETURN, Opcodes.ILOAD, Opcodes.LLOAD, Opcodes.FLOAD, Opcodes.DLOAD, Opcodes.IALOAD, Opcodes.LALOAD, Opcodes.FALOAD, Opcodes.DALOAD,
Opcodes.AALOAD, Opcodes.BALOAD, Opcodes.CALOAD, Opcodes.SALOAD, Opcodes.ISTORE, Opcodes.LSTORE, Opcodes.FSTORE, Opcodes.DSTORE,
Opcodes.ASTORE, Opcodes.IASTORE, Opcodes.LASTORE, Opcodes.FASTORE, Opcodes.DASTORE, Opcodes.AASTORE, Opcodes.BASTORE, Opcodes.CASTORE,
@@ -155,39 +197,64 @@ public class MixinApplicator {
/**
* Log more things
*/
private final Logger logger = LogManager.getLogger("mixin");
protected final Logger logger = LogManager.getLogger("mixin");
/**
* Session ID, used as a check when parsing {@link MixinMerged} annotations
* to prevent them being applied at compile time by people trying to
* circumvent mixin application
* Target class context
*/
private final String sessionId;
protected final TargetClassContext context;
/**
* Target class name
*/
private final String targetName;
protected final String targetName;
/**
* Target class tree
*/
private final ClassNode targetClass;
protected final ClassNode targetClass;
MixinApplicator(String sessionId, String transformedName, ClassNode targetClass) {
this.sessionId = sessionId;
this.targetName = transformedName;
this.targetClass = targetClass;
MixinApplicatorStandard(TargetClassContext context) {
this.context = context;
this.targetName = context.getClassName();
this.targetClass = context.getClassNode();
}
/**
* Apply supplied mixins to the target class
*/
void apply(SortedSet<MixinInfo> mixins) {
List<MixinTargetContext> mixinContexts = new ArrayList<MixinTargetContext>();
for (MixinInfo mixin : mixins) {
this.logger.log(mixin.getLoggingLevel(), "Mixing {} from {} into {}", mixin.getName(), mixin.getParent(), this.targetName);
this.applyMixin(mixin.createContextFor(this.targetClass));
mixinContexts.add(mixin.createContextFor(this.context));
}
MixinTargetContext current = null;
try {
for (MixinTargetContext context : mixinContexts) {
(current = context).preApply(this.targetName, this.targetClass);
}
for (ApplicatorPass pass : ApplicatorPass.values()) {
for (MixinTargetContext context : mixinContexts) {
this.applyMixin(current = context, pass);
}
}
for (MixinTargetContext context : mixinContexts) {
(current = context).postApply(this.targetName, this.targetClass);
}
} catch (InvalidMixinException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidMixinException(current, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst applying the mixin class: "
+ ex.getMessage(), ex);
}
this.context.processDebugTasks();
}
/**
@@ -195,23 +262,28 @@ public class MixinApplicator {
*
* @param mixin Mixin to apply
*/
private void applyMixin(MixinTargetContext mixin) {
try {
mixin.preApply(this.targetName, this.targetClass);
this.applyInterfaces(mixin);
this.applyAttributes(mixin);
this.applyAnnotations(mixin);
this.applyFields(mixin);
this.applyMethods(mixin);
this.applyInitialisers(mixin);
this.applyInjections(mixin);
mixin.postApply(this.targetName, this.targetClass);
} catch (InvalidMixinException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidMixinException(mixin, "Unexpecteded error whilst applying the mixin class", ex);
protected final void applyMixin(MixinTargetContext mixin, ApplicatorPass pass) {
switch (pass) {
case MAIN:
this.applyInterfaces(mixin);
this.applyAttributes(mixin);
this.applyAnnotations(mixin);
this.applyFields(mixin);
this.applyMethods(mixin);
this.applyInitialisers(mixin);
break;
case PREINJECT:
this.prepareInjections(mixin);
break;
case INJECT:
this.applyInjections(mixin);
break;
default:
// wat?
throw new IllegalStateException("Invalid pass specified " + pass);
}
}
@@ -220,10 +292,11 @@ public class MixinApplicator {
*
* @param mixin
*/
private void applyInterfaces(MixinTargetContext mixin) {
protected void applyInterfaces(MixinTargetContext mixin) {
for (String interfaceName : mixin.getInterfaces()) {
if (!this.targetClass.interfaces.contains(interfaceName)) {
this.targetClass.interfaces.add(interfaceName);
mixin.getTargetClassInfo().addInterface(interfaceName);
}
}
}
@@ -233,10 +306,11 @@ public class MixinApplicator {
*
* @param mixin
*/
private void applyAttributes(MixinTargetContext mixin) {
protected void applyAttributes(MixinTargetContext mixin) {
if (mixin.shouldSetSourceFile()) {
this.targetClass.sourceFile = mixin.getSourceFile();
}
this.targetClass.version = Math.max(this.targetClass.version, mixin.getMinRequiredClassVersion());
}
/**
@@ -244,7 +318,7 @@ public class MixinApplicator {
*
* @param mixin
*/
private void applyAnnotations(MixinTargetContext mixin) {
protected void applyAnnotations(MixinTargetContext mixin) {
ClassNode sourceClass = mixin.getClassNode();
this.mergeAnnotations(sourceClass, this.targetClass);
}
@@ -257,14 +331,27 @@ public class MixinApplicator {
*
* @param mixin
*/
private void applyFields(MixinTargetContext mixin) {
for (FieldNode shadow : mixin.getShadowFields()) {
protected void applyFields(MixinTargetContext mixin) {
this.mergeShadowFields(mixin);
this.mergeNewFields(mixin);
}
protected void mergeShadowFields(MixinTargetContext mixin) {
for (Entry<FieldNode, Field> entry : mixin.getShadowFields()) {
FieldNode shadow = entry.getKey();
FieldNode target = this.findTargetField(shadow);
if (target != null) {
this.mergeAnnotations(shadow, target);
// Strip the FINAL flag from @Mutable non-private fields
if (entry.getValue().isDecoratedMutable() && !ASMHelper.hasFlag(target, Opcodes.ACC_PRIVATE)) {
target.access &= ~Opcodes.ACC_FINAL;
}
}
}
}
protected void mergeNewFields(MixinTargetContext mixin) {
for (FieldNode field : mixin.getFields()) {
FieldNode target = this.findTargetField(field);
if (target == null) {
@@ -279,7 +366,7 @@ public class MixinApplicator {
*
* @param mixin
*/
private void applyMethods(MixinTargetContext mixin) {
protected void applyMethods(MixinTargetContext mixin) {
for (MethodNode shadow : mixin.getShadowMethods()) {
MethodNode target = this.findTargetMethod(shadow);
if (target != null) {
@@ -292,21 +379,9 @@ public class MixinApplicator {
mixin.transformMethod(mixinMethod);
if (!mixinMethod.name.startsWith("<")) {
AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class);
boolean isOverwrite = overwrite != null;
if (isOverwrite) {
this.checkConstraints(mixin, overwrite);
}
if (MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_STATIC)
&& !MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE)
&& !MixinApplicator.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)
&& !isOverwrite) {
throw new InvalidMixinException(mixin,
String.format("Mixin classes cannot contain visible static methods or fields, found %s", mixinMethod.name));
}
this.mergeMethod(mixin, mixinMethod, isOverwrite);
this.checkMethodVisibility(mixin, mixinMethod);
this.checkMethodConstraints(mixin, mixinMethod);
this.mergeMethod(mixin, mixinMethod);
} else if (Constants.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
this.appendInsns(mixinMethod);
@@ -319,14 +394,13 @@ public class MixinApplicator {
*
* @param mixin Mixin being applied
* @param method Method to merge
* @param isOverwrite true if the method is annotated with an
* {@link Overwrite} annotation
*/
private void mergeMethod(MixinTargetContext mixin, MethodNode method, boolean isOverwrite) {
protected void mergeMethod(MixinTargetContext mixin, MethodNode method) {
boolean isOverwrite = ASMHelper.getVisibleAnnotation(method, Overwrite.class) != null;
MethodNode target = this.findTargetMethod(method);
if (target != null) {
if (this.alreadyMerged(mixin, method, isOverwrite, target)) {
if (this.isAlreadyMerged(mixin, method, isOverwrite, target)) {
return;
}
@@ -339,16 +413,12 @@ public class MixinApplicator {
this.targetClass.methods.remove(target);
}
} else if (isOverwrite) {
throw new InvalidMixinException(mixin, String.format("Overwrite target %s was not located in the target class", method.name));
throw new InvalidMixinException(mixin, String.format("Overwrite target \"%s\" was not located in target class %s",
method.name, mixin.getTargetClassRef()));
}
this.targetClass.methods.add(method);
mixin.getTargetClassInfo().addMethod(method);
ASMHelper.setVisibleAnnotation(method, MixinMerged.class,
"mixin", mixin.getClassName(),
"priority", mixin.getPriority(),
"sessionId", this.sessionId);
mixin.addMergedMethod(method);
}
/**
@@ -362,23 +432,40 @@ public class MixinApplicator {
* @param target target method being checked
* @return true if the target was already merged and should be skipped
*/
private boolean alreadyMerged(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target) {
protected boolean isAlreadyMerged(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target) {
AnnotationNode merged = ASMHelper.getVisibleAnnotation(target, MixinMerged.class);
if (merged == null) {
if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) {
this.logger.warn("Overwrite prohibited for @Final method {} in {}. Skipping method.", method.name, mixin);
return true;
}
return false;
}
String sessionId = ASMHelper.<String>getAnnotationValue(merged, "sessionId");
if (!this.sessionId.equals(sessionId)) {
if (!this.context.getSessionId().equals(sessionId)) {
throw new ClassFormatError("Invalid @MixinMerged annotation found in" + mixin + " at " + method.name + " in " + this.targetClass.name);
}
if (ASMHelper.hasFlag(target, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE)
&& ASMHelper.hasFlag(method, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE)) {
if (mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE)) {
this.logger.warn("Synthetic bridge method clash for {} in {}", method.name, mixin);
}
return true;
}
String owner = ASMHelper.<String>getAnnotationValue(merged, "mixin");
int priority = ASMHelper.<Integer>getAnnotationValue(merged, "priority");
if (priority >= mixin.getPriority() && !owner.equals(mixin.getClassName())) {
this.logger.warn("Method overwrite conflict for {}, previously written by {}. Skipping method.", method.name, owner);
this.logger.warn("Method overwrite conflict for {} in {}, previously written by {}. Skipping method.", method.name, mixin, owner);
return true;
}
if (ASMHelper.getVisibleAnnotation(target, Final.class) != null) {
this.logger.warn("Method overwrite conflict for @Final method {} in {} declared by {}. Skipping method.", method.name, mixin, owner);
return true;
}
@@ -398,25 +485,27 @@ public class MixinApplicator {
* @return true if the intrinsic method was skipped (short-circuit further
* merge operations)
*/
private boolean mergeIntrinsic(MixinTargetContext mixin, MethodNode method, boolean isOverwrite,
protected boolean mergeIntrinsic(MixinTargetContext mixin, MethodNode method, boolean isOverwrite,
MethodNode target, AnnotationNode intrinsic) {
if (isOverwrite) {
throw new InvalidMixinException(mixin, "@Intrinsic is not compatible with @Overwrite, remove one of these annotations on "
+ method.name);
+ method.name + " in " + mixin);
}
if (MixinApplicator.hasFlag(method, Opcodes.ACC_STATIC)) {
throw new InvalidMixinException(mixin, "@Intrinsic method cannot be static, found " + method.name);
String methodName = method.name + method.desc;
if (ASMHelper.hasFlag(method, Opcodes.ACC_STATIC)) {
throw new InvalidMixinException(mixin, "@Intrinsic method cannot be static, found " + methodName + " in " + mixin);
}
AnnotationNode renamed = ASMHelper.getVisibleAnnotation(method, MixinRenamed.class);
if (renamed == null || !ASMHelper.getAnnotationValue(renamed, "isInterfaceMember", false)) {
throw new InvalidMixinException(mixin, "@Intrinsic method must be prefixed interface method, no rename encountered on " + method.name);
throw new InvalidMixinException(mixin, "@Intrinsic method must be prefixed interface method, no rename encountered on "
+ methodName + " in " + mixin);
}
if (!ASMHelper.getAnnotationValue(intrinsic, "displace", false)) {
this.logger.log(mixin.getLoggingLevel(), "Skipping Intrinsic mixin method {}", method.name);
this.logger.log(mixin.getLoggingLevel(), "Skipping Intrinsic mixin method {} for {}", methodName, mixin.getTargetClassRef());
return true;
}
@@ -431,7 +520,7 @@ public class MixinApplicator {
* @param method Method being merged
* @param target target method being checked
*/
private void displaceIntrinsic(MixinTargetContext mixin, MethodNode method, MethodNode target) {
protected void displaceIntrinsic(MixinTargetContext mixin, MethodNode method, MethodNode target) {
// Deliberately include invalid character in the method name so that
// we guarantee no hackiness
String proxyName = "proxy+" + target.name;
@@ -455,7 +544,7 @@ public class MixinApplicator {
*
* @param method
*/
private void appendInsns(MethodNode method) {
protected final void appendInsns(MethodNode method) {
if (Type.getReturnType(method.desc) != Type.VOID_TYPE) {
throw new IllegalArgumentException("Attempted to merge insns from a method which does not return void");
}
@@ -463,7 +552,7 @@ public class MixinApplicator {
MethodNode target = this.findTargetMethod(method);
if (target != null) {
AbstractInsnNode returnNode = MixinApplicator.findInsn(target, Opcodes.RETURN);
AbstractInsnNode returnNode = MixinApplicatorStandard.findInsn(target, Opcodes.RETURN);
if (returnNode != null) {
Iterator<AbstractInsnNode> injectIter = method.instructions.iterator();
@@ -490,7 +579,7 @@ public class MixinApplicator {
*
* @param mixin
*/
private void applyInitialisers(MixinTargetContext mixin) {
protected void applyInitialisers(MixinTargetContext mixin) {
// Try to find a suitable constructor, we need a constructor with line numbers in order to extract the initialiser
MethodNode ctor = this.getConstructor(mixin);
if (ctor == null) {
@@ -505,7 +594,7 @@ public class MixinApplicator {
// Patch the initialiser into the target class ctors
for (MethodNode method : this.targetClass.methods) {
if (Constants.INIT.equals(method.name)) {
if (Constants.CTOR.equals(method.name)) {
method.maxStack = Math.max(method.maxStack, ctor.maxStack);
this.injectInitialiser(mixin, method, initialiser);
}
@@ -516,20 +605,18 @@ public class MixinApplicator {
* Finds a suitable ctor for reading the instance initialiser bytecode
*
* @param mixin mixin to search
* @return
* @return appropriate ctor or null if none found
*/
private MethodNode getConstructor(MixinTargetContext mixin) {
protected MethodNode getConstructor(MixinTargetContext mixin) {
MethodNode ctor = null;
for (MethodNode mixinMethod : mixin.getMethods()) {
if (Constants.INIT.equals(mixinMethod.name)) {
if (MixinApplicator.hasLineNumbers(mixinMethod)) {
if (ctor == null) {
ctor = mixinMethod;
} else {
// Not an error condition, just weird
this.logger.warn(String.format("Mixin %s has multiple constructors, %s was selected\n", mixin, ctor.desc));
}
if (Constants.CTOR.equals(mixinMethod.name) && MixinApplicatorStandard.hasLineNumbers(mixinMethod)) {
if (ctor == null) {
ctor = mixinMethod;
} else {
// Not an error condition, just weird
this.logger.warn(String.format("Mixin %s has multiple constructors, %s was selected\n", mixin, ctor.desc));
}
}
}
@@ -556,7 +643,7 @@ public class MixinApplicator {
line = ((LineNumberNode)insn).line;
lineNumberIsValid = true;
} else if (insn instanceof MethodInsnNode) {
if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.INIT.equals(((MethodInsnNode)insn).name) && superIndex == -1) {
if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.CTOR.equals(((MethodInsnNode)insn).name) && superIndex == -1) {
superIndex = ctor.instructions.indexOf(insn);
start = line;
}
@@ -592,7 +679,7 @@ public class MixinApplicator {
* @return initialiser bytecode extracted from the supplied constructor, or
* null if the constructor range could not be parsed
*/
private Deque<AbstractInsnNode> getInitialiser(MixinTargetContext mixin, MethodNode ctor) {
protected final Deque<AbstractInsnNode> getInitialiser(MixinTargetContext mixin, MethodNode ctor) {
// Find the range of line numbers which corresponds to the constructor body
Range init = this.getConstructorRange(ctor);
if (!init.isValid()) {
@@ -631,7 +718,7 @@ public class MixinApplicator {
trimAtOpcode = -1;
continue;
}
for (int ivalidOp : MixinApplicator.INITIALISER_OPCODE_BLACKLIST) {
for (int ivalidOp : MixinApplicatorStandard.INITIALISER_OPCODE_BLACKLIST) {
if (opcode == ivalidOp) {
// At the moment I don't handle any transient locals because I haven't seen any in the wild, but let's avoid writing
// code which will likely break things and fix it if a real test case ever appears
@@ -650,7 +737,7 @@ public class MixinApplicator {
if (last != null) {
if (last.getOpcode() != Opcodes.PUTFIELD) {
throw new InvalidMixinException(mixin, "Could not parse initialiser, expected 0xB5, found 0x"
+ Integer.toHexString(last.getOpcode()));
+ Integer.toHexString(last.getOpcode()) + " in " + mixin);
}
}
@@ -663,22 +750,22 @@ public class MixinApplicator {
* @param ctor
* @param initialiser
*/
private void injectInitialiser(MixinTargetContext mixin, MethodNode ctor, Deque<AbstractInsnNode> initialiser) {
protected final void injectInitialiser(MixinTargetContext mixin, MethodNode ctor, Deque<AbstractInsnNode> initialiser) {
Map<LabelNode, LabelNode> labels = ASMHelper.cloneLabels(ctor.instructions);
for (Iterator<AbstractInsnNode> iter = ctor.instructions.iterator(0); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.INIT.equals(((MethodInsnNode)insn).name)) {
if (insn.getOpcode() == Opcodes.INVOKESPECIAL && Constants.CTOR.equals(((MethodInsnNode)insn).name)) {
for (AbstractInsnNode node : initialiser) {
if (node instanceof LabelNode) {
continue;
}
if (node instanceof JumpInsnNode) {
throw new InvalidMixinException(mixin, "Unsupported opcode in initialiser");
throw new InvalidMixinException(mixin, "Unsupported JUMP opcode in initialiser in " + mixin);
}
AbstractInsnNode iThinkWereACloneNow = node.clone(labels);
ctor.instructions.insert(insn, iThinkWereACloneNow);
insn = iThinkWereACloneNow;
AbstractInsnNode imACloneNow = node.clone(labels);
ctor.instructions.insert(insn, imACloneNow);
insn = imACloneNow;
}
return;
}
@@ -688,50 +775,73 @@ public class MixinApplicator {
}
/**
* Process {@link Inject} annotations and inject callbacks to annotated
* methods
* @param mixin
* Scan for injector methods and injection points
*
* @param mixin Mixin being scanned
*/
private void applyInjections(MixinTargetContext mixin) {
List<InjectionInfo> injected = new ArrayList<InjectionInfo>();
for (MethodNode method : this.targetClass.methods) {
InjectionInfo injectInfo = InjectionInfo.parse(mixin, method);
if (injectInfo == null) {
continue;
}
if (injectInfo.isValid()) {
injectInfo.inject();
injected.add(injectInfo);
}
method.visibleAnnotations.remove(injectInfo.getAnnotation());
}
for (InjectionInfo injectInfo : injected) {
injectInfo.postInject();
protected void prepareInjections(MixinTargetContext mixin) {
mixin.prepareInjections();
}
/**
* Apply all injectors discovered in the previous pass
*
* @param mixin Mixin being applied
*/
protected void applyInjections(MixinTargetContext mixin) {
mixin.applyInjections();
}
/**
* Check visibility before merging a mixin method
*
* @param mixin
* @param mixinMethod
*/
protected void checkMethodVisibility(MixinTargetContext mixin, MethodNode mixinMethod) {
if (ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_STATIC)
&& !ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_PRIVATE)
&& !ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_SYNTHETIC)
&& !(ASMHelper.getVisibleAnnotation(mixinMethod, Overwrite.class) != null)) {
throw new InvalidMixinException(mixin,
String.format("Mixin %s contains non-private static method %s", mixin, mixinMethod));
}
}
/**
* Check constraints in annotations on the specified mixin method
*
* @param mixin Target context
* @param method Mixin method
*/
protected void checkMethodConstraints(MixinTargetContext mixin, MethodNode method) {
for (Class<? extends Annotation> annotationType : MixinApplicatorStandard.CONSTRAINED_ANNOTATIONS) {
AnnotationNode annotation = ASMHelper.getVisibleAnnotation(method, annotationType);
if (annotation != null) {
this.checkConstraints(mixin, method, annotation);
}
}
}
/**
* Check constraints for the specified annotation based on token values in
* the current environment
*
* @param mixin Mixin being applied
* @param method annotated method
* @param annotation Annotation node to check constraints
*/
private void checkConstraints(MixinTargetContext mixin, AnnotationNode annotation) {
protected final void checkConstraints(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
try {
Constraint constraint = ConstraintParser.parse(annotation);
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
try {
constraint.check(environment);
} catch (ConstraintViolationException ex) {
if (environment.getOption(Option.IGNORE_CONSTRAINTS)) {
this.logger.warn("Constraint violation: {}", ex.getMessage());
} else {
throw new InvalidMixinException(mixin, ex.getMessage(), ex);
String message = String.format("Constraint violation: %s on %s in %s", ex.getMessage(), method, mixin);
this.logger.warn(message);
if (!environment.getOption(Option.IGNORE_CONSTRAINTS)) {
throw new InvalidMixinException(mixin, message, ex);
}
}
} catch (InvalidConstraintException ex) {
@@ -750,7 +860,7 @@ public class MixinApplicator {
* @param from ClassNode to merge annotations from
* @param to ClassNode to merge annotations to
*/
private void mergeAnnotations(ClassNode from, ClassNode to) {
protected final void mergeAnnotations(ClassNode from, ClassNode to) {
to.visibleAnnotations = this.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, from.name);
to.invisibleAnnotations = this.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, from.name);
}
@@ -766,7 +876,7 @@ public class MixinApplicator {
* @param from MethodNode to merge annotations from
* @param to MethodNode to merge annotations to
*/
private void mergeAnnotations(MethodNode from, MethodNode to) {
protected final void mergeAnnotations(MethodNode from, MethodNode to) {
to.visibleAnnotations = this.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, from.name);
to.invisibleAnnotations = this.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, from.name);
}
@@ -782,7 +892,7 @@ public class MixinApplicator {
* @param from FieldNode to merge annotations from
* @param to FieldNode to merge annotations to
*/
private void mergeAnnotations(FieldNode from, FieldNode to) {
protected final void mergeAnnotations(FieldNode from, FieldNode to) {
to.visibleAnnotations = this.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, from.name);
to.invisibleAnnotations = this.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, from.name);
}
@@ -807,7 +917,7 @@ public class MixinApplicator {
}
for (AnnotationNode annotation : from) {
if (annotation.desc.startsWith("L" + Constants.MIXIN_PACKAGE_REF)) {
if (!this.isMergeableAnnotation(annotation)) {
continue;
}
@@ -827,6 +937,13 @@ public class MixinApplicator {
return to;
}
private boolean isMergeableAnnotation(AnnotationNode annotation) {
if (annotation.desc.startsWith("L" + Constants.MIXIN_PACKAGE_REF)) {
return annotation.desc.endsWith("Debug;");
}
return true;
}
/**
* Find the first insn node with a matching opcode in the specified method
*
@@ -834,7 +951,7 @@ public class MixinApplicator {
* @param opcode opcode to search for
* @return found node or null if not found
*/
private static AbstractInsnNode findInsn(MethodNode method, int opcode) {
protected static AbstractInsnNode findInsn(MethodNode method, int opcode) {
Iterator<AbstractInsnNode> findReturnIter = method.instructions.iterator();
while (findReturnIter.hasNext()) {
AbstractInsnNode insn = findReturnIter.next();
@@ -866,7 +983,7 @@ public class MixinApplicator {
*
* @return Target method matching searchFor, or null if not found
*/
private MethodNode findTargetMethod(MethodNode searchFor) {
protected final MethodNode findTargetMethod(MethodNode searchFor) {
for (MethodNode target : this.targetClass.methods) {
if (target.name.equals(searchFor.name) && target.desc.equals(searchFor.desc)) {
return target;
@@ -882,7 +999,7 @@ public class MixinApplicator {
*
* @return Target field matching searchFor, or null if not found
*/
private FieldNode findTargetField(FieldNode searchFor) {
protected final FieldNode findTargetField(FieldNode searchFor) {
for (FieldNode target : this.targetClass.fields) {
if (target.name.equals(searchFor.name)) {
return target;
@@ -892,25 +1009,4 @@ public class MixinApplicator {
return null;
}
/**
* Check whether the specified flag is set on the specified method
*
* @param method
* @param flag
* @return True if the specified flag is set in this method's access flags
*/
static boolean hasFlag(MethodNode method, int flag) {
return (method.access & flag) == flag;
}
/**
* Check whether the specified flag is set on the specified field
*
* @param field
* @param flag
* @return True if the specified flag is set in this field's access flags
*/
static boolean hasFlag(FieldNode field, int flag) {
return (field.access & flag) == flag;
}
}
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.transformer;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -33,29 +34,49 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.Launch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.launch.MixinInitialisationError;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.VersionNumber;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import net.minecraft.launchwrapper.Launch;
/**
* Mixin configuration bundle
*/
class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
/**
* Wrapper for injection options
*/
static class InjectorOptions {
@SerializedName("defaultRequire")
int defaultRequireValue = 0;
@SerializedName("defaultGroup")
String defaultGroup = "default";
}
/**
* Global order of mixin configs, used to determine ordering between configs
* with equivalent priority
@@ -66,7 +87,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Global list of mixin classes, so we can skip any duplicates
*/
private static final Set<String> globalMixinList = new HashSet<String>();
/**
* Log even more things
*/
@@ -91,13 +112,30 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Synthetic inner classes for mixins in this set
*/
private final transient Set<String> syntheticInnerClasses = new HashSet<String>();
/**
* Marshal
*/
private transient Config handle;
/**
* Target selector, eg. &#064;env(DEFAULT)
*/
@SerializedName("target")
private String selector;
/**
* Minimum version of the mixin subsystem required to correctly apply mixins
* in this configuration.
*/
@SerializedName("minVersion")
private String version;
private String version;
/**
* Minimum compatibility level required for mixins in this set
*/
@SerializedName("compatibilityLevel")
private String compatibility;
/**
* Determines whether failures in this mixin config are considered terminal
@@ -171,7 +209,17 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Intrinsic order (for sorting configurations with identical priority)
*/
private final transient int order = MixinConfig.configOrder++;
// /**
// * Phase selector
// */
// private transient List<Selector> selectors;
/**
* Parent environment
*/
private transient MixinEnvironment env;
/**
* Name of the file this config was initialised from
*/
@@ -183,6 +231,12 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
@SerializedName("plugin")
private String pluginClassName;
/**
* Injector options
*/
@SerializedName("injectors")
private InjectorOptions injectorOptions = new InjectorOptions();
/**
* Config plugin, if supplied
*/
@@ -196,8 +250,8 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
/**
* Keep track of initialisation state
*/
private transient boolean initialised = false;
private transient boolean prepared = false;
/**
* Spawn via GSON, no public ctor for you
*/
@@ -207,15 +261,73 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Called immediately after deserialisation
*
* @param name Mixin config name
* @param fallbackEnvironment Fallback environment if not specified in
* config
* @return true if the config was successfully initialised and should be
* returned, or false if initialisation failed and the config should
* be discarded
*/
private boolean onLoad(String name) {
private boolean onLoad(String name, MixinEnvironment fallbackEnvironment) {
this.name = name;
this.env = this.parseSelector(this.selector, fallbackEnvironment);
this.initCompatibilityLevel();
return this.checkVersion();
}
@SuppressWarnings("deprecation")
private void initCompatibilityLevel() {
if (this.compatibility == null) {
return;
}
CompatibilityLevel level = CompatibilityLevel.valueOf(this.compatibility.trim().toUpperCase());
CompatibilityLevel current = MixinEnvironment.getCompatibilityLevel();
if (level == current) {
return;
}
// Current level is higher than required but too new to support it
if (current.isAtLeast(level)) {
if (!current.canSupport(level)) {
throw new MixinInitialisationError("Mixin config " + this.name + " requires compatibility level " + level + " which is too old");
}
}
// Current level is lower than required but current level prohibits elevation
if (!current.canElevateTo(level)) {
throw new MixinInitialisationError("Mixin config " + this.name + " requires compatibility level " + level + " which is prohibited by "
+ current);
}
MixinEnvironment.setCompatibilityLevel(level);
}
// AMS - temp
private MixinEnvironment parseSelector(String target, MixinEnvironment fallbackEnvironment) {
if (target != null) {
String[] selectors = target.split("[&\\| ]");
for (String selector : selectors) {
selector = selector.trim();
Pattern environmentSelector = Pattern.compile("^@env(?:ironment)?\\(([A-Z]+)\\)$");
Matcher environmentSelectorMatcher = environmentSelector.matcher(selector);
if (environmentSelectorMatcher.matches()) {
// only parse first env selector
return MixinEnvironment.getEnvironment(Phase.forName(environmentSelectorMatcher.group(1)));
}
}
Phase phase = Phase.forName(target);
if (phase != null) {
return MixinEnvironment.getEnvironment(phase);
}
}
return fallbackEnvironment;
}
private boolean checkVersion() throws MixinInitialisationError {
VersionNumber minVersion = VersionNumber.parse(this.version);
VersionNumber curVersion = VersionNumber.parse(MixinEnvironment.getCurrentEnvironment().getVersion());
VersionNumber curVersion = VersionNumber.parse(this.env.getVersion());
if (minVersion.compareTo(curVersion) > 0) {
this.logger.warn("Mixin config {} requires mixin subsystem version {} but {} was found. The mixin config will not be applied.",
this.name, minVersion, curVersion);
@@ -227,6 +339,13 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
return false;
}
return true;
}
/**
* Initialise the config once it's selected
*/
void onSelect() {
if (this.pluginClassName != null) {
try {
Class<?> pluginClass = Class.forName(this.pluginClassName, true, Launch.classLoader);
@@ -256,9 +375,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
this.refMapper = ReferenceMapper.read(this.refMapperConfig);
this.verboseLogging |= MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERBOSE);
return true;
this.verboseLogging |= this.env.getOption(Option.DEBUG_VERBOSE);
}
/**
@@ -274,20 +391,20 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* either the <em>hasMixinsFor()</em> or <em>getMixinsFor()</em> methods.
* </p>
*/
void initialise() {
if (this.initialised) {
void prepare(IHotSwap hotSwapper) {
if (this.prepared) {
return;
}
this.initialised = true;
this.prepared = true;
this.initialiseMixins(this.mixinClasses, false);
this.prepareMixins(this.mixinClasses, false, hotSwapper);
switch (MixinEnvironment.getCurrentEnvironment().getSide()) {
switch (this.env.getSide()) {
case CLIENT:
this.initialiseMixins(this.mixinClassesClient, false);
this.prepareMixins(this.mixinClassesClient, false, hotSwapper);
break;
case SERVER:
this.initialiseMixins(this.mixinClassesServer, false);
this.prepareMixins(this.mixinClassesServer, false, hotSwapper);
break;
case UNKNOWN:
//$FALL-THROUGH$
@@ -297,10 +414,10 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
void postInitialise() {
void postInitialise(IHotSwap hotSwapper) {
if (this.plugin != null) {
List<String> pluginMixins = this.plugin.getMixins();
this.initialiseMixins(pluginMixins, true);
this.prepareMixins(pluginMixins, true, hotSwapper);
}
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
@@ -310,6 +427,10 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
for (String innerClass : mixin.getSyntheticInnerClasses()) {
this.syntheticInnerClasses.add(innerClass.replace('/', '.'));
}
} catch (InvalidMixinException ex) {
this.logger.error(ex.getMixin() + ": " + ex.getMessage(), ex);
this.removeMixin(mixin);
iter.remove();
} catch (Exception ex) {
this.logger.error(ex.getMessage(), ex);
this.removeMixin(mixin);
@@ -328,7 +449,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
private void initialiseMixins(List<String> mixinClasses, boolean suppressPlugin) {
private void prepareMixins(List<String> mixinClasses, boolean suppressPlugin, IHotSwap hotSwapper) {
if (mixinClasses == null) {
return;
}
@@ -340,8 +461,10 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
continue;
}
MixinInfo mixin = null;
try {
MixinInfo mixin = new MixinInfo(this, mixinClass, true, this.plugin, suppressPlugin);
mixin = new MixinInfo(this, mixinClass, true, this.plugin, suppressPlugin);
if (mixin.getTargetClasses().size() > 0) {
MixinConfig.globalMixinList.add(fqMixinClass);
for (String targetClass : mixin.getTargetClasses()) {
@@ -349,9 +472,20 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
this.mixinsFor(targetClassName).add(mixin);
this.unhandledTargets.add(targetClassName);
}
if (hotSwapper != null) {
hotSwapper.registerMixinClass(mixin.getClassName());
}
this.mixins.add(mixin);
}
} catch (InvalidMixinException ex) {
if (this.required) {
throw ex;
}
this.logger.error(ex.getMessage(), ex);
} catch (Exception ex) {
if (this.required) {
throw new InvalidMixinException(mixin, "Error initialising mixin " + mixin + " - " + ex.getClass() + ": " + ex.getMessage(), ex);
}
this.logger.error(ex.getMessage(), ex);
}
}
@@ -361,6 +495,16 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
this.unhandledTargets.remove(transformedName);
}
/**
* Get marshalling handle
*/
public Config getHandle() {
if (this.handle == null) {
this.handle = new Config(this);
}
return this.handle;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinConfig#isRequired()
*/
@@ -368,7 +512,16 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
public boolean isRequired() {
return this.required;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.extensibility.IMixinConfig
* #getEnvironment()
*/
@Override
public MixinEnvironment getEnvironment() {
return this.env;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinConfig#getName()
*/
@@ -400,6 +553,49 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
public int getDefaultMixinPriority() {
return this.mixinPriority;
}
/**
* Get the defined value for the {@link Inject#require} parameter on
* injectors defined in mixins in this configuration.
*
* @return default require value
*/
public int getDefaultRequiredInjections() {
return this.injectorOptions.defaultRequireValue;
}
/**
* Get the defined injector group for injectors
*
* @return default group name
*/
public String getDefaultInjectorGroup() {
String defaultGroup = this.injectorOptions.defaultGroup;
return defaultGroup != null && !defaultGroup.isEmpty() ? defaultGroup : "default";
}
// AMS - temp
public boolean select(MixinEnvironment environment) {
return this.env == environment;
}
/**
* Get the number of mixins in this config, for debug logging
*
* @return total enumerated mixins in set
*/
int getDeclaredMixinCount() {
return MixinConfig.getCollectionSize(this.mixinClasses, this.mixinClassesClient, this.mixinClassesServer);
}
/**
* Get the number of mixins actually initialised, for debug logging
*
* @return total enumerated mixins in set
*/
int getMixinCount() {
return this.mixins.size();
}
/**
* Get the list of mixin classes we will be applying
@@ -420,9 +616,21 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Get the reference remapper for injectors
*/
public ReferenceMapper getReferenceMapper() {
if (this.env.getOption(Option.DISABLE_REFMAP)) {
return ReferenceMapper.DEFAULT_MAPPER;
}
this.refMapper.setContext(this.env.getRefmapObfuscationContext());
return this.refMapper;
}
String remapClassName(String className, String reference) {
// String remapped = this.plugin != null ? this.plugin.remap(className, reference) : null;
// if (remapped != null) {
// return remapped;
// }
return this.getReferenceMapper().remap(className, reference);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinConfig#getPlugin()
*/
@@ -480,7 +688,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* class
*
* @param targetClass
* @return
* @return true if this bundle contains any mixins for the specified target
*/
public boolean hasMixinsFor(String targetClass) {
return this.mixinMapping.containsKey(targetClass);
@@ -490,7 +698,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Get mixins for the specified target class
*
* @param targetClass
* @return
* @return mixins for the specified target
*/
public List<MixinInfo> getMixinsFor(String targetClass) {
return this.mixinsFor(targetClass);
@@ -504,6 +712,24 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
return mixins;
}
/**
* Updates a mixin with new bytecode
*
* @param mixinClass Name of the mixin class
* @param bytes New bytecode
* @return List of classes that need to be updated
*/
public List<String> reloadMixin(String mixinClass, byte[] bytes) {
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
MixinInfo mixin = iter.next();
if (mixin.getClassName().equals(mixinClass)) {
mixin.reloadMixin(bytes);
return mixin.getTargetClasses();
}
}
return Collections.<String>emptyList();
}
@Override
public String toString() {
@@ -529,18 +755,30 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* specified configFile, which must be accessible on the classpath
*
* @param configFile
* @return
* @param outer fallback environment
* @return new Config
*/
static MixinConfig create(String configFile) {
static Config create(String configFile, MixinEnvironment outer) {
try {
MixinConfig config = new Gson().fromJson(new InputStreamReader(Launch.classLoader.getResourceAsStream(configFile)), MixinConfig.class);
if (config.onLoad(configFile)) {
return config;
if (config.onLoad(configFile, outer)) {
return config.getHandle();
}
return null;
} catch (Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException(String.format("The specified configuration file '%s' was invalid or could not be read", configFile));
throw new IllegalArgumentException(String.format("The specified resource '%s' was invalid or could not be read", configFile), ex);
}
}
private static int getCollectionSize(Collection<?>... collections) {
int total = 0;
for (Collection<?> collection : collections) {
if (collection != null) {
total += collection.size();
}
}
return total;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,366 +0,0 @@
/*
* 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.transformer;
import java.lang.annotation.Annotation;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
/**
* <p>Mixin bytecode pre-processor. This class is responsible for bytecode pre-
* processing tasks required to be performed on mixin bytecode before the mixin
* can be applied. In previous versions the duties performed by this class were
* performed by {@link MixinInfo}.</p>
*
* <p>Before a mixin can be applied to the target class, it is necessary to
* convert certain aspects of the mixin bytecode into the intended final form of
* the mixin, this involves for example stripping the prefix from shadow and
* soft-implemented methods. This preparation is done in two stages: first the
* target-context-insensitive transformations are applied (this also acts as a
* validation pass when the mixin is first loaded) and then transformations
* which depend on the target class are applied in a second stage.</p>
*
* <p>The validation pass propagates method renames into the metadata tree and
* thus changes made during this phase are visible to all other mixins. The
* target-context-sensitive pass on the other hand can only operate on private
* class members for obvious reasons.</p>
*/
class MixinPreProcessor {
/**
* The mixin
*/
private final MixinInfo mixin;
/**
* Mixin class node
*/
private final ClassNode classNode;
private boolean prepared, attached;
MixinPreProcessor(MixinInfo mixin, ClassNode classNode) {
this.mixin = mixin;
this.classNode = classNode;
}
/**
* Run the first pass. Propagates changes into the metadata tree.
*
* @return Prepared classnode
*/
ClassNode prepare() {
if (!this.prepared) {
this.prepared = true;
for (MethodNode mixinMethod : this.classNode.methods) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod);
this.prepareShadow(mixinMethod, method);
this.prepareSoftImplements(mixinMethod, method);
}
}
return this.classNode;
}
private void prepareShadow(MethodNode mixinMethod, Method method) {
AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class);
if (shadowAnnotation == null) {
return;
}
String prefix = ASMHelper.<String>getAnnotationValue(shadowAnnotation, "prefix", Shadow.class);
if (mixinMethod.name.startsWith(prefix)) {
ASMHelper.setVisibleAnnotation(mixinMethod, MixinRenamed.class, "originalName", mixinMethod.name);
String newName = mixinMethod.name.substring(prefix.length());
method.renameTo(newName);
mixinMethod.name = newName;
}
}
private void prepareSoftImplements(MethodNode mixinMethod, Method method) {
for (InterfaceInfo iface : this.mixin.getSoftImplements()) {
if (iface.renameMethod(mixinMethod)) {
method.renameTo(mixinMethod.name);
}
}
}
MixinTargetContext createContextFor(ClassNode target) {
this.prepare();
MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target);
this.attach(context);
return context;
}
/**
* Run the second pass, attach to the specified context
*
* @param context
*/
void attach(MixinTargetContext context) {
if (this.attached) {
throw new IllegalStateException("Preprocessor was already attached");
}
this.attached = true;
// Perform context-sensitive attachment phase
this.attachMethods(context);
this.attachFields(context);
// Apply transformations to the mixin bytecode
this.transform(context);
}
private void attachMethods(MixinTargetContext context) {
for (Iterator<MethodNode> iter = this.classNode.methods.iterator(); iter.hasNext();) {
MethodNode mixinMethod = iter.next();
if (this.processMethod(context, mixinMethod, Shadow.class, true, true)) {
iter.remove();
context.addShadowMethod(mixinMethod);
continue;
}
this.processMethod(context, mixinMethod, Overwrite.class, false, false);
}
}
private boolean processMethod(MixinTargetContext context, MethodNode mixinMethod, Class<? extends Annotation> annotationType,
boolean mustExist, boolean mustBePrivate) {
AnnotationNode annotation = ASMHelper.getVisibleAnnotation(mixinMethod, annotationType);
if (annotation == null) {
return false;
}
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_PRIVATE);
MethodNode target = MixinPreProcessor.findMethod(context.getTargetClass(), mixinMethod, annotation);
if (target == null) {
if (!mustExist) {
return false;
}
throw new InvalidMixinException(this.mixin, annotationType.getSimpleName() + " method " + mixinMethod.name
+ " was not located in the target class");
}
if (Constants.INIT.equals(target.name)) {
throw new InvalidMixinException(this.mixin, "Nice try! Cannot alias a constructor!");
}
if (!target.name.equals(mixinMethod.name)) {
if (mustBePrivate && (target.access & Opcodes.ACC_PRIVATE) == 0) {
throw new InvalidMixinException(this.mixin, "Non-private method cannot be aliased. Found " + target.name);
}
mixinMethod.name = target.name;
method.renameTo(target.name);
}
return true;
}
private void attachFields(MixinTargetContext context) {
for (Iterator<FieldNode> iter = this.classNode.fields.iterator(); iter.hasNext();) {
FieldNode mixinField = iter.next();
AnnotationNode shadow = ASMHelper.getVisibleAnnotation(mixinField, Shadow.class);
if (!this.validateField(context, mixinField, shadow)) {
iter.remove();
continue;
}
context.transformDescriptor(mixinField);
Field field = this.mixin.getClassInfo().findField(mixinField);
FieldNode target = this.findField(context.getTargetClass(), mixinField, shadow);
if (target == null) {
// If this field is a shadow field but is NOT found in the target class, that's bad, mmkay
if (shadow != null) {
throw new InvalidMixinException(this.mixin, "Shadow field " + mixinField.name + " was not located in the target class");
}
} else {
// Check that the shadow field has a matching descriptor
if (!target.desc.equals(mixinField.desc)) {
throw new InvalidMixinException(this.mixin, "The field " + mixinField.name + " in the target class has a conflicting signature");
}
if (!target.name.equals(mixinField.name)) {
if ((target.access & Opcodes.ACC_PRIVATE) == 0 && (target.access & Opcodes.ACC_SYNTHETIC) == 0) {
throw new InvalidMixinException(this.mixin, "Non-private field cannot be aliased. Found " + target.name);
}
mixinField.name = target.name;
field.renameTo(target.name);
}
// Shadow fields get stripped from the mixin class
iter.remove();
if (shadow != null) {
context.addShadowField(mixinField);
}
}
}
}
private boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) {
// Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition
if (MixinApplicator.hasFlag(field, Opcodes.ACC_STATIC)
&& !MixinApplicator.hasFlag(field, Opcodes.ACC_PRIVATE)
&& !MixinApplicator.hasFlag(field, Opcodes.ACC_SYNTHETIC)) {
throw new InvalidMixinException(context, String.format("Mixin classes cannot contain visible static methods or fields, found %s",
field.name));
}
// Shadow fields can't have prefixes, it's meaningless for them anyway
String prefix = ASMHelper.<String>getAnnotationValue(shadow, "prefix", Shadow.class);
if (field.name.startsWith(prefix)) {
throw new InvalidMixinException(context, String.format("Shadow field %s in %s has a shadow prefix. This is not allowed.",
field.name, context));
}
// Imaginary super fields get stripped from the class, but first we validate them
if (Constants.IMAGINARY_SUPER.equals(field.name)) {
if (field.access != Opcodes.ACC_PRIVATE) {
throw new InvalidMixinException(this.mixin, "Imaginary super field " + field.name + " must be private and non-final");
}
if (!field.desc.equals("L" + this.mixin.getClassRef() + ";")) {
throw new InvalidMixinException(this.mixin, "Imaginary super field " + field.name + " must have the same type as the parent mixin");
}
return false;
}
return true;
}
/**
* Apply discovered method and field renames to method invocations and field
* accesses in the mixin
*/
private void transform(MixinTargetContext context) {
for (MethodNode mixinMethod : this.classNode.methods) {
for (Iterator<AbstractInsnNode> iter = mixinMethod.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodNode = (MethodInsnNode)insn;
Method method = this.mixin.getClassInfo().findMethodInHierarchy(methodNode, true, ClassInfo.INCLUDE_PRIVATE);
if (method != null && method.isRenamed()) {
methodNode.name = method.getName();
}
} else if (insn instanceof FieldInsnNode) {
FieldInsnNode fieldNode = (FieldInsnNode)insn;
Field field = this.mixin.getClassInfo().findField(fieldNode, ClassInfo.INCLUDE_PRIVATE);
if (field != null && field.isRenamed()) {
fieldNode.name = field.getName();
}
}
}
}
}
private static MethodNode findMethod(ClassNode classNode, MethodNode method, AnnotationNode annotation) {
Deque<String> aliases = new LinkedList<String>();
aliases.add(method.name);
if (annotation != null) {
List<String> aka = ASMHelper.<List<String>>getAnnotationValue(annotation, "aliases");
if (aka != null) {
aliases.addAll(aka);
}
}
return MixinPreProcessor.findMethod(classNode, aliases, method.desc);
}
private static MethodNode findMethod(ClassNode classNode, Deque<String> aliases, String desc) {
String alias = aliases.poll();
if (alias == null) {
return null;
}
for (MethodNode target : classNode.methods) {
if (target.name.equals(alias) && target.desc.equals(desc)) {
return target;
}
}
return MixinPreProcessor.findMethod(classNode, aliases, desc);
}
private FieldNode findField(ClassNode classNode, FieldNode field, AnnotationNode shadow) {
Deque<String> aliases = new LinkedList<String>();
aliases.add(field.name);
if (shadow != null) {
List<String> aka = ASMHelper.<List<String>>getAnnotationValue(shadow, "aliases");
if (aka != null) {
aliases.addAll(aka);
}
}
return this.findField(classNode, aliases, field.desc);
}
/**
* Finds a field in the target class
*
* @param aliases
* @param desc
* @return Target field or null if not found
*/
private FieldNode findField(ClassNode classNode, Deque<String> aliases, String desc) {
String alias = aliases.poll();
if (alias == null) {
return null;
}
for (FieldNode target : classNode.fields) {
if (target.name.equals(alias) && target.desc.equals(desc)) {
return target;
}
}
return this.findField(classNode, aliases, desc);
}
}
@@ -0,0 +1,85 @@
/*
* 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.transformer;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinException;
import org.spongepowered.asm.util.ASMHelper;
/**
* Bytecode preprocessor for interface mixins, simply performs some additional
* verification for things which are unsupported in interfaces
*/
class MixinPreProcessorInterface extends MixinPreProcessorStandard {
/**
* Ctor
*
* @param mixin Mixin info
* @param classNode Mixin classnode
*/
MixinPreProcessorInterface(MixinInfo mixin, MixinClassNode classNode) {
super(mixin, classNode);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinPreProcessor
* #prepareMethod(org.spongepowered.asm.lib.tree.MethodNode,
* org.spongepowered.asm.mixin.transformer.ClassInfo.Method)
*/
@Override
protected void prepareMethod(MixinMethodNode mixinMethod, Method method) {
// I have no idea how the hell you'd compile this, but we make sure anyway!
if (!ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_PUBLIC)) {
throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains a non-public method! Found " + method + " in "
+ this.mixin);
}
super.prepareMethod(mixinMethod, method);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinPreProcessor
* #validateField(
* org.spongepowered.asm.mixin.transformer.MixinTargetContext,
* org.spongepowered.asm.lib.tree.FieldNode,
* org.spongepowered.asm.lib.tree.AnnotationNode)
*/
@Override
protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) {
if (!ASMHelper.hasFlag(field, Opcodes.ACC_STATIC)) {
throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains an instance field! Found " + field.name + " in "
+ this.mixin);
}
return super.validateField(context, field, shadow);
}
}
@@ -0,0 +1,481 @@
/*
* 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.transformer;
import java.lang.annotation.Annotation;
import java.util.Iterator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode;
import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
/**
* <p>Mixin bytecode pre-processor. This class is responsible for bytecode pre-
* processing tasks required to be performed on mixin bytecode before the mixin
* can be applied. In previous versions the duties performed by this class were
* performed by {@link MixinInfo}.</p>
*
* <p>Before a mixin can be applied to the target class, it is necessary to
* convert certain aspects of the mixin bytecode into the intended final form of
* the mixin, this involves for example stripping the prefix from shadow and
* soft-implemented methods. This preparation is done in two stages: first the
* target-context-insensitive transformations are applied (this also acts as a
* validation pass when the mixin is first loaded) and then transformations
* which depend on the target class are applied in a second stage.</p>
*
* <p>The validation pass propagates method renames into the metadata tree and
* thus changes made during this phase are visible to all other mixins. The
* target-context-sensitive pass on the other hand can only operate on private
* class members for obvious reasons.</p>
*/
class MixinPreProcessorStandard {
/**
* Logger
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* The mixin
*/
protected final MixinInfo mixin;
/**
* Mixin class node
*/
protected final MixinClassNode classNode;
private final boolean verboseLogging, strictUnique;
private boolean prepared, attached;
MixinPreProcessorStandard(MixinInfo mixin, MixinClassNode classNode) {
this.mixin = mixin;
this.classNode = classNode;
MixinEnvironment env = mixin.getParent().getEnvironment();
this.verboseLogging = env.getOption(Option.DEBUG_VERBOSE);
this.strictUnique = env.getOption(Option.DEBUG_UNIQUE);
}
/**
* Run the first pass. Propagates changes into the metadata tree.
*
* @return Prepared classnode
*/
MixinPreProcessorStandard prepare() {
if (!this.prepared) {
this.prepared = true;
for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod);
this.prepareMethod(mixinMethod, method);
}
for (FieldNode mixinField : this.classNode.fields) {
this.prepareField(mixinField);
}
}
return this;
}
protected void prepareMethod(MixinMethodNode mixinMethod, Method method) {
this.prepareShadow(mixinMethod, method);
this.prepareSoftImplements(mixinMethod, method);
}
protected void prepareShadow(MixinMethodNode mixinMethod, Method method) {
AnnotationNode shadowAnnotation = ASMHelper.getVisibleAnnotation(mixinMethod, Shadow.class);
if (shadowAnnotation == null) {
return;
}
String prefix = ASMHelper.<String>getAnnotationValue(shadowAnnotation, "prefix", Shadow.class);
if (mixinMethod.name.startsWith(prefix)) {
ASMHelper.setVisibleAnnotation(mixinMethod, MixinRenamed.class, "originalName", mixinMethod.name);
String newName = mixinMethod.name.substring(prefix.length());
method.renameTo(newName);
mixinMethod.name = newName;
}
}
protected void prepareSoftImplements(MixinMethodNode mixinMethod, Method method) {
for (InterfaceInfo iface : this.mixin.getSoftImplements()) {
if (iface.renameMethod(mixinMethod)) {
method.renameTo(mixinMethod.name);
}
}
}
protected void prepareField(FieldNode mixinField) {
// stub
}
MixinTargetContext createContextFor(TargetClassContext target) {
MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target);
this.attach(context);
return context;
}
/**
* Run the second pass, attach to the specified context
*
* @param context
*/
void attach(MixinTargetContext context) {
if (this.attached) {
throw new IllegalStateException("Preprocessor was already attached");
}
this.attached = true;
// Perform context-sensitive attachment phase
this.attachMethods(context);
this.attachFields(context);
// Apply transformations to the mixin bytecode
this.transform(context);
}
protected void attachMethods(MixinTargetContext context) {
for (Iterator<MixinMethodNode> iter = this.classNode.mixinMethods.iterator(); iter.hasNext();) {
MixinMethodNode mixinMethod = iter.next();
if (!this.validateMethod(context, mixinMethod)) {
iter.remove();
continue;
}
if (this.processInjectorMethod(context, mixinMethod)) {
continue;
}
if (this.processShadowMethod(context, mixinMethod)) {
iter.remove();
context.addShadowMethod(mixinMethod);
continue;
}
if (this.processOverwriteMethod(context, mixinMethod)) {
continue;
}
if (this.processUniqueMethod(context, mixinMethod)) {
iter.remove();
continue;
}
this.processMethod(mixinMethod);
}
}
protected boolean validateMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return true;
}
protected boolean processInjectorMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
AnnotationNode annotation = InjectionInfo.getInjectorAnnotation(context, mixinMethod);
boolean surrogate = ASMHelper.getVisibleAnnotation(mixinMethod, Surrogate.class) != null;
if (annotation == null && !surrogate) {
return false;
}
String handlerName = context.getHandlerName(annotation, mixinMethod, surrogate);
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
if (method.isUnique()) {
MixinPreProcessorStandard.logger.warn("Redundant @Unique on injector method {} in {}. Injectors are implicitly unique", method, context);
}
method.renameTo(handlerName);
mixinMethod.name = handlerName;
return true;
}
protected boolean processShadowMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return this.processSpecialMethod(context, mixinMethod, Shadow.class, false);
}
protected boolean processOverwriteMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return this.processSpecialMethod(context, mixinMethod, Overwrite.class, true);
}
protected boolean processSpecialMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class<? extends Annotation> type,
boolean overwrite) {
AnnotationNode annotation = ASMHelper.getVisibleAnnotation(mixinMethod, type);
if (annotation == null) {
return false;
}
if (this.mixin.isUnique() && overwrite) {
throw new InvalidMixinException(this.mixin, "@Overwrite method " + mixinMethod.name + " found in a @Unique mixin");
}
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
MethodNode target = context.findMethod(mixinMethod, annotation);
if (method.isUnique()) {
throw new InvalidMixinException(this.mixin, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be @Unique");
}
if (target == null) {
if (overwrite) {
return false;
}
target = context.findRemappedMethod(mixinMethod);
if (target == null) {
throw new InvalidMixinException(this.mixin, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name
+ " was not located in the target class");
}
mixinMethod.name = target.name;
method.renameTo(target.name);
}
if (Constants.CTOR.equals(target.name)) {
throw new InvalidMixinException(this.mixin, "Nice try! Cannot alias a constructor!");
}
if (!target.name.equals(mixinMethod.name)) {
if (!overwrite && (target.access & Opcodes.ACC_PRIVATE) == 0) {
throw new InvalidMixinException(this.mixin, "Non-private method cannot be aliased. Found " + target.name);
}
mixinMethod.name = target.name;
method.renameTo(target.name);
}
return true;
}
protected boolean processUniqueMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
if (method == null || (!method.isUnique() && !this.mixin.isUnique())) {
return false;
}
MethodNode target = context.findMethod(mixinMethod, null);
if (target == null) {
return false;
}
if ((mixinMethod.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) != 0) {
String uniqueName = context.getUniqueName(mixinMethod);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique method {}{} to {} in {}",
mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
mixinMethod.name = uniqueName;
method.renameTo(uniqueName);
return false;
}
if (this.strictUnique) {
throw new InvalidMixinException(this.mixin, "Method conflict, @Unique method " + mixinMethod.name + " in " + this.mixin
+ " cannot overwrite " + target.name + target.desc + " in " + context.getTarget());
}
MixinPreProcessorStandard.logger.warn("Discarding @Unique public method {} in {} because it already exists in {}", mixinMethod.name,
this.mixin, context.getTarget());
return true;
}
protected void processMethod(MixinMethodNode mixinMethod) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod);
if (method == null) {
return;
}
Method parentMethod = this.mixin.getClassInfo().findMethodInHierarchy(mixinMethod, false);
if (parentMethod != null && parentMethod.isRenamed()) {
mixinMethod.name = parentMethod.getName();
method.renameTo(parentMethod.getName());
}
}
protected void attachFields(MixinTargetContext context) {
for (Iterator<FieldNode> iter = this.classNode.fields.iterator(); iter.hasNext();) {
FieldNode mixinField = iter.next();
AnnotationNode shadow = ASMHelper.getVisibleAnnotation(mixinField, Shadow.class);
boolean isShadow = shadow != null;
if (!this.validateField(context, mixinField, shadow)) {
iter.remove();
continue;
}
context.transformDescriptor(mixinField);
Field field = this.mixin.getClassInfo().findField(mixinField);
if (field.isUnique() && isShadow) {
throw new InvalidMixinException(this.mixin, "@Shadow field " + mixinField.name + " cannot be @Unique");
}
FieldNode target = context.findField(mixinField, shadow);
if (target == null) {
if (shadow == null) {
continue;
}
target = context.findRemappedField(mixinField);
if (target == null) {
// If this field is a shadow field but is NOT found in the target class, that's bad, mmkay
throw new InvalidMixinException(this.mixin, "Shadow field " + mixinField.name + " was not located in the target class");
}
mixinField.name = target.name;
field.renameTo(target.name);
}
if (field.isUnique()) {
if ((mixinField.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) != 0) {
String uniqueName = context.getUniqueName(mixinField);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique field {}{} to {} in {}",
mixinField.name, mixinField.desc, uniqueName, this.mixin);
mixinField.name = uniqueName;
field.renameTo(uniqueName);
continue;
}
if (this.strictUnique) {
throw new InvalidMixinException(this.mixin, "Field conflict, @Unique field " + mixinField.name + " in " + this.mixin
+ " cannot overwrite " + target.name + target.desc + " in " + context.getTarget());
}
MixinPreProcessorStandard.logger.warn("Discarding @Unique public field {} in {} because it already exists in {}. "
+ "Note that declared FIELD INITIALISERS will NOT be removed!", mixinField.name, this.mixin, context.getTarget());
iter.remove();
continue;
}
// Check that the shadow field has a matching descriptor
if (!target.desc.equals(mixinField.desc)) {
throw new InvalidMixinException(this.mixin, "The field " + mixinField.name + " in the target class has a conflicting signature");
}
if (!target.name.equals(mixinField.name)) {
if ((target.access & Opcodes.ACC_PRIVATE) == 0 && (target.access & Opcodes.ACC_SYNTHETIC) == 0) {
throw new InvalidMixinException(this.mixin, "Non-private field cannot be aliased. Found " + target.name);
}
mixinField.name = target.name;
field.renameTo(target.name);
}
// Shadow fields get stripped from the mixin class
iter.remove();
if (isShadow) {
boolean isFinal = field.isDecoratedFinal();
if (this.verboseLogging && ASMHelper.hasFlag(target, Opcodes.ACC_FINAL) != isFinal) {
String message = isFinal
? "@Shadow field {}::{} is decorated with @Final but target is not final"
: "@Shadow target {}::{} is final but shadow is not decorated with @Final";
MixinPreProcessorStandard.logger.warn(message, this.mixin, mixinField.name);
}
context.addShadowField(mixinField, field);
}
}
}
protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) {
// Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition
if (ASMHelper.hasFlag(field, Opcodes.ACC_STATIC)
&& !ASMHelper.hasFlag(field, Opcodes.ACC_PRIVATE)
&& !ASMHelper.hasFlag(field, Opcodes.ACC_SYNTHETIC)
&& shadow == null) {
throw new InvalidMixinException(context, String.format("Mixin %s contains non-private static field %s:%s",
context, field.name, field.desc));
}
// Shadow fields can't have prefixes, it's meaningless for them anyway
String prefix = ASMHelper.<String>getAnnotationValue(shadow, "prefix", Shadow.class);
if (field.name.startsWith(prefix)) {
throw new InvalidMixinException(context, String.format("@Shadow field %s.%s has a shadow prefix. This is not allowed.",
context, field.name));
}
// Imaginary super fields get stripped from the class, but first we validate them
if (Constants.IMAGINARY_SUPER.equals(field.name)) {
if (field.access != Opcodes.ACC_PRIVATE) {
throw new InvalidMixinException(this.mixin, "Imaginary super field " + context + "." + field.name
+ " must be private and non-final");
}
if (!field.desc.equals("L" + this.mixin.getClassRef() + ";")) {
throw new InvalidMixinException(this.mixin, "Imaginary super field " + context + "." + field.name
+ " must have the same type as the parent mixin");
}
return false;
}
return true;
}
/**
* Apply discovered method and field renames to method invocations and field
* accesses in the mixin
*/
protected void transform(MixinTargetContext context) {
for (MethodNode mixinMethod : this.classNode.methods) {
for (Iterator<AbstractInsnNode> iter = mixinMethod.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodNode = (MethodInsnNode)insn;
Method method = ClassInfo.forName(methodNode.owner).findMethodInHierarchy(methodNode, true, ClassInfo.INCLUDE_PRIVATE);
if (method != null && method.isRenamed()) {
methodNode.name = method.getName();
}
} else if (insn instanceof FieldInsnNode) {
FieldInsnNode fieldNode = (FieldInsnNode)insn;
Field field = ClassInfo.forName(fieldNode.owner).findField(fieldNode, ClassInfo.INCLUDE_PRIVATE);
if (field != null && field.isRenamed()) {
fieldNode.name = field.getName();
}
}
}
}
}
}
@@ -25,32 +25,45 @@
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Handle;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.LdcInsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.TypeInsnNode;
import org.spongepowered.asm.lib.tree.*;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectorGroupInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.obfuscation.RemapperChain;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
/**
* This object keeps track of data for applying a mixin to a specific target
* class <em>during</em> a mixin application. This is a single-use object which
@@ -60,6 +73,11 @@ import org.spongepowered.asm.util.Constants;
* in the mixin to the appropriate members in the target class hierarchy.
*/
public class MixinTargetContext implements IReferenceMapperContext {
/**
* Logger
*/
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Mixin info
@@ -74,7 +92,12 @@ public class MixinTargetContext implements IReferenceMapperContext {
/**
*
*/
private final ClassNode targetClass;
private final TargetClassContext targetClass;
/**
* Session ID from context
*/
private final String sessionId;
/**
* Target ClassInfo
@@ -89,13 +112,22 @@ public class MixinTargetContext implements IReferenceMapperContext {
/**
* Shadow field list
*/
private final List<FieldNode> shadowFields = new ArrayList<FieldNode>();
private final Map<FieldNode, Field> shadowFields = new LinkedHashMap<FieldNode, Field>();
/**
* Information about methods in the target class, used to keep track of
* transformations we apply
* List of methods successfully merged from this mixin
*/
private final Map<String, Target> targetMethods = new HashMap<String, Target>();
private final List<MethodNode> mergedMethods = new ArrayList<MethodNode>();
/**
* Injector groups
*/
private final InjectorGroupInfo.Map injectorGroups = new InjectorGroupInfo.Map();
/**
* Injectors for this target
*/
private final List<InjectionInfo> injectors = new ArrayList<InjectionInfo>();
/**
* True if this mixin inherits from a mixin at any point in its hierarchy
@@ -106,21 +138,30 @@ public class MixinTargetContext implements IReferenceMapperContext {
* True if this mixin's superclass is detached from the target superclass
*/
private final boolean detachedSuper;
/**
* Minimum class version required to apply this mixin, target class will be
* upgraded if the version is below this value
*/
private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion();
/**
* ctor
*
* @param mixin Mixin information
* @param classNode Mixin classnode
* @param target target class
* @param context target class
*/
MixinTargetContext(MixinInfo mixin, ClassNode classNode, ClassNode target) {
MixinTargetContext(MixinInfo mixin, ClassNode classNode, TargetClassContext context) {
this.mixin = mixin;
this.classNode = classNode;
this.targetClass = target;
this.targetClassInfo = ClassInfo.forName(target.name);
this.targetClass = context;
this.targetClassInfo = ClassInfo.forName(this.targetClass.getName());
this.inheritsFromMixin = mixin.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy();
this.detachedSuper = !this.classNode.superName.equals(this.targetClass.superName);
this.detachedSuper = !this.classNode.superName.equals(this.targetClass.getClassNode().superName);
this.sessionId = context.getSessionId();
this.requireVersion(classNode.version);
}
/**
@@ -131,10 +172,25 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
* @param field
* @param fieldNode
*/
void addShadowField(FieldNode field) {
this.shadowFields.add(field);
void addShadowField(FieldNode fieldNode, Field fieldInfo) {
this.shadowFields.put(fieldNode, fieldInfo);
}
/**
* Callback from the applicator which notifies us that a method was merged
*
* @param method
*/
void addMergedMethod(MethodNode method) {
this.mergedMethods.add(method);
this.targetClassInfo.addMethod(method);
ASMHelper.setVisibleAnnotation(method, MixinMerged.class,
"mixin", this.getClassName(),
"priority", this.getPriority(),
"sessionId", this.sessionId);
}
/* (non-Javadoc)
@@ -144,6 +200,15 @@ public class MixinTargetContext implements IReferenceMapperContext {
public String toString() {
return this.mixin.toString();
}
/**
* Get the environment of the owning mixin config
*
* @return mixin parent environment
*/
public MixinEnvironment getEnvironment() {
return this.mixin.getParent().getEnvironment();
}
/**
* Get the mixin tree
@@ -171,6 +236,15 @@ public class MixinTargetContext implements IReferenceMapperContext {
public String getClassRef() {
return this.mixin.getClassRef();
}
/**
* Get the target class context
*
* @return the target class context
*/
public TargetClassContext getTarget() {
return this.targetClass;
}
/**
* Get the target class reference
@@ -179,7 +253,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
* mixins)
*/
public String getTargetClassRef() {
return this.targetClass.name;
return this.targetClass.getName();
}
/**
@@ -187,8 +261,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
*
* @return the target class
*/
public ClassNode getTargetClass() {
return this.targetClass;
public ClassNode getTargetClassNode() {
return this.targetClass.getClassNode();
}
/**
@@ -199,6 +273,41 @@ public class MixinTargetContext implements IReferenceMapperContext {
public ClassInfo getTargetClassInfo() {
return this.targetClassInfo;
}
/**
* Get the minimum required class version for this mixin
*/
public int getMinRequiredClassVersion() {
return this.minRequiredClassVersion;
}
/**
* Get the defined value for the {@link Inject#require} parameter on
* injectors defined in mixins in this configuration.
*
* @return default require value
*/
public int getDefaultRequiredInjections() {
return this.mixin.getParent().getDefaultRequiredInjections();
}
/**
* Get the defined injector group for injectors
*
* @return default group name
*/
public String getDefaultInjectorGroup() {
return this.mixin.getParent().getDefaultInjectorGroup();
}
/**
* Get the injector groups for this target
*
* @return injector groups
*/
public InjectorGroupInfo.Map getInjectorGroups() {
return this.injectorGroups;
}
/**
* Find the corresponding class type for the supplied mixin class in this
@@ -224,7 +333,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
/**
* Handles "re-parenting" the method supplied, changes all references to the
* mixin class to refer to the target class (for field accesses and method
* invokations) and also handles fixing up the targets of INVOKESPECIAL
* invocations) and also handles fixing up the targets of INVOKESPECIAL
* opcodes for mixins with detached targets.
*
* @param method Method to transform
@@ -233,18 +342,24 @@ public class MixinTargetContext implements IReferenceMapperContext {
this.validateMethod(method);
this.transformDescriptor(method);
AbstractInsnNode lastInsn = null;
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
this.transformMethodNode(method, iter, (MethodInsnNode)insn);
this.transformMethodRef(method, iter, new MemberRef.Method((MethodInsnNode)insn));
} else if (insn instanceof FieldInsnNode) {
this.transformFieldNode(method, iter, (FieldInsnNode)insn);
this.transformFieldRef(method, iter, new MemberRef.Field((FieldInsnNode)insn));
this.checkFinal(method, iter, (FieldInsnNode)insn);
} else if (insn instanceof TypeInsnNode) {
this.transformTypeNode(method, iter, (TypeInsnNode)insn);
this.transformTypeNode(method, iter, (TypeInsnNode)insn, lastInsn);
} else if (insn instanceof LdcInsnNode) {
this.transformConstantNode(method, iter, (LdcInsnNode)insn);
} else if (insn instanceof InvokeDynamicInsnNode) {
this.transformInvokeDynamicNode(method, iter, (InvokeDynamicInsnNode)insn);
}
lastInsn = insn;
}
}
@@ -257,64 +372,106 @@ public class MixinTargetContext implements IReferenceMapperContext {
private void validateMethod(MethodNode method) {
// Any method tagged with @SoftOverride must have an implementation visible from
if (ASMHelper.getInvisibleAnnotation(method, SoftOverride.class) != null) {
Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER);
ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER);
if (superMethod == null || !superMethod.isInjected()) {
throw new InvalidMixinException(this, "Mixin method " + method.name + method.desc + " is tagged with @SoftOverride but no "
+ "valid method was found in superclasses of " + this.targetClass.name);
+ "valid method was found in superclasses of " + this.targetClass.getName());
}
}
}
/**
* Transforms method invocations in the method. Updates static and dynamic
* bindings.
* Transforms a method invocation/reference in the method. Updates static
* and dynamic bindings.
*
* @param method Method being processed
* @param iter Insn interator
* @param methodInsn Insn to transform
* @param methodRef Method reference to transform
*/
private void transformMethodNode(MethodNode method, Iterator<AbstractInsnNode> iter, MethodInsnNode methodInsn) {
this.transformDescriptor(methodInsn);
private void transformMethodRef(MethodNode method, Iterator<AbstractInsnNode> iter, MemberRef methodRef) {
this.transformDescriptor(methodRef);
if (methodInsn.owner.equals(this.getClassRef())) {
methodInsn.owner = this.targetClass.name;
if (methodRef.getOwner().equals(this.getClassRef())) {
methodRef.setOwner(this.targetClass.getName());
} else if ((this.detachedSuper || this.inheritsFromMixin)) {
if (methodInsn.getOpcode() == Opcodes.INVOKESPECIAL) {
this.updateStaticBinding(method, methodInsn);
} else if (methodInsn.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodInsn.owner).isMixin()) {
this.updateDynamicBinding(method, methodInsn);
if (methodRef.getOpcode() == Opcodes.INVOKESPECIAL) {
this.updateStaticBinding(method, methodRef);
} else if (methodRef.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodRef.getOwner()).isMixin()) {
this.updateDynamicBinding(method, methodRef);
}
}
}
/**
* Transforms field accesses in the method. Handles imaginary super accesses
* and converts them to real super-invocations and rewrites field accesses
* which refer to mixin or supermixin classes to their relevant targets.
* Transforms field access/reference in the method. Handles imaginary super
* accesses and converts them to real super-invocations and rewrites field
* accesses which refer to mixin or supermixin classes to their relevant
* targets.
*
* @param method Method being processed
* @param iter Insn interator
* @param fieldInsn Insn to transform
* @param fieldRef Field Reference to transform
*/
private void transformFieldNode(MethodNode method, Iterator<AbstractInsnNode> iter, FieldInsnNode fieldInsn) {
if (Constants.IMAGINARY_SUPER.equals(fieldInsn.name)) {
this.processImaginarySuper(method, fieldInsn);
iter.remove();
private void transformFieldRef(MethodNode method, Iterator<AbstractInsnNode> iter, MemberRef fieldRef) {
if (Constants.IMAGINARY_SUPER.equals(fieldRef.getName())) {
if (fieldRef instanceof MemberRef.Field) {
this.processImaginarySuper(method, ((MemberRef.Field) fieldRef).insn);
iter.remove();
} else {
throw new InvalidMixinException(this.mixin, "Cannot call imaginary super from method handle.");
}
}
this.transformDescriptor(fieldInsn);
this.transformDescriptor(fieldRef);
if (fieldInsn.owner.equals(this.getClassRef())) {
fieldInsn.owner = this.targetClass.name;
if (fieldRef.getOwner().equals(this.getClassRef())) {
fieldRef.setOwner(this.targetClass.getName());
} else {
ClassInfo fieldOwner = ClassInfo.forName(fieldInsn.owner);
ClassInfo fieldOwner = ClassInfo.forName(fieldRef.getOwner());
if (fieldOwner.isMixin()) {
ClassInfo actualOwner = this.targetClassInfo.findCorrespondingType(fieldOwner);
fieldInsn.owner = actualOwner != null ? actualOwner.getName() : this.targetClass.name;
fieldRef.setOwner(actualOwner != null ? actualOwner.getName() : this.targetClass.getName());
}
}
}
private void checkFinal(MethodNode method, Iterator<AbstractInsnNode> iter, FieldInsnNode fieldNode) {
if (!fieldNode.owner.equals(this.targetClass.getName())) {
return;
}
int opcode = fieldNode.getOpcode();
if (opcode == Opcodes.GETFIELD || opcode == Opcodes.GETSTATIC) {
return;
}
for (Entry<FieldNode, Field> shadow : this.shadowFields.entrySet()) {
FieldNode shadowFieldNode = shadow.getKey();
if (!shadowFieldNode.desc.equals(fieldNode.desc) || !shadowFieldNode.name.equals(fieldNode.name)) {
continue;
}
Field shadowField = shadow.getValue();
if (shadowField.isDecoratedFinal()) {
if (shadowField.isDecoratedMutable()) {
if (this.mixin.getParent().getEnvironment().getOption(Option.DEBUG_VERBOSE)) {
MixinTargetContext.logger.warn("Write access to @Mutable @Final field {} in {}::{}", shadowField, this.mixin, method.name);
}
} else {
if (Constants.CTOR.equals(method.name) || Constants.CLINIT.equals(method.name)) {
MixinTargetContext.logger.warn("@Final field {} in {} should be final", shadowField, this.mixin);
} else {
MixinTargetContext.logger.error("Write access detected to @Final field {} in {}::{}", shadowField, this.mixin, method.name);
if (this.mixin.getParent().getEnvironment().getOption(Option.DEBUG_VERIFY)) {
throw new InvalidMixinException(this.mixin, "Write access detected to @Final field " + shadowField + " in " + this.mixin
+ "::" + method.name);
}
}
}
}
return;
}
}
/**
* Transforms type operations (eg. cast, instanceof) in the method being
* processed. Changes references to mixin classes to that of the appropriate
@@ -323,34 +480,94 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param method Method being processed
* @param iter Insn interator
* @param typeInsn Insn to transform
* @param lastNode Last insn in the method
*/
private void transformTypeNode(MethodNode method, Iterator<AbstractInsnNode> iter, TypeInsnNode typeInsn) {
private void transformTypeNode(MethodNode method, Iterator<AbstractInsnNode> iter, TypeInsnNode typeInsn, AbstractInsnNode lastNode) {
if (typeInsn.getOpcode() == Opcodes.CHECKCAST
&& typeInsn.desc.equals(this.targetClass.getName())
&& lastNode.getOpcode() == Opcodes.ALOAD
&& ((VarInsnNode)lastNode).var == 0) {
iter.remove();
return;
}
if (typeInsn.desc.equals(this.getClassRef())) {
typeInsn.desc = this.targetClass.name;
typeInsn.desc = this.targetClass.getName();
}
this.transformDescriptor(typeInsn);
}
/**
* Transforms class literals in the method being processed.
* Transforms class literals and method handle loads in the method being
* processed.
*
* @param method Method being processed
* @param iter Insn interator
* @param ldcInsn Insn to transform
*/
private void transformConstantNode(MethodNode method, Iterator<AbstractInsnNode> iter, LdcInsnNode ldcInsn) {
if (ldcInsn.cst instanceof Type) {
Type type = (Type)ldcInsn.cst;
String desc = this.transformSingleDescriptor(type);
if (!type.toString().equals(desc)) {
ldcInsn.cst = Type.getType(desc);
}
ldcInsn.cst = this.transformConstant(method, iter, ldcInsn.cst);
}
/**
* Transforms a invoke dynamic instruction in the method being processed.
*
* @param method Method being processed
* @param iter Insn interator
* @param dynInsn Insn to transform
*/
private void transformInvokeDynamicNode(MethodNode method, Iterator<AbstractInsnNode> iter, InvokeDynamicInsnNode dynInsn) {
this.requireVersion(Opcodes.V1_7);
dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc);
dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm);
for (int i = 0; i < dynInsn.bsmArgs.length; i++) {
dynInsn.bsmArgs[i] = this.transformConstant(method, iter, dynInsn.bsmArgs[i]);
}
}
/**
* Handle "imaginary super" invokations, these are invokations in
* Transforms a constant in the constant pool.
*
* @param method Method being processed
* @param iter Insn interator
* @param constant Consatnt pool entry
* @return Transformed constant
*/
private Object transformConstant(MethodNode method, Iterator<AbstractInsnNode> iter, Object constant) {
if (constant instanceof Type) {
Type type = (Type)constant;
String desc = this.transformDescriptor(type);
if (!type.toString().equals(desc)) {
return Type.getType(desc);
}
return constant;
} else if (constant instanceof Handle) {
return this.transformHandle(method, iter, (Handle)constant);
}
return constant;
}
/**
* Transforms a method handle that is referenced from the method being
* processed.
*
* @param method Method being processed
* @param iter Insn interator
* @param handle Handle to transform
*/
private Handle transformHandle(MethodNode method, Iterator<AbstractInsnNode> iter, Handle handle) {
MemberRef.Handle memberRef = new MemberRef.Handle(handle);
if (memberRef.isField()) {
this.transformFieldRef(method, iter, memberRef);
} else {
this.transformMethodRef(method, iter, memberRef);
}
return memberRef.getMethodHandle();
}
/**
* Handle "imaginary super" invocations, these are invocations in
* non-derived mixins for accessing methods known to exist in a supermixin
* which is not directly inherited by this mixix. The method can only call
* its <b>own</b> super-implmentation and the methd must also be tagged with
@@ -363,7 +580,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
*/
private void processImaginarySuper(MethodNode method, FieldInsnNode fieldInsn) {
if (fieldInsn.getOpcode() != Opcodes.GETFIELD) {
if (Constants.INIT.equals(method.name)) {
if (Constants.CTOR.equals(method.name)) {
throw new InvalidMixinException(this, "Illegal imaginary super declaration: field " + fieldInsn.name
+ " must not specify an initialiser");
}
@@ -388,7 +605,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
MethodInsnNode methodNode = (MethodInsnNode)insn;
if (methodNode.owner.equals(this.getClassRef()) && methodNode.name.equals(method.name) && methodNode.desc.equals(method.desc)) {
methodNode.setOpcode(Opcodes.INVOKESPECIAL);
this.updateStaticBinding(method, methodNode);
this.updateStaticBinding(method, new MemberRef.Method(methodNode));
return;
}
}
@@ -402,10 +619,10 @@ public class MixinTargetContext implements IReferenceMapperContext {
* which contains the specified method.
*
* @param method Method containing the instruction
* @param insn INVOKE instruction node
* @param methodRef Unbound reference to the method
*/
private void updateStaticBinding(MethodNode method, MethodInsnNode insn) {
this.updateBinding(method, insn, Traversal.SUPER);
private void updateStaticBinding(MethodNode method, MemberRef methodRef) {
this.updateBinding(method, methodRef, Traversal.SUPER);
}
/**
@@ -413,27 +630,29 @@ public class MixinTargetContext implements IReferenceMapperContext {
* which contains the specified method.
*
* @param method Method containing the instruction
* @param insn INVOKE instruction node
* @param methodRef Unbound reference to the method
*/
private void updateDynamicBinding(MethodNode method, MethodInsnNode insn) {
this.updateBinding(method, insn, Traversal.ALL);
private void updateDynamicBinding(MethodNode method, MemberRef methodRef) {
this.updateBinding(method, methodRef, Traversal.ALL);
}
private void updateBinding(MethodNode method, MethodInsnNode insn, Traversal traversal) {
if (Constants.INIT.equals(method.name) || insn.owner.equals(this.targetClass.name) || this.targetClass.name.startsWith("<")) {
private void updateBinding(MethodNode method, MemberRef methodRef, Traversal traversal) {
if (Constants.CTOR.equals(method.name)
|| methodRef.getOwner().equals(this.targetClass.getName())
|| this.targetClass.getName().startsWith("<")) {
return;
}
Method superMethod = this.targetClassInfo.findMethodInHierarchy(insn.name, insn.desc, traversal == Traversal.ALL, traversal);
ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(methodRef.getName(), methodRef.getDesc(),
traversal == Traversal.ALL, traversal);
if (superMethod != null) {
if (superMethod.getOwner().isMixin()) {
throw new InvalidMixinException(this, "Invalid " + ASMHelper.getOpcodeName(insn) + " in " + this + " resolved " + insn.owner
+ " -> " + superMethod.getOwner() + " for " + insn.name + insn.desc);
throw new InvalidMixinException(this, "Invalid " + methodRef + " in " + this + " resolved " + superMethod.getOwner()
+ " but is mixin.");
}
insn.owner = superMethod.getOwner().getName();
} else if (ClassInfo.forName(insn.owner).isMixin()) {
throw new MixinTransformerError("Error resolving " + ASMHelper.getOpcodeName(insn) + " target for " + insn.owner + "." + insn.name
+ " in " + this);
methodRef.setOwner(superMethod.getImplementor().getName());
} else if (ClassInfo.forName(methodRef.getOwner()).isMixin()) {
throw new MixinTransformerError("Error resolving " + methodRef + " in " + this);
}
}
@@ -449,18 +668,6 @@ public class MixinTargetContext implements IReferenceMapperContext {
field.desc = this.transformSingleDescriptor(field.desc, false);
}
/**
* Transforms a field insn descriptor in the context of this mixin target
*
* @param field Field instruction node to transform
*/
public void transformDescriptor(FieldInsnNode field) {
if (!this.inheritsFromMixin) {
return;
}
field.desc = this.transformSingleDescriptor(field.desc, false);
}
/**
* Transforms a method descriptor in the context of this mixin target
*
@@ -474,15 +681,20 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
* Transforms a method insn descriptor in the context of this mixin target
* Transforms a method or field reference descriptor in the context of this
* mixin target
*
* @param method Method instruction node to transform
* @param member Reference to the method or field
*/
public void transformDescriptor(MethodInsnNode method) {
public void transformDescriptor(MemberRef member) {
if (!this.inheritsFromMixin) {
return;
}
method.desc = this.transformMethodDescriptor(method.desc);
if (member.isField()) {
member.setDesc(this.transformSingleDescriptor(member.getDesc(), false));
} else {
member.setDesc(this.transformMethodDescriptor(member.getDesc()));
}
}
/**
@@ -496,6 +708,13 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
typeInsn.desc = this.transformSingleDescriptor(typeInsn.desc, true);
}
private String transformDescriptor(Type type) {
if (type.getSort() == Type.METHOD) {
return this.transformMethodDescriptor(type.getDescriptor());
}
return this.transformSingleDescriptor(type);
}
private String transformSingleDescriptor(Type type) {
if (type.getSort() < Type.ARRAY) {
@@ -545,19 +764,86 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @return new or existing target handle for the supplied method
*/
public Target getTargetMethod(MethodNode method) {
if (!this.targetClass.methods.contains(method)) {
throw new IllegalArgumentException("Invalid target method supplied to getTargetMethod()");
}
String targetName = method.name + method.desc;
Target target = this.targetMethods.get(targetName);
if (target == null) {
target = new Target(method);
this.targetMethods.put(targetName, target);
}
return target;
return this.targetClass.getTargetMethod(method);
}
MethodNode findMethod(MethodNode method, AnnotationNode annotation) {
Deque<String> aliases = new LinkedList<String>();
aliases.add(method.name);
if (annotation != null) {
List<String> aka = ASMHelper.<List<String>>getAnnotationValue(annotation, "aliases");
if (aka != null) {
aliases.addAll(aka);
}
}
return this.targetClass.findAliasedMethod(aliases, method.desc);
}
MethodNode findRemappedMethod(MethodNode method) {
RemapperChain remapperChain = MixinEnvironment.getCurrentEnvironment().getRemappers();
String remappedName = remapperChain.mapMethodName(this.targetClass.getName(), method.name, method.desc);
if (remappedName.equals(method.name)) {
return null;
}
Deque<String> aliases = new LinkedList<String>();
aliases.add(remappedName);
return this.targetClass.findAliasedMethod(aliases, method.desc);
}
FieldNode findField(FieldNode field, AnnotationNode shadow) {
Deque<String> aliases = new LinkedList<String>();
aliases.add(field.name);
if (shadow != null) {
List<String> aka = ASMHelper.<List<String>>getAnnotationValue(shadow, "aliases");
if (aka != null) {
aliases.addAll(aka);
}
}
return this.targetClass.findAliasedField(aliases, field.desc);
}
FieldNode findRemappedField(FieldNode field) {
RemapperChain remapperChain = MixinEnvironment.getCurrentEnvironment().getRemappers();
String remappedName = remapperChain.mapFieldName(this.targetClass.getName(), field.name, field.desc);
if (remappedName.equals(field.name)) {
return null;
}
Deque<String> aliases = new LinkedList<String>();
aliases.add(remappedName);
return this.targetClass.findAliasedField( aliases, field.desc);
}
/**
* Mark this mixin as requiring the specified class version in the context
* of the current target
*
* @param version version to require
*/
protected void requireVersion(int version) {
this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version);
// This validation is done on the mixin beforehand, however it's still
// possible that an upstream transformer can inject java 7 instructions
// without updating the class version.
if (version > MixinEnvironment.getCompatibilityLevel().classVersion()) {
throw new InvalidMixinException(this, "Unsupported mixin class version " + version);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.refmap.IReferenceMapperContext
* #getMixin()
*/
@Override
public IMixinInfo getMixin() {
return this.mixin;
}
/**
* Get the mixin info for this mixin
*/
@@ -588,7 +874,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
*
* @return shadow methods in the mixin
*/
public List<MethodNode> getShadowMethods() {
public Collection<MethodNode> getShadowMethods() {
return this.shadowMethods;
}
@@ -606,8 +892,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
*
* @return shadow fields in the mixin
*/
public List<FieldNode> getShadowFields() {
return this.shadowFields;
public Set<Entry<FieldNode, Field>> getShadowFields() {
return this.shadowFields.entrySet();
}
/**
@@ -673,6 +959,65 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param targetClass Target class
*/
public void postApply(String transformedName, ClassNode targetClass) {
try {
this.injectorGroups.validateAll();
} catch (InjectionValidationException ex) {
InjectorGroupInfo group = ex.getGroup();
throw new InjectionError(
String.format("Critical injection failure: Callback group %s in %s failed injection check: %s",
group, this.mixin, ex.getMessage()));
}
this.mixin.postApply(transformedName, targetClass);
}
public String getHandlerName(AnnotationNode annotation, MethodNode method, boolean surrogate) {
return this.targetClass.getHandlerName(annotation, method, surrogate);
}
public String getUniqueName(MethodNode method) {
return this.targetClass.getUniqueName(method);
}
public String getUniqueName(FieldNode field) {
return this.targetClass.getUniqueName(field);
}
/**
* Scans the target class for injector methods and prepares discovered
* injectors
*/
public void prepareInjections() {
this.injectors.clear();
for (MethodNode method : this.mergedMethods) {
InjectionInfo injectInfo = InjectionInfo.parse(this, method);
if (injectInfo == null) {
continue;
}
if (injectInfo.isValid()) {
injectInfo.prepare();
this.injectors.add(injectInfo);
}
method.visibleAnnotations.remove(injectInfo.getAnnotation());
}
}
/**
* Apply injectors discovered in the {@link #prepareInjections()} pass
*/
public void applyInjections() {
for (InjectionInfo injectInfo : this.injectors) {
injectInfo.inject();
}
for (InjectionInfo injectInfo : this.injectors) {
injectInfo.postInject();
}
this.injectors.clear();
}
}
@@ -27,9 +27,11 @@ package org.spongepowered.asm.mixin.transformer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
@@ -37,9 +39,6 @@ import java.util.TreeSet;
import java.util.UUID;
import java.util.regex.Pattern;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
@@ -48,22 +47,104 @@ import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinApplyError;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.Mixins;
import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler;
import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction;
import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException;
import org.spongepowered.asm.mixin.throwables.MixinApplyError;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.throwables.MixinPrepareError;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.transformer.MixinTransformerModuleCheckClass.ValidationFailedException;
import org.spongepowered.asm.mixin.transformer.debug.IDecompiler;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.PrettyPrinter;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
/**
* Transformer which manages the mixin configuration and application process
*/
public class MixinTransformer extends TreeTransformer {
/**
* Phase during which an error occurred, delegates to functionality in
* available handler
*/
static enum ErrorPhase {
/**
* Error during initialisation of a MixinConfig
*/
PREPARE {
@Override
ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) {
try {
return handler.onPrepareError(mixin.getConfig(), ex, mixin, action);
} catch (AbstractMethodError ame) {
// Catch if error handler is pre-0.5.4
return action;
}
}
@Override
protected String getContext(IMixinInfo mixin, String context) {
return String.format("preparing %s in %s", mixin.getName(), context);
}
},
/**
* Error during application of a mixin to a target class
*/
APPLY {
@Override
ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) {
try {
return handler.onApplyError(context, ex, mixin, action);
} catch (AbstractMethodError ame) {
// Catch if error handler is pre-0.5.4
return action;
}
}
@Override
protected String getContext(IMixinInfo mixin, String context) {
return String.format("%s -> %s", mixin, context);
}
};
/**
* Human-readable name
*/
private final String text;
private ErrorPhase() {
this.text = this.name().toLowerCase();
}
abstract ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action);
protected abstract String getContext(IMixinInfo mixin, String context);
public String getLogMessage(String context, InvalidMixinException ex, IMixinInfo mixin) {
return String.format("Mixin %s failed %s: %s %s", this.text, this.getContext(mixin, context), ex.getClass().getName(), ex.getMessage());
}
public String getErrorMessage(IMixinInfo mixin, IMixinConfig config, Phase phase) {
return String.format("Mixin [%s] from phase [%s] in config [%s] FAILED during %s", mixin, phase, config, this.name());
}
}
/**
* Proxy transformer for the mixin transformer. These transformers are used
* to allow the mixin transformer to be re-registered in the transformer
@@ -277,6 +358,11 @@ public class MixinTransformer extends TreeTransformer {
*/
private final IDecompiler decompiler;
/**
* Hot-Swap agent
*/
private final IHotSwap hotSwapper;
/**
* ctor
*/
@@ -285,7 +371,7 @@ public class MixinTransformer extends TreeTransformer {
Object globalMixinTransformer = environment.getActiveTransformer();
if (globalMixinTransformer instanceof IClassTransformer) {
throw new RuntimeException("Terminating MixinTransformer instance " + this);
throw new MixinException("Terminating MixinTransformer instance " + this);
}
// I am a leaf on the wind
@@ -294,7 +380,8 @@ public class MixinTransformer extends TreeTransformer {
TreeInfo.setLock(this.lock);
this.decompiler = this.initDecompiler(new File(MixinTransformer.DEBUG_OUTPUT, "java"));
this.hotSwapper = this.initHotSwapper();
try {
FileUtils.deleteDirectory(this.classExportDir);
} catch (IOException ex) {
@@ -303,7 +390,7 @@ public class MixinTransformer extends TreeTransformer {
}
private IDecompiler initDecompiler(File outputPath) {
if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT)) {
if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT_DECOMPILE)) {
return null;
}
@@ -313,7 +400,9 @@ public class MixinTransformer extends TreeTransformer {
Class<? extends IDecompiler> clazz =
(Class<? extends IDecompiler>)Class.forName("org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler");
Constructor<? extends IDecompiler> ctor = clazz.getDeclaredConstructor(File.class);
return ctor.newInstance(outputPath);
IDecompiler decompiler = ctor.newInstance(outputPath);
this.logger.info("Fernflower decompiler was successfully initialised, exported classes will be decompiled");
return decompiler;
} catch (Throwable th) {
this.logger.info("Fernflower could not be loaded, exported classes will not be decompiled. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
@@ -321,6 +410,26 @@ public class MixinTransformer extends TreeTransformer {
return null;
}
private IHotSwap initHotSwapper() {
if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.HOT_SWAP)) {
return null;
}
try {
this.logger.info("Attempting to load Hot-Swap agent");
@SuppressWarnings("unchecked")
Class<? extends IHotSwap> clazz =
(Class<? extends IHotSwap>)Class.forName("org.spongepowered.tools.agent.MixinAgent");
Constructor<? extends IHotSwap> ctor = clazz.getDeclaredConstructor(MixinTransformer.class);
return ctor.newInstance(this);
} catch (Throwable th) {
this.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
return null;
}
/**
* Force-load all classes targetted by mixins but not yet applied
*/
@@ -330,13 +439,22 @@ public class MixinTransformer extends TreeTransformer {
for (MixinConfig config : this.configs) {
unhandled.addAll(config.getUnhandledTargets());
}
for (String nextClass : unhandled) {
Logger auditLogger = LogManager.getLogger("mixin/audit");
for (String target : unhandled) {
try {
this.logger.info("Force-loading class {}", nextClass);
Class.forName(nextClass, true, Launch.classLoader);
auditLogger.info("Force-loading class {}", target);
Class.forName(target, true, Launch.classLoader);
} catch (ClassNotFoundException ex) {
throw new Error("Could not force-load " + nextClass);
auditLogger.error("Could not force-load " + target, ex);
}
}
for (MixinConfig config : this.configs) {
for (String target : config.getUnhandledTargets()) {
ClassAlreadyLoadedException ex = new ClassAlreadyLoadedException(target + " was already classloaded");
auditLogger.error("Could not force-load " + target, ex);
}
}
}
@@ -346,7 +464,7 @@ public class MixinTransformer extends TreeTransformer {
* #transform(java.lang.String, java.lang.String, byte[])
*/
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
public synchronized byte[] transform(String name, String transformedName, byte[] basicClass) {
if (basicClass == null || transformedName == null || this.errorState) {
return basicClass;
}
@@ -357,10 +475,10 @@ public class MixinTransformer extends TreeTransformer {
if (this.currentEnvironment != environment && !locked) {
try {
this.init(environment);
this.select(environment);
} catch (Exception ex) {
this.lock.pop();
throw new RuntimeException(ex);
throw new MixinException(ex);
}
}
@@ -394,41 +512,69 @@ public class MixinTransformer extends TreeTransformer {
if (mixins != null) {
// Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now
if (locked) {
this.logger.warn("Re-entrance detected, this will cause serious problems.", new RuntimeException());
this.logger.warn("Re-entrance detected, this will cause serious problems.", new MixinException());
throw new MixinApplyError("Re-entrance error.");
}
if (this.hotSwapper != null) {
this.hotSwapper.registerTargetClass(transformedName, basicClass);
}
try {
basicClass = this.applyMixins(transformedName, basicClass, mixins);
// Tree for target class
ClassNode targetClassNode = this.readClass(basicClass, true);
TargetClassContext context = new TargetClassContext(this.sessionId, transformedName, targetClassNode, mixins);
basicClass = this.applyMixins(context);
} catch (InvalidMixinException th) {
if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) {
this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass);
}
this.handleMixinErrorState(transformedName, th);
this.dumpClassOnFailure(transformedName, basicClass, environment);
this.handleMixinApplyError(transformedName, th, environment);
}
}
return basicClass;
} catch (Exception ex) {
if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) {
this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass);
}
throw new MixinTransformerError("An unexpected critical error was encountered", ex);
} catch (Throwable th) {
th.printStackTrace();
this.dumpClassOnFailure(transformedName, basicClass, environment);
throw new MixinTransformerError("An unexpected critical error was encountered", th);
} finally {
this.lock.pop();
}
}
private void init(MixinEnvironment environment) {
/**
* Update a mixin class with new bytecode.
*
* @param mixinClass Name of the mixin
* @param bytes New bytecode
* @return List of classes that need to be updated
*/
public List<String> reload(String mixinClass, byte[] bytes) {
if (this.lock.getDepth() > 0) {
throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered");
}
List<String> targets = new ArrayList<String>();
for (MixinConfig config : this.configs) {
targets.addAll(config.reloadMixin(mixinClass, bytes));
}
return targets;
}
private void select(MixinEnvironment environment) {
this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG;
this.logger.log(this.verboseLoggingLevel, "Preparing mixins for {}", environment);
long startTime = System.currentTimeMillis();
this.addConfigs(environment);
this.addModules(environment);
this.initConfigs();
this.selectConfigs(environment);
this.selectModules(environment);
int totalMixins = this.prepareConfigs(environment);
this.currentEnvironment = environment;
double elapsedTime = (System.currentTimeMillis() - startTime) * 0.001D;
if (elapsedTime > 0.25D) {
String elapsed = new DecimalFormat("###0.000").format(elapsedTime);
String perMixinTime = new DecimalFormat("###0.0").format((elapsedTime / totalMixins) * 1000.0);
this.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({} msec avg.)", totalMixins, elapsed, perMixinTime);
}
}
/**
@@ -436,20 +582,19 @@ public class MixinTransformer extends TreeTransformer {
*
* @param environment Environment to query
*/
private void addConfigs(MixinEnvironment environment) {
List<String> configs = environment.getMixinConfigs();
if (configs != null) {
for (String configFile : configs) {
try {
MixinConfig config = MixinConfig.create(configFile);
if (config != null) {
this.logger.log(this.verboseLoggingLevel, "Adding mixin config {}", config);
this.pendingConfigs.add(config);
}
} catch (Exception ex) {
this.logger.warn(String.format("Failed to load mixin config: %s", configFile), ex);
private void selectConfigs(MixinEnvironment environment) {
for (Iterator<Config> iter = Mixins.getConfigs().iterator(); iter.hasNext();) {
Config handle = iter.next();
try {
MixinConfig config = handle.get();
if (config.select(environment)) {
iter.remove();
this.logger.log(this.verboseLoggingLevel, "Selecting config {}", config);
config.onSelect();
this.pendingConfigs.add(config);
}
} catch (Exception ex) {
this.logger.warn(String.format("Failed to select mixin config: %s", handle), ex);
}
}
@@ -461,7 +606,7 @@ public class MixinTransformer extends TreeTransformer {
*
* @param environment Environment to query
*/
private void addModules(MixinEnvironment environment) {
private void selectModules(MixinEnvironment environment) {
this.modules.clear();
// Run CheckClassAdapter on the mixin bytecode if debug option is enabled
@@ -476,12 +621,21 @@ public class MixinTransformer extends TreeTransformer {
}
/**
* Initialise mixin configs
* Prepare mixin configs
*
* @param environment Environment
* @return total number of mixins initialised
*/
private void initConfigs() {
private int prepareConfigs(MixinEnvironment environment) {
int totalMixins = 0;
for (MixinConfig config : this.pendingConfigs) {
try {
config.initialise();
this.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount());
config.prepare(this.hotSwapper);
totalMixins += config.getMixinCount();
} catch (InvalidMixinException ex) {
this.handleMixinPrepareError(config, ex, environment);
} catch (Exception ex) {
this.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + ex.getMessage(), ex);
}
@@ -505,15 +659,19 @@ public class MixinTransformer extends TreeTransformer {
for (MixinConfig config : this.pendingConfigs) {
try {
config.postInitialise();
config.postInitialise(this.hotSwapper);
} catch (InvalidMixinException ex) {
this.handleMixinPrepareError(config, ex, environment);
} catch (Exception ex) {
this.logger.error("Error encountered during mixin config postInit setp'" + config.getName() + "': " + ex.getMessage(), ex);
this.logger.error("Error encountered during mixin config postInit step'" + config.getName() + "': " + ex.getMessage(), ex);
}
}
this.configs.addAll(this.pendingConfigs);
Collections.sort(this.configs);
this.pendingConfigs.clear();
return totalMixins;
}
/**
@@ -546,100 +704,122 @@ public class MixinTransformer extends TreeTransformer {
}
}
return this.writeClass(transformedName, passThroughClass);
return this.writeClass(transformedName, passThroughClass, false);
}
/**
* Apply mixins for specified target class to the class described by the
* supplied byte array.
*
* @param transformedName
* @param basicClass
* @param mixins
* @param context
* @return class bytecode after application of mixins
*/
private byte[] applyMixins(String transformedName, byte[] basicClass, SortedSet<MixinInfo> mixins) {
// Tree for target class
ClassNode targetClass = this.readClass(basicClass, true);
this.preApply(transformedName, targetClass, mixins);
this.apply(transformedName, targetClass, mixins);
this.postApply(transformedName, targetClass, mixins);
return this.writeClass(transformedName, targetClass);
private byte[] applyMixins(TargetClassContext context) {
this.preApply(context);
this.apply(context);
try {
this.postApply(context);
} catch (ValidationFailedException ex) {
this.logger.info(ex.getMessage());
// If verify is enabled and failed, write out the bytecode to allow us to inspect it
if (context.isExportForced() || MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_EXPORT)) {
this.writeClass(context);
}
}
return this.writeClass(context);
}
/**
* Process tasks before mixin application
*
* @param transformedName Target class transformed name
* @param targetClass Target class
* @param mixins Mixin which were just applied
* @param context Target class context
*/
private void preApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
private void preApply(TargetClassContext context) {
for (IMixinTransformerModule module : this.modules) {
module.preApply(transformedName, targetClass, mixins);
module.preApply(context);
}
}
/**
* Apply the mixins to the target class
*
* @param transformedName Target class transformed name
* @param targetClass Target class
* @param mixins Mixin which were just applied
* @param context Target class context
*/
private void apply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
MixinApplicator applicator = new MixinApplicator(this.sessionId, transformedName, targetClass);
applicator.apply(mixins);
private void apply(TargetClassContext context) {
context.applyMixins();
}
/**
* Process tasks after mixin application
*
* @param transformedName Target class transformed name
* @param targetClass Target class
* @param mixins Mixin which were just applied
* @param context Target class context
*/
private void postApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
private void postApply(TargetClassContext context) {
for (IMixinTransformerModule module : this.modules) {
module.postApply(transformedName, targetClass, mixins);
module.postApply(context);
}
}
private void handleMixinErrorState(String targetClassName, InvalidMixinException th) throws MixinApplyError {
private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError {
this.handleMixinError(config.getName(), ex, environment, ErrorPhase.PREPARE);
}
private void handleMixinApplyError(String targetClass, InvalidMixinException ex, MixinEnvironment environment) throws MixinApplyError {
this.handleMixinError(targetClass, ex, environment, ErrorPhase.APPLY);
}
private void handleMixinError(String context, InvalidMixinException ex, MixinEnvironment environment, ErrorPhase errorPhase) throws Error {
this.errorState = true;
MixinInfo mixin = th.getMixin();
MixinConfig config = mixin.getParent();
ErrorAction action = config.isRequired() ? ErrorAction.ERROR : ErrorAction.WARN;
IMixinInfo mixin = ex.getMixin();
if (MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERBOSE)) {
th.printStackTrace();
if (mixin == null) {
this.logger.error("InvalidMixinException has no mixin!", ex);
throw ex;
}
IMixinConfig config = mixin.getConfig();
Phase phase = mixin.getPhase();
ErrorAction action = config.isRequired() ? ErrorAction.ERROR : ErrorAction.WARN;
if (environment.getOption(Option.DEBUG_VERBOSE)) {
new PrettyPrinter()
.add("Invalid Mixin").centre()
.hr('-')
.kvWidth(10)
.kv("Action", errorPhase.name())
.kv("Mixin", mixin.getClassName())
.kv("Config", config.getName())
.kv("Phase", phase)
.hr('-')
.add(" %s", ex.getClass().getName())
.hr('-')
.addWrapped(" %s", ex.getMessage())
.hr('-')
.add(ex.getStackTrace(), 8)
.trace(action.logLevel);
}
for (IMixinErrorHandler handler : this.getErrorHandlers(mixin.getPhase())) {
ErrorAction newAction = handler.onError(targetClassName, th, mixin, action);
ErrorAction newAction = errorPhase.onError(handler, context, ex, mixin, action);
if (newAction != null) {
action = newAction;
}
}
this.logger.log(action.logLevel, String.format("Mixin failed applying %s -> %s: %s %s", mixin, targetClassName,
th.getClass().getName(), th.getMessage()), th);
this.logger.log(action.logLevel, errorPhase.getLogMessage(context, ex, mixin), ex);
this.errorState = false;
if (action == ErrorAction.ERROR) {
throw new MixinApplyError(String.format("Mixin [%s] from phase [%s] in config [%s] FAILED", mixin, mixin.getPhase(),
config), th);
throw new MixinApplyError(errorPhase.getErrorMessage(mixin, config, phase), ex);
}
}
private List<IMixinErrorHandler> getErrorHandlers(Phase phase) {
List<IMixinErrorHandler> handlers = new ArrayList<IMixinErrorHandler>();
for (String handlerClassName : MixinEnvironment.getEnvironment(phase).getErrorHandlerClasses()) {
for (String handlerClassName : Mixins.getErrorHandlerClasses()) {
try {
this.logger.info("Instancing error handler class {}", handlerClassName);
Class<?> handlerClass = Class.forName(handlerClassName, true, Launch.classLoader);
@@ -664,15 +844,19 @@ public class MixinTransformer extends TreeTransformer {
return Pattern.compile(this.prepareFilter(filter), Pattern.CASE_INSENSITIVE).matcher(subject).matches();
}
private byte[] writeClass(String transformedName, ClassNode targetClass) {
private byte[] writeClass(TargetClassContext context) {
return this.writeClass(context.getClassName(), context.getClassNode(), context.isExportForced());
}
private byte[] writeClass(String transformedName, ClassNode targetClass, boolean forceExport) {
// Collapse tree to bytes
byte[] bytes = this.writeClass(targetClass);
// Export transformed class for debugging purposes
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
if (environment.getOption(Option.DEBUG_EXPORT)) {
if (forceExport || environment.getOption(Option.DEBUG_EXPORT)) {
String filter = environment.getOptionValue(Option.DEBUG_EXPORT_FILTER);
if (filter == null || this.applyFilter(filter, transformedName)) {
if (forceExport || filter == null || this.applyFilter(filter, transformedName)) {
File outputFile = this.dumpClass(transformedName.replace('.', '/'), bytes);
if (this.decompiler != null) {
this.decompiler.decompile(outputFile);
@@ -683,6 +867,12 @@ public class MixinTransformer extends TreeTransformer {
return bytes;
}
private void dumpClassOnFailure(String className, byte[] bytes, MixinEnvironment env) {
if (env.getOption(Option.DUMP_TARGET_ON_FAILURE)) {
this.dumpClass(className.replace('.', '/') + ".target", bytes);
}
}
private File dumpClass(String fileName, byte[] bytes) {
File outputFile = new File(this.classExportDir, fileName + ".class");
try {
@@ -24,36 +24,56 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.SortedSet;
import org.spongepowered.asm.lib.ClassWriter;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.util.CheckClassAdapter;
import org.spongepowered.asm.mixin.throwables.MixinException;
/**
* Mixin transformer module which runs CheckClassAdapter on the post-mixin
* bytecode
*/
public class MixinTransformerModuleCheckClass implements IMixinTransformerModule {
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #preTransform(java.lang.String, org.objectweb.asm.tree.ClassNode,
* java.util.SortedSet)
/**
* Exception thrown when checkclass fails
*/
@Override
public void preApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
public static class ValidationFailedException extends MixinException {
private static final long serialVersionUID = 1L;
public ValidationFailedException(String message, Throwable cause) {
super(message, cause);
}
public ValidationFailedException(String message) {
super(message);
}
public ValidationFailedException(Throwable cause) {
super(cause);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #postTransform(java.lang.String, org.objectweb.asm.tree.ClassNode,
* java.util.SortedSet)
* #preApply(org.spongepowered.asm.mixin.transformer.TargetClassContext)
*/
@Override
public void postApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
targetClass.accept(new CheckClassAdapter(new MixinClassWriter(ClassWriter.COMPUTE_FRAMES)));
public void preApply(TargetClassContext context) {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #postApply(org.spongepowered.asm.mixin.transformer.TargetClassContext)
*/
@Override
public void postApply(TargetClassContext context) {
try {
context.getClassNode().accept(new CheckClassAdapter(new MixinClassWriter(ClassWriter.COMPUTE_FRAMES)));
} catch (RuntimeException ex) {
throw new ValidationFailedException(ex.getMessage(), ex);
}
}
}
@@ -32,10 +32,8 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import org.apache.commons.io.IOUtils;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal;
import org.spongepowered.asm.util.PrettyPrinter;
@@ -46,41 +44,40 @@ import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
/**
* Checks whether interfaces declared on mixin target classes are actually fully
* implemented and generates reports to the console and to files on disk
*/
public class MixinTransformerModuleInterfaceChecker implements IMixinTransformerModule {
/**
* CSV Report file
*/
private final File csv;
/**
* Text Report file
*/
private final File report;
/**
* Methods from interfaces that are already in the class before mixins are
* applied.
*/
private final Multimap<ClassInfo, Method> interfaceMethods = HashMultimap.create();
public MixinTransformerModuleInterfaceChecker() {
File debugOutputFolder = new File(MixinTransformer.DEBUG_OUTPUT, "audit");
debugOutputFolder.mkdirs();
this.csv = new File(debugOutputFolder, "mixin_implementation_report.csv");
this.report = new File(debugOutputFolder, "mixin_implementation_report.txt");
try {
Files.write("Class,Method,Signature,Interface\n", this.csv, Charsets.ISO_8859_1);
} catch (IOException ex) {
// well this sucks
}
try {
String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Files.write("Mixin Implementation Report generated on " + dateTime + "\n", this.report, Charsets.ISO_8859_1);
@@ -91,49 +88,48 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #preTransform(java.lang.String, org.objectweb.asm.tree.ClassNode,
* java.util.SortedSet)
* #preApply(org.spongepowered.asm.mixin.transformer.TargetClassContext)
*/
@Override
public void preApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
ClassInfo targetClassInfo = ClassInfo.forName(targetClass.name);
for (Method m : targetClassInfo.getInterfaceMethods()) {
public void preApply(TargetClassContext context) {
ClassInfo targetClassInfo = context.getClassInfo();
for (Method m : targetClassInfo.getInterfaceMethods(false)) {
this.interfaceMethods.put(targetClassInfo, m);
}
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformerModule
* #postTransform(java.lang.String, org.objectweb.asm.tree.ClassNode,
* java.util.SortedSet)
* #postApply(org.spongepowered.asm.mixin.transformer.TargetClassContext)
*/
@Override
public void postApply(String transformedName, ClassNode targetClass, SortedSet<MixinInfo> mixins) {
ClassInfo targetClassInfo = ClassInfo.forName(targetClass.name);
public void postApply(TargetClassContext context) {
ClassInfo targetClassInfo = context.getClassInfo();
String className = targetClassInfo.getName().replace('/', '.');
int missingMethodCount = 0;
PrettyPrinter printer = new PrettyPrinter();
printer.add("Class: %s", className).hr();
printer.add("%-32s %-47s %s", "Return Type", "Missing Method", "From Interface").hr();
Set<Method> interfaceMethods = targetClassInfo.getInterfaceMethods();
Set<Method> implementedMethods = new HashSet<Method>(targetClassInfo.getSuperClass().getInterfaceMethods());
Set<Method> interfaceMethods = targetClassInfo.getInterfaceMethods(true);
Set<Method> implementedMethods = new HashSet<Method>(targetClassInfo.getSuperClass().getInterfaceMethods(true));
implementedMethods.addAll(this.interfaceMethods.removeAll(targetClassInfo));
for (Method method : interfaceMethods) {
Method found = targetClassInfo.findMethodInHierarchy(method.getName(), method.getDesc(), true, Traversal.ALL);
if (found != null) {
// If method IS found and IS implemented, then do nothing (don't print an error)
if (found != null && !found.isAbstract()) {
continue;
}
// Don't blame the subclass for not implementing methods that it does not need to implement.
if (implementedMethods.contains(method)) {
continue;
}
if (missingMethodCount > 0) {
printer.add();
}
@@ -143,7 +139,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
missingMethodCount++;
printer.add("%-32s%s", signaturePrinter.getReturnType(), signaturePrinter);
printer.add("%-80s %s", "", iface);
this.appendToCSVReport(className, method, iface);
}
@@ -164,7 +160,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
private void appendToTextReport(PrettyPrinter printer) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(this.report, true);
PrintStream stream = new PrintStream(fos);
@@ -0,0 +1,316 @@
/*
* 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.transformer;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Debug;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.ASMHelper;
/**
* Struct for containing target class information during mixin application
*/
class TargetClassContext {
/**
* Mutable integer
*/
static class Counter {
public int value;
}
/**
* Transformer session ID
*/
private final String sessionId;
/**
* Target class name
*/
private final String className;
/**
* Target class as tree
*/
private final ClassNode classNode;
/**
* Target class metadata
*/
private final ClassInfo classInfo;
/**
* Mixins to apply
*/
private final SortedSet<MixinInfo> mixins;
/**
* Injector Method descriptor to ID map
*/
private final Map<String, Counter> injectorMethodIndices = new HashMap<String, Counter>();
/**
* Information about methods in the target class, used to keep track of
* transformations we apply
*/
private final Map<String, Target> targetMethods = new HashMap<String, Target>();
/**
* Do not remap injector handler methods (debug option)
*/
private final boolean disableHandlerRemap;
/**
* Unique method and field indices
*/
private int nextUniqueMethodIndex, nextUniqueFieldIndex;
/**
* True once mixins have been applied to this class
*/
private boolean applied;
/**
* True if this class is decorated with an {@link Debug} annotation which
* instructs an export
*/
private boolean forceExport;
TargetClassContext(String sessionId, String name, ClassNode classNode, SortedSet<MixinInfo> mixins) {
this.sessionId = sessionId;
this.className = name;
this.classNode = classNode;
this.classInfo = ClassInfo.fromClassNode(classNode);
this.mixins = mixins;
this.disableHandlerRemap = MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_DISABLE_HANDLER_REMAP);
}
@Override
public String toString() {
return this.className;
}
public boolean isApplied() {
return this.applied;
}
public boolean isExportForced() {
return this.forceExport;
}
/**
* Get the transformer session ID
*/
public String getSessionId() {
return this.sessionId;
}
/**
* Get the internal class name
*/
public String getName() {
return this.classNode.name;
}
/**
* Get the class name
*/
public String getClassName() {
return this.className;
}
/**
* Get the class tree
*/
public ClassNode getClassNode() {
return this.classNode;
}
/**
* Get the class methods (from the tree)
*/
public List<MethodNode> getMethods() {
return this.classNode.methods;
}
/**
* Get the class fields (from the tree)
*/
public List<FieldNode> getFields() {
return this.classNode.fields;
}
/**
* Get the target class metadata
*/
public ClassInfo getClassInfo() {
return this.classInfo;
}
/**
* Get the mixins for this target class
*/
public SortedSet<MixinInfo> getMixins() {
return this.mixins;
}
MethodNode findAliasedMethod(Deque<String> aliases, String desc) {
String alias = aliases.poll();
if (alias == null) {
return null;
}
for (MethodNode target : this.classNode.methods) {
if (target.name.equals(alias) && target.desc.equals(desc)) {
return target;
}
}
return this.findAliasedMethod(aliases, desc);
}
/**
* Finds a field in the target class
*
* @param aliases
* @param desc
* @return Target field or null if not found
*/
FieldNode findAliasedField(Deque<String> aliases, String desc) {
String alias = aliases.poll();
if (alias == null) {
return null;
}
for (FieldNode target : this.classNode.fields) {
if (target.name.equals(alias) && target.desc.equals(desc)) {
return target;
}
}
return this.findAliasedField(aliases, desc);
}
/**
* Get a target method handle from the target class
*
* @param method method to get a target handle for
* @return new or existing target handle for the supplied method
*/
public Target getTargetMethod(MethodNode method) {
if (!this.classNode.methods.contains(method)) {
throw new IllegalArgumentException("Invalid target method supplied to getTargetMethod()");
}
String targetName = method.name + method.desc;
Target target = this.targetMethods.get(targetName);
if (target == null) {
target = new Target(this.classNode, method);
this.targetMethods.put(targetName, target);
}
return target;
}
public String getHandlerName(AnnotationNode annotation, MethodNode method, boolean surrogate) {
if (this.disableHandlerRemap) {
return method.name;
}
String descriptor = String.format("%s%s", method.name, method.desc);
Counter id = this.injectorMethodIndices.get(descriptor);
if (id == null) {
id = new Counter();
this.injectorMethodIndices.put(descriptor, id);
} else if (!surrogate) {
id.value++;
}
return String.format("%s$%s$%d", InjectionInfo.getInjectorPrefix(annotation), method.name, id.value);
}
public String getUniqueName(MethodNode method) {
return String.format("md%s$%s$%d", this.sessionId.substring(30), method.name, this.nextUniqueMethodIndex++);
}
public String getUniqueName(FieldNode field) {
return String.format("fd%s$%s$%d", this.sessionId.substring(30), field.name, this.nextUniqueFieldIndex++);
}
/**
* Apply mixins to this class
*/
public void applyMixins() {
if (this.applied) {
throw new IllegalStateException("Mixins already applied to target class " + this.className);
}
this.applied = true;
MixinApplicatorStandard applicator = this.createApplicator();
applicator.apply(this.mixins);
}
private MixinApplicatorStandard createApplicator() {
if (this.classInfo.isInterface()) {
return new MixinApplicatorInterface(this);
}
return new MixinApplicatorStandard(this);
}
/**
* Process {@link Debug} annotations on the class after application
*/
public void processDebugTasks() {
if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERBOSE)) {
return;
}
AnnotationNode classDebugAnnotation = ASMHelper.getVisibleAnnotation(this.classNode, Debug.class);
if (classDebugAnnotation != null) {
this.forceExport = Boolean.TRUE.equals(ASMHelper.getAnnotationValue(classDebugAnnotation, "export"));
if (Boolean.TRUE.equals(ASMHelper.getAnnotationValue(classDebugAnnotation, "print"))) {
ASMHelper.textify(this.classNode, System.err);
}
}
for (MethodNode method : this.classNode.methods) {
AnnotationNode methodDebugAnnotation = ASMHelper.getVisibleAnnotation(method, Debug.class);
if (methodDebugAnnotation != null && Boolean.TRUE.equals(ASMHelper.getAnnotationValue(methodDebugAnnotation, "print"))) {
ASMHelper.textify(method, System.err);
}
}
}
}
@@ -28,9 +28,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.URLClassLoader;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -38,6 +35,10 @@ import org.spongepowered.asm.lib.ClassReader;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.transformer.MixinTransformer.ReEntranceState;
import org.spongepowered.asm.util.launchwrapper.LaunchClassLoaderUtil;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
/**
* Base class for "info" objects which use ASM tree API to do stuff, with things
@@ -86,16 +87,16 @@ abstract class TreeInfo {
protected static byte[] loadClass(String className, boolean runTransformers) throws ClassNotFoundException, IOException {
String transformedName = className.replace('/', '.');
String name = MixinEnvironment.getCurrentEnvironment().unmap(transformedName);
byte[] classBytes = null;
if ((classBytes = TreeInfo.getClassBytes(name, transformedName)) == null) {
throw new ClassNotFoundException(String.format("The specified class '%s' was not found", transformedName));
}
byte[] classBytes = TreeInfo.getClassBytes(name, transformedName);
if (runTransformers) {
classBytes = TreeInfo.applyTransformers(name, transformedName, classBytes);
}
if (classBytes == null) {
throw new ClassNotFoundException(String.format("The specified class '%s' was not found", transformedName));
}
return classBytes;
}
@@ -136,6 +137,10 @@ abstract class TreeInfo {
* except the excluded transformers
*/
private static byte[] applyTransformers(String name, String transformedName, byte[] basicClass) {
if (LaunchClassLoaderUtil.forClassLoader(Launch.classLoader).isClassExcluded(name, transformedName)) {
return basicClass;
}
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
for (IClassTransformer transformer : environment.getTransformers()) {
@@ -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.transformer.debug;
/**
* Interface to allow the hot-swap agent to be loaded on-demand
*/
public interface IHotSwap {
/**
* Registers a mixin class with the agent.
*
* This is needed as the mixin needs to be loaded to be redefined.
*
* @param name Fully qualified name of the mixin class
*/
public abstract void registerMixinClass(String name);
/**
* Registers a class targeted by at least one mixin.
*
* This is used to rollback the target class to a state before the mixin's
* where applied.
*
* @param name Name of the class
* @param bytecode Bytecode of the class before mixin's have been applied
*/
public abstract void registerTargetClass(String name, byte[] bytecode);
}
@@ -29,14 +29,14 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.transformer.MixinApplicator;
import org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard;
/**
* <p><b>For internal use only!</b> Contains small parts. Keep out of reach of
* children.</p>
*
* <p>Decoration annotation used by the {@link MixinApplicator} to mark methods
* in a class which have been added or overwritten by a mixin.</p>
* <p>Decoration annotation used by the {@link MixinApplicatorStandard} to mark
* methods in a class which have been added or overwritten by a mixin.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -29,7 +29,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>Internal use only.</p>
*
@@ -0,0 +1,61 @@
/*
* 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.transformer.throwables;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
/**
* Exception thrown for bad states when parsing/loading interface mixins
*/
public class InvalidInterfaceMixinException extends InvalidMixinException {
private static final long serialVersionUID = 2L;
public InvalidInterfaceMixinException(IMixinInfo mixin, String message) {
super(mixin, message);
}
public InvalidInterfaceMixinException(IReferenceMapperContext context, String message) {
super(context, message);
}
public InvalidInterfaceMixinException(IMixinInfo mixin, Throwable cause) {
super(mixin, cause);
}
public InvalidInterfaceMixinException(IReferenceMapperContext context, Throwable cause) {
super(context, cause);
}
public InvalidInterfaceMixinException(IMixinInfo mixin, String message, Throwable cause) {
super(mixin, message, cause);
}
public InvalidInterfaceMixinException(IReferenceMapperContext context, String message, Throwable cause) {
super(context, message, cause);
}
}
@@ -22,45 +22,50 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
package org.spongepowered.asm.mixin.transformer.throwables;
public class InvalidMixinException extends RuntimeException {
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
import org.spongepowered.asm.mixin.throwables.MixinException;
private static final long serialVersionUID = 1L;
/**
* Thrown by the mixin validator when a mixin fails a pre-flight check
*/
public class InvalidMixinException extends MixinException {
private static final long serialVersionUID = 2L;
private final MixinInfo mixin;
private final IMixinInfo mixin;
public InvalidMixinException(MixinInfo mixin, String message) {
public InvalidMixinException(IMixinInfo mixin, String message) {
super(message);
this.mixin = mixin;
}
public InvalidMixinException(MixinTargetContext mixin, String message) {
super(message);
this.mixin = mixin.getInfo();
public InvalidMixinException(IReferenceMapperContext context, String message) {
this(context.getMixin(), message);
}
public InvalidMixinException(MixinInfo mixin, Throwable message) {
super(message);
public InvalidMixinException(IMixinInfo mixin, Throwable cause) {
super(cause);
this.mixin = mixin;
}
public InvalidMixinException(MixinTargetContext mixin, Throwable message) {
super(message);
this.mixin = mixin.getInfo();
public InvalidMixinException(IReferenceMapperContext context, Throwable cause) {
this(context.getMixin(), cause);
}
public InvalidMixinException(MixinInfo mixin, String message, Throwable cause) {
public InvalidMixinException(IMixinInfo mixin, String message, Throwable cause) {
super(message, cause);
this.mixin = mixin;
}
public InvalidMixinException(MixinTargetContext mixin, String message, Throwable cause) {
public InvalidMixinException(IReferenceMapperContext context, String message, Throwable cause) {
super(message, cause);
this.mixin = mixin.getInfo();
this.mixin = context.getMixin();
}
public MixinInfo getMixin() {
public IMixinInfo getMixin() {
return this.mixin;
}
}
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more