From a8558bb5f0b7df57e54c9fd467dd6e161f1a018a Mon Sep 17 00:00:00 2001 From: BenLewis Date: Tue, 20 Oct 2015 10:53:41 +1300 Subject: [PATCH 1/9] 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); + +} From 7b0a8f5d0577f8d8ea3845aa079070e1785fcc10 Mon Sep 17 00:00:00 2001 From: BenLewis Date: Tue, 20 Oct 2015 10:54:52 +1300 Subject: [PATCH 2/9] Fix typo --- .../java/org/spongepowered/tools/agent/MixinClassLoader.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java index 264e59b6..22c87e77 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java @@ -39,6 +39,9 @@ class MixinClassLoader extends ClassLoader { void addMixinClass(String name, byte[] bytes){ logger.debug("add class "+name+" to class loader"); try { + Class clazz = this.defineClass(name, bytes, 0, bytes.length); + bytecodes.put(clazz, bytes); + }catch(Throwable e){ logger.catching(e); } } From 4ffea5561b92a9e51f34c717e0bfe52e540962e0 Mon Sep 17 00:00:00 2001 From: BenLewis Date: Wed, 21 Oct 2015 10:36:01 +1300 Subject: [PATCH 3/9] Fixed issues with detecting chnaged mixin classes --- build.gradle | 22 +++++++++++-- .../spongepowered/tools/agent/MixinAgent.java | 21 +++++++----- .../tools/agent/MixinClassLoader.java | 33 +++++++++++++++++-- .../asm/mixin/transformer/MixinConfig.java | 4 ++- 4 files changed, 66 insertions(+), 14 deletions(-) diff --git a/build.gradle b/build.gradle index b97e08e5..d950f965 100644 --- a/build.gradle +++ b/build.gradle @@ -92,6 +92,9 @@ sourceSets { fernflower { compileClasspath += main.output } + agent { + compileClasspath += main.output + } } // Dependencies for renamed ASM @@ -132,7 +135,6 @@ task renamedASM { dependencies { compile 'org.slf4j:slf4j-api:1.7.7' compile 'com.google.guava:guava:17.0' - compile 'net.minecraft:launchwrapper:1.11' compile 'com.google.code.gson:gson:2.2.4' compile 'commons-io:commons-io:2.4' compile 'commons-codec:commons-codec:1.9' @@ -150,6 +152,7 @@ dependencies { // remapped ASM compile tasks.renamedASM.outputs.files apCompile tasks.renamedASM.outputs.files + agentCompile tasks.renamedASM.outputs.files // fernflower bridge fernflowerCompile 'commons-io:commons-io:2.4' @@ -157,6 +160,9 @@ dependencies { fernflowerCompile 'com.google.guava:guava:17.0' fernflowerCompile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' compile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' + + compile 'net.minecraft:launchwrapper:1.11' + agentCompile 'net.minecraft:launchwrapper:1.11' } // Filter, process, and include resources @@ -212,7 +218,10 @@ jar { // Include fernflower bridge from sourceSets.fernflower.output - + + // Include hotswap agent + from sourceSets.agent.output + // Renamed ASM from zipTree(tasks.renamedASM.outputs.files[0]) @@ -226,7 +235,12 @@ jar { "Created-By": System.properties['java.vm.version'] + " (" + System.properties['java.vm.vendor'] + ")", "Implementation-Title": name, "Implementation-Version": version + "+" + ciSystem + "-b" + buildNumber + ".git-" + commit, - "Implementation-Vendor": url) + "Implementation-Vendor": url, + // for hotswap agent + "Premain-Class": "org.spongepowered.tools.agent.MixinAgent", + "Agent-Class": "org.spongepowered.tools.agent.MixinAgent", + "Can-Redefine-Classes": true, + "Can-Retransform-Classes": true) } // generate shadow jar so we can use the AP standalone @@ -259,6 +273,8 @@ task sourceJar(type: Jar) { from sourceSets.ap.resources from sourceSets.fernflower.java from sourceSets.fernflower.resources + from sourceSets.agent.java + from sourceSets.agent.resources classifier = "sources" } diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 4807bb3e..0a6a8590 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -25,6 +25,8 @@ package org.spongepowered.tools.agent; import net.minecraft.launchwrapper.Launch; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.transformer.MixinTransformer; import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; @@ -50,17 +52,18 @@ public class MixinAgent implements IHotSwap{ public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if(classBeingRedefined == null) return null; + MixinAgent.logger.info("Redefining class "+className); byte[] mixinBytecode = MixinAgent.classLoader.getOriginalBytecode(classBeingRedefined); if(mixinBytecode != null){ + MixinAgent.logger.info("Redefining mixin "+className); List targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); - try { - for (String target:targets) { + for (String target:targets) { + MixinAgent.logger.debug("Re-transforming target class "+target); + try { instrumentation.retransformClasses(Launch.classLoader.findClass(target)); + } catch (Exception e) { + MixinAgent.logger.error("Error while re-transforming target class "+target); } - } catch (UnmodifiableClassException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); } return mixinBytecode; } @@ -73,6 +76,8 @@ public class MixinAgent implements IHotSwap{ */ private static final MixinClassLoader classLoader = new MixinClassLoader(); + private static final Logger logger = LogManager.getLogger("mixin.agent"); + /** * Instance used to register the transformer */ @@ -100,12 +105,12 @@ public class MixinAgent implements IHotSwap{ } private void initTransformer() { - MixinAgent.instrumentation.addTransformer(new Transformer()); + MixinAgent.instrumentation.addTransformer(new Transformer(), true); } @Override public void registerMixinClass(String name, byte[] bytecode) { - MixinAgent.classLoader.addMixinClass(name, bytecode); + MixinAgent.classLoader.addMixinClass(name); } /** diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java index 22c87e77..f8b78997 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java @@ -26,7 +26,15 @@ package org.spongepowered.tools.agent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.lib.ClassWriter; +import org.spongepowered.asm.lib.MethodVisitor; +import org.spongepowered.asm.lib.Opcodes; +import org.spongepowered.asm.lib.Type; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; import java.util.HashMap; import java.util.Map; @@ -36,10 +44,14 @@ class MixinClassLoader extends ClassLoader { private Map, byte[]> bytecodes = new HashMap, byte[]>(); - void addMixinClass(String name, byte[] bytes){ - logger.debug("add class "+name+" to class loader"); + void addMixinClass(String name){ + logger.debug("Mixin class "+name+" added to class loader"); try { + byte[] bytes = materialize(name); Class clazz = this.defineClass(name, bytes, 0, bytes.length); + // apparently the class needs to be instantiated at least once + // to be including in list returned by allClasses() method in jdi api + clazz.newInstance(); bytecodes.put(clazz, bytes); }catch(Throwable e){ logger.catching(e); @@ -49,4 +61,21 @@ class MixinClassLoader extends ClassLoader { byte[] getOriginalBytecode(Class clazz){ return this.bytecodes.get(clazz); } + + private byte[] materialize(String name) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class), null); + + // create init method + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "", "()V", false); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } } 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 22183140..c88eaa0a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -350,7 +350,9 @@ class MixinConfig implements Comparable, IMixinConfig { this.mixinsFor(targetClassName).add(mixin); this.unhandledTargets.add(targetClassName); } - hotSwapper.registerMixinClass(mixin.getClassName(), mixin.getClassBytes()); + if (hotSwapper != null) { + hotSwapper.registerMixinClass(mixin.getClassName(), mixin.getClassBytes()); + } this.mixins.add(mixin); } } catch (Exception ex) { From 5a7eaeae79b33b5afbe3e7fe8e9e1782ea4a8ab4 Mon Sep 17 00:00:00 2001 From: BenLewis Date: Wed, 21 Oct 2015 11:55:03 +1300 Subject: [PATCH 4/9] Fix transformation errors --- .../spongepowered/tools/agent/MixinAgent.java | 29 ++++++++++++++----- .../asm/mixin/transformer/MixinConfig.java | 2 +- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 0a6a8590..bcf1cc8e 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -33,7 +33,6 @@ 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; @@ -50,24 +49,37 @@ public class MixinAgent implements IHotSwap{ @Override public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { + MixinAgent.logger.info("Redefining class "+className); if(classBeingRedefined == null) return null; - MixinAgent.logger.info("Redefining class "+className); byte[] mixinBytecode = MixinAgent.classLoader.getOriginalBytecode(classBeingRedefined); if(mixinBytecode != null){ MixinAgent.logger.info("Redefining mixin "+className); - List targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); + List targets; + try { + targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); + } catch (Throwable th) { + // catch everything as otherwise it is ignored + MixinAgent.logger.error("Error while finding targets for mixin "+className, th); + return mixinBytecode; + } for (String target:targets) { MixinAgent.logger.debug("Re-transforming target class "+target); try { - instrumentation.retransformClasses(Launch.classLoader.findClass(target)); - } catch (Exception e) { - MixinAgent.logger.error("Error while re-transforming target class "+target); + instrumentation.retransformClasses(Launch.classLoader.findClass(target.replace('/', '.'))); + } catch (Throwable th) { + MixinAgent.logger.error("Error while re-transforming target class "+target, th); } } return mixinBytecode; } - return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); + try { + MixinAgent.logger.info("Redefining class "+className); + return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); + } catch (Throwable th) { + MixinAgent.logger.error("Error while re-transforming class "+className, th); + return null; + } } } @@ -120,6 +132,9 @@ public class MixinAgent implements IHotSwap{ */ public static void init(Instrumentation instrumentation) { MixinAgent.instrumentation = instrumentation; + if(!MixinAgent.instrumentation.isRetransformClassesSupported()) { + MixinAgent.logger.error("The instrumentation doesn't support re-transformations"); + } for (MixinAgent agent:agents) { agent.initTransformer(); } 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 c88eaa0a..7dfb381c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -525,7 +525,7 @@ class MixinConfig implements Comparable, IMixinConfig { return mixin.getTargetClasses(); } } - return null; + return Collections.emptyList(); } @Override From bc8296da0e60fe6992effa3cf32a6a3cbb8e45aa Mon Sep 17 00:00:00 2001 From: BenLewis Date: Thu, 22 Oct 2015 08:17:29 +1300 Subject: [PATCH 5/9] Tidy up code --- .../spongepowered/tools/agent/MixinAgent.java | 89 ++++++++++++------- .../tools/agent/MixinClassLoader.java | 70 ++++++++++++--- .../asm/mixin/transformer/MixinConfig.java | 9 +- .../asm/mixin/transformer/MixinInfo.java | 7 +- .../mixin/transformer/MixinTransformer.java | 16 +++- .../asm/mixin/transformer/debug/IHotSwap.java | 13 ++- 6 files changed, 154 insertions(+), 50 deletions(-) diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index bcf1cc8e..22023a28 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -30,6 +30,7 @@ import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.transformer.MixinTransformer; import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; +import java.lang.instrument.ClassDefinition; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; @@ -38,46 +39,60 @@ 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. + * An agent that re-transforms a mixin's target classes if the mixin has been + * redefined. Basically this agent enables hot-swapping of mixins. */ -public class MixinAgent implements IHotSwap{ +public class MixinAgent implements IHotSwap { - private class Transformer implements ClassFileTransformer{ + /** + * Class file transformer that re-transforms mixin's target classes if the + * mixin has been redefined. + */ + private class Transformer implements ClassFileTransformer { @Override - public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { - MixinAgent.logger.info("Redefining class "+className); - if(classBeingRedefined == null) + 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){ - MixinAgent.logger.info("Redefining mixin "+className); + } + byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined); + if (mixinBytecode != null) { + MixinAgent.logger.info("Redefining mixin " + className); List targets; try { targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); } catch (Throwable th) { // catch everything as otherwise it is ignored - MixinAgent.logger.error("Error while finding targets for mixin "+className, th); + MixinAgent.logger.error("Error while finding targets for mixin " + className, th); return mixinBytecode; } - for (String target:targets) { - MixinAgent.logger.debug("Re-transforming target class "+target); + for (String target : targets) { + String targetName = target.replace('/', '.'); + MixinAgent.logger.debug("Re-transforming target class " + target); try { - instrumentation.retransformClasses(Launch.classLoader.findClass(target.replace('/', '.'))); + Class targetClass = Launch.classLoader.findClass(targetName); + byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName); + if (targetBytecode == null) { + MixinAgent.logger.error("Target class " + targetName + " hasn't registered its bytecode"); + continue; + } + targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode); + instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode)); } catch (Throwable th) { - MixinAgent.logger.error("Error while re-transforming target class "+target, th); + MixinAgent.logger.error("Error while re-transforming target class " + target, th); } } return mixinBytecode; } try { - MixinAgent.logger.info("Redefining class "+className); + MixinAgent.logger.info("Redefining class " + className); return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); } catch (Throwable th) { - MixinAgent.logger.error("Error while re-transforming class "+className, th); + MixinAgent.logger.error("Error while re-transforming class " + className, th); return null; } } @@ -100,11 +115,14 @@ public class MixinAgent implements IHotSwap{ */ private static List agents = new ArrayList(); + /** + * MixinTransformer instance to use to transform the mixin's target classes + */ private final MixinTransformer classTransformer; /** * Constructs an agent from a class transformer in which it will use to - * transform the class. + * transform mixin's target class. * * @param classTransformer Class transformer that will transform a mixin's * target class @@ -112,8 +130,9 @@ public class MixinAgent implements IHotSwap{ public MixinAgent(MixinTransformer classTransformer) { this.classTransformer = classTransformer; MixinAgent.agents.add(this); - if (MixinAgent.instrumentation != null) - initTransformer(); + if (MixinAgent.instrumentation != null) { + this.initTransformer(); + } } private void initTransformer() { @@ -121,19 +140,25 @@ public class MixinAgent implements IHotSwap{ } @Override - public void registerMixinClass(String name, byte[] bytecode) { + public void registerMixinClass(String name) { MixinAgent.classLoader.addMixinClass(name); } + @Override + public void registerTargetClass(String name, byte[] bytecode) { + MixinAgent.classLoader.addTargetClass(name, bytecode); + } + /** - * Initialize the agents + * Sets the instrumentation instance so that the mixin agents can redefine + * mixins. * - * @param instrumentation Instance to use to transform the mixins + * @param instrumentation Instance to use to redefine the mixins */ public static void init(Instrumentation instrumentation) { MixinAgent.instrumentation = instrumentation; - if(!MixinAgent.instrumentation.isRetransformClassesSupported()) { - MixinAgent.logger.error("The instrumentation doesn't support re-transformations"); + if (!MixinAgent.instrumentation.isRedefineClassesSupported()) { + MixinAgent.logger.error("The instrumentation doesn't support re-definition of classes"); } for (MixinAgent agent:agents) { agent.initTransformer(); @@ -141,7 +166,7 @@ public class MixinAgent implements IHotSwap{ } /** - * Initialize the agent + * Initialize the java agent * * This will be called automatically if the jar is in a -javaagent java * command line argument @@ -149,18 +174,18 @@ public class MixinAgent implements IHotSwap{ * @param arg Ignored * @param instrumentation Instance to use to transform the mixins */ - public static void premain(String arg, Instrumentation instrumentation){ + public static void premain(String arg, Instrumentation instrumentation) { init(instrumentation); } /** - * Initialize the agent + * Initialize the java agent * - * This will be called automatically if the agent is loaded after jvm + * This will be called automatically if the java agent is loaded after jvm * startup * * @param arg Ignored - * @param instrumentation Instance to use to transform the mixins + * @param instrumentation Instance to use to re-define 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 index f8b78997..950432bb 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java @@ -31,38 +31,84 @@ import org.spongepowered.asm.lib.MethodVisitor; import org.spongepowered.asm.lib.Opcodes; import org.spongepowered.asm.lib.Type; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; import java.util.HashMap; import java.util.Map; +/** + * Class loader that is used to load fake mixin classes so that they can be + * re-defined. + */ class MixinClassLoader extends ClassLoader { private static final Logger logger = LogManager.getLogger("mixin.agent"); - private Map, byte[]> bytecodes = new HashMap, byte[]>(); + /** + * Mapping of mixin mixin classes to their fake classes + */ + private Map, byte[]> mixins = new HashMap, byte[]>(); - void addMixinClass(String name){ - logger.debug("Mixin class "+name+" added to class loader"); + /** + * Mapping that keep track of bytecode for classes that are targeted by + * mixins + */ + private Map targets = new HashMap(); + + /** + * Add a fake mixin class + * + * @param name Name of the fake class + */ + void addMixinClass(String name) { + logger.debug("Mixin class " + name + " added to class loader"); try { byte[] bytes = materialize(name); Class clazz = this.defineClass(name, bytes, 0, bytes.length); // apparently the class needs to be instantiated at least once // to be including in list returned by allClasses() method in jdi api clazz.newInstance(); - bytecodes.put(clazz, bytes); - }catch(Throwable e){ + this.mixins.put(clazz, bytes); + } catch (Throwable e) { logger.catching(e); } } - byte[] getOriginalBytecode(Class clazz){ - return this.bytecodes.get(clazz); + /** + * Registers the bytecode for a class targeted by a mixin + * + * @param name Name of the target clas + * @param bytecode Bytecode of the target class + */ + void addTargetClass(String name, byte[] bytecode) { + this.targets.put(name, bytecode); } - private byte[] materialize(String name) { + /** + * Gets the bytecode for a fake mixin class + * + * @param clazz Mixin class + * @return Bytecode of the fake mixin class + */ + byte[] getFakeMixinBytecode(Class clazz) { + return this.mixins.get(clazz); + } + + /** + * Gets the original bytecode for a target class + * + * @param name Name of the target class + * @return Original bytecode + */ + byte[] getOriginalTargetBytecode(String name) { + return this.targets.get(name); + } + + /** + * Generates the simplest possible class that is instantiable + * + * @param name Name of the generated class + * @return Bytecode of the generated class + */ + private static byte[] materialize(String name) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class), null); 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 7dfb381c..a07a4f33 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -351,7 +351,7 @@ class MixinConfig implements Comparable, IMixinConfig { this.unhandledTargets.add(targetClassName); } if (hotSwapper != null) { - hotSwapper.registerMixinClass(mixin.getClassName(), mixin.getClassBytes()); + hotSwapper.registerMixinClass(mixin.getClassName()); } this.mixins.add(mixin); } @@ -509,6 +509,13 @@ class MixinConfig implements Comparable, IMixinConfig { return mixins; } + /** + * Updates a mixin with new bytecode + * + * @param mixinClass Name of the mixin class + * @param bytes New bytecode + * @return List of classes that need to be updated + */ public List reloadMixin(String mixinClass, byte[] bytes) { for (Iterator iter = this.mixins.iterator(); iter.hasNext();) { MixinInfo mixin = iter.next(); 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 f1977ff0..b74d2a28 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -539,9 +539,14 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { return mixinBytes; } + /** + * Updates this mixin with new bytecode + * + * @param mixinBytes New bytecode + */ void reloadMixin(byte[] mixinBytes) { this.mixinBytes = mixinBytes; - this.validationClassNode = getClassNode(0); + this.validationClassNode = this.getClassNode(0); } /* (non-Javadoc) 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 11f7cb41..5020cd9d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -425,7 +425,11 @@ public class MixinTransformer extends TreeTransformer { this.logger.warn("Re-entrance detected, this will cause serious problems.", new RuntimeException()); throw new MixinApplyError("Re-entrance error."); } - + + if (this.hotSwapper != null) { + this.hotSwapper.registerTargetClass(transformedName, basicClass); + } + try { basicClass = this.applyMixins(transformedName, basicClass, mixins); } catch (InvalidMixinException th) { @@ -449,9 +453,17 @@ public class MixinTransformer extends TreeTransformer { } } + /** + * Update a mixin class with new bytecode. + * + * @param mixinClass Name of the mixin + * @param bytes New bytecode + * @return List of classes that need to be updated + */ public List reload(String mixinClass, byte[] bytes) { - if (this.lock.getDepth() > 0) + 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)); 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 index dceecdbd..cca77c9a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/debug/IHotSwap.java @@ -35,8 +35,17 @@ public interface IHotSwap { * 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); + public abstract void registerMixinClass(String name); + /** + * Registers a class targeted by at least one mixin. + * + * This is used to rollback the target class to a state before the mixin's + * where applied. + * + * @param name Name of the class + * @param bytecode Bytecode of the class before mixin's have been applied + */ + public abstract void registerTargetClass(String name, byte[] bytecode); } From 09b01109b8d0a607595f3ac4546585043e3523be Mon Sep 17 00:00:00 2001 From: BenLewis Date: Fri, 23 Oct 2015 17:36:10 +1300 Subject: [PATCH 6/9] Refactored MixinInfo to handle errors on reload gracefully Also - Fixed formatting error - Fixed changing of classinfo's on reload validation - Changed agent to return some invalid bytecode on error, to clearly signal an error occured --- .../spongepowered/tools/agent/MixinAgent.java | 31 ++- ...Loader.java => MixinAgentClassLoader.java} | 8 +- .../asm/mixin/transformer/MixinConfig.java | 8 - .../asm/mixin/transformer/MixinInfo.java | 241 ++++++++++++------ .../transformer/MixinReloadException.java | 44 ++++ .../mixin/transformer/MixinTransformer.java | 2 +- 6 files changed, 237 insertions(+), 97 deletions(-) rename src/agent/java/org/spongepowered/tools/agent/{MixinClassLoader.java => MixinAgentClassLoader.java} (94%) create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/MixinReloadException.java diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 22023a28..64522bad 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -27,6 +27,7 @@ package org.spongepowered.tools.agent; import net.minecraft.launchwrapper.Launch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.mixin.transformer.MixinReloadException; import org.spongepowered.asm.mixin.transformer.MixinTransformer; import org.spongepowered.asm.mixin.transformer.debug.IHotSwap; @@ -51,11 +52,8 @@ 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 { + public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain domain, byte[] classfileBuffer) + throws IllegalClassFormatException { if (classBeingRedefined == null) { return null; } @@ -65,10 +63,13 @@ public class MixinAgent implements IHotSwap { List targets; try { targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); + } catch (MixinReloadException e) { + MixinAgent.logger.error("mixin " + e.getMixinInfo() + " cannot be reloaded, needs a restart to be applied: " + e.getMessage()); + return ERROR_BYTECODE; } catch (Throwable th) { // catch everything as otherwise it is ignored MixinAgent.logger.error("Error while finding targets for mixin " + className, th); - return mixinBytecode; + return ERROR_BYTECODE; } for (String target : targets) { String targetName = target.replace('/', '.'); @@ -78,12 +79,13 @@ public class MixinAgent implements IHotSwap { byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName); if (targetBytecode == null) { MixinAgent.logger.error("Target class " + targetName + " hasn't registered its bytecode"); - continue; + return ERROR_BYTECODE; } targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode); instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode)); } catch (Throwable th) { MixinAgent.logger.error("Error while re-transforming target class " + target, th); + return ERROR_BYTECODE; } } return mixinBytecode; @@ -93,15 +95,22 @@ public class MixinAgent implements IHotSwap { return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); } catch (Throwable th) { MixinAgent.logger.error("Error while re-transforming class " + className, th); - return null; + return ERROR_BYTECODE; } } } + /** + * Bytecode that signals an error. When returned from the class file + * transformer this causes a class file format exception and indicates in + * the ide that somethings went wrong. + */ + public static byte[] ERROR_BYTECODE = new byte[]{1}; + /** * Class loader used to load mixin classes */ - private static final MixinClassLoader classLoader = new MixinClassLoader(); + private static final MixinAgentClassLoader classLoader = new MixinAgentClassLoader(); private static final Logger logger = LogManager.getLogger("mixin.agent"); @@ -175,7 +184,7 @@ public class MixinAgent implements IHotSwap { * @param instrumentation Instance to use to transform the mixins */ public static void premain(String arg, Instrumentation instrumentation) { - init(instrumentation); + MixinAgent.init(instrumentation); } /** @@ -188,6 +197,6 @@ public class MixinAgent implements IHotSwap { * @param instrumentation Instance to use to re-define the mixins */ public static void agentmain(String arg, Instrumentation instrumentation) { - init(instrumentation); + MixinAgent.init(instrumentation); } } diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java similarity index 94% rename from src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java rename to src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java index 950432bb..5aa06541 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java @@ -38,7 +38,7 @@ import java.util.Map; * Class loader that is used to load fake mixin classes so that they can be * re-defined. */ -class MixinClassLoader extends ClassLoader { +class MixinAgentClassLoader extends ClassLoader { private static final Logger logger = LogManager.getLogger("mixin.agent"); @@ -59,9 +59,9 @@ class MixinClassLoader extends ClassLoader { * @param name Name of the fake class */ void addMixinClass(String name) { - logger.debug("Mixin class " + name + " added to class loader"); + MixinAgentClassLoader.logger.debug("Mixin class " + name + " added to class loader"); try { - byte[] bytes = materialize(name); + byte[] bytes = this.materialise(name); Class clazz = this.defineClass(name, bytes, 0, bytes.length); // apparently the class needs to be instantiated at least once // to be including in list returned by allClasses() method in jdi api @@ -108,7 +108,7 @@ class MixinClassLoader extends ClassLoader { * @param name Name of the generated class * @return Bytecode of the generated class */ - private static byte[] materialize(String name) { + private byte[] materialise(String name) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class), null); 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 a07a4f33..2138bf48 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -521,14 +521,6 @@ class MixinConfig implements Comparable, IMixinConfig { 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(); } } 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 b74d2a28..140407e9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -65,7 +65,103 @@ import com.google.common.collect.Lists; * Runtime information bundle about a mixin */ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { - + + /** + * State that can be reloaded. + */ + private class ValidationState { + /** + * Mixin bytes (read once, generate tree on demand) + */ + byte[] mixinBytes; + + /** + * All interfaces implemented by this mixin, including soft implementations + */ + final Set interfaces = new HashSet(); + + /** + * Interfaces soft-implemented using {@link Implements} + */ + final List softImplements = new ArrayList(); + + /** + * Synthetic inner classes + */ + final Set syntheticInnerClasses = new HashSet(); + + /** + * Mixin ClassInfo + */ + final ClassInfo classInfo; + + /** + * True if the superclass of the mixin is not the direct superclass + * of one or more targets + */ + boolean detachedSuper; + + /** + * Initial ClassNode created for mixin validation, not used for actual + * application + */ + ClassNode validationClassNode; + + ValidationState(byte[] mixinBytes, ClassInfo classInfo) { + this.mixinBytes = mixinBytes; + this.validationClassNode = this.getClassNode(0); + this.classInfo = classInfo; + } + + ValidationState(byte[] mixinBytes) { + this.mixinBytes = mixinBytes; + this.validationClassNode = this.getClassNode(0); + this.classInfo = ClassInfo.fromClassNode(this.validationClassNode); + } + + /** + * Gets a new tree from the bytecode + * + * @param flags Flags passed into classReader + * @return Tree representing the bytecode + */ + ClassNode getClassNode(int flags) { + MixinClassNode classNode = new MixinClassNode(MixinInfo.this); + ClassReader classReader = new ClassReader(this.mixinBytes); + classReader.accept(classNode, flags); + return classNode; + } + } + + private class ReloadedState extends ValidationState { + final ValidationState parent; + + ReloadedState(ValidationState parent, byte[] mixinBytes) { + super(mixinBytes, parent.classInfo); + this.parent = parent; + } + + void validateChanges() { + if (!this.syntheticInnerClasses.equals(this.parent.syntheticInnerClasses)) { + throw new MixinReloadException(MixinInfo.this, "Cannot change inner classes"); + } + if (!this.interfaces.equals(this.parent.interfaces)) { + throw new MixinReloadException(MixinInfo.this, "Cannot change interfaces"); + } + if (!new HashSet(this.softImplements).equals(new HashSet(this.parent.softImplements))) { + throw new MixinReloadException(MixinInfo.this, "Cannot change soft interfaces"); + } + List targets = MixinInfo.this.readTargetClasses(this.validationClassNode, true); + if (!new HashSet(targets).equals(new HashSet(MixinInfo.this.targetClasses))) { + throw new MixinReloadException(MixinInfo.this, "Cannot change target classes"); + } + int priority = MixinInfo.this.readPriority(this.validationClassNode); + if (priority != MixinInfo.this.priority) { + throw new MixinReloadException(MixinInfo.this, "Cannot change mixin priority"); + } + } + } + /** * Global order of mixin infos, used to determine ordering between mixins * with equivalent priority @@ -94,11 +190,6 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ private final String className; - /** - * Mixin ClassInfo - */ - private final transient ClassInfo classInfo; - /** * Mixin priority, read from the {@link Mixin} annotation on the mixin class */ @@ -118,48 +209,26 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * Intrinsic order (for sorting mixins with identical priority) */ private final transient int order = MixinInfo.mixinOrder++; - - /** - * Mixin bytes (read once, generate tree on demand) - */ - private transient byte[] mixinBytes; /** * Configuration plugin */ private final transient IMixinConfigPlugin plugin; - - /** - * All interfaces implemented by this mixin, including soft implementations - */ - private final transient Set interfaces = new HashSet(); /** - * Interfaces soft-implemented using {@link Implements} + * Holds state that currently is not fully initialised */ - private final transient List softImplements = new ArrayList(); - + private transient ValidationState uninitialisedState; + /** - * Synthetic inner classes + * Holds state that can be reloaded */ - private final transient Set syntheticInnerClasses = new HashSet(); - + private transient ValidationState validationState; + /** * The environment phase in which this mixin was initialised */ private final transient Phase phase; - - /** - * Initial ClassNode created for mixin validation, not used for actual - * application - */ - private transient ClassNode validationClassNode; - - /** - * True if the superclass of the mixin is not the direct superclass - * of one or more targets - */ - private boolean detachedSuper; /** * Internal ctor, called by {@link MixinConfig} @@ -180,23 +249,33 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { this.phase = MixinEnvironment.getCurrentEnvironment().getPhase(); // Read the class bytes and transform - this.mixinBytes = this.loadMixinClass(this.className, runTransformers); - - ClassNode classNode = this.getClassNode(0); + byte[] mixinBytes = this.loadMixinClass(this.className, runTransformers); + this.uninitialisedState = new ValidationState(mixinBytes); + + ClassNode classNode = this.uninitialisedState.getClassNode(0); this.priority = this.readPriority(classNode); this.targetClasses = this.readTargetClasses(classNode, suppressPlugin); this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction())); - this.validationClassNode = classNode; - this.classInfo = ClassInfo.fromClassNode(classNode); } void validate() { - this.detachedSuper = this.validateTargetClasses(this.validationClassNode); - this.validateMixin(this.validationClassNode); - this.readImplementations(this.validationClassNode); - this.readInnerClasses(this.validationClassNode); - new MixinPreProcessor(this, this.validationClassNode).prepare(); - this.validationClassNode = null; + try { + ClassNode classNode = this.uninitialisedState.validationClassNode; + this.uninitialisedState.detachedSuper = this.validateTargetClasses(classNode); + this.validateMixin(this.uninitialisedState); + this.readImplementations(this.uninitialisedState); + this.readInnerClasses(this.uninitialisedState); + if (this.uninitialisedState instanceof ReloadedState) { + ((ReloadedState) this.uninitialisedState).validateChanges(); + } else { + new MixinPreProcessor(this, classNode).prepare(); + } + this.uninitialisedState.validationClassNode = null; + // the state is now fully initialised and validated + this.validationState = this.uninitialisedState; + } finally { + this.uninitialisedState = null; + } } /** @@ -296,21 +375,21 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Performs pre-flight checks on the mixin * - * @param classNode + * @param state ReloadableState to validate */ - private void validateMixin(ClassNode classNode) { + private void validateMixin(ValidationState state) { // isInner (shouldn't) return true for static inner classes - if (!this.classInfo.isProbablyStatic()) { + if (!state.classInfo.isProbablyStatic()) { throw new InvalidMixinException(this, "Inner class mixin must be declared static"); } // Can't have remappable fields or methods on a multi-target mixin, because after obfuscation the fields will remap to conflicting names if (this.targetClasses.size() > 1) { - for (FieldNode field : classNode.fields) { + for (FieldNode field : state.validationClassNode.fields) { this.checkRemappable(Shadow.class, field.name, ASMHelper.getVisibleAnnotation(field, Shadow.class)); } - for (MethodNode method : classNode.methods) { + for (MethodNode method : state.validationClassNode.methods) { this.checkRemappable(Shadow.class, method.name, ASMHelper.getVisibleAnnotation(method, Shadow.class)); AnnotationNode overwrite = ASMHelper.getVisibleAnnotation(method, Overwrite.class); if (overwrite != null && ((method.access & Opcodes.ACC_STATIC) == 0 || (method.access & Opcodes.ACC_PUBLIC) == 0)) { @@ -330,10 +409,10 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Read and process any {@link Implements} annotations on the mixin */ - private void readImplementations(ClassNode classNode) { - this.interfaces.addAll(classNode.interfaces); + private void readImplementations(ValidationState state) { + state.interfaces.addAll(state.validationClassNode.interfaces); - AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(classNode, Implements.class); + AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(state.validationClassNode, Implements.class); if (implementsAnnotation == null) { return; } @@ -345,9 +424,12 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { for (AnnotationNode interfaceNode : interfaces) { InterfaceInfo interfaceInfo = InterfaceInfo.fromAnnotation(this, interfaceNode); - this.softImplements.add(interfaceInfo); - this.interfaces.add(interfaceInfo.getInternalName()); - this.classInfo.addInterface(interfaceInfo.getInternalName()); + state.softImplements.add(interfaceInfo); + state.interfaces.add(interfaceInfo.getInternalName()); + // only add interface if its initial initialisation + if (!(state instanceof ReloadedState)) { + state.classInfo.addInterface(interfaceInfo.getInternalName()); + } } } @@ -356,12 +438,13 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * classes so that we can add them to the passthrough set in our parent * config. */ - private void readInnerClasses(ClassNode classNode) { - for (InnerClassNode inner : classNode.innerClasses) { + private void readInnerClasses(ValidationState state) { + for (InnerClassNode inner : state.validationClassNode.innerClasses) { ClassInfo innerClass = ClassInfo.forName(inner.name); if (innerClass.isSynthetic() && innerClass.isProbablyStatic()) { - if ((inner.outerName != null && inner.outerName.equals(this.classInfo.getName())) || inner.name.startsWith(classNode.name + "$")) { - this.syntheticInnerClasses.add(inner.name); + if ((inner.outerName != null && inner.outerName.equals(state.classInfo.getName())) || + inner.name.startsWith(state.validationClassNode.name + "$")) { + state.syntheticInnerClasses.add(inner.name); } else { throw new InvalidMixinException(this, "Unhandled synthetic inner class found: " + inner.name); } @@ -369,8 +452,19 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { } } + /** + * Current state, either the initialised state or the uninitialised state if + * it initialising for the first time. Should never return null. + */ + private ValidationState getCurrentState() { + if (this.validationState == null) { + return this.uninitialisedState; + } + return this.validationState; + } + ClassInfo getClassInfo() { - return this.classInfo; + return this.getCurrentState().classInfo; } /** @@ -409,7 +503,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public String getClassRef() { - return this.classInfo.getName(); + return this.getClassInfo().getName(); } /** @@ -417,7 +511,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public byte[] getClassBytes() { - return this.mixinBytes; + return this.getCurrentState().mixinBytes; } /** @@ -426,7 +520,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public boolean isDetachedSuper() { - return this.detachedSuper; + return this.getCurrentState().detachedSuper; } /** @@ -449,10 +543,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { */ @Override public ClassNode getClassNode(int flags) { - MixinClassNode classNode = new MixinClassNode(this); - ClassReader classReader = new ClassReader(this.mixinBytes); - classReader.accept(classNode, flags); - return classNode; + return this.getCurrentState().getClassNode(flags); } /** @@ -467,14 +558,14 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * Get the soft implementations for this mixin */ List getSoftImplements() { - return Collections.unmodifiableList(this.softImplements); + return Collections.unmodifiableList(this.getCurrentState().softImplements); } /** * Get the synthetic inner classes for this mixin */ public Set getSyntheticInnerClasses() { - return Collections.unmodifiableSet(this.syntheticInnerClasses); + return Collections.unmodifiableSet(this.getCurrentState().syntheticInnerClasses); } /** @@ -498,7 +589,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * @return mixin interfaces */ public Set getInterfaces() { - return this.interfaces; + return this.getCurrentState().interfaces; } /** @@ -545,8 +636,12 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { * @param mixinBytes New bytecode */ void reloadMixin(byte[] mixinBytes) { - this.mixinBytes = mixinBytes; - this.validationClassNode = this.getClassNode(0); + if (this.uninitialisedState != null) { + throw new IllegalStateException("Cannot reload mixin while it is initialising"); + } + ReloadedState state = new ReloadedState(this.validationState, mixinBytes); + this.uninitialisedState = state; + this.validate(); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinReloadException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinReloadException.java new file mode 100644 index 00000000..c9ad46f6 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinReloadException.java @@ -0,0 +1,44 @@ +/* + * 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; + +/** + * An exception that occurs when a mixin reloads and does something it is + * normally allowed to do but isn't due to reloading restrictions. + */ +public class MixinReloadException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final MixinInfo mixinInfo; + + public MixinReloadException(MixinInfo mixinInfo, String message) { + super(message); + this.mixinInfo = mixinInfo; + } + + public MixinInfo getMixinInfo() { + return this.mixinInfo; + } +} 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 5020cd9d..a86d11b1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -465,7 +465,7 @@ public class MixinTransformer extends TreeTransformer { throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered"); } List targets = new ArrayList(); - for (MixinConfig config:this.configs) { + for (MixinConfig config : this.configs) { targets.addAll(config.reloadMixin(mixinClass, bytes)); } return targets; From bbdac72be56e89587c87616a1cb08c27759131ef Mon Sep 17 00:00:00 2001 From: BenLewis Date: Sat, 24 Oct 2015 09:07:41 +1300 Subject: [PATCH 7/9] Fixed false positive of changes to soft interfaces --- .../asm/mixin/transformer/InterfaceInfo.java | 22 +++++++++++++ .../asm/mixin/transformer/MixinInfo.java | 31 ++++++++++++------- 2 files changed, 41 insertions(+), 12 deletions(-) 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 1b3baaec..d51321db 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -178,4 +178,26 @@ public class InterfaceInfo extends TreeInfo { return new InterfaceInfo(mixin, prefix, iface); } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + InterfaceInfo that = (InterfaceInfo) o; + + return this.mixin.equals(that.mixin) && this.prefix.equals(that.prefix) && this.iface.equals(that.iface); + } + + @Override + public int hashCode() { + int result = this.mixin.hashCode(); + result = 31 * result + this.prefix.hashCode(); + result = 31 * result + this.iface.hashCode(); + return result; + } } 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 140407e9..b21ffe91 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -76,7 +76,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { byte[] mixinBytes; /** - * All interfaces implemented by this mixin, including soft implementations + * All interfaces implemented by this mixin, including soft + * implementations */ final Set interfaces = new HashSet(); @@ -96,8 +97,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { final ClassInfo classInfo; /** - * True if the superclass of the mixin is not the direct superclass - * of one or more targets + * True if the superclass of the mixin is not the direct + * superclass of one or more targets */ boolean detachedSuper; @@ -134,6 +135,9 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { } private class ReloadedState extends ValidationState { + /** + * The previous validation state to compare the changes to + */ final ValidationState parent; ReloadedState(ValidationState parent, byte[] mixinBytes) { @@ -141,6 +145,10 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { this.parent = parent; } + /** + * Validates that the changes are allowed to be made, these restrictions + * only exits while reloading mixins. + */ void validateChanges() { if (!this.syntheticInnerClasses.equals(this.parent.syntheticInnerClasses)) { throw new MixinReloadException(MixinInfo.this, "Cannot change inner classes"); @@ -216,12 +224,12 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { private final transient IMixinConfigPlugin plugin; /** - * Holds state that currently is not fully initialised + * Holds state that currently is not fully initialised or validated */ private transient ValidationState uninitialisedState; /** - * Holds state that can be reloaded + * Holds the current validated state */ private transient ValidationState validationState; @@ -375,7 +383,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { /** * Performs pre-flight checks on the mixin * - * @param state ReloadableState to validate + * @param state State to validate */ private void validateMixin(ValidationState state) { // isInner (shouldn't) return true for static inner classes @@ -442,8 +450,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { for (InnerClassNode inner : state.validationClassNode.innerClasses) { ClassInfo innerClass = ClassInfo.forName(inner.name); if (innerClass.isSynthetic() && innerClass.isProbablyStatic()) { - if ((inner.outerName != null && inner.outerName.equals(state.classInfo.getName())) || - inner.name.startsWith(state.validationClassNode.name + "$")) { + if ((inner.outerName != null && inner.outerName.equals(state.classInfo.getName())) + || inner.name.startsWith(state.validationClassNode.name + "$")) { state.syntheticInnerClasses.add(inner.name); } else { throw new InvalidMixinException(this, "Unhandled synthetic inner class found: " + inner.name); @@ -453,8 +461,8 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { } /** - * Current state, either the initialised state or the uninitialised state if - * it initialising for the first time. Should never return null. + * Current state, either the validated state or the uninitialised state if + * the mixin is initialising for the first time. Should never return null. */ private ValidationState getCurrentState() { if (this.validationState == null) { @@ -639,8 +647,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo { if (this.uninitialisedState != null) { throw new IllegalStateException("Cannot reload mixin while it is initialising"); } - ReloadedState state = new ReloadedState(this.validationState, mixinBytes); - this.uninitialisedState = state; + this.uninitialisedState = new ReloadedState(this.validationState, mixinBytes); this.validate(); } From 61dd93eaa02b70b701b18ad930a5a18c760ab955 Mon Sep 17 00:00:00 2001 From: BenLewis Date: Sun, 25 Oct 2015 07:38:08 +1300 Subject: [PATCH 8/9] Fixed formatting errors --- .../org/spongepowered/tools/agent/MixinAgent.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 64522bad..bb0e7ce3 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -65,11 +65,11 @@ public class MixinAgent implements IHotSwap { targets = MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); } catch (MixinReloadException e) { MixinAgent.logger.error("mixin " + e.getMixinInfo() + " cannot be reloaded, needs a restart to be applied: " + e.getMessage()); - return ERROR_BYTECODE; + return MixinAgent.ERROR_BYTECODE; } catch (Throwable th) { // catch everything as otherwise it is ignored MixinAgent.logger.error("Error while finding targets for mixin " + className, th); - return ERROR_BYTECODE; + return MixinAgent.ERROR_BYTECODE; } for (String target : targets) { String targetName = target.replace('/', '.'); @@ -79,13 +79,13 @@ public class MixinAgent implements IHotSwap { byte[] targetBytecode = MixinAgent.classLoader.getOriginalTargetBytecode(targetName); if (targetBytecode == null) { MixinAgent.logger.error("Target class " + targetName + " hasn't registered its bytecode"); - return ERROR_BYTECODE; + return MixinAgent.ERROR_BYTECODE; } targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode); instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode)); } catch (Throwable th) { MixinAgent.logger.error("Error while re-transforming target class " + target, th); - return ERROR_BYTECODE; + return MixinAgent.ERROR_BYTECODE; } } return mixinBytecode; @@ -95,7 +95,7 @@ public class MixinAgent implements IHotSwap { return MixinAgent.this.classTransformer.transform(null, className, classfileBuffer); } catch (Throwable th) { MixinAgent.logger.error("Error while re-transforming class " + className, th); - return ERROR_BYTECODE; + return MixinAgent.ERROR_BYTECODE; } } } @@ -105,7 +105,7 @@ public class MixinAgent implements IHotSwap { * transformer this causes a class file format exception and indicates in * the ide that somethings went wrong. */ - public static byte[] ERROR_BYTECODE = new byte[]{1}; + public static final byte[] ERROR_BYTECODE = new byte[]{1}; /** * Class loader used to load mixin classes From b86b843bb30bc25a464be3de478b9b3cd7e43f57 Mon Sep 17 00:00:00 2001 From: BenLewis Date: Sun, 25 Oct 2015 19:02:40 +1300 Subject: [PATCH 9/9] Fixed re-entrant error caused by both the launch classloader and the java agent trying to transform a class at the same time --- .../spongepowered/asm/mixin/transformer/MixinTransformer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 a86d11b1..4cd00bcf 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -374,7 +374,7 @@ public class MixinTransformer extends TreeTransformer { * #transform(java.lang.String, java.lang.String, byte[]) */ @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) { + public synchronized byte[] transform(String name, String transformedName, byte[] basicClass) { if (basicClass == null || transformedName == null || this.errorState) { return basicClass; }