Hot Code Replacement support thanks to @skinny121

This commit is contained in:
Mumfrey committed 2015-11-02 11:34:17 +00:00
commit b09b5b4c48
10 files changed
+740 -89

No files matched your search

+19 -3
View File
@@ -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"
}
@@ -0,0 +1,202 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.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;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
/**
* 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 {
/**
* 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 domain, byte[] classfileBuffer)
throws IllegalClassFormatException {
if (classBeingRedefined == null) {
return null;
}
byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined);
if (mixinBytecode != null) {
MixinAgent.logger.info("Redefining mixin " + className);
List<String> 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 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 MixinAgent.ERROR_BYTECODE;
}
for (String target : targets) {
String targetName = target.replace('/', '.');
MixinAgent.logger.debug("Re-transforming target class " + target);
try {
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");
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 MixinAgent.ERROR_BYTECODE;
}
}
return mixinBytecode;
}
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 MixinAgent.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 final byte[] ERROR_BYTECODE = new byte[]{1};
/**
* Class loader used to load mixin classes
*/
private static final MixinAgentClassLoader classLoader = new MixinAgentClassLoader();
private static final Logger logger = LogManager.getLogger("mixin.agent");
/**
* Instance used to register the transformer
*/
private static Instrumentation instrumentation = null;
/**
* Instances of all agents
*/
private static List<MixinAgent> agents = new ArrayList<MixinAgent>();
/**
* 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 mixin's target 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) {
this.initTransformer();
}
}
private void initTransformer() {
MixinAgent.instrumentation.addTransformer(new Transformer(), true);
}
@Override
public void registerMixinClass(String name) {
MixinAgent.classLoader.addMixinClass(name);
}
@Override
public void registerTargetClass(String name, byte[] bytecode) {
MixinAgent.classLoader.addTargetClass(name, bytecode);
}
/**
* Sets the instrumentation instance so that the mixin agents can redefine
* mixins.
*
* @param instrumentation Instance to use to redefine the mixins
*/
public static void init(Instrumentation instrumentation) {
MixinAgent.instrumentation = instrumentation;
if (!MixinAgent.instrumentation.isRedefineClassesSupported()) {
MixinAgent.logger.error("The instrumentation doesn't support re-definition of classes");
}
for (MixinAgent agent:agents) {
agent.initTransformer();
}
}
/**
* Initialize the java 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) {
MixinAgent.init(instrumentation);
}
/**
* Initialize the java agent
*
* This will be called automatically if the java agent is loaded after jvm
* startup
*
* @param arg Ignored
* @param instrumentation Instance to use to re-define the mixins
*/
public static void agentmain(String arg, Instrumentation instrumentation) {
MixinAgent.init(instrumentation);
}
}
@@ -0,0 +1,127 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.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.util.HashMap;
import java.util.Map;
/**
* Class loader that is used to load fake mixin classes so that they can be
* re-defined.
*/
class MixinAgentClassLoader extends ClassLoader {
private static final Logger logger = LogManager.getLogger("mixin.agent");
/**
* Mapping of mixin mixin classes to their fake classes
*/
private Map<Class<?>, byte[]> mixins = new HashMap<Class<?>, byte[]>();
/**
* Mapping that keep track of bytecode for classes that are targeted by
* mixins
*/
private Map<String, byte[]> targets = new HashMap<String, byte[]>();
/**
* Add a fake mixin class
*
* @param name Name of the fake class
*/
void addMixinClass(String name) {
MixinAgentClassLoader.logger.debug("Mixin class " + name + " added to class loader");
try {
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
clazz.newInstance();
this.mixins.put(clazz, bytes);
} catch (Throwable e) {
logger.catching(e);
}
}
/**
* 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);
}
/**
* 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 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);
// create init method
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
cw.visitEnd();
return cw.toByteArray();
}
}
@@ -289,8 +289,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
*/
@@ -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;
}
}
@@ -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<MixinConfig>, IMixinConfig {
* either the <em>hasMixinsFor()</em> or <em>getMixinsFor()</em> methods.
* </p>
*/
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<MixinConfig>, IMixinConfig {
}
}
void postInitialise() {
void postInitialise(IHotSwap hotSwapper) {
if (this.plugin != null) {
List<String> pluginMixins = this.plugin.getMixins();
this.initialiseMixins(pluginMixins, true);
this.initialiseMixins(pluginMixins, true, hotSwapper);
}
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
@@ -328,7 +329,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
private void initialiseMixins(List<String> mixinClasses, boolean suppressPlugin) {
private void initialiseMixins(List<String> mixinClasses, boolean suppressPlugin, IHotSwap hotSwapper) {
if (mixinClasses == null) {
return;
}
@@ -349,6 +350,9 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
this.mixinsFor(targetClassName).add(mixin);
this.unhandledTargets.add(targetClassName);
}
if (hotSwapper != null) {
hotSwapper.registerMixinClass(mixin.getClassName());
}
this.mixins.add(mixin);
}
} catch (Exception ex) {
@@ -504,6 +508,24 @@ class MixinConfig implements Comparable<MixinConfig>, 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<String> reloadMixin(String mixinClass, byte[] bytes) {
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
MixinInfo mixin = iter.next();
if (mixin.getClassName().equals(mixinClass)) {
mixin.reloadMixin(bytes);
return mixin.getTargetClasses();
}
}
return Collections.<String>emptyList();
}
@Override
public String toString() {
@@ -65,7 +65,111 @@ import com.google.common.collect.Lists;
* Runtime information bundle about a mixin
*/
class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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<String> interfaces = new HashSet<String>();
/**
* Interfaces soft-implemented using {@link Implements}
*/
final List<InterfaceInfo> softImplements = new ArrayList<InterfaceInfo>();
/**
* Synthetic inner classes
*/
final Set<String> syntheticInnerClasses = new HashSet<String>();
/**
* Mixin ClassInfo
*/
final ClassInfo classInfo;
/**
* True if the superclass of the mixin is <b>not</b> 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 {
/**
* The previous validation state to compare the changes to
*/
final ValidationState parent;
ReloadedState(ValidationState parent, byte[] mixinBytes) {
super(mixinBytes, parent.classInfo);
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");
}
if (!this.interfaces.equals(this.parent.interfaces)) {
throw new MixinReloadException(MixinInfo.this, "Cannot change interfaces");
}
if (!new HashSet<InterfaceInfo>(this.softImplements).equals(new HashSet<InterfaceInfo>(this.parent.softImplements))) {
throw new MixinReloadException(MixinInfo.this, "Cannot change soft interfaces");
}
List<ClassInfo> targets = MixinInfo.this.readTargetClasses(this.validationClassNode, true);
if (!new HashSet<ClassInfo>(targets).equals(new HashSet<ClassInfo>(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 +198,6 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 +217,26 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 final transient byte[] mixinBytes;
/**
* Configuration plugin
*/
private final transient IMixinConfigPlugin plugin;
/**
* All interfaces implemented by this mixin, including soft implementations
*/
private final transient Set<String> interfaces = new HashSet<String>();
/**
* Interfaces soft-implemented using {@link Implements}
* Holds state that currently is not fully initialised or validated
*/
private final transient List<InterfaceInfo> softImplements = new ArrayList<InterfaceInfo>();
private transient ValidationState uninitialisedState;
/**
* Synthetic inner classes
* Holds the current validated state
*/
private final transient Set<String> syntheticInnerClasses = new HashSet<String>();
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 <b>not</b> the direct superclass
* of one or more targets
*/
private boolean detachedSuper;
/**
* Internal ctor, called by {@link MixinConfig}
@@ -180,23 +257,33 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 +383,21 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Performs pre-flight checks on the mixin
*
* @param classNode
* @param state State 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 +417,10 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 +432,12 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 +446,13 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 +460,19 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
}
}
/**
* 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) {
return this.uninitialisedState;
}
return this.validationState;
}
ClassInfo getClassInfo() {
return this.classInfo;
return this.getCurrentState().classInfo;
}
/**
@@ -409,7 +511,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
*/
@Override
public String getClassRef() {
return this.classInfo.getName();
return this.getClassInfo().getName();
}
/**
@@ -417,7 +519,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
*/
@Override
public byte[] getClassBytes() {
return this.mixinBytes;
return this.getCurrentState().mixinBytes;
}
/**
@@ -426,7 +528,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
*/
@Override
public boolean isDetachedSuper() {
return this.detachedSuper;
return this.getCurrentState().detachedSuper;
}
/**
@@ -449,10 +551,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, 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 +566,14 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* Get the soft implementations for this mixin
*/
List<InterfaceInfo> getSoftImplements() {
return Collections.unmodifiableList(this.softImplements);
return Collections.unmodifiableList(this.getCurrentState().softImplements);
}
/**
* Get the synthetic inner classes for this mixin
*/
public Set<String> getSyntheticInnerClasses() {
return Collections.unmodifiableSet(this.syntheticInnerClasses);
return Collections.unmodifiableSet(this.getCurrentState().syntheticInnerClasses);
}
/**
@@ -498,7 +597,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* @return mixin interfaces
*/
public Set<String> getInterfaces() {
return this.interfaces;
return this.getCurrentState().interfaces;
}
/**
@@ -539,6 +638,19 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
return mixinBytes;
}
/**
* Updates this mixin with new bytecode
*
* @param mixinBytes New bytecode
*/
void reloadMixin(byte[] mixinBytes) {
if (this.uninitialisedState != null) {
throw new IllegalStateException("Cannot reload mixin while it is initialising");
}
this.uninitialisedState = new ReloadedState(this.validationState, mixinBytes);
this.validate();
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@@ -0,0 +1,44 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
/**
* 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;
}
}
@@ -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<? extends IHotSwap> clazz =
(Class<? extends IHotSwap>)Class.forName("org.spongepowered.tools.agent.MixinAgent");
Constructor<? extends IHotSwap> 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
*/
@@ -346,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;
}
@@ -397,14 +425,18 @@ 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) {
if (environment.getOption(Option.DUMP_TARGET_ON_FAILURE)) {
this.dumpClass(transformedName.replace('.', '/') + ".target", basicClass);
}
this.handleMixinErrorState(transformedName, th);
}
}
@@ -421,6 +453,24 @@ 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<String> reload(String mixinClass, byte[] bytes) {
if (this.lock.getDepth() > 0) {
throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered");
}
List<String> targets = new ArrayList<String>();
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 +531,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 +555,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);
}
@@ -0,0 +1,51 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer.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
*/
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);
}