From a8558bb5f0b7df57e54c9fd467dd6e161f1a018a Mon Sep 17 00:00:00 2001 From: BenLewis Date: Tue, 20 Oct 2015 10:53:41 +1300 Subject: [PATCH] Add java agent to reload mixin --- .../spongepowered/tools/agent/MixinAgent.java | 148 ++++++++++++++++++ .../tools/agent/MixinClassLoader.java | 49 ++++++ .../asm/mixin/MixinEnvironment.java | 9 +- .../asm/mixin/transformer/MixinConfig.java | 35 ++++- .../asm/mixin/transformer/MixinInfo.java | 7 +- .../mixin/transformer/MixinTransformer.java | 46 +++++- .../asm/mixin/transformer/debug/IHotSwap.java | 42 +++++ 7 files changed, 322 insertions(+), 14 deletions(-) create mode 100644 src/agent/java/org/spongepowered/tools/agent/MixinAgent.java create mode 100644 src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java new file mode 100644 index 00000000..4807bb3e --- /dev/null +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -0,0 +1,148 @@ +/* + * 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.tools.agent; + +import net.minecraft.launchwrapper.Launch; +import org.spongepowered.asm.mixin.transformer.MixinTransformer; +import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; + +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; +import java.lang.instrument.Instrumentation; +import java.lang.instrument.UnmodifiableClassException; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.List; + +/** + * A java agent that re-transforms a mixin's target class if the mixin has been + * redefined. This agent enables hot-swapping of mixins. + * + * This class is a singleton because it needs to conofrm to the IHotSwap interface. + */ +public class MixinAgent implements IHotSwap{ + + private class Transformer implements ClassFileTransformer{ + + @Override + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + if(classBeingRedefined == null) + return null; + byte[] mixinBytecode = MixinAgent.classLoader.getOriginalBytecode(classBeingRedefined); + if(mixinBytecode != null){ + List targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); + try { + for (String target:targets) { + instrumentation.retransformClasses(Launch.classLoader.findClass(target)); + } + } catch (UnmodifiableClassException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return mixinBytecode; + } + return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); + } + } + + /** + * Class loader used to load mixin classes + */ + private static final MixinClassLoader classLoader = new MixinClassLoader(); + + /** + * Instance used to register the transformer + */ + private static Instrumentation instrumentation = null; + + /** + * Instances of all agents + */ + private static List agents = new ArrayList(); + + private final MixinTransformer classTransformer; + + /** + * Constructs an agent from a class transformer in which it will use to + * transform the class. + * + * @param classTransformer Class transformer that will transform a mixin's + * target class + */ + public MixinAgent(MixinTransformer classTransformer) { + this.classTransformer = classTransformer; + MixinAgent.agents.add(this); + if (MixinAgent.instrumentation != null) + initTransformer(); + } + + private void initTransformer() { + MixinAgent.instrumentation.addTransformer(new Transformer()); + } + + @Override + public void registerMixinClass(String name, byte[] bytecode) { + MixinAgent.classLoader.addMixinClass(name, bytecode); + } + + /** + * Initialize the agents + * + * @param instrumentation Instance to use to transform the mixins + */ + public static void init(Instrumentation instrumentation) { + MixinAgent.instrumentation = instrumentation; + for (MixinAgent agent:agents) { + agent.initTransformer(); + } + } + + /** + * Initialize the agent + * + * This will be called automatically if the jar is in a -javaagent java + * command line argument + * + * @param arg Ignored + * @param instrumentation Instance to use to transform the mixins + */ + public static void premain(String arg, Instrumentation instrumentation){ + init(instrumentation); + } + + /** + * Initialize the agent + * + * This will be called automatically if the agent is loaded after jvm + * startup + * + * @param arg Ignored + * @param instrumentation Instance to use to transform the mixins + */ + public static void agentmain(String arg, Instrumentation instrumentation) { + init(instrumentation); + } +} diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java new file mode 100644 index 00000000..264e59b6 --- /dev/null +++ b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java @@ -0,0 +1,49 @@ +/* + * 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.tools.agent; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.HashMap; +import java.util.Map; + +class MixinClassLoader extends ClassLoader { + + private static final Logger logger = LogManager.getLogger("mixin.agent"); + + private Map, byte[]> bytecodes = new HashMap, byte[]>(); + + void addMixinClass(String name, byte[] bytes){ + logger.debug("add class "+name+" to class loader"); + try { + logger.catching(e); + } + } + + byte[] getOriginalBytecode(Class clazz){ + return this.bytecodes.get(clazz); + } +} diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index ea2f47b3..7b327b4f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -290,8 +290,13 @@ public class MixinEnvironment implements ITokenProvider { /** * Ignore all constraints on mixin annotations, output warnings instead */ - IGNORE_CONSTRAINTS("ignoreConstraints"); - + IGNORE_CONSTRAINTS("ignoreConstraints"), + + /** + * Enables the hot-swap agent + */ + HOT_SWAP("hotSwap"); + /** * Prefix for mixin options */ 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 1a0e9df5..22183140 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -46,6 +46,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper; +import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; import org.spongepowered.asm.util.VersionNumber; import com.google.gson.Gson; @@ -274,20 +275,20 @@ class MixinConfig implements Comparable, IMixinConfig { * either the hasMixinsFor() or getMixinsFor() methods. *

*/ - void initialise() { + void initialise(IHotSwap hotSwapper) { if (this.initialised) { return; } this.initialised = true; - this.initialiseMixins(this.mixinClasses, false); + this.initialiseMixins(this.mixinClasses, false, hotSwapper); switch (MixinEnvironment.getCurrentEnvironment().getSide()) { case CLIENT: - this.initialiseMixins(this.mixinClassesClient, false); + this.initialiseMixins(this.mixinClassesClient, false, hotSwapper); break; case SERVER: - this.initialiseMixins(this.mixinClassesServer, false); + this.initialiseMixins(this.mixinClassesServer, false, hotSwapper); break; case UNKNOWN: //$FALL-THROUGH$ @@ -297,10 +298,10 @@ class MixinConfig implements Comparable, IMixinConfig { } } - void postInitialise() { + void postInitialise(IHotSwap hotSwapper) { if (this.plugin != null) { List pluginMixins = this.plugin.getMixins(); - this.initialiseMixins(pluginMixins, true); + this.initialiseMixins(pluginMixins, true, hotSwapper); } for (Iterator iter = this.mixins.iterator(); iter.hasNext();) { @@ -328,7 +329,7 @@ class MixinConfig implements Comparable, IMixinConfig { } } - private void initialiseMixins(List mixinClasses, boolean suppressPlugin) { + private void initialiseMixins(List mixinClasses, boolean suppressPlugin, IHotSwap hotSwapper) { if (mixinClasses == null) { return; } @@ -349,6 +350,7 @@ class MixinConfig implements Comparable, IMixinConfig { this.mixinsFor(targetClassName).add(mixin); this.unhandledTargets.add(targetClassName); } + hotSwapper.registerMixinClass(mixin.getClassName(), mixin.getClassBytes()); this.mixins.add(mixin); } } catch (Exception ex) { @@ -504,6 +506,25 @@ class MixinConfig implements Comparable, IMixinConfig { } return mixins; } + + public List reloadMixin(String mixinClass, byte[] bytes) { + for (Iterator iter = this.mixins.iterator(); iter.hasNext();) { + MixinInfo mixin = iter.next(); + if (mixin.getClassName().equals(mixinClass)) { + mixin.reloadMixin(bytes); + try { + mixin.validate(); + } catch (Exception e) { + this.logger.error(e.getMessage(), e); + this.removeMixin(mixin); + iter.remove(); + return Collections.emptyList(); + } + return mixin.getTargetClasses(); + } + } + return null; + } @Override public String toString() { 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 58a62684..f1977ff0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -122,7 +122,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Mixin bytes (read once, generate tree on demand) */ - private final transient byte[] mixinBytes; + private transient byte[] mixinBytes; /** * Configuration plugin @@ -539,6 +539,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { return mixinBytes; } + void reloadMixin(byte[] mixinBytes) { + this.mixinBytes = mixinBytes; + this.validationClassNode = getClassNode(0); + } + /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ 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 4c5325c7..11f7cb41 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -56,6 +56,7 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; import org.spongepowered.asm.mixin.transformer.debug.IDecompiler; +import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; import org.spongepowered.asm.transformers.TreeTransformer; import org.spongepowered.asm.util.Constants; @@ -277,6 +278,11 @@ public class MixinTransformer extends TreeTransformer { */ private final IDecompiler decompiler; + /** + * Hot-Swap agent + */ + private final IHotSwap hotSwapper; + /** * ctor */ @@ -294,7 +300,9 @@ public class MixinTransformer extends TreeTransformer { TreeInfo.setLock(this.lock); this.decompiler = this.initDecompiler(new File(MixinTransformer.DEBUG_OUTPUT, "java")); - + + this.hotSwapper = this.initHotSwapper(); + try { FileUtils.deleteDirectory(this.classExportDir); } catch (IOException ex) { @@ -321,6 +329,26 @@ public class MixinTransformer extends TreeTransformer { return null; } + private IHotSwap initHotSwapper() { + if (!MixinEnvironment.getCurrentEnvironment().getOption(Option.HOT_SWAP)) { + return null; + } + + try { + this.logger.info("Attempting to load Hot-Swap agent"); + @SuppressWarnings("unchecked") + Class clazz = + (Class)Class.forName("org.spongepowered.tools.agent.MixinAgent"); + Constructor ctor = clazz.getDeclaredConstructor(MixinTransformer.class); + return ctor.newInstance(this); + } catch (Throwable th) { + this.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}", + th.getClass().getSimpleName(), th.getMessage()); + } + + return null; + } + /** * Force-load all classes targetted by mixins but not yet applied */ @@ -404,7 +432,7 @@ public class MixinTransformer extends TreeTransformer { if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) { this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass); } - + this.handleMixinErrorState(transformedName, th); } } @@ -421,6 +449,16 @@ public class MixinTransformer extends TreeTransformer { } } + public List reload(String mixinClass, byte[] bytes) { + if (this.lock.getDepth() > 0) + throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered"); + List targets = new ArrayList(); + for (MixinConfig config:this.configs) { + targets.addAll(config.reloadMixin(mixinClass, bytes)); + } + return targets; + } + private void init(MixinEnvironment environment) { this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG; this.logger.log(this.verboseLoggingLevel, "Preparing mixins for {}", environment); @@ -481,7 +519,7 @@ public class MixinTransformer extends TreeTransformer { private void initConfigs() { for (MixinConfig config : this.pendingConfigs) { try { - config.initialise(); + config.initialise(this.hotSwapper); } catch (Exception ex) { this.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + ex.getMessage(), ex); } @@ -505,7 +543,7 @@ public class MixinTransformer extends TreeTransformer { for (MixinConfig config : this.pendingConfigs) { try { - config.postInitialise(); + config.postInitialise(this.hotSwapper); } catch (Exception ex) { this.logger.error("Error encountered during mixin config postInit setp'" + config.getName() + "': " + ex.getMessage(), ex); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java b/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java new file mode 100644 index 00000000..dceecdbd --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java @@ -0,0 +1,42 @@ +/* + * 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.debug; + +/** + * Interface to allow the hot-swap agent to be loaded on-demand + */ +public interface IHotSwap { + + /** + * Registers a mixin class with the agent. + * + * This is needed as the mixin needs to be loaded to be redefined. + * + * @param name Fully qualified name of the mixin class + * @param bytecode Bytecode of the mixin + */ + public abstract void registerMixinClass(String name, byte[] bytecode); + +}