diff --git a/build.gradle b/build.gradle index 1f3c81f9..9bccad2d 100644 --- a/build.gradle +++ b/build.gradle @@ -91,6 +91,9 @@ sourceSets { compileClasspath += main.output compileClasspath += ap.output } + launchwrapper { + compileClasspath += main.output + } } // Dependencies for renamed ASM @@ -98,7 +101,6 @@ dependencies { asm 'org.ow2.asm:asm-debug-all:5.2' asm 'org.ow2.asm:asm-debug-all:5.2:sources' jarjar 'com.googlecode.jarjar:jarjar:1.1' - compile 'com.googlecode.jarjar:jarjar:1.1' } // Task to read ASM library and rename packages @@ -147,44 +149,52 @@ eclipseClasspath.dependsOn(renamedASM) // Project dependencies dependencies { - compile 'com.google.guava:guava:17.0' - compile 'com.google.code.gson:gson:2.2.4' - compile 'commons-io:commons-io:2.4' - apCompile 'com.google.guava:guava:17.0' - testCompile 'junit:junit:4.11' - testCompile 'org.hamcrest:hamcrest-library:1.3' - testCompile 'org.mockito:mockito-core:1.9.0' + def guava = 'com.google.guava:guava:17.0' + def log4j2 = 'org.apache.logging.log4j:log4j-core:2.0-beta9' - // example - exampleCompile 'com.google.code.gson:gson:2.2.4' - exampleCompile 'com.google.guava:guava:17.0' - exampleCompile 'org.apache.logging.log4j:log4j-core:2.0-beta9' + compile guava + compile log4j2 + compile 'commons-io:commons-io:2.4' + compile 'com.google.code.gson:gson:2.2.4' + compile files(tasks.renamedASM.outputs.files[0]) // Establish implicit dependency on remapped ASM - // maven + // Tests +// testCompile 'junit:junit:4.11' +// testCompile 'org.hamcrest:hamcrest-library:1.3' +// testCompile 'org.mockito:mockito-core:1.9.0' + + // Annotation Processor + apCompile guava + + // AP extension example + exampleCompile configurations.compile + + // Maven FTP deployerJars 'org.apache.maven.wagon:wagon-ftp:2.7' - // Establish implicit dependency on remapped ASM - compile files(tasks.renamedASM.outputs.files[0]) - - // fernflower bridge - fernflowerCompile 'commons-io:commons-io:2.4' - fernflowerCompile 'org.apache.logging.log4j:log4j-core:2.0-beta9' - fernflowerCompile 'com.google.guava:guava:17.0' + // Fernflower decompiler + fernflowerCompile configurations.compile fernflowerCompile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' - compile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' - compile('net.minecraft:launchwrapper:1.11') { - exclude module: 'lwjgl' - } - agentCompile('net.minecraft:launchwrapper:1.11') { + // LegacyLauncher service + launchwrapperCompile configurations.compile + launchwrapperCompile('net.minecraft:launchwrapper:1.11') { exclude module: 'lwjgl' } + // agent + agentCompile configurations.compile + // asm bridge + bridgeCompile log4j2 bridgeCompile 'org.ow2.asm:asm-commons:5.0.3' - bridgeCompile 'org.apache.logging.log4j:log4j-core:2.0-beta9' } +eclipse.classpath.plusConfigurations += [ + configurations.fernflowerCompile, + configurations.launchwrapperCompile +] + // Filter, process, and include resources processResources { // Include in final JAR @@ -246,6 +256,9 @@ jar { // Bridge from sourceSets.bridge.output + // Launchwrapper + from sourceSets.launchwrapper.output + // Renamed ASM from zipTree(tasks.renamedASM.outputs.files[0]).matching { include 'org/spongepowered/asm/lib/*' diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 5798ba54..f20ebc7f 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -37,8 +37,8 @@ import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.transformer.MixinTransformer; import org.spongepowered.asm.mixin.transformer.ext.IHotSwap; import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; - -import net.minecraft.launchwrapper.Launch; +import org.spongepowered.asm.service.IMixinService; +import org.spongepowered.asm.service.MixinService; /** * An agent that re-transforms a mixin's target classes if the mixin has been @@ -71,7 +71,7 @@ public class MixinAgent implements IHotSwap { try { MixinAgent.logger.info("Redefining class " + className); - return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); + return MixinAgent.this.classTransformer.transformClassBytes(null, className, classfileBuffer); } catch (Throwable th) { MixinAgent.logger.error("Error while re-transforming class " + className, th); return MixinAgent.ERROR_BYTECODE; @@ -99,17 +99,19 @@ public class MixinAgent implements IHotSwap { * failed */ private boolean reApplyMixins(List targets) { + IMixinService service = MixinService.getService(); + for (String target : targets) { String targetName = target.replace('/', '.'); MixinAgent.logger.debug("Re-transforming target class {}", target); try { - Class targetClass = Launch.classLoader.findClass(targetName); + Class targetClass = service.findClass(targetName); byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName); if (targetBytecode == null) { MixinAgent.logger.error("Target class {} bytecode is not registered", targetName); return false; } - targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode); + targetBytecode = MixinAgent.this.classTransformer.transformClassBytes(null, targetName, targetBytecode); MixinAgent.instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode)); } catch (Throwable th) { MixinAgent.logger.error("Error while re-transforming target class " + target, th); diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java b/src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java similarity index 97% rename from src/main/java/org/spongepowered/asm/launch/MixinTweaker.java rename to src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java index d87904db..9de14aeb 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java @@ -59,7 +59,7 @@ public class MixinTweaker implements ITweaker { */ @Override public final void injectIntoClassLoader(LaunchClassLoader classLoader) { - MixinBootstrap.injectIntoClassLoader(classLoader); + MixinBootstrap.inject(); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java similarity index 98% rename from src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java rename to src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java index b20b8bd8..a53aa594 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java @@ -298,14 +298,13 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { } /* (non-Javadoc) - * @see org.spongepowered.asm.launch.IMixinPlatformAgent - * #injectIntoClassLoader(net.minecraft.launchwrapper.LaunchClassLoader) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformAgent#inject() */ @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) { + public void inject() { 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); + this.coreModWrapper.injectIntoClassLoader(Launch.classLoader); } } diff --git a/src/launchwrapper/java/org/spongepowered/asm/mixin/EnvironmentStateTweaker.java b/src/launchwrapper/java/org/spongepowered/asm/mixin/EnvironmentStateTweaker.java new file mode 100644 index 00000000..8a65cee7 --- /dev/null +++ b/src/launchwrapper/java/org/spongepowered/asm/mixin/EnvironmentStateTweaker.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin; + +import java.io.File; +import java.util.List; + +import org.spongepowered.asm.launch.MixinBootstrap; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; + +import net.minecraft.launchwrapper.ITweaker; +import net.minecraft.launchwrapper.LaunchClassLoader; + +/** + * Tweaker used to notify the environment when we transition from preinit to + * default + */ +public class EnvironmentStateTweaker implements ITweaker { + + @Override + public void acceptOptions(List args, File gameDir, File assetsDir, String profile) { + } + + @Override + public void injectIntoClassLoader(LaunchClassLoader classLoader) { + MixinBootstrap.getPlatform().inject(); + } + + @Override + public String getLaunchTarget() { + return ""; + } + + @Override + public String[] getLaunchArguments() { + MixinEnvironment.gotoPhase(Phase.DEFAULT); + return new String[0]; + } + +} diff --git a/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java b/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java new file mode 100644 index 00000000..64590d30 --- /dev/null +++ b/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java @@ -0,0 +1,77 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.LogManager; + +import net.minecraft.launchwrapper.IClassTransformer; + +/** + * 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 final class Proxy implements IClassTransformer { + + /** + * All existing proxies + */ + private static List proxies = new ArrayList(); + + /** + * 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.transformClassBytes(name, transformedName, basicClass); + } + + return basicClass; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/launchwrapper/LaunchClassLoaderUtil.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java similarity index 99% rename from src/main/java/org/spongepowered/asm/util/launchwrapper/LaunchClassLoaderUtil.java rename to src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java index 1d764b6f..29fb183a 100644 --- a/src/main/java/org/spongepowered/asm/util/launchwrapper/LaunchClassLoaderUtil.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java @@ -22,7 +22,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package org.spongepowered.asm.util.launchwrapper; +package org.spongepowered.asm.service.mojang; import java.lang.reflect.Field; import java.util.Collections; diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LegacyTransformerHandle.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LegacyTransformerHandle.java new file mode 100644 index 00000000..9f926003 --- /dev/null +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LegacyTransformerHandle.java @@ -0,0 +1,74 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.mojang; + +import javax.annotation.Resource; + +import org.spongepowered.asm.service.ILegacyClassTransformer; + +import net.minecraft.launchwrapper.IClassTransformer; + +/** + * A handle for a legacy {@link IClassTransformer} for processing as a legacy + * transformer + */ +public class LegacyTransformerHandle implements ILegacyClassTransformer { + + /** + * Wrapped transformer + */ + private final IClassTransformer transformer; + + public LegacyTransformerHandle(IClassTransformer transformer) { + this.transformer = transformer; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.ILegacyClassTransformer#getName() + */ + @Override + public String getName() { + return this.transformer.getClass().getName(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.ILegacyClassTransformer + * #isDelegationExcluded() + */ + @Override + public boolean isDelegationExcluded() { + return this.transformer.getClass().getAnnotation(Resource.class) != null; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.ILegacyClassTransformer + * #transformClassBytes(java.lang.String, java.lang.String, byte[]) + */ + @Override + public byte[] transformClassBytes(String name, String transformedName, byte[] basicClass) { + return this.transformer.transform(name, transformedName, basicClass); + } + +} diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java new file mode 100644 index 00000000..fbe48358 --- /dev/null +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java @@ -0,0 +1,473 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.mojang; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.Blackboard; +import org.spongepowered.asm.lib.ClassReader; +import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.service.ILegacyClassTransformer; +import org.spongepowered.asm.service.IMixinService; +import org.spongepowered.asm.service.ITransformer; +import org.spongepowered.asm.util.ReEntranceLock; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; + +import com.google.common.collect.ImmutableList; + +import net.minecraft.launchwrapper.IClassNameTransformer; +import net.minecraft.launchwrapper.IClassTransformer; +import net.minecraft.launchwrapper.ITweaker; +import net.minecraft.launchwrapper.Launch; + +/** + * Mixin service for launchwrapper + */ +public class MixinServiceLaunchWrapper implements IMixinService { + + // 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 STATE_TWEAKER = MixinServiceLaunchWrapper.MIXIN_PACKAGE + "EnvironmentStateTweaker"; + private static final String TRANSFORMER_PROXY_CLASS = MixinServiceLaunchWrapper.MIXIN_PACKAGE + "transformer.Proxy"; + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + private final LaunchClassLoaderUtil classLoaderUtil = LaunchClassLoaderUtil.forClassLoader(Launch.classLoader); + + private final ReEntranceLock lock = new ReEntranceLock(1); + + /** + * Class name transformer (if present) + */ + private IClassNameTransformer nameTransformer; + + @Override + public String getName() { + return "LaunchWrapper"; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#isValid() + */ + @Override + public boolean isValid() { + try { + // Detect launchwrapper + Launch.classLoader.hashCode(); + } catch (Throwable ex) { + return false; + } + return true; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#prepare() + */ + @Override + public void prepare() { + // The important ones + Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapper.ASM_PACKAGE); + Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapper.MIXIN_PACKAGE); + Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapper.MIXIN_UTIL_PACKAGE); + + // Only needed in dev, in production this would be handled by the tweaker + Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapper.LAUNCH_PACKAGE); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#init() + */ + @Override + public void init() { + List tweakClasses = Blackboard.>get(Blackboard.Keys.TWEAKCLASSES); + if (tweakClasses != null) { + tweakClasses.add(MixinServiceLaunchWrapper.STATE_TWEAKER); + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getReEntranceLock() + */ + @Override + public ReEntranceLock getReEntranceLock() { + return this.lock; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getPlatformAgents() + */ + @Override + public Collection getPlatformAgents() { + return ImmutableList.of( + "org.spongepowered.asm.launch.platform.MixinPlatformAgentFML" + ); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassLoader() + */ + @Override + public ClassLoader getClassLoader() { + return Launch.classLoader; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService + * #getApplicationClassLoader() + */ + @Override + public ClassLoader getApplicationClassLoader() { + return Launch.class.getClassLoader(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#beginPhase() + */ + @Override + public void beginPhase() { + Launch.classLoader.registerTransformer(MixinServiceLaunchWrapper.TRANSFORMER_PROXY_CLASS); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getResourceAsStream( + * java.lang.String) + */ + @Override + public InputStream getResourceAsStream(String name) { + return Launch.classLoader.getResourceAsStream(name); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#findClass( + * java.lang.String) + */ + @Override + public Class findClass(String name) throws ClassNotFoundException { + return Launch.classLoader.findClass(name); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#registerInvalidClass( + * java.lang.String) + */ + @Override + public void registerInvalidClass(String className) { + this.classLoaderUtil.registerInvalidClass(className); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#isClassLoaded( + * java.lang.String) + */ + @Override + public boolean isClassLoaded(String className) { + return this.classLoaderUtil.isClassLoaded(className); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#isClassExcluded( + * java.lang.String, java.lang.String) + */ + @Override + public boolean isClassExcluded(String name, String transformedName) { + return this.classLoaderUtil.isClassExcluded(name, transformedName); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassPath() + */ + @Override + public URL[] getClassPath() { + return Launch.classLoader.getSources().toArray(new URL[0]); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getTransformers() + */ + @Override + public Collection getTransformers() { + List transformers = Launch.classLoader.getTransformers(); + List wrapped = new ArrayList(transformers.size()); + for (IClassTransformer transformer : transformers) { + wrapped.add(new LegacyTransformerHandle(transformer)); + + if (transformer instanceof IClassNameTransformer) { + MixinServiceLaunchWrapper.logger.debug("Found name transformer: {}", transformer.getClass().getName()); + this.nameTransformer = (IClassNameTransformer) transformer; + } + + } + return wrapped; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassBytes( + * java.lang.String, java.lang.String) + */ + @Override + public 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); + } + } + + /** + * 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 + */ + @Override + public byte[] getClassBytes(String className, boolean runTransformers) throws ClassNotFoundException, IOException { + String transformedName = className.replace('/', '.'); + String name = this.unmapClassName(transformedName); + + Profiler profiler = MixinEnvironment.getProfiler(); + Section loadTime = profiler.begin(Profiler.ROOT, "class.load"); + byte[] classBytes = this.getClassBytes(name, transformedName); + loadTime.end(); + + if (runTransformers) { + Section transformTime = profiler.begin(Profiler.ROOT, "class.transform"); + classBytes = this.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; + } + + /** + * 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 byte[] applyTransformers(String name, String transformedName, byte[] basicClass, Profiler profiler) { + if (this.isClassExcluded(name, transformedName)) { + return basicClass; + } + + MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); + + for (ILegacyClassTransformer transformer : environment.getTransformers()) { + if (this.lock != null) { + // Clear the re-entrance semaphore + this.lock.clear(); + } + + int pos = transformer.getName().lastIndexOf('.'); + String simpleName = transformer.getName().substring(pos + 1); + Section transformTime = profiler.begin(Profiler.FINE, simpleName.toLowerCase()); + transformTime.setInfo(transformer.getName()); + basicClass = transformer.transformClassBytes(name, transformedName, basicClass); + transformTime.end(); + + if (this.lock != null && this.lock.isSet()) { + // Also add it to the exclusion list so we can exclude it if the environment triggers a rebuild + environment.addTransformerExclusion(transformer.getName()); + + this.lock.clear(); + MixinServiceLaunchWrapper.logger.info("A re-entrant transformer '{}' was detected and will no longer process meta class data", + transformer.getName()); + } + } + + return basicClass; + } + + private String unmapClassName(String className) { + if (this.nameTransformer != null) { + return this.nameTransformer.unmapClassName(className); + } + + return className; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassNode( + * java.lang.String) + */ + @Override + public ClassNode getClassNode(String className) throws ClassNotFoundException, IOException { + return this.getClassNode(this.getClassBytes(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 + */ + private ClassNode getClassNode(byte[] classBytes, int flags) { + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(classBytes); + classReader.accept(classNode, flags); + return classNode; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getSideName() + */ + @Override + public 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 : this.>getGlobalProperty(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; + } + } + + /** + * Get a value from the blackboard and duck-type it to the specified type + * + * @param key blackboard key + * @return value + * @param duck type + */ + @Override + @SuppressWarnings("unchecked") + public final T getGlobalProperty(String key) { + return (T)Launch.blackboard.get(key); + } + + /** + * Put the specified value onto the blackboard + * + * @param key blackboard key + * @param value new value + */ + @Override + public final void setGlobalProperty(String key, Object value) { + Launch.blackboard.put(key, value); + } + + /** + * Get the value from the blackboard but return defaultValue 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 + * @return value from blackboard or default value + * @param duck type + */ + @Override + @SuppressWarnings("unchecked") + public final T getGlobalProperty(String key, T defaultValue) { + Object value = Launch.blackboard.get(key); + return value != null ? (T)value : defaultValue; + } + + /** + * Get a string from the 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 + */ + @Override + public final String getGlobalPropertyString(String key, String defaultValue) { + Object value = Launch.blackboard.get(key); + return value != null ? value.toString() : defaultValue; + } + +} diff --git a/src/launchwrapper/resources/META-INF/services/org.spongepowered.asm.service.IMixinService b/src/launchwrapper/resources/META-INF/services/org.spongepowered.asm.service.IMixinService new file mode 100644 index 00000000..808bf7d3 --- /dev/null +++ b/src/launchwrapper/resources/META-INF/services/org.spongepowered.asm.service.IMixinService @@ -0,0 +1 @@ +org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper \ No newline at end of file diff --git a/src/main/java/org/spongepowered/asm/launch/Blackboard.java b/src/main/java/org/spongepowered/asm/launch/Blackboard.java index fd5278ac..eb3860c7 100644 --- a/src/main/java/org/spongepowered/asm/launch/Blackboard.java +++ b/src/main/java/org/spongepowered/asm/launch/Blackboard.java @@ -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 duck type + * @return value */ - @SuppressWarnings("unchecked") public static T get(String key) { - return (T)Launch.blackboard.get(key); + return Blackboard.getService().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 duck type + * @return value from blackboard or default value */ - @SuppressWarnings("unchecked") public static 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); } } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index d91c77ca..6b14d263 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -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 MixinService.getService().beginPhase() 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 tweakClasses = Blackboard.>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() { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java index 221f18e6..c57062a7 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java @@ -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 injectIntoClassLoader in the parent tweaker but - * only called on the primary tweak container. This is useful if the - * agent needs to perform some environment-specific setup just once. + * Called from inject in the parent tweaker but only called on + * the primary tweak container. This is useful if the agent needs to + * perform some environment-specific setup just once. */ public abstract void initPrimaryContainer(); /** - * Called from injectIntoClassLoader in the parent tweaker - * - * @param classLoader classLoader to inject into + * Called from inject 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 diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index 9d7c9a79..0a4a5131 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -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 ITweaker::getLaunchTarget, queries all agents and * returns first valid launch target. Returns null if no agents have launch * target. * diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java index 1f7ac52a..e48d3659 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java @@ -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 * MixinConfigs and MixinTokenProviders. @@ -72,7 +70,7 @@ public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract { } @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) { + public void inject() { } @Override diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java index c9aaec4c..133428cd 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java @@ -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); } diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 2582e3eb..2ca0b23c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -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.>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 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 transformers; - - /** - * Class name transformer (if present) - */ - private IClassNameTransformer nameTransformer; + private List 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 mixinConfigs = Blackboard.>get(this.configsKey); if (mixinConfigs == null) { mixinConfigs = new ArrayList(); - 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 providerClass = - (Class)Class.forName(providerName, true, Launch.classLoader); + (Class)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 getTransformers() { + public List getTransformers() { if (this.transformers == null) { this.buildTransformerDelegationList(); } - return Collections.unmodifiableList(this.transformers); + return Collections.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(); - for (IClassTransformer transformer : Launch.classLoader.getTransformers()) { - String transformerName = transformer.getClass().getName(); + this.transformers = new ArrayList(); + 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) { diff --git a/src/main/java/org/spongepowered/asm/mixin/Mixins.java b/src/main/java/org/spongepowered/asm/mixin/Mixins.java index 52e03082..fa805a5b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Mixins.java +++ b/src/main/java/org/spongepowered/asm/mixin/Mixins.java @@ -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 mixinConfigs = Blackboard.>get(Mixins.CONFIGS_KEY); if (mixinConfigs == null) { mixinConfigs = new LinkedHashSet(); - Launch.blackboard.put(Mixins.CONFIGS_KEY, mixinConfigs); + MixinService.getService().setGlobalProperty(Mixins.CONFIGS_KEY, mixinConfigs); } return mixinConfigs; } diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java index 8fe8bded..3139edd2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java @@ -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); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java index 38f94207..91131184 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -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); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java index 616e35d5..34b0dc4d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java @@ -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); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java index 8bcd7c7f..a9eb1731 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -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 diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index c7438313..0bd01359 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -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, IMixinConfig { // * Phase selector // */ // private transient List selectors; + + private transient IMixinService service; /** * Parent environment @@ -319,7 +321,8 @@ final class MixinConfig implements Comparable, 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, 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)injectionPointClass); } else { @@ -435,7 +438,7 @@ final class MixinConfig implements Comparable, 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, 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, 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; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index cb587374..f6287efb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -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, IMixinInfo { +class MixinInfo implements Comparable, IMixinInfo { /** * A MethodNode in a mixin @@ -664,9 +663,9 @@ class MixinInfo extends TreeInfo implements Comparable, 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, 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, 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, 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) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java index 72f26bac..30df42fc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java @@ -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); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index 86a2dea2..c57935b6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -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 proxies = new ArrayList(); - - /** - * 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); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java deleted file mode 100644 index d9af1bbe..00000000 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/TreeInfo.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * This file is part of Mixin, licensed under the MIT License (MIT). - * - * Copyright (c) SpongePowered - * 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 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; - } -} diff --git a/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java b/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java new file mode 100644 index 00000000..d2816c34 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java @@ -0,0 +1,63 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 excluded 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); + +} diff --git a/src/main/java/org/spongepowered/asm/service/IMixinService.java b/src/main/java/org/spongepowered/asm/service/IMixinService.java new file mode 100644 index 00000000..8ae7cf59 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/IMixinService.java @@ -0,0 +1,226 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 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 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 duck type + * @return value + */ + public abstract 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 + * defaultValue 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 duck type + * @return value from blackboard or default value + */ + public abstract 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); + +} diff --git a/src/main/java/org/spongepowered/asm/service/ITransformer.java b/src/main/java/org/spongepowered/asm/service/ITransformer.java new file mode 100644 index 00000000..99336d66 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ITransformer.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 { + +} diff --git a/src/main/java/org/spongepowered/asm/service/MixinService.java b/src/main/java/org/spongepowered/asm/service/MixinService.java new file mode 100644 index 00000000..af139640 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/MixinService.java @@ -0,0 +1,115 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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 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.load(IMixinService.class, this.getClass().getClassLoader()); + Iterator 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; + } + +} diff --git a/src/main/java/org/spongepowered/asm/service/ServiceNotAvailableError.java b/src/main/java/org/spongepowered/asm/service/ServiceNotAvailableError.java new file mode 100644 index 00000000..5197aad3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ServiceNotAvailableError.java @@ -0,0 +1,38 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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); + } + +} diff --git a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java index c0f46c26..dbc75b5f 100644 --- a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java +++ b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java @@ -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; diff --git a/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java b/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java new file mode 100644 index 00000000..3fdab6d0 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java @@ -0,0 +1,136 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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; + } + +}