Refactor launchwrapper support into separate service

This represents the first stage of adding support for cpw's new
modlauncher in preparation for supporting java 9
This commit is contained in:
Mumfrey committed 2017-08-31 18:21:53 +01:00
1 parent b08f87e202
commit d31ccf1220
34 files changed
+1532 -617

No files matched your search

@@ -24,10 +24,11 @@
*/
package org.spongepowered.asm.launch;
import net.minecraft.launchwrapper.Launch;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
/**
* Abstractions for working with {@link Launch#blackboard}
* Abstractions for working with the blackboard
*/
public final class Blackboard {
@@ -54,18 +55,26 @@ public final class Blackboard {
}
private static IMixinService service;
private Blackboard() {}
private static IMixinService getService() {
if (Blackboard.service == null) {
Blackboard.service = MixinService.getService();
}
return Blackboard.service;
}
/**
* Get a value from the blackboard and duck-type it to the specified type
*
* @param key blackboard key
* @return value
* @param <T> duck type
* @return value
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return (T)Launch.blackboard.get(key);
return Blackboard.getService().<T>getGlobalProperty(key);
}
/**
@@ -75,7 +84,7 @@ public final class Blackboard {
* @param value new value
*/
public static void put(String key, Object value) {
Launch.blackboard.put(key, value);
Blackboard.getService().setGlobalProperty(key, value);
}
/**
@@ -84,13 +93,11 @@ public final class Blackboard {
*
* @param key blackboard key
* @param defaultValue value to return if the key is not set or is null
* @return value from blackboard or default value
* @param <T> duck type
* @return value from blackboard or default value
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key, T defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? (T)value : defaultValue;
return Blackboard.getService().getGlobalProperty(key, defaultValue);
}
/**
@@ -103,8 +110,7 @@ public final class Blackboard {
* @return value from blackboard or default
*/
public static String getString(String key, String defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? value.toString() : defaultValue;
return Blackboard.getService().getGlobalPropertyString(key, defaultValue);
}
}
@@ -31,9 +31,7 @@ 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;
import org.spongepowered.asm.service.MixinService;
/**
* Bootstaps the mixin subsystem. This class acts as a bridge between the mixin
@@ -64,13 +62,6 @@ public abstract class MixinBootstrap {
*/
public static final String VERSION = "0.7.3";
// Consts
private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch.";
private static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin.";
private static final String MIXIN_UTIL_PACKAGE = "org.spongepowered.asm.util.";
private static final String ASM_PACKAGE = "org.spongepowered.asm.lib.";
private static final String TRANSFORMER_PROXY_CLASS = MixinBootstrap.MIXIN_PACKAGE + "transformer.MixinTransformer$Proxy";
/**
* Log all the things
*/
@@ -82,13 +73,7 @@ public abstract class MixinBootstrap {
// Static initialiser, add classloader exclusions as early as possible
static {
// The important ones
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.ASM_PACKAGE);
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.MIXIN_PACKAGE);
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.MIXIN_UTIL_PACKAGE);
// Only needed in dev, in production this would be handled by the tweaker
Launch.classLoader.addClassLoaderExclusion(MixinBootstrap.LAUNCH_PACKAGE);
MixinService.getService().prepare();
}
/**
@@ -99,10 +84,11 @@ public abstract class MixinBootstrap {
private MixinBootstrap() {}
/**
* Register a new proxy transformer
* @deprecated use <tt>MixinService.getService().beginPhase()</tt> instead
*/
@Deprecated
public static void addProxy() {
Launch.classLoader.registerTransformer(MixinBootstrap.TRANSFORMER_PROXY_CLASS);
MixinService.getService().beginPhase();
}
/**
@@ -155,7 +141,7 @@ public abstract class MixinBootstrap {
System.setProperty("mixin.env.remapRefMap", "true");
}
if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") > 132) {
if (MixinBootstrap.findInStackTrace("net.minecraft.launchwrapper.Launch", "launch") > 132) {
MixinBootstrap.logger.error("Initialising mixin subsystem after game pre-init phase! Some mixins may be skipped.");
MixinEnvironment.init(Phase.DEFAULT);
MixinBootstrap.getPlatform().prepare(null);
@@ -194,19 +180,16 @@ public abstract class MixinBootstrap {
if (MixinBootstrap.initState) {
MixinBootstrap.getPlatform().prepare(args);
if (MixinBootstrap.findInStackTrace(Launch.class.getName(), "launch") < 4) {
if (MixinBootstrap.findInStackTrace("net.minecraft.launchwrapper.Launch", "launch") < 4) {
MixinBootstrap.logger.warn("MixinBootstrap.doInit() called during a tweak constructor. Expect CoModificationException in 5.. 4..");
}
List<String> tweakClasses = Blackboard.<List<String>>get(Blackboard.Keys.TWEAKCLASSES);
if (tweakClasses != null) {
tweakClasses.add(MixinEnvironment.class.getName() + "$EnvironmentStateTweaker");
}
MixinService.getService().init();
}
}
static void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader);
static void inject() {
MixinBootstrap.getPlatform().inject();
}
private static boolean isSubsystemRegistered() {
@@ -1,81 +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.launch;
import java.io.File;
import java.util.List;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* 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
* inject the FML coremod by hand if running under FML.
*/
public class MixinTweaker implements ITweaker {
/**
* Hello world
*/
public MixinTweaker() {
MixinBootstrap.start();
}
/* (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.doInit(args);
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#injectIntoClassLoader(
* net.minecraft.launchwrapper.LaunchClassLoader)
*/
@Override
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.injectIntoClassLoader(classLoader);
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#getLaunchTarget()
*/
@Override
public String getLaunchTarget() {
return MixinBootstrap.getPlatform().getLaunchTarget();
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.ITweaker#getLaunchArguments()
*/
@Override
public String[] getLaunchArguments() {
return new String[]{};
}
}
@@ -24,8 +24,6 @@
*/
package org.spongepowered.asm.launch.platform;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Base interface for platform agents. Platform agents are environment-specific
* handlers which are used by the Mixin subsystem to perform platform-specific
@@ -50,18 +48,16 @@ public interface IMixinPlatformAgent {
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.
* Called from <tt>inject</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
*
* @param classLoader classLoader to inject into
* Called from <tt>inject</tt> in the parent tweaker
*/
public abstract void injectIntoClassLoader(LaunchClassLoader classLoader);
public abstract void inject();
/**
* Get the launch target from this container, should return null if no
@@ -33,9 +33,7 @@ import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.Blackboard;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
import org.spongepowered.asm.service.MixinService;
/**
* A collection of {@link IMixinPlatformAgent} platform agents)
@@ -46,7 +44,9 @@ public class MixinContainer {
static {
Blackboard.put(Blackboard.Keys.AGENTS, MixinContainer.agentClasses);
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentFML");
for (String agent : MixinService.getService().getPlatformAgents()) {
MixinContainer.agentClasses.add(agent);
}
MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentDefault");
}
@@ -117,18 +117,16 @@ public class MixinContainer {
/**
* Notify all agents to inject into classLoader
*
* @param classLoader classLoader to injec
*/
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
public void inject() {
for (IMixinPlatformAgent agent : this.agents) {
this.logger.debug("Processing injectIntoClassLoader() for {}", agent);
agent.injectIntoClassLoader(classLoader);
this.logger.debug("Processing inject() for {}", agent);
agent.inject();
}
}
/**
* Analogue of {@link ITweaker#getLaunchTarget}, queries all agents and
* Analogue of <tt>ITweaker::getLaunchTarget</tt>, queries all agents and
* returns first valid launch target. Returns null if no agents have launch
* target.
*
@@ -28,8 +28,6 @@ import java.net.URI;
import org.spongepowered.asm.util.Constants.ManifestAttributes;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Default platform agent, handles the mixin manifest keys such as
* <tt>MixinConfigs</tt> and <tt>MixinTokenProviders</tt>.
@@ -72,7 +70,7 @@ public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract {
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
public void inject() {
}
@Override
@@ -1,392 +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.launch.platform;
import java.io.File;
import java.lang.reflect.Field;
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.HashSet;
import java.util.List;
import java.util.Set;
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;
/**
* 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 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 CORE_MOD_MANAGER_CLASS_LEGACY = "cpw.mods.fml.relauncher.CoreModManager";
private static final String GET_IGNORED_MODS_METHOD = "getIgnoredMods";
private static final String GET_IGNORED_MODS_METHOD_LEGACY = "getLoadedCoremods";
private static final String FML_REMAPPER_ADAPTER_CLASS = "org.spongepowered.asm.bridge.RemapperAdapterFML";
private static final String FML_CMDLINE_COREMODS = "fml.coreMods.load";
private static final String FML_PLUGIN_WRAPPER_CLASS = "FMLPluginWrapper";
private static final String FML_CORE_MOD_INSTANCE_FIELD = "coreModInstance";
private static final String MFATT_FORCELOADASMOD = "ForceLoadAsMod";
private static final String MFATT_FMLCOREPLUGIN = "FMLCorePlugin";
private static final String MFATT_COREMODCONTAINSMOD = "FMLCorePluginContainsFMLMod";
private static final String FML_TWEAKER_DEOBF = "FMLDeobfTweaker";
private static final String FML_TWEAKER_INJECTION = "FMLInjectionAndSortingTweaker";
private static final String FML_TWEAKER_TERMINAL = "TerminalTweaker";
/**
* Coremod classes which have already been bootstrapped, so that we know not
* to inject them
*/
private static final Set<String> loadedCoreMods = new HashSet<String>();
/**
* Discover mods specified to FML on the command line (via JVM arg) at
* startup so that we know to ignore them
*/
static {
for (String cmdLineCoreMod : System.getProperty(MixinPlatformAgentFML.FML_CMDLINE_COREMODS, "").split(",")) {
if (!cmdLineCoreMod.isEmpty()) {
MixinPlatformAgentAbstract.logger.debug("FML platform agent will ignore coremod {} specified on the command line", cmdLineCoreMod);
MixinPlatformAgentFML.loadedCoreMods.add(cmdLineCoreMod);
}
}
}
/**
* If running under FML, we will attempt to inject any coremod specified in
* the metadata, FML's CoremodManager returns an ITweaker instance which is
* the "handle" to the injected mod, we will need to proxy calls through to
* the wrapper. If initialisation fails (for example if we are not running
* under FML or if an FMLCorePlugin key is not specified in the metadata)
* then this handle will be null.
*/
private final ITweaker coreModWrapper;
/**
* Name of this container
*/
private final String fileName;
/**
* Core mod manager class
*/
private Class<?> clCoreModManager;
/**
* True if this agent is initialised during pre-injection
*/
private boolean initInjectionState;
/**
* @param manager platform manager
* @param uri URI of the resource for this agent
*/
public MixinPlatformAgentFML(MixinPlatformManager manager, URI uri) {
super(manager, uri);
this.fileName = this.container.getName();
this.coreModWrapper = this.initFMLCoreMod();
}
/**
* Attempts to initialise the FML coremod (if specified in the jar metadata)
*/
private ITweaker initFMLCoreMod() {
try {
try {
this.clCoreModManager = MixinPlatformAgentFML.getCoreModManagerClass();
} catch (ClassNotFoundException ex) {
MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.",
ex.getMessage());
return null;
}
if ("true".equalsIgnoreCase(this.attributes.get(MixinPlatformAgentFML.MFATT_FORCELOADASMOD))) {
MixinPlatformAgentAbstract.logger.debug("ForceLoadAsMod was specified for {}, attempting force-load", this.fileName);
this.loadAsMod();
}
return this.injectCorePlugin();
} catch (Exception ex) {
MixinPlatformAgentAbstract.logger.catching(ex);
return null;
}
}
/**
* If the "force load as mod" manifest setting is set to true, this agent
* will attempt to forcibly inject the container as a coremod by first
* removing the container from fml's "loaded coremods" list causing
* fml to subsequently re-evaluate the container for coremod candidacy.
*
* <p>Further, if the "fml core plugin contains fml mod" flag is set in the
* manifest, the container will be manually injected by this agent into the
* "reparseable coremods" collection which will cause it to be crawled for
* regular mods as well.</p>
*/
private void loadAsMod() {
try {
MixinPlatformAgentFML.getIgnoredMods(this.clCoreModManager).remove(this.fileName);
} catch (Exception ex) {
MixinPlatformAgentAbstract.logger.catching(ex);
}
if (this.attributes.get(MixinPlatformAgentFML.MFATT_COREMODCONTAINSMOD) != null) {
this.addReparseableJar();
}
}
/**
* Called by {@link #loadAsMod} if the "fml core plugin contains fml mod" is
* set, adds this container to the "reparsable coremods" collection.
*/
private void addReparseableJar() {
try {
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)) {
MixinPlatformAgentAbstract.logger.debug("Adding {} to reparseable coremod collection", this.fileName);
reparsedCoremods.add(this.fileName);
}
} catch (Exception ex) {
MixinPlatformAgentAbstract.logger.catching(ex);
}
}
private ITweaker injectCorePlugin() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String coreModName = this.attributes.get(MixinPlatformAgentFML.MFATT_FMLCOREPLUGIN);
if (coreModName == null) {
return null;
}
if (this.isAlreadyInjected(coreModName)) {
MixinPlatformAgentAbstract.logger.debug("{} has core plugin {}. Skipping because it was already injected.", this.fileName, coreModName);
return null;
}
MixinPlatformAgentAbstract.logger.debug("{} has core plugin {}. Injecting it into FML for co-initialisation:", this.fileName, coreModName);
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) {
MixinPlatformAgentAbstract.logger.debug("Core plugin {} could not be loaded.", coreModName);
return null;
}
// If the injection tweaker is queued, we are most likely in development
// and will NOT need to co-init the coremod
this.initInjectionState = MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_INJECTION);
MixinPlatformAgentFML.loadedCoreMods.add(coreModName);
return wrapper;
}
private boolean isAlreadyInjected(String coreModName) {
// Did we already inject this ourselves, or was it specified on the command line
if (MixinPlatformAgentFML.loadedCoreMods.contains(coreModName)) {
return true;
}
// Was it already loaded, check the tweakers list
try {
List<ITweaker> tweakers = Blackboard.<List<ITweaker>>get(Blackboard.Keys.TWEAKS);
if (tweakers == null) {
return false;
}
for (ITweaker tweaker : tweakers) {
Class<? extends ITweaker> tweakClass = tweaker.getClass();
if (MixinPlatformAgentFML.FML_PLUGIN_WRAPPER_CLASS.equals(tweakClass.getSimpleName())) {
Field fdCoreModInstance = tweakClass.getField(MixinPlatformAgentFML.FML_CORE_MOD_INSTANCE_FIELD);
fdCoreModInstance.setAccessible(true);
Object coreMod = fdCoreModInstance.get(tweaker);
if (coreModName.equals(coreMod.getClass().getName())) {
return true;
}
}
}
} catch (Exception ex) {
// ex.printStackTrace();
}
return false;
}
@Override
public String getPhaseProvider() {
return MixinPlatformAgentFML.class.getName() + "$PhaseProvider";
}
/* (non-Javadoc)
* @see org.spongepowered.asm.launch.IMixinPlatformAgent#prepare()
*/
@Override
public void prepare() {
this.initInjectionState |= MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_INJECTION);
}
/* (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 {
MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFML.FML_REMAPPER_ADAPTER_CLASS);
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.IMixinPlatformAgent
* #injectIntoClassLoader(net.minecraft.launchwrapper.LaunchClassLoader)
*/
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
if (this.coreModWrapper != null && this.checkForCoInitialisation()) {
MixinPlatformAgentAbstract.logger.debug("FML agent is co-initiralising coremod instance {} for {}", this.coreModWrapper, this.uri);
this.coreModWrapper.injectIntoClassLoader(classLoader);
}
}
/* (non-Javadoc)
* @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>
* manually call <tt>injectIntoClassLoader</tt> on the wrapper because FML
* will add the wrapper to the tweaker list itself. This occurs when mixin
* tweaker is loaded explicitly.
*
* <p>In the event that we are <i>post</i> FML's injection, then we must
* instead call <tt>injectIntoClassLoader</tt> on the wrapper manually.</p>
*
* @return true if FML was already injected
*/
protected final boolean checkForCoInitialisation() {
boolean injectionTweaker = MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_INJECTION);
boolean terminalTweaker = MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_TERMINAL);
if ((this.initInjectionState && terminalTweaker) || injectionTweaker) {
MixinPlatformAgentAbstract.logger.debug("FML agent is skipping co-init for {} because FML will inject it normally", this.coreModWrapper);
return false;
}
return !MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_DEOBF);
}
/**
* Check whether a tweaker ending with <tt>tweakName</tt> has been enqueued
* but not yet visited.
*
* @param tweakerName Tweaker name to
* @return true if a tweaker with the specified name is queued
*/
private static boolean isTweakerQueued(String tweakerName) {
for (String tweaker : Blackboard.<List<String>>get(Blackboard.Keys.TWEAKCLASSES)) {
if (tweaker.endsWith(tweakerName)) {
return true;
}
}
return false;
}
/**
* Attempt to get the FML CoreModManager, tries the post-1.8 namespace first
* and falls back to 1.7.10 if class lookup fails
*/
private static Class<?> getCoreModManagerClass() throws ClassNotFoundException {
try {
return Class.forName(Blackboard.getString(
Blackboard.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS));
} catch (ClassNotFoundException ex) {
return Class.forName(MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS_LEGACY);
}
}
@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(MixinPlatformAgentFML.GET_IGNORED_MODS_METHOD_LEGACY);
} catch (NoSuchMethodException ex2) {
MixinPlatformAgentAbstract.logger.catching(Level.DEBUG, ex2);
return Collections.<String>emptyList();
}
}
return (List<String>)mdGetIgnoredMods.invoke(null);
}
}
@@ -38,17 +38,14 @@ 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.service.MixinService;
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.
@@ -57,6 +54,7 @@ public class MixinPlatformManager {
private static final String MFATT_TWEAKER = "TweakClass";
private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main";
private static final String MIXIN_TWEAKER_CLASS = "org.spongepowered.asm.launch.MixinTweaker";
/**
* Make with the logging already
@@ -85,7 +83,7 @@ public class MixinPlatformManager {
private boolean prepared = false;
/**
* Tracks whether {@link #injectIntoClassLoader} was called yet
* Tracks whether {@link #inject} was called yet
*/
private boolean injected;
@@ -186,12 +184,9 @@ public class MixinPlatformManager {
}
/**
* Initialise the primary container and dispatch injectIntoClassLoader to
* all containers
*
* @param classLoader classloader to inject into
* Initialise the primary container and dispatch inject to all containers
*/
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
public final void inject() {
if (this.injected) {
return;
}
@@ -202,10 +197,10 @@ public class MixinPlatformManager {
}
this.scanClasspath();
MixinPlatformManager.logger.debug("injectIntoClassLoader running with {} agents", this.containers.size());
MixinPlatformManager.logger.debug("inject() running with {} agents", this.containers.size());
for (MixinContainer container : this.containers.values()) {
try {
container.injectIntoClassLoader(classLoader);
container.inject();
} catch (Exception ex) {
ex.printStackTrace();
}
@@ -217,7 +212,7 @@ public class MixinPlatformManager {
* mixin tweaker in their manifest) and add agents for them
*/
private void scanClasspath() {
URL[] sources = Launch.classLoader.getSources().toArray(new URL[0]);
URL[] sources = MixinService.getService().getClassPath();
for (URL url : sources) {
try {
URI uri = url.toURI();
@@ -230,7 +225,7 @@ public class MixinPlatformManager {
}
MainAttributes attributes = MainAttributes.of(uri);
String tweaker = attributes.get(MixinPlatformManager.MFATT_TWEAKER);
if (MixinTweaker.class.getName().equals(tweaker)) {
if (MixinPlatformManager.MIXIN_TWEAKER_CLASS.equals(tweaker)) {
MixinPlatformManager.logger.debug("{} contains a mixin tweaker, adding agents", uri);
this.addContainer(uri);
}
@@ -24,9 +24,7 @@
*/
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;
@@ -35,8 +33,6 @@ 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;
@@ -53,6 +49,10 @@ 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.service.ILegacyClassTransformer;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.ITransformer;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.JavaVersion;
import org.spongepowered.asm.util.PrettyPrinter;
@@ -61,12 +61,6 @@ import org.spongepowered.asm.util.perf.Profiler;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import net.minecraft.launchwrapper.IClassNameTransformer;
import net.minecraft.launchwrapper.IClassTransformer;
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.
@@ -183,7 +177,7 @@ public final class MixinEnvironment implements ITokenProvider {
CLIENT {
@Override
protected boolean detect() {
String sideName = this.getSideName();
String sideName = MixinService.getService().getSideName();
return "CLIENT".equals(sideName);
}
},
@@ -194,51 +188,12 @@ public final class MixinEnvironment implements ITokenProvider {
SERVER {
@Override
protected boolean detect() {
String sideName = this.getSideName();
String sideName = MixinService.getService().getSideName();
return "SERVER".equals(sideName) || "DEDICATEDSERVER".equals(sideName);
}
};
protected abstract boolean detect();
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 : 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")) {
return "CLIENT";
}
}
String name = this.getSideName("net.minecraftforge.fml.relauncher.FMLLaunchHandler", "side");
if (name != null) {
return name;
}
name = this.getSideName("cpw.mods.fml.relauncher.FMLLaunchHandler", "side");
if (name != null) {
return name;
}
name = this.getSideName("com.mumfrey.liteloader.launch.LiteLoaderTweaker", "getEnvironmentType");
if (name != null) {
return name;
}
return "UNKNOWN";
}
private String getSideName(String className, String methodName) {
try {
Class<?> clazz = Class.forName(className, false, Launch.classLoader);
Method method = clazz.getDeclaredMethod(methodName);
return ((Enum<?>)method.invoke(null)).name();
} catch (Exception ex) {
return null;
}
}
}
/**
@@ -741,34 +696,6 @@ public final class MixinEnvironment implements ITokenProvider {
}
/**
* Tweaker used to notify the environment when we transition from preinit to
* default
*/
public static class EnvironmentStateTweaker implements ITweaker {
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
MixinBootstrap.getPlatform().injectIntoClassLoader(classLoader);
}
@Override
public String getLaunchTarget() {
return "";
}
@Override
public String[] getLaunchArguments() {
MixinEnvironment.gotoPhase(Phase.DEFAULT);
return new String[0];
}
}
/**
* Wrapper for providing a natural sorting order for providers
*/
@@ -884,6 +811,11 @@ public final class MixinEnvironment implements ITokenProvider {
* Performance profiler
*/
private static final Profiler profiler = new Profiler();
/**
* Service
*/
private final IMixinService service;
/**
* The phase for this environment
@@ -931,12 +863,7 @@ public final class MixinEnvironment implements ITokenProvider {
* re-entrant transformers. Detected re-entrant transformers will be
* subsequently removed.
*/
private List<IClassTransformer> transformers;
/**
* Class name transformer (if present)
*/
private IClassNameTransformer nameTransformer;
private List<ILegacyClassTransformer> transformers;
/**
* Obfuscation context (refmap key to use in this environment)
@@ -944,6 +871,7 @@ public final class MixinEnvironment implements ITokenProvider {
private String obfuscationContext = null;
MixinEnvironment(Phase phase) {
this.service = MixinService.getService();
this.phase = phase;
this.configsKey = Blackboard.Keys.CONFIGS + "." + this.phase.name.toLowerCase();
@@ -954,7 +882,7 @@ public final class MixinEnvironment implements ITokenProvider {
}
// Also sanity check
if (this.getClass().getClassLoader() != Launch.class.getClassLoader()) {
if (this.getClass().getClassLoader() != this.service.getApplicationClassLoader()) {
throw new MixinException("Attempted to init the mixin environment in the wrong classloader");
}
@@ -970,9 +898,10 @@ public final class MixinEnvironment implements ITokenProvider {
}
private void printHeader(Object version) {
Side side = this.getSide();
String codeSource = this.getCodeSource();
MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
String serviceName = this.service.getName();
Side side = this.getSide();
MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Service={} Env={}", version, codeSource, serviceName, side);
boolean verbose = this.getOption(Option.DEBUG_VERBOSE);
if (verbose || this.getOption(Option.DEBUG_EXPORT) || this.getOption(Option.DEBUG_PROFILER)) {
@@ -981,6 +910,8 @@ public final class MixinEnvironment implements ITokenProvider {
printer.kv("Code source", codeSource);
printer.kv("Internal Version", version);
printer.kv("Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr();
printer.kv("Service Name", serviceName);
printer.kv("Service Class", this.service.getClass().getName()).hr();
for (Option option : Option.values()) {
StringBuilder indent = new StringBuilder();
for (int i = 0; i < option.depth; i++) {
@@ -1021,7 +952,7 @@ public final class MixinEnvironment implements ITokenProvider {
List<String> mixinConfigs = Blackboard.<List<String>>get(this.configsKey);
if (mixinConfigs == null) {
mixinConfigs = new ArrayList<String>();
Launch.blackboard.put(this.configsKey, mixinConfigs);
this.service.setGlobalProperty(this.configsKey, mixinConfigs);
}
return mixinConfigs;
}
@@ -1071,7 +1002,7 @@ public final class MixinEnvironment implements ITokenProvider {
try {
@SuppressWarnings("unchecked")
Class<? extends IEnvironmentTokenProvider> providerClass =
(Class<? extends IEnvironmentTokenProvider>)Class.forName(providerName, true, Launch.classLoader);
(Class<? extends IEnvironmentTokenProvider>)Class.forName(providerName, true, this.service.getClassLoader());
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
@@ -1146,7 +1077,7 @@ public final class MixinEnvironment implements ITokenProvider {
*
* @param transformer Mixin Transformer
*/
public void setActiveTransformer(IClassTransformer transformer) {
public void setActiveTransformer(ITransformer transformer) {
if (transformer != null) {
Blackboard.put(Blackboard.Keys.TRANSFORMER, transformer);
}
@@ -1285,12 +1216,12 @@ public final class MixinEnvironment implements ITokenProvider {
*
* @return current transformer delegation list (read-only)
*/
public List<IClassTransformer> getTransformers() {
public List<ILegacyClassTransformer> getTransformers() {
if (this.transformers == null) {
this.buildTransformerDelegationList();
}
return Collections.<IClassTransformer>unmodifiableList(this.transformers);
return Collections.<ILegacyClassTransformer>unmodifiableList(this.transformers);
}
/**
@@ -1305,24 +1236,6 @@ public final class MixinEnvironment implements ITokenProvider {
this.transformers = null;
}
/**
* Map a class name back to its obfuscated counterpart
*
* @param className class name to unmap
* @return obfuscated name for the specified deobfuscated reference
*/
public String unmap(String className) {
if (this.transformers == null) {
this.buildTransformerDelegationList();
}
if (this.nameTransformer != null) {
return this.nameTransformer.unmapClassName(className);
}
return className;
}
/**
* Builds the transformer list to apply to loaded mixin bytecode. Since
* generating this list requires inspecting each transformer by name (to
@@ -1331,9 +1244,14 @@ public final class MixinEnvironment implements ITokenProvider {
*/
private void buildTransformerDelegationList() {
MixinEnvironment.logger.debug("Rebuilding transformer delegation list:");
this.transformers = new ArrayList<IClassTransformer>();
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
String transformerName = transformer.getClass().getName();
this.transformers = new ArrayList<ILegacyClassTransformer>();
for (ITransformer transformer : this.service.getTransformers()) {
if (!(transformer instanceof ILegacyClassTransformer)) {
continue;
}
ILegacyClassTransformer legacyTransformer = (ILegacyClassTransformer)transformer;
String transformerName = legacyTransformer.getName();
boolean include = true;
for (String excludeClass : MixinEnvironment.excludeTransformers) {
if (transformerName.contains(excludeClass)) {
@@ -1341,23 +1259,15 @@ public final class MixinEnvironment implements ITokenProvider {
break;
}
}
boolean ignoreTransformer = transformer.getClass().getAnnotation(Resource.class) != null;
if (include && !ignoreTransformer && !transformerName.contains(MixinTransformer.class.getName())) {
if (include && !legacyTransformer.isDelegationExcluded()) {
MixinEnvironment.logger.debug(" Adding: {}", transformerName);
this.transformers.add(transformer);
this.transformers.add(legacyTransformer);
} else {
MixinEnvironment.logger.debug(" Excluding: {}", transformerName);
}
}
MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
if (transformer instanceof IClassNameTransformer) {
MixinEnvironment.logger.debug("Found name transformer: {}", transformer.getClass().getName());
this.nameTransformer = (IClassNameTransformer) transformer;
}
}
}
/* (non-Javadoc)
@@ -1481,7 +1391,7 @@ public final class MixinEnvironment implements ITokenProvider {
}
if (phase.ordinal > MixinEnvironment.getCurrentPhase().ordinal) {
MixinBootstrap.addProxy();
MixinService.getService().beginPhase();
}
if (phase == Phase.DEFAULT) {
@@ -32,8 +32,7 @@ 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;
import org.spongepowered.asm.service.MixinService;
/**
* Entry point for registering global mixin resources. Compatibility with
@@ -143,7 +142,7 @@ public final class Mixins {
Set<Config> mixinConfigs = Blackboard.<Set<Config>>get(Mixins.CONFIGS_KEY);
if (mixinConfigs == null) {
mixinConfigs = new LinkedHashSet<Config>();
Launch.blackboard.put(Mixins.CONFIGS_KEY, mixinConfigs);
MixinService.getService().setGlobalProperty(Mixins.CONFIGS_KEY, mixinConfigs);
}
return mixinConfigs;
}
@@ -34,14 +34,14 @@ import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
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
@@ -254,7 +254,8 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable {
Logger logger = LogManager.getLogger("mixin");
Reader reader = null;
try {
InputStream resource = Launch.classLoader.getResourceAsStream(resourcePath);
IMixinService service = MixinService.getService();
InputStream resource = service.getResourceAsStream(resourcePath);
if (resource != null) {
reader = new InputStreamReader(resource);
ReferenceMapper mapper = ReferenceMapper.readJson(reader);
@@ -52,6 +52,7 @@ import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.ClassSignature;
import org.spongepowered.asm.util.perf.Profiler;
@@ -65,7 +66,7 @@ import com.google.common.collect.ImmutableSet;
* information needed to support more complex mixin behaviour such as detached
* superclass and mixin inheritance.
*/
public final class ClassInfo extends TreeInfo {
public final class ClassInfo {
public static final int INCLUDE_PRIVATE = Opcodes.ACC_PRIVATE;
public static final int INCLUDE_STATIC = Opcodes.ACC_STATIC;
@@ -1671,7 +1672,7 @@ public final class ClassInfo extends TreeInfo {
ClassInfo info = ClassInfo.cache.get(className);
if (info == null) {
try {
ClassNode classNode = TreeInfo.getClassNode(className);
ClassNode classNode = MixinService.getService().getClassNode(className);
info = new ClassInfo(classNode);
} catch (Exception ex) {
ClassInfo.logger.warn("Error loading class: {}", className);
@@ -41,6 +41,7 @@ import org.spongepowered.asm.lib.commons.ClassRemapper;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.transformers.MixinClassWriter;
/**
@@ -119,7 +120,7 @@ final class InnerClassGenerator implements IClassGenerator {
}
byte[] getClassBytes() throws ClassNotFoundException, IOException {
return TreeInfo.loadClass(this.originalName, true);
return MixinService.getService().getClassBytes(this.originalName, true);
}
/**
@@ -42,7 +42,7 @@ import org.spongepowered.asm.util.Annotations;
* Information about an interface being runtime-patched onto a mixin target
* class, see {@link org.spongepowered.asm.mixin.Implements Implements}
*/
public final class InterfaceInfo extends TreeInfo {
public final class InterfaceInfo {
/**
* Parent mixin
@@ -56,13 +56,13 @@ import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.refmap.RemappingReferenceMapper;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
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
*/
@@ -255,6 +255,8 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
// * Phase selector
// */
// private transient List<Selector> selectors;
private transient IMixinService service;
/**
* Parent environment
@@ -319,7 +321,8 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* returned, or false if initialisation failed and the config should
* be discarded
*/
private boolean onLoad(String name, MixinEnvironment fallbackEnvironment) {
private boolean onLoad(IMixinService service, String name, MixinEnvironment fallbackEnvironment) {
this.service = service;
this.name = name;
this.env = this.parseSelector(this.selector, fallbackEnvironment);
this.required &= !this.env.getOption(Option.IGNORE_REQUIRED);
@@ -387,7 +390,7 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
for (String injectionPoint : this.injectorOptions.injectionPoints) {
try {
Class<?> injectionPointClass = Class.forName(injectionPoint, true, Launch.classLoader);
Class<?> injectionPointClass = Class.forName(injectionPoint, true, this.service.getClassLoader());
if (InjectionPoint.class.isAssignableFrom(injectionPointClass)) {
InjectionPoint.register((Class<? extends InjectionPoint>)injectionPointClass);
} else {
@@ -435,7 +438,7 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
void onSelect() {
if (this.pluginClassName != null) {
try {
Class<?> pluginClass = Class.forName(this.pluginClassName, true, Launch.classLoader);
Class<?> pluginClass = Class.forName(this.pluginClassName, true, this.service.getClassLoader());
this.plugin = (IMixinConfigPlugin)pluginClass.newInstance();
if (this.plugin != null) {
@@ -563,7 +566,7 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
MixinInfo mixin = null;
try {
mixin = new MixinInfo(this, mixinClass, true, this.plugin, suppressPlugin);
mixin = new MixinInfo(this.service, this, mixinClass, true, this.plugin, suppressPlugin);
if (mixin.getTargetClasses().size() > 0) {
MixinConfig.globalMixinList.add(fqMixinClass);
for (String targetClass : mixin.getTargetClasses()) {
@@ -886,8 +889,9 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
*/
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, outer)) {
IMixinService service = MixinService.getService();
MixinConfig config = new Gson().fromJson(new InputStreamReader(service.getResourceAsStream(configFile)), MixinConfig.class);
if (config.onLoad(service, configFile, outer)) {
return config.getHandle();
}
return null;
@@ -63,9 +63,10 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.launchwrapper.LaunchClassLoaderUtil;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
@@ -73,12 +74,10 @@ import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import net.minecraft.launchwrapper.Launch;
/**
* Runtime information bundle about a mixin
*/
class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* A MethodNode in a mixin
@@ -664,9 +663,9 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
}
/**
* Class loader utility
* Mixin service
*/
private static final LaunchClassLoaderUtil classLoaderUtil = LaunchClassLoaderUtil.forClassLoader(Launch.classLoader);
private static final IMixinService classLoaderUtil = MixinService.getService();
/**
* Global order of mixin infos, used to determine ordering between mixins
@@ -723,6 +722,11 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* Intrinsic order (for sorting mixins with identical priority)
*/
private final transient int order = MixinInfo.mixinOrder++;
/**
* Service
*/
private final transient IMixinService service;
/**
* Configuration plugin
@@ -763,17 +767,18 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* Internal ctor, called by {@link MixinConfig}
*
* @param parent configuration which owns this mixin, the parent
* @param mixinName name of this mixin (class name stub)
* @param name name of this mixin (class name stub)
* @param runTransformers true if this mixin should run transformers on its
* bytecode when loading
* @param plugin mixin config companion plugin, may be null
* @param suppressPlugin true to suppress the plugin from filtering targets
* of this mixin
*/
MixinInfo(MixinConfig parent, String mixinName, boolean runTransformers, IMixinConfigPlugin plugin, boolean suppressPlugin) {
MixinInfo(IMixinService service, MixinConfig parent, String name, boolean runTransformers, IMixinConfigPlugin plugin, boolean suppressPlugin) {
this.service = service;
this.parent = parent;
this.name = mixinName;
this.className = parent.getMixinPackage() + mixinName;
this.name = name;
this.className = parent.getMixinPackage() + name;
this.plugin = plugin;
this.phase = parent.getEnvironment().getPhase();
this.strict = parent.getEnvironment().getOption(Option.DEBUG_TARGETS);
@@ -1153,7 +1158,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
byte[] mixinBytes = null;
try {
mixinBytes = TreeInfo.loadClass(mixinClassName, runTransformers);
mixinBytes = this.service.getClassBytes(mixinClassName, runTransformers);
} catch (ClassNotFoundException ex) {
throw new ClassNotFoundException(String.format("The specified mixin '%s' was not found", mixinClassName));
} catch (IOException ex) {
@@ -119,13 +119,30 @@ class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListene
boolean canTransform(String className) {
return this.syntheticInnerClasses.contains(className) || this.loadable.contains(className);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.ILegacyClassTransformer#getName()
*/
@Override
public String getName() {
return this.getClass().getName();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.ILegacyClassTransformer
* #isDelegationExcluded()
*/
@Override
public boolean isDelegationExcluded() {
return true;
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.IClassTransformer
* #transform(java.lang.String, java.lang.String, byte[])
*/
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
public byte[] transformClassBytes(String name, String transformedName, byte[] bytes) {
if (this.syntheticInnerClasses.contains(transformedName)) {
return this.processSyntheticInner(bytes);
}
@@ -59,14 +59,15 @@ import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExpo
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.service.IMixinService;
import org.spongepowered.asm.service.ITransformer;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.ReEntranceLock;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
import net.minecraft.launchwrapper.IClassTransformer;
import net.minecraft.launchwrapper.Launch;
/**
* Transformer which manages the mixin configuration and application process
*/
@@ -139,160 +140,6 @@ public class MixinTransformer extends TreeTransformer {
}
/**
* Proxy transformer for the mixin transformer. These transformers are used
* to allow the mixin transformer to be re-registered in the transformer
* chain at a later stage in startup without having to fully re-initialise
* the mixin transformer itself. Only the latest proxy to be instantiated
* will actually provide callbacks to the underlying mixin transformer.
*/
public static class Proxy implements IClassTransformer {
/**
* All existing proxies
*/
private static List<Proxy> proxies = new ArrayList<Proxy>();
/**
* Actual mixin transformer instance
*/
private static MixinTransformer transformer = new MixinTransformer();
/**
* True if this is the active proxy, newer proxies disable their older
* siblings
*/
private boolean isActive = true;
public Proxy() {
for (Proxy hook : Proxy.proxies) {
hook.isActive = false;
}
Proxy.proxies.add(this);
LogManager.getLogger("mixin").debug("Adding new mixin transformer proxy #{}", Proxy.proxies.size());
}
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
if (this.isActive) {
return Proxy.transformer.transform(name, transformedName, basicClass);
}
return basicClass;
}
}
/**
* Re-entrance semaphore used to share re-entrance data with the TreeInfo
*/
class ReEntranceState {
/**
* Max valid depth
*/
private final int maxDepth;
/**
* Re-entrance depth
*/
private int depth = 0;
/**
* Semaphore set when check exceeds a depth of 1
*/
private boolean semaphore = false;
public ReEntranceState(int maxDepth) {
this.maxDepth = maxDepth;
}
/**
* Get max depth
*/
public int getMaxDepth() {
return this.maxDepth;
}
/**
* Get current depth
*/
public int getDepth() {
return this.depth;
}
/**
* Increase the re-entrance depth counter and set the semaphore if depth
* exceeds max depth
*
* @return fluent interface
*/
ReEntranceState push() {
this.depth++;
this.checkAndSet();
return this;
}
/**
* Decrease the re-entrance depth
*
* @return fluent interface
*/
ReEntranceState pop() {
if (this.depth == 0) {
throw new IllegalStateException("ReEntranceState pop() with zero depth");
}
this.depth--;
return this;
}
/**
* Run the depth check but do not set the semaphore
*
* @return true if depth has exceeded max
*/
boolean check() {
return this.depth > this.maxDepth;
}
/**
* Run the depth check and set the semaphore if depth is exceeded
*
* @return true if semaphore is set
*/
boolean checkAndSet() {
return this.semaphore |= this.check();
}
/**
* Set the semaphore
*
* @return fluent interface
*/
ReEntranceState set() {
this.semaphore = true;
return this;
}
/**
* Get whether the semaphore is set
*/
boolean isSet() {
return this.semaphore;
}
/**
* Clear the semaphore
*
* @return fluent interface
*/
ReEntranceState clear() {
this.semaphore = false;
return this;
}
}
private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent";
private static final String METRONOME_AGENT_CLASS = "org.spongepowered.metronome.Agent";
@@ -301,6 +148,11 @@ public class MixinTransformer extends TreeTransformer {
*/
static final Logger logger = LogManager.getLogger("mixin");
/**
* Service
*/
private final IMixinService service = MixinService.getService();
/**
* All mixin configuration bundles
*/
@@ -314,7 +166,7 @@ public class MixinTransformer extends TreeTransformer {
/**
* Re-entrance detector
*/
private final ReEntranceState lock = new ReEntranceState(1);
private final ReEntranceLock lock;
/**
* Session ID, used as a check when parsing {@link MixinMerged} annotations
@@ -370,14 +222,14 @@ public class MixinTransformer extends TreeTransformer {
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
Object globalMixinTransformer = environment.getActiveTransformer();
if (globalMixinTransformer instanceof IClassTransformer) {
if (globalMixinTransformer instanceof ITransformer) {
throw new MixinException("Terminating MixinTransformer instance " + this);
}
// I am a leaf on the wind
environment.setActiveTransformer(this);
TreeInfo.setLock(this.lock);
this.lock = this.service.getReEntranceLock();
this.extensions = new Extensions(this);
this.hotSwapper = this.initHotSwapper(environment);
@@ -430,7 +282,7 @@ public class MixinTransformer extends TreeTransformer {
for (String target : unhandled) {
try {
auditLogger.info("Force-loading class {}", target);
Class.forName(target, true, Launch.classLoader);
Class.forName(target, true, this.service.getClassLoader());
} catch (ClassNotFoundException ex) {
auditLogger.error("Could not force-load " + target, ex);
}
@@ -508,7 +360,7 @@ public class MixinTransformer extends TreeTransformer {
printer.add();
try {
Class<?> agent = Class.forName(MixinTransformer.METRONOME_AGENT_CLASS, false, Launch.class.getClassLoader());
Class<?> agent = Class.forName(MixinTransformer.METRONOME_AGENT_CLASS, false, this.service.getApplicationClassLoader());
Method mdGetTimes = agent.getDeclaredMethod("getTimes");
@SuppressWarnings("unchecked")
@@ -547,13 +399,30 @@ public class MixinTransformer extends TreeTransformer {
printer.print();
}
/* (non-Javadoc)
* @see net.minecraft.launchwrapper.IClassTransformer
* #transform(java.lang.String, java.lang.String, byte[])
* @see org.spongepowered.asm.service.ILegacyClassTransformer#getName()
*/
@Override
public synchronized byte[] transform(String name, String transformedName, byte[] basicClass) {
public String getName() {
return this.getClass().getName();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.ILegacyClassTransformer
* #isDelegationExcluded()
*/
@Override
public boolean isDelegationExcluded() {
return true;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.ILegacyClassTransformer#transform(
* java.lang.String, java.lang.String, byte[])
*/
@Override
public synchronized byte[] transformClassBytes(String name, String transformedName, byte[] basicClass) {
if (transformedName == null || this.errorState) {
return basicClass;
}
@@ -590,7 +459,7 @@ public class MixinTransformer extends TreeTransformer {
try {
if (this.postProcessor.canTransform(transformedName)) {
Section postTimer = this.profiler.begin("postprocessor");
byte[] bytes = this.postProcessor.transform(name, transformedName, basicClass);
byte[] bytes = this.postProcessor.transformClassBytes(name, transformedName, basicClass);
postTimer.end();
this.extensions.export(environment, transformedName, false, bytes);
return bytes;
@@ -917,7 +786,7 @@ public class MixinTransformer extends TreeTransformer {
for (String handlerClassName : Mixins.getErrorHandlerClasses()) {
try {
MixinTransformer.logger.info("Instancing error handler class {}", handlerClassName);
Class<?> handlerClass = Class.forName(handlerClassName, true, Launch.classLoader);
Class<?> handlerClass = Class.forName(handlerClassName, true, this.service.getClassLoader());
IMixinErrorHandler handler = (IMixinErrorHandler)handlerClass.newInstance();
if (handler != null) {
handlers.add(handler);
@@ -1,178 +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.io.IOException;
import java.io.InputStream;
import java.net.URLClassLoader;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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 org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
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
*/
abstract class TreeInfo {
private static final Logger logger = LogManager.getLogger("mixin");
/**
* Re-entrance lock
*/
private static ReEntranceState lock;
static void setLock(ReEntranceState lock) {
TreeInfo.lock = lock;
}
static ClassNode getClassNode(String className) throws ClassNotFoundException, IOException {
return TreeInfo.getClassNode(TreeInfo.loadClass(className, true), 0);
}
/**
* Gets an ASM Tree for the supplied class bytecode
*
* @param classBytes Class bytecode
* @param flags ClassReader flags
* @return ASM Tree view of the specified class
*/
static ClassNode getClassNode(byte[] classBytes, int flags) {
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(classBytes);
classReader.accept(classNode, flags);
return classNode;
}
/**
* Loads class bytecode from the classpath
*
* @param className Name of the class to load
* @param runTransformers True to run the loaded bytecode through the
* delegate transformer chain
* @return Transformed class bytecode for the specified class
* @throws ClassNotFoundException if the specified class could not be loaded
* @throws IOException if an error occurs whilst reading the specified class
*/
static byte[] loadClass(String className, boolean runTransformers) throws ClassNotFoundException, IOException {
String transformedName = className.replace('/', '.');
String name = MixinEnvironment.getCurrentEnvironment().unmap(transformedName);
Profiler profiler = MixinEnvironment.getProfiler();
Section loadTime = profiler.begin(Profiler.ROOT, "class.load");
byte[] classBytes = TreeInfo.getClassBytes(name, transformedName);
loadTime.end();
if (runTransformers) {
Section transformTime = profiler.begin(Profiler.ROOT, "class.transform");
classBytes = TreeInfo.applyTransformers(name, transformedName, classBytes, profiler);
transformTime.end();
}
if (classBytes == null) {
throw new ClassNotFoundException(String.format("The specified class '%s' was not found", transformedName));
}
return classBytes;
}
/**
* @param name Original class name
* @param transformedName Name of the class to load
* @return raw class bytecode
* @throws IOException if an error occurs reading the class bytes
*/
private static byte[] getClassBytes(String name, String transformedName) throws IOException {
byte[] classBytes = Launch.classLoader.getClassBytes(name);
if (classBytes != null) {
return classBytes;
}
URLClassLoader appClassLoader = (URLClassLoader)Launch.class.getClassLoader();
InputStream classStream = null;
try {
final String resourcePath = transformedName.replace('.', '/').concat(".class");
classStream = appClassLoader.getResourceAsStream(resourcePath);
return IOUtils.toByteArray(classStream);
} catch (Exception ex) {
return null;
} finally {
IOUtils.closeQuietly(classStream);
}
}
/**
* Since we obtain the class bytes with getClassBytes(), we need to apply
* the transformers ourself
*
* @param name class name
* @param transformedName transformed class name
* @param basicClass input class bytes
* @return class bytecode after processing by all registered transformers
* except the excluded transformers
*/
private static byte[] applyTransformers(String name, String transformedName, byte[] basicClass, Profiler profiler) {
if (LaunchClassLoaderUtil.forClassLoader(Launch.classLoader).isClassExcluded(name, transformedName)) {
return basicClass;
}
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
for (IClassTransformer transformer : environment.getTransformers()) {
if (TreeInfo.lock != null) {
// Clear the re-entrance semaphore
TreeInfo.lock.clear();
}
Class<? extends IClassTransformer> clazz = transformer.getClass();
Section transformTime = profiler.begin(Profiler.FINE, clazz.getSimpleName().toLowerCase());
transformTime.setInfo(clazz.getName());
basicClass = transformer.transform(name, transformedName, basicClass);
transformTime.end();
if (TreeInfo.lock != null && TreeInfo.lock.isSet()) {
// Also add it to the exclusion list so we can exclude it if the environment triggers a rebuild
environment.addTransformerExclusion(clazz.getName());
TreeInfo.lock.clear();
TreeInfo.logger.info("A re-entrant transformer '{}' was detected and will no longer process meta class data",
clazz.getName());
}
}
return basicClass;
}
}
@@ -0,0 +1,63 @@
/*
* 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.service;
/**
* Adapter interface for legacy class transformers. Legacy class transformers
* operate on raw byte arrays.
*/
public interface ILegacyClassTransformer extends ITransformer {
/**
* Get the identifier for this transformer, usually the class name but for
* wrapped transformers this is the class name of the wrapped transformer
*
* @return transformer's identifying name
*/
public abstract String getName();
/**
* Get whether this transformer is excluded from delegation. Some
* transformers (such as the mixin transformer itself) should not be
* included in the delegation list because they are re-entrant or do not
* need to run on incoming bytecode.
*
* @return true if this transformer should be <em>excluded</em> from the
* transformer delegation list
*/
public abstract boolean isDelegationExcluded();
/**
* Transform a class in byte array form.
*
* @param name Class original name
* @param transformedName Class name after being processed by the class name
* transformer
* @param basicClass class byte array
* @return transformed bytes
*/
public abstract byte[] transformClassBytes(String name, String transformedName, byte[] basicClass);
}
@@ -0,0 +1,226 @@
/*
* 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.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.util.ReEntranceLock;
/**
* Mixin Service interface. Mixin services connect the mixin subsytem to the
* underlying environment. It is something of a god interface at present because
* it contains all of the current functionality accessors for calling into
* launchwrapper. In the future once support for modlauncher is added, it is
* anticipated that the interface can be split down into sub-services which
* handle different aspects of interacting with the environment.
*/
public interface IMixinService {
/**
* Get the friendly name for this service
*/
public abstract String getName();
/**
* True if this service type is valid in the current environment
*/
public abstract boolean isValid();
/**
* Called at subsystem boot
*/
public abstract void prepare();
/**
* Called at the end of subsystem boot
*/
public abstract void init();
/**
* Called whenever a new phase is started
*/
public abstract void beginPhase();
/**
* Get the transformer re-entrance lock for this service, the transformer
* uses this lock to track transformer re-entrance when co-operative load
* and transform is performed by the service.
*/
public abstract ReEntranceLock getReEntranceLock();
/**
* Get additional platform agents for this service
*/
public abstract Collection<String> getPlatformAgents();
/**
* Get the main classloader for this service
*/
public abstract ClassLoader getClassLoader();
/**
* Get the application classloader for this service (usually the system
* classloader)
*/
public abstract ClassLoader getApplicationClassLoader();
/**
* Get a resource as a stream from the appropriate classloader, this is
* delegated via the service so that the service can choose the correct
* classloader from which to obtain the resource.
*
* @param name resource path
* @return input stream or null if resource not found
*/
public abstract InputStream getResourceAsStream(String name);
/**
* Find a class in the service classloader
*
* @param name class name
* @return resultant class
* @throws ClassNotFoundException if the class was not found
*/
public abstract Class<?> findClass(final String name) throws ClassNotFoundException;
/**
* Register an invalid class with the service classloader
*
* @param className invalid class name
*/
public abstract void registerInvalidClass(String className);
/**
* Check whether the specified class was already loaded by the service
* classloader
*
* @param className class name to check
* @return true if the class was already loaded
*/
public abstract boolean isClassLoaded(String className);
/**
* Check whether the specified class is excluded in the service classloader
*
* @param name class name to check
* @param transformedName transformed name to check
* @return true if the class is excluded in the service classloader
*/
public abstract boolean isClassExcluded(String name, String transformedName);
/**
* Get the current classpath from the service classloader
*/
public abstract URL[] getClassPath();
/**
* Get currently available transformers in the environment
*/
public abstract Collection<ITransformer> getTransformers();
/**
* Retrieve class bytes using available classloaders, does not transform the
* class
*
* @param name class name
* @param transformedName transformed class name
* @return class bytes or null if not found
* @throws IOException propagated
*/
public abstract byte[] getClassBytes(String name, String transformedName) throws IOException;
/**
* Retrieve transformed class bytes by using available classloaders and
* running transformer delegation chain on the result if the runTransformers
* option is enabled
*
* @param name full class name
* @param runTransformers true to run transformers on the loaded bytecode
* @return transformed bytes
* @throws ClassNotFoundException if class not found
* @throws IOException propagated
*/
public abstract byte[] getClassBytes(String name, boolean runTransformers) throws ClassNotFoundException, IOException;
/**
* Retrieve transformed class as an ASM tree
*
* @param name full class name
* @return tree
* @throws ClassNotFoundException if class not found
* @throws IOException propagated
*/
public abstract ClassNode getClassNode(String name) throws ClassNotFoundException, IOException;
/**
* Get the detected side name for this environment
*/
public abstract String getSideName();
/**
* Get a value from the global property store (blackboard) and duck-type it
* to the specified type
*
* @param key blackboard key
* @param <T> duck type
* @return value
*/
public abstract <T> T getGlobalProperty(String key);
/**
* Set the specified value in the global property store (blackboard)
*
* @param key blackboard key
* @param value new value
*/
public abstract void setGlobalProperty(String key, Object value);
/**
* Get the value from the global property store (blackboard) but return
* <tt>defaultValue</tt> if the specified key is not set.
*
* @param key blackboard key
* @param defaultValue value to return if the key is not set or is null
* @param <T> duck type
* @return value from blackboard or default value
*/
public abstract <T> T getGlobalProperty(String key, T defaultValue);
/**
* Get a string from the global property store (blackboard), returns default
* value if not set or null.
*
* @param key blackboard key
* @param defaultValue default value to return if the specified key is not
* set or is null
* @return value from blackboard or default
*/
public abstract String getGlobalPropertyString(String key, String defaultValue);
}
@@ -0,0 +1,32 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.service;
/**
* Base interface for transformer types
*/
public interface ITransformer {
}
@@ -0,0 +1,115 @@
/*
* 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.service;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
/**
* Provides access to the service layer which connects the mixin transformer to
* a particular host environment. Host environments are implemented as services
* implementing {@link IMixinService} in order to decouple them from mixin's
* core. This allows us to support LegacyLauncher
*/
public final class MixinService {
/**
* Singleton
*/
private static MixinService instance;
/**
* Service loader
*/
private ServiceLoader<IMixinService> serviceLoader;
/**
* Service
*/
private IMixinService service = null;
/**
* Singleton pattern
*/
private MixinService() {
}
/**
* Singleton pattern, get or create the instance
*/
private static MixinService getCanonicalInstance() {
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
if (MixinService.class.getClassLoader() != systemClassLoader) {
try {
Class<?> contextServiceClass = Class.forName(MixinService.class.getName(), true, systemClassLoader);
Method mdGetInstance = contextServiceClass.getMethod("getInstance");
MixinService.instance = (MixinService)mdGetInstance.invoke(null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (MixinService.instance == null) {
MixinService.instance = new MixinService();
}
return MixinService.instance;
}
public static IMixinService getService() {
return MixinService.getCanonicalInstance().getServiceInstance();
}
private synchronized IMixinService getServiceInstance() {
if (this.service == null) {
this.service = this.initService();
if (this.service == null) {
throw new ServiceNotAvailableError("No mixin host service is available");
}
}
return this.service;
}
private IMixinService initService() {
this.serviceLoader = ServiceLoader.<IMixinService>load(IMixinService.class, this.getClass().getClassLoader());
Iterator<IMixinService> iter = this.serviceLoader.iterator();
while (iter.hasNext()) {
try {
IMixinService service = iter.next();
if (service.isValid()) {
return service;
}
} catch (ServiceConfigurationError serviceError) {
serviceError.printStackTrace();
} catch (Throwable th) {
th.printStackTrace();
}
}
return null;
}
}
@@ -0,0 +1,38 @@
/*
* 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.service;
/**
* Error to throw when no service is available in the current environment
*/
public class ServiceNotAvailableError extends Error {
private static final long serialVersionUID = 1L;
public ServiceNotAvailableError(String message) {
super(message);
}
}
@@ -27,13 +27,12 @@ package org.spongepowered.asm.transformers;
import org.spongepowered.asm.lib.ClassReader;
import org.spongepowered.asm.lib.ClassWriter;
import org.spongepowered.asm.lib.tree.ClassNode;
import net.minecraft.launchwrapper.IClassTransformer;
import org.spongepowered.asm.service.ILegacyClassTransformer;
/**
* Base class for transformers which work with ASM tree model
*/
public abstract class TreeTransformer implements IClassTransformer {
public abstract class TreeTransformer implements ILegacyClassTransformer {
private ClassReader classReader;
private ClassNode classNode;
@@ -0,0 +1,136 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.util;
/**
* Re-entrance semaphore used to share re-entrance data with the TreeInfo
*/
public class ReEntranceLock {
/**
* Max valid depth
*/
private final int maxDepth;
/**
* Re-entrance depth
*/
private int depth = 0;
/**
* Semaphore set when check exceeds a depth of 1
*/
private boolean semaphore = false;
public ReEntranceLock(int maxDepth) {
this.maxDepth = maxDepth;
}
/**
* Get max depth
*/
public int getMaxDepth() {
return this.maxDepth;
}
/**
* Get current depth
*/
public int getDepth() {
return this.depth;
}
/**
* Increase the re-entrance depth counter and set the semaphore if depth
* exceeds max depth
*
* @return fluent interface
*/
public ReEntranceLock push() {
this.depth++;
this.checkAndSet();
return this;
}
/**
* Decrease the re-entrance depth
*
* @return fluent interface
*/
public ReEntranceLock pop() {
if (this.depth == 0) {
throw new IllegalStateException("ReEntranceLock pop() with zero depth");
}
this.depth--;
return this;
}
/**
* Run the depth check but do not set the semaphore
*
* @return true if depth has exceeded max
*/
public boolean check() {
return this.depth > this.maxDepth;
}
/**
* Run the depth check and set the semaphore if depth is exceeded
*
* @return true if semaphore is set
*/
public boolean checkAndSet() {
return this.semaphore |= this.check();
}
/**
* Set the semaphore
*
* @return fluent interface
*/
public ReEntranceLock set() {
this.semaphore = true;
return this;
}
/**
* Get whether the semaphore is set
*/
public boolean isSet() {
return this.semaphore;
}
/**
* Clear the semaphore
*
* @return fluent interface
*/
public ReEntranceLock clear() {
this.semaphore = false;
return this;
}
}
@@ -1,208 +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.util.launchwrapper;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
* Utility class for reflecting into {@link LaunchClassLoader}. We <b>do not
* write</b> anything of the classloader fields, but we need to be able to read
* them to perform some validation tasks, and insert entries for mixin "classes"
* into the invalid classes set.
*/
public final class LaunchClassLoaderUtil {
private static final String CACHED_CLASSES_FIELD = "cachedClasses";
private static final String INVALID_CLASSES_FIELD = "invalidClasses";
private static final String CLASS_LOADER_EXCEPTIONS_FIELD = "classLoaderExceptions";
private static final String TRANSFORMER_EXCEPTIONS_FIELD = "transformerExceptions";
/**
* ClassLoader -> util mapping
*/
private static final Map<LaunchClassLoader, LaunchClassLoaderUtil> utils = new HashMap<LaunchClassLoader, LaunchClassLoaderUtil>();
/**
* ClassLoader for this util
*/
private final LaunchClassLoader classLoader;
// Reflected fields
private Map<String, Class<?>> cachedClasses;
private final Set<String> invalidClasses;
private final Set<String> classLoaderExceptions;
private final Set<String> transformerExceptions;
/**
* Singleton, use factory to get an instance
*
* @param classLoader class loader
*/
private LaunchClassLoaderUtil(LaunchClassLoader classLoader) {
this.classLoader = classLoader;
this.cachedClasses = LaunchClassLoaderUtil.<Map<String, Class<?>>>getField(classLoader, LaunchClassLoaderUtil.CACHED_CLASSES_FIELD);
this.invalidClasses = LaunchClassLoaderUtil.<Set<String>>getField(classLoader, LaunchClassLoaderUtil.INVALID_CLASSES_FIELD);
this.classLoaderExceptions = LaunchClassLoaderUtil.<Set<String>>getField(classLoader, LaunchClassLoaderUtil.CLASS_LOADER_EXCEPTIONS_FIELD);
this.transformerExceptions = LaunchClassLoaderUtil.<Set<String>>getField(classLoader, LaunchClassLoaderUtil.TRANSFORMER_EXCEPTIONS_FIELD);
}
/**
* Get the classloader
*/
public LaunchClassLoader getClassLoader() {
return this.classLoader;
}
/**
* Get all loaded class names from the cache
*/
public Set<String> getLoadedClasses() {
return this.getLoadedClasses(null);
}
/**
* Get the names of loaded classes from the cache, filter using the supplied
* filter string
*
* @param filter filter string or null
* @return set of class names
*/
public Set<String> getLoadedClasses(String filter) {
Set<String> loadedClasses = new HashSet<String>();
for (String className : this.cachedClasses.keySet()) {
if (filter == null || className.startsWith(filter)) {
loadedClasses.add(className);
}
}
return loadedClasses;
}
/**
* Get whether a class name exists in the cache (indicating it was loaded
* via the inner loader
*
* @param name class name
* @return true if the class name exists in the cache
*/
public boolean isClassLoaded(String name) {
if (this.cachedClasses != null && this.cachedClasses.containsKey(name)) {
return true;
}
return false;
}
/**
* Get whether the specified name or transformedName exist in either of the
* exclusion lists
*
* @param name class name
* @param transformedName transformed class name
* @return true if either exclusion list contains either of the names
*/
public boolean isClassExcluded(String name, String transformedName) {
for (final String exception : this.getClassLoaderExceptions()) {
if (transformedName.startsWith(exception) || name.startsWith(exception)) {
return true;
}
}
for (final String exception : this.getTransformerExceptions()) {
if (transformedName.startsWith(exception) || name.startsWith(exception)) {
return true;
}
}
return false;
}
/**
* Stuff a class name directly into the invalidClasses set, this prevents
* the loader from classloading the named class. This is used by the mixin
* processor to prevent classloading of mixin classes
*
* @param name class name
*/
public void registerInvalidClass(String name) {
if (this.invalidClasses != null) {
this.invalidClasses.add(name);
}
}
/**
* Get the classloader exclusions from the target classloader
*/
public Set<String> getClassLoaderExceptions() {
if (this.classLoaderExceptions != null) {
return this.classLoaderExceptions;
}
return Collections.<String>emptySet();
}
/**
* Get the transformer exclusions from the target classloader
*/
public Set<String> getTransformerExceptions() {
if (this.transformerExceptions != null) {
return this.transformerExceptions;
}
return Collections.<String>emptySet();
}
@SuppressWarnings("unchecked")
private static <T> T getField(LaunchClassLoader classLoader, String fieldName) {
try {
Field field = LaunchClassLoader.class.getDeclaredField(fieldName);
field.setAccessible(true);
return (T)field.get(classLoader);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Get the utility class for the supplied classloader
*
* @param classLoader classLoader to fetch utility wrapper for
* @return utility wrapper
*/
public static LaunchClassLoaderUtil forClassLoader(LaunchClassLoader classLoader) {
LaunchClassLoaderUtil util = LaunchClassLoaderUtil.utils.get(classLoader);
if (util == null) {
util = new LaunchClassLoaderUtil(classLoader);
LaunchClassLoaderUtil.utils.put(classLoader, util);
}
return util;
}
}