From bc8296da0e60fe6992effa3cf32a6a3cbb8e45aa Mon Sep 17 00:00:00 2001 From: BenLewis Date: Thu, 22 Oct 2015 08:17:29 +1300 Subject: [PATCH] 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); }