From 8f9b6148a1f2d185e5b8244edb8cbd9971f6eae7 Mon Sep 17 00:00:00 2001
From: bloodmc
Date: Tue, 15 Sep 2015 14:35:19 -0400
Subject: [PATCH 001/169] Add new INIT phase to handle FML deobf transformer.
---
gradle.properties | 2 +-
.../asm/launch/MixinBootstrap.java | 2 +-
.../asm/mixin/MixinEnvironment.java | 48 ++++++++++++++++++-
3 files changed, 49 insertions(+), 3 deletions(-)
diff --git a/gradle.properties b/gradle.properties
index 53acb410..a8b235bd 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -4,5 +4,5 @@ packaging=jar
description=Mixin
url=https://www.spongepowered.org
organization=SpongePowered
-buildVersion=0.4.5
+buildVersion=0.4.6
buildType=SNAPSHOT
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java
index 8aa58ebd..e48bcec4 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java
@@ -60,7 +60,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
- public static final String VERSION = "0.4.5";
+ public static final String VERSION = "0.4.6";
/**
* Blackboard key where the subsystem version will be stored to indicate
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index f9f3466f..57a43040 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin;
import java.io.File;
+import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
@@ -35,9 +36,14 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.helpers.Booleans;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
@@ -76,16 +82,22 @@ public class MixinEnvironment implements ITokenProvider {
*/
public static final Phase PREINIT = new Phase(0, "PREINIT");
+ /**
+ * "Initialisation" phase, after FML's deobf transformer has loaded
+ */
+ public static final Phase INIT = new Phase(1, "INIT");
+
/**
* "Default" phase, during runtime
*/
- public static final Phase DEFAULT = new Phase(1, "DEFAULT");
+ public static final Phase DEFAULT = new Phase(2, "DEFAULT");
/**
* All phases
*/
static final List phases = ImmutableList.of(
Phase.PREINIT,
+ Phase.INIT,
Phase.DEFAULT
);
@@ -392,6 +404,33 @@ public class MixinEnvironment implements ITokenProvider {
}
+ static class MixinLogger {
+
+ static MixinAppender appender = new MixinAppender("MixinLogger", null, null);
+
+ public MixinLogger() {
+ org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
+ log.addAppender(appender);
+ }
+
+ static class MixinAppender extends AbstractAppender {
+
+ protected MixinAppender(String name, Filter filter, Layout extends Serializable> layout) {
+ super(name, filter, layout);
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void append(LogEvent event) {
+ if (event.getLevel() == Level.DEBUG && "Validating minecraft".equals(event.getMessage().getFormat())) {
+ // transition to INIT
+ MixinEnvironment.gotoPhase(Phase.INIT);
+ }
+ }
+
+ }
+ }
+
/**
* Known re-entrant transformers, other re-entrant transformers will
* detected automatically
@@ -861,6 +900,7 @@ public class MixinEnvironment implements ITokenProvider {
if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) {
MixinEnvironment.currentPhase = phase;
MixinEnvironment.getEnvironment(phase);
+ new MixinLogger();
}
}
@@ -913,6 +953,12 @@ public class MixinEnvironment implements ITokenProvider {
MixinBootstrap.addProxy();
}
+ if (phase == Phase.DEFAULT) {
+ // remove appender
+ org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
+ log.removeAppender(MixinLogger.appender);
+ }
+
MixinEnvironment.currentPhase = phase;
MixinEnvironment.currentEnvironment = MixinEnvironment.getEnvironment(MixinEnvironment.getCurrentPhase());
}
From bdda81fb265a56ab0262e9b71fd87f7f7441becb Mon Sep 17 00:00:00 2001
From: Chris Sanders
Date: Tue, 15 Sep 2015 21:20:21 -0500
Subject: [PATCH 002/169] Perform nasty filter switch to gurarantee that we'll
switch into INIT.
While @bloodmc 's changes did fix dev and prod time, it doesn't work with
the IVY launcher built into the Sponge mod. This works around it by
manipulating logger levels and adding a filter to hide what we are doing.
@Mumfrey you'll definately want to get rid of this ASAP...
Signed-off-by: Chris Sanders
---
.../asm/mixin/MixinEnvironment.java | 112 ++++++++++++------
.../mixin/transformer/MixinTransformer.java | 4 +-
2 files changed, 79 insertions(+), 37 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index 57a43040..20e97f33 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -24,40 +24,39 @@
*/
package org.spongepowered.asm.mixin;
-import java.io.File;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Sets;
+import net.minecraft.launchwrapper.IClassNameTransformer;
+import net.minecraft.launchwrapper.IClassTransformer;
+import net.minecraft.launchwrapper.ITweaker;
+import net.minecraft.launchwrapper.Launch;
+import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.helpers.Booleans;
+import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.Filter;
-import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.filter.AbstractFilter;
+import org.apache.logging.log4j.core.helpers.Booleans;
+import org.apache.logging.log4j.message.Message;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.PrettyPrinter;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
-
-import net.minecraft.launchwrapper.IClassNameTransformer;
-import net.minecraft.launchwrapper.IClassTransformer;
-import net.minecraft.launchwrapper.ITweaker;
-import net.minecraft.launchwrapper.Launch;
-import net.minecraft.launchwrapper.LaunchClassLoader;
+import java.io.File;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
/**
@@ -406,28 +405,61 @@ public class MixinEnvironment implements ITokenProvider {
static class MixinLogger {
- static MixinAppender appender = new MixinAppender("MixinLogger", null, null);
+ static MixinFilter filter = new MixinFilter();
public MixinLogger() {
+ // Prep ugly hack for INIT phase
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
- log.addAppender(appender);
+ log.addFilter(filter);
+ // Set the level to DEBUG for FML logger. We don't need to check for obfuscation as it would be debug anyways in DEV
+ log.setLevel(Level.DEBUG);
}
- static class MixinAppender extends AbstractAppender {
+ // Commence ugly hack for INIT phase
+ static class MixinFilter extends AbstractFilter {
- protected MixinAppender(String name, Filter filter, Layout extends Serializable> layout) {
- super(name, filter, layout);
- // TODO Auto-generated constructor stub
+ @Override
+ public Result filter(final org.apache.logging.log4j.core.Logger logger, final Level level, final Marker marker, final String msg,
+ final Object... params) {
+ if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(msg)) {
+ MixinEnvironment.gotoPhase(Phase.INIT);
+ }
+ // Log entries can be filtered before the blackboard has this value. We'll just look it up.
+ Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return filter != null && filter ? Result.NEUTRAL : Result.DENY;
}
@Override
- public void append(LogEvent event) {
- if (event.getLevel() == Level.DEBUG && "Validating minecraft".equals(event.getMessage().getFormat())) {
- // transition to INIT
+ public Result filter(final org.apache.logging.log4j.core.Logger logger, final Level level, final Marker marker, final Object msg,
+ final Throwable t) {
+ if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(msg)) {
MixinEnvironment.gotoPhase(Phase.INIT);
}
+ // Log entries can be filtered before the blackboard has this value. We'll just look it up.
+ Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return filter != null && filter ? Result.NEUTRAL : Result.DENY;
+ }
+
+ @Override
+ public Result filter(final org.apache.logging.log4j.core.Logger logger, final Level level, final Marker marker, final Message msg,
+ final Throwable t) {
+ if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(msg.getFormattedMessage())) {
+ MixinEnvironment.gotoPhase(Phase.INIT);
+ }
+ // Log entries can be filtered before the blackboard has this value. We'll just look it up.
+ Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return filter != null && filter ? Result.NEUTRAL : Result.DENY;
+ }
+
+ @Override
+ public Result filter(final LogEvent event) {
+ if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(event.getMessage().getFormattedMessage())) {
+ MixinEnvironment.gotoPhase(Phase.INIT);
+ }
+ // Log entries can be filtered before the blackboard has this value. We'll just look it up.
+ Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return filter != null && filter ? Result.NEUTRAL : Result.DENY;
}
-
}
}
@@ -954,9 +986,19 @@ public class MixinEnvironment implements ITokenProvider {
}
if (phase == Phase.DEFAULT) {
- // remove appender
+ // Remove filter
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
- log.removeAppender(MixinLogger.appender);
+ for (Iterator iter = log.getFilters(); iter.hasNext();) {
+ final Filter filter = iter.next();
+ if (filter instanceof MixinLogger.MixinFilter) {
+ // If FML isn't in obfuscated environment, we need to hotswap the log level back
+ if (!(Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) {
+ log.setLevel(Level.INFO);
+ }
+ iter.remove();
+ break;
+ }
+ }
}
MixinEnvironment.currentPhase = phase;
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 adcc3004..4c5325c7 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
@@ -354,7 +354,7 @@ public class MixinTransformer extends TreeTransformer {
boolean locked = this.lock.push().isSet();
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
-
+
if (this.currentEnvironment != environment && !locked) {
try {
this.init(environment);
@@ -363,7 +363,7 @@ public class MixinTransformer extends TreeTransformer {
throw new RuntimeException(ex);
}
}
-
+
try {
SortedSet mixins = null;
boolean invalidRef = false;
From d12d3f271c9a499897bb8f1d5f01ca74b8e7ae3d Mon Sep 17 00:00:00 2001
From: Chris Sanders
Date: Thu, 17 Sep 2015 15:50:55 -0500
Subject: [PATCH 003/169] Always check isFMLDeobfuscated for null status.
Signed-off-by: Chris Sanders
---
.../asm/mixin/MixinEnvironment.java | 26 +++++++++++--------
1 file changed, 15 insertions(+), 11 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index 20e97f33..b0550d23 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -411,8 +411,11 @@ public class MixinEnvironment implements ITokenProvider {
// Prep ugly hack for INIT phase
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
log.addFilter(filter);
- // Set the level to DEBUG for FML logger. We don't need to check for obfuscation as it would be debug anyways in DEV
- log.setLevel(Level.DEBUG);
+ final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ if (isFMLDeobfuscated != null && !isFMLDeobfuscated) {
+ // Set the level to DEBUG for FML logger. We don't need to check for obfuscation as it would be debug anyways in DEV
+ log.setLevel(Level.DEBUG);
+ }
}
// Commence ugly hack for INIT phase
@@ -425,8 +428,8 @@ public class MixinEnvironment implements ITokenProvider {
MixinEnvironment.gotoPhase(Phase.INIT);
}
// Log entries can be filtered before the blackboard has this value. We'll just look it up.
- Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return filter != null && filter ? Result.NEUTRAL : Result.DENY;
+ final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
}
@Override
@@ -436,8 +439,8 @@ public class MixinEnvironment implements ITokenProvider {
MixinEnvironment.gotoPhase(Phase.INIT);
}
// Log entries can be filtered before the blackboard has this value. We'll just look it up.
- Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return filter != null && filter ? Result.NEUTRAL : Result.DENY;
+ final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
}
@Override
@@ -447,8 +450,8 @@ public class MixinEnvironment implements ITokenProvider {
MixinEnvironment.gotoPhase(Phase.INIT);
}
// Log entries can be filtered before the blackboard has this value. We'll just look it up.
- Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return filter != null && filter ? Result.NEUTRAL : Result.DENY;
+ final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
}
@Override
@@ -457,8 +460,8 @@ public class MixinEnvironment implements ITokenProvider {
MixinEnvironment.gotoPhase(Phase.INIT);
}
// Log entries can be filtered before the blackboard has this value. We'll just look it up.
- Boolean filter = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return filter != null && filter ? Result.NEUTRAL : Result.DENY;
+ final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
+ return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
}
}
}
@@ -991,8 +994,9 @@ public class MixinEnvironment implements ITokenProvider {
for (Iterator iter = log.getFilters(); iter.hasNext();) {
final Filter filter = iter.next();
if (filter instanceof MixinLogger.MixinFilter) {
+ final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
// If FML isn't in obfuscated environment, we need to hotswap the log level back
- if (!(Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) {
+ if (isFMLDeobfuscated != null && !isFMLDeobfuscated) {
log.setLevel(Level.INFO);
}
iter.remove();
From f3c4945019c0725b02df085ff745ffd3fd0b38e9 Mon Sep 17 00:00:00 2001
From: Chris Sanders
Date: Sun, 27 Sep 2015 20:16:44 -0500
Subject: [PATCH 004/169] Set debug regardless. This happens before FML sets
deobfuscation.
Signed-off-by: Chris Sanders
---
.../java/org/spongepowered/asm/mixin/MixinEnvironment.java | 6 +-----
1 file changed, 1 insertion(+), 5 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index b0550d23..ea2f47b3 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -411,11 +411,7 @@ public class MixinEnvironment implements ITokenProvider {
// Prep ugly hack for INIT phase
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
log.addFilter(filter);
- final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- if (isFMLDeobfuscated != null && !isFMLDeobfuscated) {
- // Set the level to DEBUG for FML logger. We don't need to check for obfuscation as it would be debug anyways in DEV
- log.setLevel(Level.DEBUG);
- }
+ log.setLevel(Level.DEBUG);
}
// Commence ugly hack for INIT phase
From b3de136706969bdc09ff340b5ecec4415b055d72 Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Sat, 10 Oct 2015 11:26:55 +1300
Subject: [PATCH 005/169] Added support for lambda expressions inside mixins
To support lambda expression the mixin transformer will transform invoke dynamic instructions in the same way as it transforms other invoke instructions as well as transforming their static arguments. Invoke dynamic static arguments can be any constant loadable by ldc instructions and this includes MethodHandles, so it transforms the MethodHandle as if it was a normal invoke instruction.
Note any mixin class that has an invokedynamic instruction in it will now have the target class, class file version set to 52(java 8).
---
.../mixin/transformer/MixinTargetContext.java | 374 ++++++++++++++----
1 file changed, 307 insertions(+), 67 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index a5316fa5..e3cc886d 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -32,16 +32,10 @@ import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.Level;
+import org.spongepowered.asm.lib.Handle;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
-import org.spongepowered.asm.lib.tree.AbstractInsnNode;
-import org.spongepowered.asm.lib.tree.ClassNode;
-import org.spongepowered.asm.lib.tree.FieldInsnNode;
-import org.spongepowered.asm.lib.tree.FieldNode;
-import org.spongepowered.asm.lib.tree.LdcInsnNode;
-import org.spongepowered.asm.lib.tree.MethodInsnNode;
-import org.spongepowered.asm.lib.tree.MethodNode;
-import org.spongepowered.asm.lib.tree.TypeInsnNode;
+import org.spongepowered.asm.lib.tree.*;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.injection.struct.Target;
@@ -237,13 +231,15 @@ public class MixinTargetContext implements IReferenceMapperContext {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
- this.transformMethodNode(method, iter, (MethodInsnNode)insn);
+ this.transformMethodRef(method, iter, new StaticMethodRef((MethodInsnNode)insn));
} else if (insn instanceof FieldInsnNode) {
- this.transformFieldNode(method, iter, (FieldInsnNode)insn);
+ this.transformFieldRef(method, iter, new StaticFieldRef((FieldInsnNode)insn));
} else if (insn instanceof TypeInsnNode) {
this.transformTypeNode(method, iter, (TypeInsnNode)insn);
} else if (insn instanceof LdcInsnNode) {
this.transformConstantNode(method, iter, (LdcInsnNode)insn);
+ } else if (insn instanceof InvokeDynamicInsnNode) {
+ this.transformInvokeDynamicNode(method, iter, (InvokeDynamicInsnNode)insn);
}
}
}
@@ -266,51 +262,56 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
- * Transforms method invocations in the method. Updates static and dynamic
- * bindings.
+ * Transforms a method invocation/reference in the method. Updates static
+ * and dynamic bindings.
*
* @param method Method being processed
* @param iter Insn interator
- * @param methodInsn Insn to transform
+ * @param methodRef Method reference to transform
*/
- private void transformMethodNode(MethodNode method, Iterator iter, MethodInsnNode methodInsn) {
- this.transformDescriptor(methodInsn);
+ private void transformMethodRef(MethodNode method, Iterator iter, MemberRef methodRef) {
+ this.transformDescriptor(methodRef);
- if (methodInsn.owner.equals(this.getClassRef())) {
- methodInsn.owner = this.targetClass.name;
+ if (methodRef.getOwner().equals(this.getClassRef())) {
+ methodRef.setOwner(this.targetClass.name);
} else if ((this.detachedSuper || this.inheritsFromMixin)) {
- if (methodInsn.getOpcode() == Opcodes.INVOKESPECIAL) {
- this.updateStaticBinding(method, methodInsn);
- } else if (methodInsn.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodInsn.owner).isMixin()) {
- this.updateDynamicBinding(method, methodInsn);
+ if (methodRef.getOpcode() == Opcodes.INVOKESPECIAL) {
+ this.updateStaticBinding(method, methodRef);
+ } else if (methodRef.getOpcode() == Opcodes.INVOKEVIRTUAL && ClassInfo.forName(methodRef.getOwner()).isMixin()) {
+ this.updateDynamicBinding(method, methodRef);
}
}
}
/**
- * Transforms field accesses in the method. Handles imaginary super accesses
- * and converts them to real super-invocations and rewrites field accesses
- * which refer to mixin or supermixin classes to their relevant targets.
+ * Transforms field access/reference in the method. Handles imaginary super
+ * accesses and converts them to real super-invocations and rewrites field
+ * accesses which refer to mixin or supermixin classes to their relevant
+ * targets.
*
* @param method Method being processed
* @param iter Insn interator
- * @param fieldInsn Insn to transform
+ * @param fieldRef Field Reference to transform
*/
- private void transformFieldNode(MethodNode method, Iterator iter, FieldInsnNode fieldInsn) {
- if (Constants.IMAGINARY_SUPER.equals(fieldInsn.name)) {
- this.processImaginarySuper(method, fieldInsn);
- iter.remove();
+ private void transformFieldRef(MethodNode method, Iterator iter, MemberRef fieldRef) {
+ if (Constants.IMAGINARY_SUPER.equals(fieldRef.getName())) {
+ if (fieldRef instanceof StaticFieldRef) {
+ this.processImaginarySuper(method, ((StaticFieldRef) fieldRef).insn);
+ iter.remove();
+ } else {
+ throw new InvalidMixinException(this.mixin, "Cannot call imaginary super from method handle.");
+ }
}
- this.transformDescriptor(fieldInsn);
+ this.transformDescriptor(fieldRef);
- if (fieldInsn.owner.equals(this.getClassRef())) {
- fieldInsn.owner = this.targetClass.name;
+ if (fieldRef.getOwner().equals(this.getClassRef())) {
+ fieldRef.setOwner(this.targetClass.name);
} else {
- ClassInfo fieldOwner = ClassInfo.forName(fieldInsn.owner);
+ ClassInfo fieldOwner = ClassInfo.forName(fieldRef.getOwner());
if (fieldOwner.isMixin()) {
ClassInfo actualOwner = this.targetClassInfo.findCorrespondingType(fieldOwner);
- fieldInsn.owner = actualOwner != null ? actualOwner.getName() : this.targetClass.name;
+ fieldRef.setOwner(actualOwner != null ? actualOwner.getName() : this.targetClass.name);
}
}
}
@@ -342,13 +343,250 @@ public class MixinTargetContext implements IReferenceMapperContext {
private void transformConstantNode(MethodNode method, Iterator iter, LdcInsnNode ldcInsn) {
if (ldcInsn.cst instanceof Type) {
Type type = (Type)ldcInsn.cst;
- String desc = this.transformSingleDescriptor(type);
+ String desc = this.transformDescriptor(type);
if (!type.toString().equals(desc)) {
ldcInsn.cst = Type.getType(desc);
}
}
}
+ /**
+ * Transforms a invoke dynamic instruction in the method being processed.
+ *
+ * @param method Method being processed
+ * @param iter Insn interator
+ * @param dynInsn Insn to transform
+ */
+ private void transformInvokeDynamicNode(MethodNode method, Iterator iter, InvokeDynamicInsnNode dynInsn) {
+ System.out.println(targetClass.version);
+ targetClass.version = 52;
+ dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc);
+ dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm);
+ for (int i = 0; i < dynInsn.bsmArgs.length; i++) {
+ Object bsmArg = dynInsn.bsmArgs[i];
+ if (bsmArg instanceof Handle) {
+ dynInsn.bsmArgs[i] = this.transformHandle(method, iter, ((Handle) bsmArg));
+ } else if (bsmArg instanceof Type) {
+ Type type = ((Type) bsmArg);
+ String desc = this.transformDescriptor(type);
+ if (!type.toString().equals(desc)) {
+ dynInsn.bsmArgs[i] = Type.getType(desc);
+ }
+ }
+ }
+ }
+
+ /**
+ * Transforms a method handle that is referenced from the method being
+ * processed.
+ *
+ * @param handle Handle to transform
+ */
+ private Handle transformHandle(MethodNode method, Iterator iter, Handle handle) {
+ HandleRef memberRef = new HandleRef(handle);
+ if (memberRef.isField()) {
+ this.transformFieldRef(method, iter, memberRef);
+ } else {
+ this.transformMethodRef(method, iter, memberRef);
+ }
+ return memberRef.handle;
+ }
+
+ /**
+ * Reference to a field or method that also includes invocation
+ * instructions.
+ */
+ private abstract class MemberRef {
+ abstract boolean isField();
+
+ abstract int getOpcode();
+
+ abstract String getOwner();
+
+ abstract void setOwner(String owner);
+
+ abstract String getName();
+
+ abstract String getDesc();
+
+ abstract void setDesc(String desc);
+ }
+
+ /**
+ * A static reference to a method backed by an invoke instruction
+ */
+ private final class StaticMethodRef extends MemberRef {
+
+ private final MethodInsnNode insn;
+
+ private StaticMethodRef(MethodInsnNode insn) {
+ this.insn = insn;
+ }
+
+ @Override
+ boolean isField() {
+ return false;
+ }
+
+ @Override
+ int getOpcode() {
+ return this.insn.getOpcode();
+ }
+
+ @Override
+ String getOwner() {
+ return this.insn.owner;
+ }
+
+ @Override
+ void setOwner(String owner) {
+ this.insn.owner = owner;
+ }
+
+ @Override
+ String getName() {
+ return this.insn.name;
+ }
+
+ @Override
+ String getDesc() {
+ return this.insn.desc;
+ }
+
+ @Override
+ void setDesc(String desc) {
+ this.insn.desc = desc;
+ }
+ }
+
+ /**
+ * A static reference to a field backed by field get/put instruction
+ */
+ private final class StaticFieldRef extends MemberRef {
+
+ private final FieldInsnNode insn;
+
+ private StaticFieldRef(FieldInsnNode insn) {
+ this.insn = insn;
+ }
+
+ @Override
+ boolean isField() {
+ return true;
+ }
+
+ @Override
+ int getOpcode() {
+ return this.insn.getOpcode();
+ }
+
+ @Override
+ String getOwner() {
+ return this.insn.owner;
+ }
+
+ @Override
+ void setOwner(String owner) {
+ this.insn.owner = owner;
+ }
+
+ @Override
+ String getName() {
+ return this.insn.name;
+ }
+
+ @Override
+ String getDesc() {
+ return this.insn.desc;
+ }
+
+ @Override
+ void setDesc(String desc) {
+ this.insn.desc = desc;
+ }
+ }
+
+ /**
+ * A reference to a field or method backed by a method handle
+ */
+ private final class HandleRef extends MemberRef {
+
+ private Handle handle;
+
+ private HandleRef(Handle handle) {
+ this.handle = handle;
+ }
+
+ @Override
+ boolean isField() {
+ switch (this.handle.getTag()) {
+ case Opcodes.H_INVOKEVIRTUAL:
+ case Opcodes.H_INVOKESTATIC:
+ case Opcodes.H_INVOKEINTERFACE:
+ case Opcodes.H_INVOKESPECIAL:
+ case Opcodes.H_NEWINVOKESPECIAL:
+ return false;
+ case Opcodes.H_GETFIELD:
+ case Opcodes.H_GETSTATIC:
+ case Opcodes.H_PUTFIELD:
+ case Opcodes.H_PUTSTATIC:
+ return true;
+ default:
+ throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
+ }
+ }
+
+ @Override
+ int getOpcode() {
+ switch (this.handle.getTag()) {
+ case Opcodes.H_INVOKEVIRTUAL:
+ return Opcodes.INVOKEVIRTUAL;
+ case Opcodes.H_INVOKESTATIC:
+ return Opcodes.INVOKESTATIC;
+ case Opcodes.H_INVOKEINTERFACE:
+ return Opcodes.INVOKEINTERFACE;
+ case Opcodes.H_INVOKESPECIAL:
+ case Opcodes.H_NEWINVOKESPECIAL:
+ return Opcodes.INVOKESPECIAL;
+ case Opcodes.H_GETFIELD:
+ return Opcodes.GETFIELD;
+ case Opcodes.H_GETSTATIC:
+ return Opcodes.GETSTATIC;
+ case Opcodes.H_PUTFIELD:
+ return Opcodes.PUTFIELD;
+ case Opcodes.H_PUTSTATIC:
+ return Opcodes.PUTSTATIC;
+ default:
+ throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
+ }
+ }
+
+ @Override
+ String getOwner() {
+ return this.handle.getOwner();
+ }
+
+ @Override
+ void setOwner(String owner) {
+ this.handle = new Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc());
+ }
+
+ @Override
+ String getName() {
+ return this.handle.getName();
+ }
+
+ @Override
+ String getDesc() {
+ return this.handle.getDesc();
+ }
+
+ @Override
+ void setDesc(String desc) {
+ this.handle = new Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
+ }
+ }
+
/**
* Handle "imaginary super" invokations, these are invokations in
* non-derived mixins for accessing methods known to exist in a supermixin
@@ -388,7 +626,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
MethodInsnNode methodNode = (MethodInsnNode)insn;
if (methodNode.owner.equals(this.getClassRef()) && methodNode.name.equals(method.name) && methodNode.desc.equals(method.desc)) {
methodNode.setOpcode(Opcodes.INVOKESPECIAL);
- this.updateStaticBinding(method, methodNode);
+ this.updateStaticBinding(method, new StaticMethodRef(methodNode));
return;
}
}
@@ -402,10 +640,10 @@ public class MixinTargetContext implements IReferenceMapperContext {
* which contains the specified method.
*
* @param method Method containing the instruction
- * @param insn INVOKE instruction node
+ * @param methodRef Unbound reference to the method
*/
- private void updateStaticBinding(MethodNode method, MethodInsnNode insn) {
- this.updateBinding(method, insn, Traversal.SUPER);
+ private void updateStaticBinding(MethodNode method, MemberRef methodRef) {
+ this.updateBinding(method, methodRef, Traversal.SUPER);
}
/**
@@ -413,27 +651,28 @@ public class MixinTargetContext implements IReferenceMapperContext {
* which contains the specified method.
*
* @param method Method containing the instruction
- * @param insn INVOKE instruction node
+ * @param methodRef Unbound reference to the method
*/
- private void updateDynamicBinding(MethodNode method, MethodInsnNode insn) {
- this.updateBinding(method, insn, Traversal.ALL);
+ private void updateDynamicBinding(MethodNode method, MemberRef methodRef) {
+ this.updateBinding(method, methodRef, Traversal.ALL);
}
- private void updateBinding(MethodNode method, MethodInsnNode insn, Traversal traversal) {
- if (Constants.INIT.equals(method.name) || insn.owner.equals(this.targetClass.name) || this.targetClass.name.startsWith("<")) {
+ private void updateBinding(MethodNode method, MemberRef methodRef, Traversal traversal) {
+ if (Constants.INIT.equals(method.name) || methodRef.getOwner().equals(this.targetClass.name) || this.targetClass.name.startsWith("<")) {
return;
}
- Method superMethod = this.targetClassInfo.findMethodInHierarchy(insn.name, insn.desc, traversal == Traversal.ALL, traversal);
+ Method superMethod = this.targetClassInfo.findMethodInHierarchy(methodRef.getName(), methodRef.getDesc(), traversal == Traversal.ALL,
+ traversal);
if (superMethod != null) {
if (superMethod.getOwner().isMixin()) {
- throw new InvalidMixinException(this, "Invalid " + ASMHelper.getOpcodeName(insn) + " in " + this + " resolved " + insn.owner
- + " -> " + superMethod.getOwner() + " for " + insn.name + insn.desc);
+ throw new InvalidMixinException(this, "Invalid " + ASMHelper.getOpcodeName(methodRef.getOpcode()) + " in " + this + " resolved "
+ + methodRef.getOwner() + " -> " + superMethod.getOwner() + " for " + methodRef.getName() + methodRef.getDesc());
}
- insn.owner = superMethod.getOwner().getName();
- } else if (ClassInfo.forName(insn.owner).isMixin()) {
- throw new MixinTransformerError("Error resolving " + ASMHelper.getOpcodeName(insn) + " target for " + insn.owner + "." + insn.name
- + " in " + this);
+ methodRef.setOwner(superMethod.getOwner().getName());
+ } else if (ClassInfo.forName(methodRef.getOwner()).isMixin()) {
+ throw new MixinTransformerError("Error resolving " + ASMHelper.getOpcodeName(methodRef.getOpcode()) + " target for "
+ + methodRef.getOwner() + "." + methodRef.getName() + " in " + this);
}
}
@@ -449,18 +688,6 @@ public class MixinTargetContext implements IReferenceMapperContext {
field.desc = this.transformSingleDescriptor(field.desc, false);
}
- /**
- * Transforms a field insn descriptor in the context of this mixin target
- *
- * @param field Field instruction node to transform
- */
- public void transformDescriptor(FieldInsnNode field) {
- if (!this.inheritsFromMixin) {
- return;
- }
- field.desc = this.transformSingleDescriptor(field.desc, false);
- }
-
/**
* Transforms a method descriptor in the context of this mixin target
*
@@ -474,15 +701,20 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
- * Transforms a method insn descriptor in the context of this mixin target
+ * Transforms a method or field reference descriptor in the context of this
+ * mixin target
*
- * @param method Method instruction node to transform
+ * @param member Reference to the method or field
*/
- public void transformDescriptor(MethodInsnNode method) {
+ public void transformDescriptor(MemberRef member) {
if (!this.inheritsFromMixin) {
return;
}
- method.desc = this.transformMethodDescriptor(method.desc);
+ if (member.isField()) {
+ member.setDesc(this.transformSingleDescriptor(member.getDesc(), false));
+ } else {
+ member.setDesc(this.transformMethodDescriptor(member.getDesc()));
+ }
}
/**
@@ -496,6 +728,14 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
typeInsn.desc = this.transformSingleDescriptor(typeInsn.desc, true);
}
+
+ private String transformDescriptor(Type type) {
+ if (type.getSort() == Type.METHOD) {
+ return this.transformMethodDescriptor(type.getDescriptor());
+ } else {
+ return this.transformSingleDescriptor(type);
+ }
+ }
private String transformSingleDescriptor(Type type) {
if (type.getSort() < Type.ARRAY) {
From 9ab0dfc3df7dbb4e83745dd1ba9eac3f46ad74ea Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Sat, 10 Oct 2015 13:05:47 +1300
Subject: [PATCH 006/169] Removed debug statement
---
.../spongepowered/asm/mixin/transformer/MixinTargetContext.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index e3cc886d..f31d76d9 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -358,7 +358,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param dynInsn Insn to transform
*/
private void transformInvokeDynamicNode(MethodNode method, Iterator iter, InvokeDynamicInsnNode dynInsn) {
- System.out.println(targetClass.version);
+ // set class version to java 8
targetClass.version = 52;
dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc);
dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm);
From e51a2dd28830a9068b2f30531873975bc8d73452 Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Sun, 11 Oct 2015 10:43:57 +1300
Subject: [PATCH 007/169] Fixed style issues and refactored
transformConstantNode
The refactor is to get rid of code duplication between load constant
transform method and handling of invokedynamic arguments.
---
.../asm/mixin/transformer/MemberRef.java | 321 ++++++++++++++++++
.../mixin/transformer/MixinTargetContext.java | 271 +++------------
.../org/spongepowered/asm/util/Constants.java | 1 +
3 files changed, 364 insertions(+), 229 deletions(-)
create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java
new file mode 100644
index 00000000..570f39d7
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java
@@ -0,0 +1,321 @@
+/*
+ * This file is part of Mixin, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) SpongePowered
+ * Copyright (c) contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.spongepowered.asm.mixin.transformer;
+
+import org.spongepowered.asm.lib.Handle;
+import org.spongepowered.asm.lib.Opcodes;
+import org.spongepowered.asm.lib.tree.FieldInsnNode;
+import org.spongepowered.asm.lib.tree.MethodInsnNode;
+import org.spongepowered.asm.util.ASMHelper;
+
+/**
+ * Reference to a field or method that also includes invocation
+ * instructions.
+ *
+ * To instances are defined to be equal if they both refer to the same method
+ * and have the same invocation instructions.
+ */
+public abstract class MemberRef {
+
+ /**
+ * A static reference to a method backed by an invoke instruction
+ */
+ public static final class StaticMethodRef extends MemberRef {
+
+ /**
+ * Method invocation instruction
+ */
+ public final MethodInsnNode insn;
+
+ /**
+ * ctor
+ *
+ * @param insn Method instruction of this member reference
+ */
+ public StaticMethodRef(MethodInsnNode insn) {
+ this.insn = insn;
+ }
+
+ @Override
+ public boolean isField() {
+ return false;
+ }
+
+ @Override
+ public int getOpcode() {
+ return this.insn.getOpcode();
+ }
+
+ @Override
+ public String getOwner() {
+ return this.insn.owner;
+ }
+
+ @Override
+ public void setOwner(String owner) {
+ this.insn.owner = owner;
+ }
+
+ @Override
+ public String getName() {
+ return this.insn.name;
+ }
+
+ @Override
+ public String getDesc() {
+ return this.insn.desc;
+ }
+
+ @Override
+ public void setDesc(String desc) {
+ this.insn.desc = desc;
+ }
+ }
+
+ /**
+ * A static reference to a field backed by field get/put instruction
+ */
+ public static final class StaticFieldRef extends MemberRef {
+
+ /**
+ * Field accessor instruction
+ */
+ public final FieldInsnNode insn;
+
+ /**
+ * ctor
+ *
+ * @param insn Field instruction this member reference
+ */
+ public StaticFieldRef(FieldInsnNode insn) {
+ this.insn = insn;
+ }
+
+ @Override
+ public boolean isField() {
+ return true;
+ }
+
+ @Override
+ public int getOpcode() {
+ return this.insn.getOpcode();
+ }
+
+ @Override
+ public String getOwner() {
+ return this.insn.owner;
+ }
+
+ @Override
+ public void setOwner(String owner) {
+ this.insn.owner = owner;
+ }
+
+ @Override
+ public String getName() {
+ return this.insn.name;
+ }
+
+ @Override
+ public String getDesc() {
+ return this.insn.desc;
+ }
+
+ @Override
+ public void setDesc(String desc) {
+ this.insn.desc = desc;
+ }
+ }
+
+ /**
+ * A reference to a field or method backed by a method handle
+ */
+ public static final class HandleRef extends MemberRef {
+
+ private Handle handle;
+
+ /**
+ * Creates a member reference initially referring to the member referred
+ * to by the method handle and the invocation instruction of the method
+ * handle.
+ *
+ * @param handle Initial method handle.
+ */
+ public HandleRef(Handle handle) {
+ this.handle = handle;
+ }
+
+ /**
+ * Gets a method handle for the member this is object is referring to.
+ *
+ * @return Method handle representing this object
+ */
+ public Handle getMethodHandle() {
+ return this.handle;
+ }
+
+ @Override
+ public boolean isField() {
+ switch (this.handle.getTag()) {
+ case Opcodes.H_INVOKEVIRTUAL:
+ case Opcodes.H_INVOKESTATIC:
+ case Opcodes.H_INVOKEINTERFACE:
+ case Opcodes.H_INVOKESPECIAL:
+ case Opcodes.H_NEWINVOKESPECIAL:
+ return false;
+ case Opcodes.H_GETFIELD:
+ case Opcodes.H_GETSTATIC:
+ case Opcodes.H_PUTFIELD:
+ case Opcodes.H_PUTSTATIC:
+ return true;
+ default:
+ throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
+ }
+ }
+
+ @Override
+ public int getOpcode() {
+ switch (this.handle.getTag()) {
+ case Opcodes.H_INVOKEVIRTUAL:
+ return Opcodes.INVOKEVIRTUAL;
+ case Opcodes.H_INVOKESTATIC:
+ return Opcodes.INVOKESTATIC;
+ case Opcodes.H_INVOKEINTERFACE:
+ return Opcodes.INVOKEINTERFACE;
+ case Opcodes.H_INVOKESPECIAL:
+ case Opcodes.H_NEWINVOKESPECIAL:
+ return Opcodes.INVOKESPECIAL;
+ case Opcodes.H_GETFIELD:
+ return Opcodes.GETFIELD;
+ case Opcodes.H_GETSTATIC:
+ return Opcodes.GETSTATIC;
+ case Opcodes.H_PUTFIELD:
+ return Opcodes.PUTFIELD;
+ case Opcodes.H_PUTSTATIC:
+ return Opcodes.PUTSTATIC;
+ default:
+ throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
+ }
+ }
+
+ @Override
+ public String getOwner() {
+ return this.handle.getOwner();
+ }
+
+ @Override
+ public void setOwner(String owner) {
+ this.handle = new Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc());
+ }
+
+ @Override
+ public String getName() {
+ return this.handle.getName();
+ }
+
+ @Override
+ public String getDesc() {
+ return this.handle.getDesc();
+ }
+
+ @Override
+ public void setDesc(String desc) {
+ this.handle = new Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
+ }
+ }
+
+ /**
+ * Whether this member is a field.
+ *
+ * @return If this member is a field, else it is a method
+ */
+ public abstract boolean isField();
+
+ /**
+ * The opcode of the invocation.
+ *
+ * @return The opcode of the invocation
+ */
+ public abstract int getOpcode();
+
+ /**
+ * The internal name for the owner of this member.
+ *
+ * @return The owners name
+ */
+ public abstract String getOwner();
+
+ /**
+ * Changes the owner of this
+ *
+ * @param owner New owner
+ */
+ public abstract void setOwner(String owner);
+
+ /**
+ * Name of this member.
+ *
+ * @return Name of this member.
+ */
+ public abstract String getName();
+
+ /**
+ * Descriptor of this member.
+ *
+ * @return Descriptor of this member
+ */
+ public abstract String getDesc();
+
+ /**
+ * Changes the descriptor of this member
+ *
+ * @param desc New descriptor of this member
+ */
+ public abstract void setDesc(String desc);
+
+ @Override
+ public String toString() {
+ return ASMHelper.getOpcodeName(this.getOpcode()) + " for "
+ + this.getOwner() + "." + this.getName() + (this.isField() ? ":" : "") + this.getDesc();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof MemberRef)) {
+ return false;
+ }
+
+ MemberRef other = (MemberRef)obj;
+ return this.getOpcode() == other.getOpcode()
+ && this.getOwner().equals(other.getOwner())
+ && this.getName().equals(other.getName())
+ && this.getDesc().equals(other.getDesc());
+ }
+
+ @Override
+ public int hashCode() {
+ return this.toString().hashCode();
+ }
+}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index f31d76d9..3f4af6f4 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -231,9 +231,9 @@ public class MixinTargetContext implements IReferenceMapperContext {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
- this.transformMethodRef(method, iter, new StaticMethodRef((MethodInsnNode)insn));
+ this.transformMethodRef(method, iter, new MemberRef.StaticMethodRef((MethodInsnNode)insn));
} else if (insn instanceof FieldInsnNode) {
- this.transformFieldRef(method, iter, new StaticFieldRef((FieldInsnNode)insn));
+ this.transformFieldRef(method, iter, new MemberRef.StaticFieldRef((FieldInsnNode)insn));
} else if (insn instanceof TypeInsnNode) {
this.transformTypeNode(method, iter, (TypeInsnNode)insn);
} else if (insn instanceof LdcInsnNode) {
@@ -295,8 +295,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
*/
private void transformFieldRef(MethodNode method, Iterator iter, MemberRef fieldRef) {
if (Constants.IMAGINARY_SUPER.equals(fieldRef.getName())) {
- if (fieldRef instanceof StaticFieldRef) {
- this.processImaginarySuper(method, ((StaticFieldRef) fieldRef).insn);
+ if (fieldRef instanceof MemberRef.StaticFieldRef) {
+ this.processImaginarySuper(method, ((MemberRef.StaticFieldRef) fieldRef).insn);
iter.remove();
} else {
throw new InvalidMixinException(this.mixin, "Cannot call imaginary super from method handle.");
@@ -334,20 +334,15 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
- * Transforms class literals in the method being processed.
+ * Transforms class literals and method handle loads in the method being
+ * processed.
*
* @param method Method being processed
* @param iter Insn interator
* @param ldcInsn Insn to transform
*/
private void transformConstantNode(MethodNode method, Iterator iter, LdcInsnNode ldcInsn) {
- if (ldcInsn.cst instanceof Type) {
- Type type = (Type)ldcInsn.cst;
- String desc = this.transformDescriptor(type);
- if (!type.toString().equals(desc)) {
- ldcInsn.cst = Type.getType(desc);
- }
- }
+ ldcInsn.cst = this.transformConstant(method, iter, ldcInsn.cst);
}
/**
@@ -358,233 +353,53 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param dynInsn Insn to transform
*/
private void transformInvokeDynamicNode(MethodNode method, Iterator iter, InvokeDynamicInsnNode dynInsn) {
- // set class version to java 8
- targetClass.version = 52;
dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc);
dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm);
for (int i = 0; i < dynInsn.bsmArgs.length; i++) {
- Object bsmArg = dynInsn.bsmArgs[i];
- if (bsmArg instanceof Handle) {
- dynInsn.bsmArgs[i] = this.transformHandle(method, iter, ((Handle) bsmArg));
- } else if (bsmArg instanceof Type) {
- Type type = ((Type) bsmArg);
- String desc = this.transformDescriptor(type);
- if (!type.toString().equals(desc)) {
- dynInsn.bsmArgs[i] = Type.getType(desc);
- }
- }
+ dynInsn.bsmArgs[i] = this.transformConstant(method, iter, dynInsn.bsmArgs[i]);
}
}
+ /**
+ * Transforms a constant in the constant pool.
+ *
+ * @param method Method being processed
+ * @param iter Insn interator
+ * @param constant Consatnt pool entry
+ * @return Transformed constant
+ */
+ private Object transformConstant(MethodNode method, Iterator iter, Object constant) {
+ if (constant instanceof Type) {
+ Type type = (Type)constant;
+ String desc = this.transformDescriptor(type);
+ if (!type.toString().equals(desc)) {
+ return Type.getType(desc);
+ } else {
+ return constant;
+ }
+ } else if (constant instanceof Handle) {
+ return this.transformHandle(method, iter, (Handle)constant);
+ }
+ return constant;
+ }
+
/**
* Transforms a method handle that is referenced from the method being
* processed.
*
+ * @param method Method being processed
+ * @param iter Insn interator
* @param handle Handle to transform
*/
private Handle transformHandle(MethodNode method, Iterator iter, Handle handle) {
- HandleRef memberRef = new HandleRef(handle);
+ this.targetClass.version = Constants.JAVA8_CLASSFILE_VERSION;
+ MemberRef.HandleRef memberRef = new MemberRef.HandleRef(handle);
if (memberRef.isField()) {
this.transformFieldRef(method, iter, memberRef);
} else {
this.transformMethodRef(method, iter, memberRef);
}
- return memberRef.handle;
- }
-
- /**
- * Reference to a field or method that also includes invocation
- * instructions.
- */
- private abstract class MemberRef {
- abstract boolean isField();
-
- abstract int getOpcode();
-
- abstract String getOwner();
-
- abstract void setOwner(String owner);
-
- abstract String getName();
-
- abstract String getDesc();
-
- abstract void setDesc(String desc);
- }
-
- /**
- * A static reference to a method backed by an invoke instruction
- */
- private final class StaticMethodRef extends MemberRef {
-
- private final MethodInsnNode insn;
-
- private StaticMethodRef(MethodInsnNode insn) {
- this.insn = insn;
- }
-
- @Override
- boolean isField() {
- return false;
- }
-
- @Override
- int getOpcode() {
- return this.insn.getOpcode();
- }
-
- @Override
- String getOwner() {
- return this.insn.owner;
- }
-
- @Override
- void setOwner(String owner) {
- this.insn.owner = owner;
- }
-
- @Override
- String getName() {
- return this.insn.name;
- }
-
- @Override
- String getDesc() {
- return this.insn.desc;
- }
-
- @Override
- void setDesc(String desc) {
- this.insn.desc = desc;
- }
- }
-
- /**
- * A static reference to a field backed by field get/put instruction
- */
- private final class StaticFieldRef extends MemberRef {
-
- private final FieldInsnNode insn;
-
- private StaticFieldRef(FieldInsnNode insn) {
- this.insn = insn;
- }
-
- @Override
- boolean isField() {
- return true;
- }
-
- @Override
- int getOpcode() {
- return this.insn.getOpcode();
- }
-
- @Override
- String getOwner() {
- return this.insn.owner;
- }
-
- @Override
- void setOwner(String owner) {
- this.insn.owner = owner;
- }
-
- @Override
- String getName() {
- return this.insn.name;
- }
-
- @Override
- String getDesc() {
- return this.insn.desc;
- }
-
- @Override
- void setDesc(String desc) {
- this.insn.desc = desc;
- }
- }
-
- /**
- * A reference to a field or method backed by a method handle
- */
- private final class HandleRef extends MemberRef {
-
- private Handle handle;
-
- private HandleRef(Handle handle) {
- this.handle = handle;
- }
-
- @Override
- boolean isField() {
- switch (this.handle.getTag()) {
- case Opcodes.H_INVOKEVIRTUAL:
- case Opcodes.H_INVOKESTATIC:
- case Opcodes.H_INVOKEINTERFACE:
- case Opcodes.H_INVOKESPECIAL:
- case Opcodes.H_NEWINVOKESPECIAL:
- return false;
- case Opcodes.H_GETFIELD:
- case Opcodes.H_GETSTATIC:
- case Opcodes.H_PUTFIELD:
- case Opcodes.H_PUTSTATIC:
- return true;
- default:
- throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
- }
- }
-
- @Override
- int getOpcode() {
- switch (this.handle.getTag()) {
- case Opcodes.H_INVOKEVIRTUAL:
- return Opcodes.INVOKEVIRTUAL;
- case Opcodes.H_INVOKESTATIC:
- return Opcodes.INVOKESTATIC;
- case Opcodes.H_INVOKEINTERFACE:
- return Opcodes.INVOKEINTERFACE;
- case Opcodes.H_INVOKESPECIAL:
- case Opcodes.H_NEWINVOKESPECIAL:
- return Opcodes.INVOKESPECIAL;
- case Opcodes.H_GETFIELD:
- return Opcodes.GETFIELD;
- case Opcodes.H_GETSTATIC:
- return Opcodes.GETSTATIC;
- case Opcodes.H_PUTFIELD:
- return Opcodes.PUTFIELD;
- case Opcodes.H_PUTSTATIC:
- return Opcodes.PUTSTATIC;
- default:
- throw new MixinTransformerError("Invalid tag " + this.handle.getTag() + " for method handle " + this.handle + ".");
- }
- }
-
- @Override
- String getOwner() {
- return this.handle.getOwner();
- }
-
- @Override
- void setOwner(String owner) {
- this.handle = new Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc());
- }
-
- @Override
- String getName() {
- return this.handle.getName();
- }
-
- @Override
- String getDesc() {
- return this.handle.getDesc();
- }
-
- @Override
- void setDesc(String desc) {
- this.handle = new Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
- }
+ return memberRef.getMethodHandle();
}
/**
@@ -626,7 +441,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
MethodInsnNode methodNode = (MethodInsnNode)insn;
if (methodNode.owner.equals(this.getClassRef()) && methodNode.name.equals(method.name) && methodNode.desc.equals(method.desc)) {
methodNode.setOpcode(Opcodes.INVOKESPECIAL);
- this.updateStaticBinding(method, new StaticMethodRef(methodNode));
+ this.updateStaticBinding(method, new MemberRef.StaticMethodRef(methodNode));
return;
}
}
@@ -666,13 +481,12 @@ public class MixinTargetContext implements IReferenceMapperContext {
traversal);
if (superMethod != null) {
if (superMethod.getOwner().isMixin()) {
- throw new InvalidMixinException(this, "Invalid " + ASMHelper.getOpcodeName(methodRef.getOpcode()) + " in " + this + " resolved "
- + methodRef.getOwner() + " -> " + superMethod.getOwner() + " for " + methodRef.getName() + methodRef.getDesc());
+ throw new InvalidMixinException(this, "Invalid " + methodRef + " in " + this + " resolved " + superMethod.getOwner()
+ + " but is mixin.");
}
methodRef.setOwner(superMethod.getOwner().getName());
} else if (ClassInfo.forName(methodRef.getOwner()).isMixin()) {
- throw new MixinTransformerError("Error resolving " + ASMHelper.getOpcodeName(methodRef.getOpcode()) + " target for "
- + methodRef.getOwner() + "." + methodRef.getName() + " in " + this);
+ throw new MixinTransformerError("Error resolving " + methodRef + " in " + this);
}
}
@@ -732,9 +546,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
private String transformDescriptor(Type type) {
if (type.getSort() == Type.METHOD) {
return this.transformMethodDescriptor(type.getDescriptor());
- } else {
- return this.transformSingleDescriptor(type);
}
+ return this.transformSingleDescriptor(type);
}
private String transformSingleDescriptor(Type type) {
@@ -907,7 +720,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
- * Called immediately after the mixin is applied to targetClass
+ * Called imm imediately after the mixin is applied to targetClass
*
* @param transformedName Target class's transformed name
* @param targetClass Target class
diff --git a/src/main/java/org/spongepowered/asm/util/Constants.java b/src/main/java/org/spongepowered/asm/util/Constants.java
index ce791d4b..f720f090 100644
--- a/src/main/java/org/spongepowered/asm/util/Constants.java
+++ b/src/main/java/org/spongepowered/asm/util/Constants.java
@@ -32,6 +32,7 @@ import org.spongepowered.asm.mixin.Mixin;
*/
public abstract class Constants {
+ public static final int JAVA8_CLASSFILE_VERSION = 52;
public static final String INIT = "";
public static final String CLINIT = "";
public static final String IMAGINARY_SUPER = "super$";
From d742604aab4c25f3e1cbcc3b07e9c496dc0b1936 Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Mon, 12 Oct 2015 13:35:47 +1300
Subject: [PATCH 008/169] Fixed java.lang.VerifyError incorrect stack frame
errors
---
.../asm/mixin/transformer/MixinClassWriter.java | 6 +++---
.../asm/mixin/transformer/MixinPreProcessor.java | 1 +
.../asm/mixin/transformer/MixinTargetContext.java | 1 -
src/main/java/org/spongepowered/asm/util/Constants.java | 1 -
4 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java
index b61c0235..7f521ec1 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassWriter.java
@@ -53,10 +53,10 @@ public class MixinClassWriter extends ClassWriter {
ClassInfo d = ClassInfo.forName(type2);
if (c.hasSuperClass(d)) {
- return type1;
+ return type2;
}
if (d.hasSuperClass(c)) {
- return type2;
+ return type1;
}
if (c.isInterface() || d.isInterface()) {
return MixinClassWriter.JAVA_LANG_OBJECT;
@@ -68,7 +68,7 @@ public class MixinClassWriter extends ClassWriter {
return MixinClassWriter.JAVA_LANG_OBJECT;
}
- } while (!c.hasSuperClass(d));
+ } while (!d.hasSuperClass(c));
return c.getName();
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java
index 769da82d..53a4c4aa 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java
@@ -130,6 +130,7 @@ class MixinPreProcessor {
MixinTargetContext createContextFor(ClassNode target) {
this.prepare();
MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target);
+ target.version = Math.max(this.classNode.version, target.version);
this.attach(context);
return context;
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index 3f4af6f4..27d20f29 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -392,7 +392,6 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param handle Handle to transform
*/
private Handle transformHandle(MethodNode method, Iterator iter, Handle handle) {
- this.targetClass.version = Constants.JAVA8_CLASSFILE_VERSION;
MemberRef.HandleRef memberRef = new MemberRef.HandleRef(handle);
if (memberRef.isField()) {
this.transformFieldRef(method, iter, memberRef);
diff --git a/src/main/java/org/spongepowered/asm/util/Constants.java b/src/main/java/org/spongepowered/asm/util/Constants.java
index f720f090..ce791d4b 100644
--- a/src/main/java/org/spongepowered/asm/util/Constants.java
+++ b/src/main/java/org/spongepowered/asm/util/Constants.java
@@ -32,7 +32,6 @@ import org.spongepowered.asm.mixin.Mixin;
*/
public abstract class Constants {
- public static final int JAVA8_CLASSFILE_VERSION = 52;
public static final String INIT = "";
public static final String CLINIT = "";
public static final String IMAGINARY_SUPER = "super$";
From 2b715538bd782256884852dd0920236952178c6f Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Mon, 12 Oct 2015 14:26:10 +1300
Subject: [PATCH 009/169] Fixed typo
---
.../spongepowered/asm/mixin/transformer/MixinTargetContext.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index 27d20f29..007a639d 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -719,7 +719,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
- * Called imm imediately after the mixin is applied to targetClass
+ * Called imediately after the mixin is applied to targetClass
*
* @param transformedName Target class's transformed name
* @param targetClass Target class
From b4f06960dcb58aa2012a9be3a0fd49bace86d250 Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Wed, 14 Oct 2015 17:43:57 +1300
Subject: [PATCH 010/169] Renamed MemberRef inner classes
---
.../asm/mixin/transformer/MemberRef.java | 21 +++++++++----------
.../mixin/transformer/MixinTargetContext.java | 21 +++++++++----------
2 files changed, 20 insertions(+), 22 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java
index 570f39d7..fc0bf2d5 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MemberRef.java
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer;
-import org.spongepowered.asm.lib.Handle;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
@@ -42,7 +41,7 @@ public abstract class MemberRef {
/**
* A static reference to a method backed by an invoke instruction
*/
- public static final class StaticMethodRef extends MemberRef {
+ public static final class Method extends MemberRef {
/**
* Method invocation instruction
@@ -54,7 +53,7 @@ public abstract class MemberRef {
*
* @param insn Method instruction of this member reference
*/
- public StaticMethodRef(MethodInsnNode insn) {
+ public Method(MethodInsnNode insn) {
this.insn = insn;
}
@@ -97,7 +96,7 @@ public abstract class MemberRef {
/**
* A static reference to a field backed by field get/put instruction
*/
- public static final class StaticFieldRef extends MemberRef {
+ public static final class Field extends MemberRef {
/**
* Field accessor instruction
@@ -109,7 +108,7 @@ public abstract class MemberRef {
*
* @param insn Field instruction this member reference
*/
- public StaticFieldRef(FieldInsnNode insn) {
+ public Field(FieldInsnNode insn) {
this.insn = insn;
}
@@ -152,9 +151,9 @@ public abstract class MemberRef {
/**
* A reference to a field or method backed by a method handle
*/
- public static final class HandleRef extends MemberRef {
+ public static final class Handle extends MemberRef {
- private Handle handle;
+ private org.spongepowered.asm.lib.Handle handle;
/**
* Creates a member reference initially referring to the member referred
@@ -163,7 +162,7 @@ public abstract class MemberRef {
*
* @param handle Initial method handle.
*/
- public HandleRef(Handle handle) {
+ public Handle(org.spongepowered.asm.lib.Handle handle) {
this.handle = handle;
}
@@ -172,7 +171,7 @@ public abstract class MemberRef {
*
* @return Method handle representing this object
*/
- public Handle getMethodHandle() {
+ public org.spongepowered.asm.lib.Handle getMethodHandle() {
return this.handle;
}
@@ -227,7 +226,7 @@ public abstract class MemberRef {
@Override
public void setOwner(String owner) {
- this.handle = new Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc());
+ this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc());
}
@Override
@@ -242,7 +241,7 @@ public abstract class MemberRef {
@Override
public void setDesc(String desc) {
- this.handle = new Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
+ this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc);
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index 007a639d..c18799c0 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -39,7 +39,6 @@ import org.spongepowered.asm.lib.tree.*;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.injection.struct.Target;
-import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal;
import org.spongepowered.asm.util.ASMHelper;
import org.spongepowered.asm.util.Constants;
@@ -231,9 +230,9 @@ public class MixinTargetContext implements IReferenceMapperContext {
AbstractInsnNode insn = iter.next();
if (insn instanceof MethodInsnNode) {
- this.transformMethodRef(method, iter, new MemberRef.StaticMethodRef((MethodInsnNode)insn));
+ this.transformMethodRef(method, iter, new MemberRef.Method((MethodInsnNode)insn));
} else if (insn instanceof FieldInsnNode) {
- this.transformFieldRef(method, iter, new MemberRef.StaticFieldRef((FieldInsnNode)insn));
+ this.transformFieldRef(method, iter, new MemberRef.Field((FieldInsnNode)insn));
} else if (insn instanceof TypeInsnNode) {
this.transformTypeNode(method, iter, (TypeInsnNode)insn);
} else if (insn instanceof LdcInsnNode) {
@@ -253,7 +252,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
private void validateMethod(MethodNode method) {
// Any method tagged with @SoftOverride must have an implementation visible from
if (ASMHelper.getInvisibleAnnotation(method, SoftOverride.class) != null) {
- Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER);
+ ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, false, Traversal.SUPER);
if (superMethod == null || !superMethod.isInjected()) {
throw new InvalidMixinException(this, "Mixin method " + method.name + method.desc + " is tagged with @SoftOverride but no "
+ "valid method was found in superclasses of " + this.targetClass.name);
@@ -295,8 +294,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
*/
private void transformFieldRef(MethodNode method, Iterator iter, MemberRef fieldRef) {
if (Constants.IMAGINARY_SUPER.equals(fieldRef.getName())) {
- if (fieldRef instanceof MemberRef.StaticFieldRef) {
- this.processImaginarySuper(method, ((MemberRef.StaticFieldRef) fieldRef).insn);
+ if (fieldRef instanceof MemberRef.Field) {
+ this.processImaginarySuper(method, ((MemberRef.Field) fieldRef).insn);
iter.remove();
} else {
throw new InvalidMixinException(this.mixin, "Cannot call imaginary super from method handle.");
@@ -392,7 +391,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param handle Handle to transform
*/
private Handle transformHandle(MethodNode method, Iterator iter, Handle handle) {
- MemberRef.HandleRef memberRef = new MemberRef.HandleRef(handle);
+ MemberRef.Handle memberRef = new MemberRef.Handle(handle);
if (memberRef.isField()) {
this.transformFieldRef(method, iter, memberRef);
} else {
@@ -440,7 +439,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
MethodInsnNode methodNode = (MethodInsnNode)insn;
if (methodNode.owner.equals(this.getClassRef()) && methodNode.name.equals(method.name) && methodNode.desc.equals(method.desc)) {
methodNode.setOpcode(Opcodes.INVOKESPECIAL);
- this.updateStaticBinding(method, new MemberRef.StaticMethodRef(methodNode));
+ this.updateStaticBinding(method, new MemberRef.Method(methodNode));
return;
}
}
@@ -476,8 +475,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
return;
}
- Method superMethod = this.targetClassInfo.findMethodInHierarchy(methodRef.getName(), methodRef.getDesc(), traversal == Traversal.ALL,
- traversal);
+ ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(methodRef.getName(), methodRef.getDesc(),
+ traversal == Traversal.ALL, traversal);
if (superMethod != null) {
if (superMethod.getOwner().isMixin()) {
throw new InvalidMixinException(this, "Invalid " + methodRef + " in " + this + " resolved " + superMethod.getOwner()
@@ -719,7 +718,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
}
/**
- * Called imediately after the mixin is applied to targetClass
+ * Called immediately after the mixin is applied to targetClass
*
* @param transformedName Target class's transformed name
* @param targetClass Target class
From 10b0cec45e065f51d9581d2a25af4dc3ae8bd86f Mon Sep 17 00:00:00 2001
From: Aaron Hill
Date: Wed, 14 Oct 2015 20:22:25 -0400
Subject: [PATCH 011/169] Fix implemented interface methods report
---
.../asm/mixin/transformer/ClassInfo.java | 448 +++++++++---------
...ixinTransformerModuleInterfaceChecker.java | 30 +-
2 files changed, 240 insertions(+), 238 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
index a86fa7ee..14ee1f78 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
@@ -52,80 +52,80 @@ import com.google.common.collect.ImmutableSet;
/**
* Information about a class, used as a way of keeping track of class hierarchy
* information needed to support more complex mixin behaviour such as detached
- * superclass and mixin inheritance.
+ * superclass and mixin inheritance.
*/
public class ClassInfo extends TreeInfo {
-
+
public static final int INCLUDE_PRIVATE = 0x0002;
public static final int INCLUDE_STATIC = 0x0008;
-
+
/**
* To all intents and purposes, the "real" class hierarchy and the mixin
* class hierarchy exist in parallel, this means that for some hierarchy
* validation operations we need to walk across to the other
* hierarchy in order to allow meaningful validation to occur.
- *
+ *
* This enum defines the type of traversal operations which are allowed
* for a particular lookup.
- *
+ *
* Each traversal type has a next property which defines
* the traversal type to use on the next step of the hierarchy
- * validation. For example, the type {@link #IMMEDIATE} which requires an
+ * validation. For example, the type {@link #IMMEDIATE} which requires an
* immediate match falls through to {@link #NONE} on the next step, which
* prevents further traversals from occurring in the lookup.
*/
public static enum Traversal {
-
+
/**
* No traversals are allowed.
*/
NONE(null, false),
-
+
/**
* Traversal is allowed at all stages.
*/
ALL(null, true),
-
+
/**
* Traversal is allowed at the bottom of the hierarchy but no further.
*/
IMMEDIATE(Traversal.NONE, true),
-
+
/**
* Traversal is allowed only on superclasses and not at the bottom of
* the hierarchy.
*/
SUPER(Traversal.ALL, false);
-
+
private final Traversal next;
-
+
private final boolean traverse;
-
+
private Traversal(Traversal next, boolean traverse) {
this.next = next != null ? next : this;
this.traverse = traverse;
}
-
+
public Traversal next() {
return this.next;
}
-
+
public boolean canTraverse() {
return this.traverse;
}
}
-
+
/**
* Information about frames in a method
*/
public static class FrameData {
-
+
private static final String[] FRAMETYPES = { "NEW", "FULL", "APPEND", "CHOP", "SAME", "SAME1" };
-
+
public final int index;
-
+
public final int type;
-
+
public final int locals;
FrameData(int index, int type, int locals) {
@@ -133,13 +133,13 @@ public class ClassInfo extends TreeInfo {
this.type = type;
this.locals = locals;
}
-
+
FrameData(int index, FrameNode frameNode) {
this.index = index;
this.type = frameNode.type;
this.locals = frameNode.local != null ? frameNode.local.size() : 0;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@@ -148,54 +148,54 @@ public class ClassInfo extends TreeInfo {
return String.format("FrameData[index=%d, type=%s, locals=%d]", this.index, FrameData.FRAMETYPES[this.type + 1], this.locals);
}
}
-
+
/**
* Information about a member in this class
*/
abstract static class Member {
-
+
static enum Type {
METHOD,
FIELD
}
-
+
/**
- * Member type
+ * Member type
*/
private final Type type;
-
+
/**
- * The original name of the member
+ * The original name of the member
*/
private final String memberName;
-
+
/**
* The member's signature
*/
private final String memberDesc;
-
+
/**
* True if this member was injected by a mixin, false if it was
* originally part of the class
*/
private final boolean isInjected;
-
+
/**
* Access modifiers
*/
private final int modifiers;
-
+
/**
* Current name of the member, may be different from {@link #memberName}
* if the member has been renamed
*/
private String currentName;
-
+
protected Member(Member member) {
this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected);
this.currentName = member.currentName;
}
-
+
protected Member(Type type, String name, String desc, int access) {
this(type, name, desc, access, false);
}
@@ -208,23 +208,23 @@ public class ClassInfo extends TreeInfo {
this.currentName = name;
this.modifiers = access;
}
-
+
public String getOriginalName() {
return this.memberName;
}
-
+
public String getName() {
return this.currentName;
}
-
+
public String getDesc() {
return this.memberDesc;
}
-
+
public boolean isInjected() {
return this.isInjected;
}
-
+
public boolean isRenamed() {
return this.currentName != this.memberName;
}
@@ -236,7 +236,7 @@ public class ClassInfo extends TreeInfo {
public boolean isStatic() {
return (this.modifiers & Opcodes.ACC_STATIC) != 0;
}
-
+
public boolean matchesFlags(int flags) {
return (((~this.modifiers | (flags & ClassInfo.INCLUDE_PRIVATE)) & ClassInfo.INCLUDE_PRIVATE) != 0
&& ((~this.modifiers | (flags & ClassInfo.INCLUDE_STATIC)) & ClassInfo.INCLUDE_STATIC) != 0);
@@ -244,7 +244,7 @@ public class ClassInfo extends TreeInfo {
// Abstract because this has to be static in order to contain the enum
public abstract ClassInfo getOwner();
-
+
public int getAccess() {
return this.modifiers;
}
@@ -252,45 +252,45 @@ public class ClassInfo extends TreeInfo {
public void renameTo(String name) {
this.currentName = name;
}
-
+
public boolean equals(String name, String desc) {
return (this.memberName.equals(name)
|| this.currentName.equals(name))
&& this.memberDesc.equals(desc);
}
-
+
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Member)) {
return false;
}
-
+
Member other = (Member)obj;
- return (other.memberName.equals(this.memberName)
+ return (other.memberName.equals(this.memberName)
|| other.currentName.equals(this.currentName))
&& other.memberDesc.equals(this.memberDesc);
}
-
+
@Override
public int hashCode() {
return this.toString().hashCode();
}
-
+
@Override
public String toString() {
return this.memberName + this.memberDesc;
}
-
+
public boolean isAbstract() {
return (this.modifiers & Opcodes.ACC_ABSTRACT) != 0;
}
}
-
+
/**
* A method
*/
public class Method extends Member {
-
+
private final List frames;
public Method(Member member) {
@@ -301,12 +301,12 @@ public class ClassInfo extends TreeInfo {
public Method(MethodNode method) {
this(method, false);
}
-
+
public Method(MethodNode method, boolean injected) {
super(Type.METHOD, method.name, method.desc, method.access, injected);
this.frames = this.gatherFrames(method);
}
-
+
public Method(String name, String desc) {
super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false);
this.frames = null;
@@ -321,7 +321,7 @@ public class ClassInfo extends TreeInfo {
super(Type.METHOD, name, desc, access, injected);
this.frames = null;
}
-
+
private List gatherFrames(MethodNode method) {
List frames = new ArrayList();
for (Iterator iter = method.instructions.iterator(); iter.hasNext();) {
@@ -332,7 +332,7 @@ public class ClassInfo extends TreeInfo {
}
return frames;
}
-
+
public List getFrames() {
return this.frames;
}
@@ -340,58 +340,58 @@ public class ClassInfo extends TreeInfo {
@Override
public ClassInfo getOwner() {
return ClassInfo.this;
- }
+ }
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Method)) {
return false;
}
-
+
return super.equals(obj);
}
}
-
+
/**
* A field
*/
class Field extends Member {
-
+
public Field(Member member) {
super(member);
}
-
+
public Field(FieldNode field) {
this(field, false);
}
-
+
public Field(FieldNode field, boolean injected) {
super(Type.FIELD, field.name, field.desc, field.access, injected);
}
-
+
public Field(String name, String desc, int access) {
super(Type.FIELD, name, desc, access, false);
}
-
+
public Field(String name, String desc, int access, boolean injected) {
super(Type.FIELD, name, desc, access, injected);
}
-
+
@Override
public ClassInfo getOwner() {
return ClassInfo.this;
- }
-
+ }
+
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Field)) {
return false;
}
-
+
return super.equals(obj);
}
}
-
+
private static final Logger logger = LogManager.getLogger("mixin");
private static final String JAVA_LANG_OBJECT = "java/lang/Object";
@@ -401,90 +401,90 @@ public class ClassInfo extends TreeInfo {
* information we generate
*/
private static final Map cache = new HashMap();
-
+
private static final ClassInfo OBJECT = new ClassInfo();
-
+
static {
ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT);
}
-
+
/**
* Class name (binary name)
*/
private final String name;
-
+
/**
* Class superclass name (binary name)
*/
private final String superName;
-
+
/**
* Outer class name
*/
private final String outerName;
-
+
/**
* True either if this is not an inner class or if it is an inner class but
* does not contain a reference to its outer class.
*/
private final boolean isProbablyStatic;
-
+
/**
* Interfaces
*/
private final Set interfaces;
-
+
/**
- * Public and protected methods (instance) methods in this class
+ * Public and protected methods (instance) methods in this class
*/
private final Set methods;
-
+
/**
* Public and protected fields in this class
*/
private final Set fields;
-
+
/**
* Mixins which target this class
*/
private final Set mixins = new HashSet();
-
+
/**
- * Map of mixin types to corresponding supertypes, to avoid repeated
- * lookups
+ * Map of mixin types to corresponding supertypes, to avoid repeated
+ * lookups
*/
private final Map correspondingTypes = new HashMap();
-
+
/**
- * Mixin info if this class is a mixin itself
+ * Mixin info if this class is a mixin itself
*/
private final MixinInfo mixin;
-
+
/**
- * True if this is a mixin rather than a class
+ * True if this is a mixin rather than a class
*/
private final boolean isMixin;
-
+
/**
- * True if this is an interface
+ * True if this is an interface
*/
private final boolean isInterface;
-
+
/**
* Access flags
*/
private final int access;
-
+
/**
- * Superclass reference, not initialised until required
+ * Superclass reference, not initialised until required
*/
private ClassInfo superClass;
-
+
/**
- * Outer class reference, not initialised until required
+ * Outer class reference, not initialised until required
*/
private ClassInfo outerClass;
-
+
/**
* Private constructor used to initialise the ClassInfo for {@link Object}
*/
@@ -513,10 +513,10 @@ public class ClassInfo extends TreeInfo {
this.isMixin = false;
this.mixin = null;
}
-
+
/**
* Initialise a ClassInfo from the supplied {@link ClassNode}
- *
+ *
* @param classNode Class node to inspect
*/
private ClassInfo(ClassNode classNode) {
@@ -531,7 +531,7 @@ public class ClassInfo extends TreeInfo {
this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null;
this.interfaces.addAll(classNode.interfaces);
-
+
for (MethodNode method : classNode.methods) {
this.addMethod(method, this.isMixin);
}
@@ -548,18 +548,18 @@ public class ClassInfo extends TreeInfo {
outerName = outerName.substring(1, outerName.length() - 1);
}
}
- }
-
+ }
+
if ((field.access & Opcodes.ACC_STATIC) == 0) {
this.fields.add(new Field(field, this.isMixin));
}
}
}
-
+
this.isProbablyStatic = isProbablyStatic;
this.outerName = outerName;
}
-
+
void addInterface(String iface) {
this.interfaces.add(iface);
}
@@ -573,7 +573,7 @@ public class ClassInfo extends TreeInfo {
this.methods.add(new Method(method, injected));
}
}
-
+
/**
* Add a mixin which targets this class
*/
@@ -583,21 +583,21 @@ public class ClassInfo extends TreeInfo {
}
this.mixins.add(mixin);
}
-
+
/**
* Get all mixins which target this class
*/
public Set getMixins() {
return Collections.unmodifiableSet(this.mixins);
}
-
+
/**
* Get whether this class is a mixin
*/
public boolean isMixin() {
return this.isMixin;
}
-
+
/**
* Get whether this class has ACC_PUBLIC
*/
@@ -618,58 +618,58 @@ public class ClassInfo extends TreeInfo {
public boolean isSynthetic() {
return (this.access & Opcodes.ACC_SYNTHETIC) != 0;
}
-
+
/**
- * Get whether this class is probably static (or is not an inner class)
+ * Get whether this class is probably static (or is not an inner class)
*/
public boolean isProbablyStatic() {
return this.isProbablyStatic;
}
-
+
/**
* Get whether this class is an inner class
*/
public boolean isInner() {
return this.outerName != null;
}
-
+
/**
* Get whether this is an interface or not
*/
public boolean isInterface() {
return this.isInterface;
}
-
+
/**
* Returns the answer to life, the universe and everything
*/
public Set getInterfaces() {
return Collections.unmodifiableSet(this.interfaces);
}
-
+
@Override
public String toString() {
return this.name;
}
-
+
public int getAccess() {
return this.access;
}
-
+
/**
* Get the class name (binary name)
*/
public String getName() {
return this.name;
}
-
+
/**
* Get the superclass name (binary name)
*/
public String getSuperName() {
return this.superName;
}
-
+
/**
* Get the superclass info, can return null if the superclass cannot be
* resolved
@@ -678,17 +678,17 @@ public class ClassInfo extends TreeInfo {
if (this.superClass == null && this.superName != null) {
this.superClass = ClassInfo.forName(this.superName);
}
-
+
return this.superClass;
}
-
+
/**
* Get the name of the outer class, or null if this is not an inner class
*/
public String getOuterName() {
return this.outerName;
}
-
+
/**
* Get the outer class info, can return null if the outer class cannot be
* resolved or if this is not an inner class
@@ -697,10 +697,10 @@ public class ClassInfo extends TreeInfo {
if (this.outerClass == null && this.outerName != null) {
this.outerClass = ClassInfo.forName(this.outerName);
}
-
+
return this.outerClass;
}
-
+
/**
* Class targets
*/
@@ -711,55 +711,57 @@ public class ClassInfo extends TreeInfo {
targets.addAll(this.mixin.getTargets());
return targets;
}
-
+
return ImmutableList.of(this);
}
-
+
/**
* Get class/interface methods
- *
+ *
* @return read-only view of class methods
*/
public Set getMethods() {
return Collections.unmodifiableSet(this.methods);
}
-
+
/**
* If this is an interface, returns a set containing all methods in this
* interface and all super interfaces. If this is a class, returns a set
* containing all methods for all interfaces implemented by this class and
* all super interfaces of those interfaces.
- *
+ *
+ * @param includeMixins Whether to include methods from mixins targeting this class info
* @return read-only view of class methods
*/
- public Set getInterfaceMethods() {
+ public Set getInterfaceMethods(boolean includeMixins) {
Set methods = new HashSet();
- ClassInfo superClass = this.addMethodsRecursive(methods);
+ ClassInfo superClass = this.addMethodsRecursive(methods, includeMixins);
if (!this.isInterface) {
while (superClass != null && superClass != ClassInfo.OBJECT) {
- superClass = superClass.addMethodsRecursive(methods);
+ superClass = superClass.addMethodsRecursive(methods, includeMixins);
}
}
-
+
// Remove default methods.
for (Iterator it = methods.iterator(); it.hasNext();) {
if (!it.next().isAbstract()) {
it.remove();
}
}
-
+
return Collections.unmodifiableSet(methods);
}
/**
* Recursive function used by {@link #getInterfaceMethods} to add all
* interface methods to the supplied set
- *
+ *
* @param methods Method set to add to
+ * @param includeMixins Whether to include methods from mixins targeting this class info
* @return superclass reference, used to make the code above more fluent
*/
- private ClassInfo addMethodsRecursive(Set methods) {
+ private ClassInfo addMethodsRecursive(Set methods, boolean includeMixins) {
if (this.isInterface) {
for (Method method : this.methods) {
// Default methods take priority. They are removed later.
@@ -769,22 +771,22 @@ public class ClassInfo extends TreeInfo {
}
methods.add(method);
}
- } else if (!this.isMixin) {
+ } else if (!this.isMixin && includeMixins) {
for (MixinInfo mixin : this.mixins) {
- mixin.getClassInfo().addMethodsRecursive(methods);
+ mixin.getClassInfo().addMethodsRecursive(methods, includeMixins);
}
}
-
+
for (String iface : this.interfaces) {
- ClassInfo.forName(iface).addMethodsRecursive(methods);
+ ClassInfo.forName(iface).addMethodsRecursive(methods, includeMixins);
}
-
+
return this.getSuperClass();
}
-
+
/**
* Test whether this class has the specified superclass in its hierarchy
- *
+ *
* @param superClass Name of the superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
@@ -795,7 +797,7 @@ public class ClassInfo extends TreeInfo {
/**
* Test whether this class has the specified superclass in its hierarchy
- *
+ *
* @param superClass Name of the superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
@@ -805,13 +807,13 @@ public class ClassInfo extends TreeInfo {
if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) {
return true;
}
-
+
return this.findSuperClass(superClass, traversal) != null;
}
-
+
/**
* Test whether this class has the specified superclass in its hierarchy
- *
+ *
* @param superClass Superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
@@ -822,7 +824,7 @@ public class ClassInfo extends TreeInfo {
/**
* Test whether this class has the specified superclass in its hierarchy
- *
+ *
* @param superClass Superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
@@ -839,9 +841,9 @@ public class ClassInfo extends TreeInfo {
/**
* Search for the specified superclass in this class's hierarchy. If found
* returns the ClassInfo, otherwise returns null
- *
+ *
* @param superClass Superclass name to search for
- * @return Matched superclass or null if not found
+ * @return Matched superclass or null if not found
*/
public ClassInfo findSuperClass(String superClass) {
return this.findSuperClass(superClass, Traversal.NONE);
@@ -850,10 +852,10 @@ public class ClassInfo extends TreeInfo {
/**
* Search for the specified superclass in this class's hierarchy. If found
* returns the ClassInfo, otherwise returns null
- *
+ *
* @param superClass Superclass name to search for
* @param traversal Traversal type to allow during this lookup
- * @return Matched superclass or null if not found
+ * @return Matched superclass or null if not found
*/
public ClassInfo findSuperClass(String superClass, Traversal traversal) {
ClassInfo superClassInfo = this.getSuperClass();
@@ -879,7 +881,7 @@ public class ClassInfo extends TreeInfo {
}
}
}
-
+
return null;
}
@@ -888,7 +890,7 @@ public class ClassInfo extends TreeInfo {
* specified mixin. This is used during mixin application to translate a
* mixin reference to a "real class" reference in the context of this
* class.
- *
+ *
* @param mixin Mixin class to search for
* @return corresponding (target) class for the specified mixin or null if
* no corresponding mixin was found
@@ -897,7 +899,7 @@ public class ClassInfo extends TreeInfo {
if (mixin == null || !mixin.isMixin || this.isMixin) {
return null;
}
-
+
ClassInfo correspondingType = this.correspondingTypes.get(mixin);
if (correspondingType == null) {
correspondingType = this.findSuperTypeForMixin(mixin);
@@ -912,24 +914,24 @@ public class ClassInfo extends TreeInfo {
*/
private ClassInfo findSuperTypeForMixin(ClassInfo mixin) {
ClassInfo superClass = this;
-
+
while (superClass != null && superClass != ClassInfo.OBJECT) {
for (MixinInfo minion : superClass.mixins) {
if (minion.getClassInfo().equals(mixin)) {
return superClass;
}
}
-
+
superClass = superClass.getSuperClass();
}
-
+
return null;
}
/**
* Find out whether this (mixin) class has another mixin in its superclass
* hierarchy. This method always returns false for non-mixin classes.
- *
+ *
* @return true if and only if one or more mixins are found in the hierarchy
* of this mixin
*/
@@ -937,9 +939,9 @@ public class ClassInfo extends TreeInfo {
if (!this.isMixin) {
return false;
}
-
+
ClassInfo superClass = this.getSuperClass();
-
+
while (superClass != null && superClass != ClassInfo.OBJECT) {
if (superClass.isMixin) {
return true;
@@ -949,12 +951,12 @@ public class ClassInfo extends TreeInfo {
return false;
}
-
+
/**
* Find out whether this (non-mixin) class has a mixin targetting
* any of its superclasses. This method always returns false for
* mixin classes.
- *
+ *
* @return true if and only if one or more classes in this class's hierarchy
* are targetted by a mixin
*/
@@ -962,22 +964,22 @@ public class ClassInfo extends TreeInfo {
if (this.isMixin) {
return false;
}
-
+
ClassInfo superClass = this.getSuperClass();
-
+
while (superClass != null && superClass != ClassInfo.OBJECT) {
if (superClass.mixins.size() > 0) {
return true;
}
superClass = superClass.getSuperClass();
}
-
+
return false;
}
/**
* Finds the specified private or protected method in this class's hierarchy
- *
+ *
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
@@ -989,7 +991,7 @@ public class ClassInfo extends TreeInfo {
/**
* Finds the specified private or protected method in this class's hierarchy
- *
+ *
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
@@ -999,10 +1001,10 @@ public class ClassInfo extends TreeInfo {
public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass, int flags) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, flags);
}
-
+
/**
* Finds the specified public or protected method in this class's hierarchy
- *
+ *
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
@@ -1011,10 +1013,10 @@ public class ClassInfo extends TreeInfo {
public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE);
}
-
+
/**
* Finds the specified public or protected method in this class's hierarchy
- *
+ *
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
@@ -1024,10 +1026,10 @@ public class ClassInfo extends TreeInfo {
public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass, int flags) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, flags);
}
-
+
/**
* Finds the specified public or protected method in this class's hierarchy
- *
+ *
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
@@ -1040,7 +1042,7 @@ public class ClassInfo extends TreeInfo {
/**
* Finds the specified public or protected method in this class's hierarchy
- *
+ *
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
@@ -1051,10 +1053,10 @@ public class ClassInfo extends TreeInfo {
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
return this.findMethodInHierarchy(name, desc, includeThisClass, traversal, 0);
}
-
+
/**
* Finds the specified public or protected method in this class's hierarchy
- *
+ *
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
@@ -1066,10 +1068,10 @@ public class ClassInfo extends TreeInfo {
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, int flags) {
return this.findInHierarchy(name, desc, includeThisClass, traversal, flags, Type.METHOD);
}
-
+
/**
* Finds the specified private or protected field in this class's hierarchy
- *
+ *
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
@@ -1078,10 +1080,10 @@ public class ClassInfo extends TreeInfo {
public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE);
}
-
+
/**
* Finds the specified private or protected field in this class's hierarchy
- *
+ *
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
@@ -1091,10 +1093,10 @@ public class ClassInfo extends TreeInfo {
public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass, int flags) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, flags);
}
-
+
/**
* Finds the specified public or protected field in this class's hierarchy
- *
+ *
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
@@ -1103,10 +1105,10 @@ public class ClassInfo extends TreeInfo {
public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE);
}
-
+
/**
* Finds the specified public or protected field in this class's hierarchy
- *
+ *
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
@@ -1116,10 +1118,10 @@ public class ClassInfo extends TreeInfo {
public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass, int flags) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, flags);
}
-
+
/**
* Finds the specified public or protected field in this class's hierarchy
- *
+ *
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
@@ -1132,7 +1134,7 @@ public class ClassInfo extends TreeInfo {
/**
* Finds the specified public or protected field in this class's hierarchy
- *
+ *
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
@@ -1143,10 +1145,10 @@ public class ClassInfo extends TreeInfo {
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
return this.findFieldInHierarchy(name, desc, includeThisClass, traversal, 0);
}
-
+
/**
* Finds the specified public or protected field in this class's hierarchy
- *
+ *
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
@@ -1158,11 +1160,11 @@ public class ClassInfo extends TreeInfo {
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, int flags) {
return this.findInHierarchy(name, desc, includeThisClass, traversal, flags, Type.FIELD);
}
-
+
/**
* Finds a public or protected member in the hierarchy of this class which
- * matches the supplied details
- *
+ * matches the supplied details
+ *
* @param name Member name to search
* @param desc Member descriptor
* @param includeThisClass True to return this class if the field exists
@@ -1178,17 +1180,17 @@ public class ClassInfo extends TreeInfo {
if (member != null) {
return member;
}
-
+
if (traversal.canTraverse()) {
for (MixinInfo mixin : this.mixins) {
M mixinMember = mixin.getClassInfo().findMember(name, desc, flags, type);
if (mixinMember != null) {
return this.cloneMember(mixinMember);
}
- }
+ }
}
}
-
+
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
for (ClassInfo superTarget : superClassInfo.getTargets()) {
@@ -1198,16 +1200,16 @@ public class ClassInfo extends TreeInfo {
}
}
}
-
+
return null;
}
-
+
/**
* Effectively a clone method for member, placed here so that the enclosing
* instance for the inner class is this class and not the enclosing instance
- * of the existing class. Basically creates a cloned member with this
+ * of the existing class. Basically creates a cloned member with this
* ClassInfo as its parent.
- *
+ *
* @param member
* @return
*/
@@ -1216,23 +1218,23 @@ public class ClassInfo extends TreeInfo {
if (member instanceof Method) {
return (M)new Method(member);
}
-
+
return (M)new Field(member);
}
-
+
/**
* Finds the specified public or protected method in this class
- *
+ *
* @param method Method to search for
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodNode method) {
return this.findMethod(method.name, method.desc, method.access);
}
-
+
/**
* Finds the specified public or protected method in this class
- *
+ *
* @param method Method to search for
* @param flags search flags
* @return the method object or null if the method could not be resolved
@@ -1240,20 +1242,20 @@ public class ClassInfo extends TreeInfo {
public Method findMethod(MethodNode method, int flags) {
return this.findMethod(method.name, method.desc, flags);
}
-
+
/**
* Finds the specified public or protected method in this class
- *
+ *
* @param method Method to search for
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodInsnNode method) {
return this.findMethod(method.name, method.desc, 0);
}
-
+
/**
* Finds the specified public or protected method in this class
- *
+ *
* @param method Method to search for
* @param flags search flags
* @return the method object or null if the method could not be resolved
@@ -1261,10 +1263,10 @@ public class ClassInfo extends TreeInfo {
public Method findMethod(MethodInsnNode method, int flags) {
return this.findMethod(method.name, method.desc, flags);
}
-
+
/**
* Finds the specified public or protected method in this class
- *
+ *
* @param name Method name to search for
* @param desc Method signature to search for
* @param flags search flags
@@ -1273,20 +1275,20 @@ public class ClassInfo extends TreeInfo {
public Method findMethod(String name, String desc, int flags) {
return this.findMember(name, desc, flags, Type.METHOD);
}
-
+
/**
* Finds the specified field in this class
- *
+ *
* @param field Field to search for
* @return the field object or null if the field could not be resolved
*/
public Field findField(FieldNode field) {
return this.findField(field.name, field.desc, field.access);
}
-
+
/**
* Finds the specified public or protected method in this class
- *
+ *
* @param field Field to search for
* @param flags search flags
* @return the field object or null if the field could not be resolved
@@ -1294,10 +1296,10 @@ public class ClassInfo extends TreeInfo {
public Field findField(FieldInsnNode field, int flags) {
return this.findField(field.name, field.desc, flags);
}
-
+
/**
* Finds the specified field in this class
- *
+ *
* @param name Field name to search for
* @param desc Field signature to search for
* @param flags search flags
@@ -1309,7 +1311,7 @@ public class ClassInfo extends TreeInfo {
/**
* Finds the specified member in this class
- *
+ *
* @param name Field name to search for
* @param desc Field signature to search for
* @param flags search flags
@@ -1319,13 +1321,13 @@ public class ClassInfo extends TreeInfo {
private M findMember(String name, String desc, int flags, Type memberType) {
@SuppressWarnings("unchecked")
Set members = (Set)(memberType == Type.METHOD ? this.methods : this.fields);
-
+
for (M member : members) {
if (member.equals(name, desc) && member.matchesFlags(flags)) {
return member;
}
}
-
+
return null;
}
@@ -1339,7 +1341,7 @@ public class ClassInfo extends TreeInfo {
}
return ((ClassInfo)other).name.equals(this.name);
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@@ -1353,7 +1355,7 @@ public class ClassInfo extends TreeInfo {
* the class was already defined, then the original ClassInfo is returned
* from the internal cache. Otherwise a new ClassInfo is created and
* returned.
- *
+ *
* @param classNode
* @return
*/
@@ -1363,21 +1365,21 @@ public class ClassInfo extends TreeInfo {
info = new ClassInfo(classNode);
ClassInfo.cache.put(classNode.name, info);
}
-
+
return info;
}
/**
* Return a ClassInfo for the specified class name, fetches the ClassInfo
* from the cache where possible
- *
+ *
* @param className Binary name of the class to look up
* @return ClassInfo for the specified class name or null if the specified
* name cannot be resolved for some reason
*/
public static ClassInfo forName(String className) {
className = className.replace('.', '/');
-
+
ClassInfo info = ClassInfo.cache.get(className);
if (info == null) {
try {
@@ -1386,19 +1388,19 @@ public class ClassInfo extends TreeInfo {
} catch (Exception ex) {
ex.printStackTrace();
}
-
+
// Put null in the cache if load failed
ClassInfo.cache.put(className, info);
ClassInfo.logger.trace("Added class metadata for {} to metadata cache", className);
}
-
+
return info;
}
/**
* Return a ClassInfo for the specified class type, fetches the ClassInfo
* from the cache where possible and generates the class meta if not.
- *
+ *
* @param type Type to look up
* @return ClassInfo for the supplied type or null if the supplied type
* cannot be found or is a primitive type
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java
index 3a0f6e17..4643f620 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformerModuleInterfaceChecker.java
@@ -52,35 +52,35 @@ import com.google.common.io.Files;
* implemented and generates reports to the console and to files on disk
*/
public class MixinTransformerModuleInterfaceChecker implements IMixinTransformerModule {
-
+
/**
* CSV Report file
*/
private final File csv;
-
+
/**
* Text Report file
*/
private final File report;
-
+
/**
* Methods from interfaces that are already in the class before mixins are
* applied.
*/
private final Multimap interfaceMethods = HashMultimap.create();
-
+
public MixinTransformerModuleInterfaceChecker() {
File debugOutputFolder = new File(MixinTransformer.DEBUG_OUTPUT, "audit");
debugOutputFolder.mkdirs();
this.csv = new File(debugOutputFolder, "mixin_implementation_report.csv");
this.report = new File(debugOutputFolder, "mixin_implementation_report.txt");
-
+
try {
Files.write("Class,Method,Signature,Interface\n", this.csv, Charsets.ISO_8859_1);
} catch (IOException ex) {
// well this sucks
}
-
+
try {
String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Files.write("Mixin Implementation Report generated on " + dateTime + "\n", this.report, Charsets.ISO_8859_1);
@@ -97,7 +97,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
@Override
public void preApply(String transformedName, ClassNode targetClass, SortedSet mixins) {
ClassInfo targetClassInfo = ClassInfo.forName(targetClass.name);
- for (Method m : targetClassInfo.getInterfaceMethods()) {
+ for (Method m : targetClassInfo.getInterfaceMethods(false)) {
this.interfaceMethods.put(targetClassInfo, m);
}
}
@@ -114,26 +114,26 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
String className = targetClassInfo.getName().replace('/', '.');
int missingMethodCount = 0;
PrettyPrinter printer = new PrettyPrinter();
-
+
printer.add("Class: %s", className).hr();
printer.add("%-32s %-47s %s", "Return Type", "Missing Method", "From Interface").hr();
- Set interfaceMethods = targetClassInfo.getInterfaceMethods();
- Set implementedMethods = new HashSet(targetClassInfo.getSuperClass().getInterfaceMethods());
+ Set interfaceMethods = targetClassInfo.getInterfaceMethods(true);
+ Set implementedMethods = new HashSet(targetClassInfo.getSuperClass().getInterfaceMethods(true));
implementedMethods.addAll(this.interfaceMethods.removeAll(targetClassInfo));
-
+
for (Method method : interfaceMethods) {
Method found = targetClassInfo.findMethodInHierarchy(method.getName(), method.getDesc(), true, Traversal.ALL);
if (found != null) {
continue;
}
-
+
// Don't blame the subclass for not implementing methods that it does not need to implement.
if (implementedMethods.contains(method)) {
continue;
}
-
+
if (missingMethodCount > 0) {
printer.add();
}
@@ -143,7 +143,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
missingMethodCount++;
printer.add("%-32s%s", signaturePrinter.getReturnType(), signaturePrinter);
printer.add("%-80s %s", "", iface);
-
+
this.appendToCSVReport(className, method, iface);
}
@@ -164,7 +164,7 @@ public class MixinTransformerModuleInterfaceChecker implements IMixinTransformer
private void appendToTextReport(PrettyPrinter printer) {
FileOutputStream fos = null;
-
+
try {
fos = new FileOutputStream(this.report, true);
PrintStream stream = new PrintStream(fos);
From a8558bb5f0b7df57e54c9fd467dd6e161f1a018a Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Tue, 20 Oct 2015 10:53:41 +1300
Subject: [PATCH 012/169] 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 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
*/
@@ -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 013/169] 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 014/169] 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 015/169] 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 016/169] 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 017/169] 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 018/169] 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 019/169] 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 75f738cf28160f0d0950bcd7cf815754490e465b Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Sun, 25 Oct 2015 01:37:03 +0100
Subject: [PATCH 020/169] Fix issue with arrays of primitive types in local
variable tables
---
.../org/spongepowered/asm/mixin/transformer/MixinVerifier.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java
index c7869a82..99276ea1 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinVerifier.java
@@ -94,6 +94,9 @@ public class MixinVerifier extends SimpleVerifier {
return false;
}
ClassInfo typeInfo = ClassInfo.forType(type);
+ if (typeInfo == null) {
+ return false;
+ }
if (typeInfo.isInterface()) {
typeInfo = ClassInfo.forName("java/lang/Object");
}
From b86b843bb30bc25a464be3de478b9b3cd7e43f57 Mon Sep 17 00:00:00 2001
From: BenLewis
Date: Sun, 25 Oct 2015 19:02:40 +1300
Subject: [PATCH 021/169] 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;
}
From 960b215139a340be2976c07a4e6f270e2856dfaf Mon Sep 17 00:00:00 2001
From: Chris Sanders
Date: Thu, 29 Oct 2015 16:39:39 -0500
Subject: [PATCH 022/169] Revert "Set debug regardless. This happens before FML
sets deobfuscation."
This reverts commit f3c4945019c0725b02df085ff745ffd3fd0b38e9.
Revert "Always check isFMLDeobfuscated for null status."
This reverts commit d12d3f271c9a499897bb8f1d5f01ca74b8e7ae3d.
Revert "Perform nasty filter switch to gurarantee that we'll switch into INIT."
This reverts commit bdda81fb265a56ab0262e9b71fd87f7f7441becb.
---
.../asm/mixin/MixinEnvironment.java | 114 ++++++------------
.../mixin/transformer/MixinTransformer.java | 4 +-
2 files changed, 38 insertions(+), 80 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index ea2f47b3..57a43040 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -24,39 +24,40 @@
*/
package org.spongepowered.asm.mixin;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
-import net.minecraft.launchwrapper.IClassNameTransformer;
-import net.minecraft.launchwrapper.IClassTransformer;
-import net.minecraft.launchwrapper.ITweaker;
-import net.minecraft.launchwrapper.Launch;
-import net.minecraft.launchwrapper.LaunchClassLoader;
+import java.io.File;
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.Marker;
-import org.apache.logging.log4j.core.Filter;
-import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.core.helpers.Booleans;
-import org.apache.logging.log4j.message.Message;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
import org.spongepowered.asm.mixin.transformer.MixinTransformer;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.PrettyPrinter;
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Sets;
+
+import net.minecraft.launchwrapper.IClassNameTransformer;
+import net.minecraft.launchwrapper.IClassTransformer;
+import net.minecraft.launchwrapper.ITweaker;
+import net.minecraft.launchwrapper.Launch;
+import net.minecraft.launchwrapper.LaunchClassLoader;
/**
@@ -405,60 +406,28 @@ public class MixinEnvironment implements ITokenProvider {
static class MixinLogger {
- static MixinFilter filter = new MixinFilter();
+ static MixinAppender appender = new MixinAppender("MixinLogger", null, null);
public MixinLogger() {
- // Prep ugly hack for INIT phase
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
- log.addFilter(filter);
- log.setLevel(Level.DEBUG);
+ log.addAppender(appender);
}
- // Commence ugly hack for INIT phase
- static class MixinFilter extends AbstractFilter {
+ static class MixinAppender extends AbstractAppender {
- @Override
- public Result filter(final org.apache.logging.log4j.core.Logger logger, final Level level, final Marker marker, final String msg,
- final Object... params) {
- if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(msg)) {
- MixinEnvironment.gotoPhase(Phase.INIT);
- }
- // Log entries can be filtered before the blackboard has this value. We'll just look it up.
- final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
+ protected MixinAppender(String name, Filter filter, Layout extends Serializable> layout) {
+ super(name, filter, layout);
+ // TODO Auto-generated constructor stub
}
@Override
- public Result filter(final org.apache.logging.log4j.core.Logger logger, final Level level, final Marker marker, final Object msg,
- final Throwable t) {
- if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(msg)) {
+ public void append(LogEvent event) {
+ if (event.getLevel() == Level.DEBUG && "Validating minecraft".equals(event.getMessage().getFormat())) {
+ // transition to INIT
MixinEnvironment.gotoPhase(Phase.INIT);
}
- // Log entries can be filtered before the blackboard has this value. We'll just look it up.
- final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
- }
-
- @Override
- public Result filter(final org.apache.logging.log4j.core.Logger logger, final Level level, final Marker marker, final Message msg,
- final Throwable t) {
- if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(msg.getFormattedMessage())) {
- MixinEnvironment.gotoPhase(Phase.INIT);
- }
- // Log entries can be filtered before the blackboard has this value. We'll just look it up.
- final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
- }
-
- @Override
- public Result filter(final LogEvent event) {
- if (MixinEnvironment.getCurrentPhase().equals(Phase.PREINIT) && "Validating minecraft".equals(event.getMessage().getFormattedMessage())) {
- MixinEnvironment.gotoPhase(Phase.INIT);
- }
- // Log entries can be filtered before the blackboard has this value. We'll just look it up.
- final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- return isFMLDeobfuscated != null && isFMLDeobfuscated ? Result.NEUTRAL : Result.DENY;
}
+
}
}
@@ -985,20 +954,9 @@ public class MixinEnvironment implements ITokenProvider {
}
if (phase == Phase.DEFAULT) {
- // Remove filter
+ // remove appender
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
- for (Iterator iter = log.getFilters(); iter.hasNext();) {
- final Filter filter = iter.next();
- if (filter instanceof MixinLogger.MixinFilter) {
- final Boolean isFMLDeobfuscated = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
- // If FML isn't in obfuscated environment, we need to hotswap the log level back
- if (isFMLDeobfuscated != null && !isFMLDeobfuscated) {
- log.setLevel(Level.INFO);
- }
- iter.remove();
- break;
- }
- }
+ log.removeAppender(MixinLogger.appender);
}
MixinEnvironment.currentPhase = phase;
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..adcc3004 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java
@@ -354,7 +354,7 @@ public class MixinTransformer extends TreeTransformer {
boolean locked = this.lock.push().isSet();
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
-
+
if (this.currentEnvironment != environment && !locked) {
try {
this.init(environment);
@@ -363,7 +363,7 @@ public class MixinTransformer extends TreeTransformer {
throw new RuntimeException(ex);
}
}
-
+
try {
SortedSet mixins = null;
boolean invalidRef = false;
From 65c103eb5a36fa3f863fb21659e714603bcf2947 Mon Sep 17 00:00:00 2001
From: Chris Sanders
Date: Thu, 29 Oct 2015 18:53:09 -0500
Subject: [PATCH 023/169] Need to actually start the appender.
Signed-off-by: Chris Sanders
---
.../asm/mixin/MixinEnvironment.java | 45 +++++++++----------
1 file changed, 22 insertions(+), 23 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index 57a43040..123d57a5 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -24,6 +24,27 @@
*/
package org.spongepowered.asm.mixin;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Sets;
+import net.minecraft.launchwrapper.IClassNameTransformer;
+import net.minecraft.launchwrapper.IClassTransformer;
+import net.minecraft.launchwrapper.ITweaker;
+import net.minecraft.launchwrapper.Launch;
+import net.minecraft.launchwrapper.LaunchClassLoader;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.helpers.Booleans;
+import org.spongepowered.asm.launch.MixinBootstrap;
+import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
+import org.spongepowered.asm.mixin.transformer.MixinTransformer;
+import org.spongepowered.asm.util.ITokenProvider;
+import org.spongepowered.asm.util.PrettyPrinter;
+
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
@@ -36,29 +57,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.helpers.Booleans;
-import org.apache.logging.log4j.core.Filter;
-import org.apache.logging.log4j.core.Layout;
-import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.appender.AbstractAppender;
-import org.spongepowered.asm.launch.MixinBootstrap;
-import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
-import org.spongepowered.asm.mixin.transformer.MixinTransformer;
-import org.spongepowered.asm.util.ITokenProvider;
-import org.spongepowered.asm.util.PrettyPrinter;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
-
-import net.minecraft.launchwrapper.IClassNameTransformer;
-import net.minecraft.launchwrapper.IClassTransformer;
-import net.minecraft.launchwrapper.ITweaker;
-import net.minecraft.launchwrapper.Launch;
-import net.minecraft.launchwrapper.LaunchClassLoader;
-
/**
* The mixin environment manages global state information for the mixin
@@ -410,6 +408,7 @@ public class MixinEnvironment implements ITokenProvider {
public MixinLogger() {
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger)LogManager.getLogger("FML");
+ appender.start();
log.addAppender(appender);
}
From dc8461901332f69f519592e100f9f97f62181fee Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Mon, 2 Nov 2015 11:35:02 +0000
Subject: [PATCH 024/169] Checkstyle fixes
---
.../org/spongepowered/asm/mixin/transformer/ClassInfo.java | 6 ++++--
.../asm/mixin/transformer/MixinTargetContext.java | 3 +--
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
index 14ee1f78..5c851ea6 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
@@ -730,7 +730,8 @@ public class ClassInfo extends TreeInfo {
* containing all methods for all interfaces implemented by this class and
* all super interfaces of those interfaces.
*
- * @param includeMixins Whether to include methods from mixins targeting this class info
+ * @param includeMixins Whether to include methods from mixins targeting
+ * this class info
* @return read-only view of class methods
*/
public Set getInterfaceMethods(boolean includeMixins) {
@@ -758,7 +759,8 @@ public class ClassInfo extends TreeInfo {
* interface methods to the supplied set
*
* @param methods Method set to add to
- * @param includeMixins Whether to include methods from mixins targeting this class info
+ * @param includeMixins Whether to include methods from mixins targeting
+ * this class info
* @return superclass reference, used to make the code above more fluent
*/
private ClassInfo addMethodsRecursive(Set methods, boolean includeMixins) {
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index c18799c0..4b66f66f 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -373,9 +373,8 @@ public class MixinTargetContext implements IReferenceMapperContext {
String desc = this.transformDescriptor(type);
if (!type.toString().equals(desc)) {
return Type.getType(desc);
- } else {
- return constant;
}
+ return constant;
} else if (constant instanceof Handle) {
return this.transformHandle(method, iter, (Handle)constant);
}
From 13ac04cc88fe7465c406467540abe1c85da347d6 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Mon, 2 Nov 2015 11:46:10 +0000
Subject: [PATCH 025/169] Clean up unnecessary synthetics
---
.../spongepowered/tools/agent/MixinAgent.java | 10 +++---
.../asm/mixin/transformer/MixinInfo.java | 33 ++++++++++++-------
2 files changed, 26 insertions(+), 17 deletions(-)
diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java
index bb0e7ce3..85132c6f 100644
--- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java
+++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java
@@ -49,7 +49,7 @@ 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 {
+ class Transformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className, Class> classBeingRedefined, ProtectionDomain domain, byte[] classfileBuffer)
@@ -110,14 +110,14 @@ public class MixinAgent implements IHotSwap {
/**
* Class loader used to load mixin classes
*/
- private static final MixinAgentClassLoader classLoader = new MixinAgentClassLoader();
+ static final MixinAgentClassLoader classLoader = new MixinAgentClassLoader();
- private static final Logger logger = LogManager.getLogger("mixin.agent");
+ static final Logger logger = LogManager.getLogger("mixin.agent");
/**
* Instance used to register the transformer
*/
- private static Instrumentation instrumentation = null;
+ static Instrumentation instrumentation = null;
/**
* Instances of all agents
@@ -127,7 +127,7 @@ public class MixinAgent implements IHotSwap {
/**
* MixinTransformer instance to use to transform the mixin's target classes
*/
- private final MixinTransformer classTransformer;
+ final MixinTransformer classTransformer;
/**
* Constructs an agent from a class transformer in which it will use to
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 b21ffe91..0a8b6c66 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
@@ -70,6 +70,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* State that can be reloaded.
*/
private class ValidationState {
+
/**
* Mixin bytes (read once, generate tree on demand)
*/
@@ -135,14 +136,15 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
}
private class ReloadedState extends ValidationState {
+
/**
* The previous validation state to compare the changes to
*/
- final ValidationState parent;
+ private final ValidationState previous;
- ReloadedState(ValidationState parent, byte[] mixinBytes) {
- super(mixinBytes, parent.classInfo);
- this.parent = parent;
+ ReloadedState(ValidationState previous, byte[] mixinBytes) {
+ super(mixinBytes, previous.classInfo);
+ this.previous = previous;
}
/**
@@ -150,21 +152,21 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* only exits while reloading mixins.
*/
void validateChanges() {
- if (!this.syntheticInnerClasses.equals(this.parent.syntheticInnerClasses)) {
+ if (!this.syntheticInnerClasses.equals(this.previous.syntheticInnerClasses)) {
throw new MixinReloadException(MixinInfo.this, "Cannot change inner classes");
}
- if (!this.interfaces.equals(this.parent.interfaces)) {
+ if (!this.interfaces.equals(this.previous.interfaces)) {
throw new MixinReloadException(MixinInfo.this, "Cannot change interfaces");
}
- if (!new HashSet(this.softImplements).equals(new HashSet(this.parent.softImplements))) {
+ if (!new HashSet(this.softImplements).equals(new HashSet(this.previous.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))) {
+ if (!new HashSet(targets).equals(new HashSet(MixinInfo.this.getTargets0()))) {
throw new MixinReloadException(MixinInfo.this, "Cannot change target classes");
}
int priority = MixinInfo.this.readPriority(this.validationClassNode);
- if (priority != MixinInfo.this.priority) {
+ if (priority != MixinInfo.this.getPriority()) {
throw new MixinReloadException(MixinInfo.this, "Cannot change mixin priority");
}
}
@@ -293,7 +295,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* @param suppressPlugin
* @return
*/
- private List readTargetClasses(ClassNode classNode, boolean suppressPlugin) {
+ protected List readTargetClasses(ClassNode classNode, boolean suppressPlugin) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
@@ -351,7 +353,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* @param classNode
* @return
*/
- private int readPriority(ClassNode classNode) {
+ protected int readPriority(ClassNode classNode) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
@@ -580,7 +582,14 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* Get the target class list for this mixin
*/
public List getTargets() {
- return Collections.unmodifiableList(this.targetClasses);
+ return Collections.unmodifiableList(this.getTargets0());
+ }
+
+ /**
+ * Internal method to avoid synthetic bridge generation
+ */
+ protected List getTargets0() {
+ return this.targetClasses;
}
/**
From 7eb61bc53a0937b2d2f6c1676d85882eeede17da Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 17 Nov 2015 15:53:31 +0000
Subject: [PATCH 026/169] Begin compatibility level support, java 8 must now be
explicitly enabled
---
.../tools/agent/MixinAgentClassLoader.java | 4 +-
.../asm/launch/MixinLaunchAgentDefault.java | 6 +
.../asm/launch/MixinTweaker.java | 17 ++
.../asm/mixin/MixinEnvironment.java | 152 ++++++++++++++----
.../mixin/transformer/MixinApplicator.java | 7 +-
.../asm/mixin/transformer/MixinInfo.java | 32 ++--
.../mixin/transformer/MixinPreProcessor.java | 1 -
.../mixin/transformer/MixinTargetContext.java | 35 ++++
.../spongepowered/asm/util/JavaVersion.java | 55 +++++++
9 files changed, 258 insertions(+), 51 deletions(-)
create mode 100644 src/main/java/org/spongepowered/asm/util/JavaVersion.java
diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java
index 5aa06541..5eaa2946 100644
--- a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java
+++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java
@@ -30,6 +30,7 @@ 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 org.spongepowered.asm.mixin.MixinEnvironment;
import java.util.HashMap;
import java.util.Map;
@@ -110,7 +111,8 @@ class MixinAgentClassLoader extends ClassLoader {
*/
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);
+ cw.visit(MixinEnvironment.getCompatibilityLevel().classVersion(), Opcodes.ACC_PUBLIC, name.replace('.', '/'), null,
+ Type.getInternalName(Object.class), null);
// create init method
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null);
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java b/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java
index ae3e978e..05afe077 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentDefault.java
@@ -37,6 +37,7 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
protected static final String MFATT_MIXINCONFIGS = "MixinConfigs";
protected static final String MFATT_TOKENPROVIDERS = "MixinTokenProviders";
protected static final String MFATT_MAINCLASS = "Main-Class";
+ protected static final String MFATT_COMPATIBILITY = "MixinCompatibilityLevel";
public MixinLaunchAgentDefault(URI uri) {
super(uri);
@@ -44,6 +45,11 @@ public class MixinLaunchAgentDefault extends MixinLaunchAgentAbstract {
@Override
public void prepare() {
+ String compatibilityLevel = this.attributes.get(MixinLaunchAgentDefault.MFATT_COMPATIBILITY);
+ if (compatibilityLevel != null) {
+ MixinTweaker.setCompatibilityLevel(compatibilityLevel);
+ }
+
String mixinConfigs = this.attributes.get(MixinLaunchAgentDefault.MFATT_MIXINCONFIGS);
if (mixinConfigs != null) {
for (String config : mixinConfigs.split(",")) {
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java b/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java
index eb6fbcbc..66677eaf 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinTweaker.java
@@ -39,6 +39,7 @@ import net.minecraft.launchwrapper.LaunchClassLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.MixinEnvironment;
+import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
@@ -195,6 +196,22 @@ public class MixinTweaker implements ITweaker {
public String[] getLaunchArguments() {
return new String[]{};
}
+
+ /**
+ * Set the desired compatibility level as a string, used by agents to set
+ * compatibility level from jar manifest
+ *
+ * @param level compatibility level as a string
+ */
+ static void setCompatibilityLevel(String level) {
+ try {
+ CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase());
+ MixinTweaker.logger.debug("Setting mixin compatibility level: {}", value);
+ MixinEnvironment.setCompatibilityLevel(value);
+ } catch (IllegalArgumentException ex) {
+ MixinTweaker.logger.warn("Invalid compatibility level specified: {}", level);
+ }
+ }
/**
* Add a config from a jar manifest source or the command line. Supports
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index edabde12..b1294206 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -24,27 +24,6 @@
*/
package org.spongepowered.asm.mixin;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
-import net.minecraft.launchwrapper.IClassNameTransformer;
-import net.minecraft.launchwrapper.IClassTransformer;
-import net.minecraft.launchwrapper.ITweaker;
-import net.minecraft.launchwrapper.Launch;
-import net.minecraft.launchwrapper.LaunchClassLoader;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.Filter;
-import org.apache.logging.log4j.core.Layout;
-import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.appender.AbstractAppender;
-import org.apache.logging.log4j.core.helpers.Booleans;
-import org.spongepowered.asm.launch.MixinBootstrap;
-import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
-import org.spongepowered.asm.mixin.transformer.MixinTransformer;
-import org.spongepowered.asm.util.ITokenProvider;
-import org.spongepowered.asm.util.PrettyPrinter;
-
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
@@ -57,6 +36,31 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import net.minecraft.launchwrapper.IClassNameTransformer;
+import net.minecraft.launchwrapper.IClassTransformer;
+import net.minecraft.launchwrapper.ITweaker;
+import net.minecraft.launchwrapper.Launch;
+import net.minecraft.launchwrapper.LaunchClassLoader;
+
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.helpers.Booleans;
+import org.spongepowered.asm.launch.MixinBootstrap;
+import org.spongepowered.asm.lib.Opcodes;
+import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider;
+import org.spongepowered.asm.mixin.transformer.MixinTransformer;
+import org.spongepowered.asm.util.ITokenProvider;
+import org.spongepowered.asm.util.JavaVersion;
+import org.spongepowered.asm.util.PrettyPrinter;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Sets;
+
/**
* The mixin environment manages global state information for the mixin
@@ -339,6 +343,58 @@ public class MixinEnvironment implements ITokenProvider {
}
}
+ /**
+ * Operational compatibility level for the mixin subsystem
+ */
+ public static enum CompatibilityLevel {
+
+ JAVA_6(Opcodes.V1_6, false),
+
+ JAVA_7(Opcodes.V1_7, false) {
+
+ @Override
+ boolean isSupported() {
+ return JavaVersion.current() >= 1.7;
+ }
+
+ },
+
+ JAVA_8(Opcodes.V1_8, true) {
+
+ @Override
+ boolean isSupported() {
+ return JavaVersion.current() >= 1.8;
+ }
+
+ };
+
+ private final int classVersion;
+
+ private final boolean resolveMethodsInInterfaces;
+
+ private CompatibilityLevel(int classVersion, boolean resolveMethodsInInterfaces) {
+ this.classVersion = classVersion;
+ this.resolveMethodsInInterfaces = resolveMethodsInInterfaces;
+ }
+
+ boolean isSupported() {
+ return true;
+ }
+
+ public int classVersion() {
+ return this.classVersion;
+ }
+
+ public boolean resolveMethodsInInterfaces() {
+ return this.resolveMethodsInInterfaces;
+ }
+
+ public boolean isAtLeast(CompatibilityLevel level) {
+ return this.ordinal() >= level.ordinal();
+ }
+
+ }
+
/**
* Tweaker used to notify the environment when we transition from preinit to
* default
@@ -461,6 +517,11 @@ public class MixinEnvironment implements ITokenProvider {
*/
private static Phase currentPhase = Phase.NOT_INITIALISED;
+ /**
+ * Current compatibility level
+ */
+ private static CompatibilityLevel compatibility = CompatibilityLevel.JAVA_6;
+
/**
* Show debug header info on first environment construction
*/
@@ -469,7 +530,7 @@ public class MixinEnvironment implements ITokenProvider {
/**
* Logger
*/
- private final Logger logger = LogManager.getLogger("mixin");
+ private static final Logger logger = LogManager.getLogger("mixin");
/**
* The phase for this environment
@@ -553,13 +614,14 @@ public class MixinEnvironment implements ITokenProvider {
private void printHeader(Object version) {
Side side = this.getSide();
String codeSource = this.getCodeSource();
- this.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
+ MixinEnvironment.logger.info("SpongePowered MIXIN Subsystem Version={} Source={} Env={}", version, codeSource, side);
if (this.getOption(Option.DEBUG_VERBOSE)) {
PrettyPrinter printer = new PrettyPrinter(32);
printer.add("SpongePowered MIXIN (Verbose debugging enabled)").centre().hr();
printer.add("%25s : %s", "Code source", codeSource);
- printer.add("%25s : %s", "Internal Version", version).hr();
+ printer.add("%25s : %s", "Internal Version", version);
+ printer.add("%25s : %s", "Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr();
for (Option option : Option.values()) {
printer.add("%25s : %s%s", option.property, option.parent == null ? "" : " - ", this.getOption(option));
}
@@ -640,7 +702,7 @@ public class MixinEnvironment implements ITokenProvider {
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
- this.logger.error("Error instantiating " + providerName, th);
+ MixinEnvironment.logger.error("Error instantiating " + providerName, th);
}
}
return this;
@@ -656,7 +718,7 @@ public class MixinEnvironment implements ITokenProvider {
if (provider != null && !this.tokenProviderClasses.contains(provider.getClass().getName())) {
String providerName = provider.getClass().getName();
TokenProviderWrapper wrapper = new TokenProviderWrapper(provider, this);
- this.logger.info("Adding new token provider {} to {}", providerName, this);
+ MixinEnvironment.logger.info("Adding new token provider {} to {}", providerName, this);
this.tokenProviders.add(wrapper);
this.tokenProviderClasses.add(providerName);
Collections.sort(this.tokenProviders);
@@ -847,7 +909,7 @@ public class MixinEnvironment implements ITokenProvider {
* list just once per environment and cache the result.
*/
private void buildTransformerDelegationList() {
- this.logger.debug("Rebuilding transformer delegation list:");
+ MixinEnvironment.logger.debug("Rebuilding transformer delegation list:");
this.transformers = new ArrayList();
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
String transformerName = transformer.getClass().getName();
@@ -859,18 +921,18 @@ public class MixinEnvironment implements ITokenProvider {
}
}
if (include && !transformerName.contains(MixinTransformer.class.getName())) {
- this.logger.debug(" Adding: {}", transformerName);
+ MixinEnvironment.logger.debug(" Adding: {}", transformerName);
this.transformers.add(transformer);
} else {
- this.logger.debug(" Excluding: {}", transformerName);
+ MixinEnvironment.logger.debug(" Excluding: {}", transformerName);
}
}
- this.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
+ MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size());
for (IClassTransformer transformer : Launch.classLoader.getTransformers()) {
if (transformer instanceof IClassNameTransformer) {
- this.logger.debug("Found name transformer: {}", transformer.getClass().getName());
+ MixinEnvironment.logger.debug("Found name transformer: {}", transformer.getClass().getName());
this.nameTransformer = (IClassNameTransformer) transformer;
}
}
@@ -904,7 +966,9 @@ public class MixinEnvironment implements ITokenProvider {
if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) {
MixinEnvironment.currentPhase = phase;
MixinEnvironment.getEnvironment(phase);
- new MixinLogger();
+
+ @SuppressWarnings("unused")
+ MixinLogger logSpy = new MixinLogger();
}
}
@@ -943,6 +1007,30 @@ public class MixinEnvironment implements ITokenProvider {
return MixinEnvironment.currentEnvironment;
}
+ /**
+ * Get the current compatibility level
+ */
+ public static CompatibilityLevel getCompatibilityLevel() {
+ return MixinEnvironment.compatibility;
+ }
+
+ /**
+ * Set desired compatibility level for the entire environment
+ *
+ * @param level Level to set, ignored if less than the current level
+ * @throws IllegalArgumentException if the specified level is not supported
+ */
+ public static void setCompatibilityLevel(CompatibilityLevel level) throws IllegalArgumentException {
+ if (level != MixinEnvironment.compatibility && level.isAtLeast(MixinEnvironment.compatibility)) {
+ if (!level.isSupported()) {
+ throw new IllegalArgumentException("The requested compatibility level " + level + " could not be set. Level is not supported");
+ }
+
+ MixinEnvironment.compatibility = level;
+ MixinEnvironment.logger.info("Compatibility level set to {}", level);
+ }
+ }
+
/**
* Internal callback
*
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
index 9ef1870b..c571d41b 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
@@ -237,6 +237,7 @@ public class MixinApplicator {
if (mixin.shouldSetSourceFile()) {
this.targetClass.sourceFile = mixin.getSourceFile();
}
+ this.targetClass.version = Math.max(this.targetClass.version, mixin.getMinRequiredClassVersion());
}
/**
@@ -676,9 +677,9 @@ public class MixinApplicator {
if (node instanceof JumpInsnNode) {
throw new InvalidMixinException(mixin, "Unsupported opcode in initialiser");
}
- AbstractInsnNode iThinkWereACloneNow = node.clone(labels);
- ctor.instructions.insert(insn, iThinkWereACloneNow);
- insn = iThinkWereACloneNow;
+ AbstractInsnNode imACloneNow = node.clone(labels);
+ ctor.instructions.insert(insn, imACloneNow);
+ insn = imACloneNow;
}
return;
}
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 0a8b6c66..4b3dd05b 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
@@ -107,18 +107,18 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* Initial ClassNode created for mixin validation, not used for actual
* application
*/
- ClassNode validationClassNode;
+ ClassNode classNode;
ValidationState(byte[] mixinBytes, ClassInfo classInfo) {
this.mixinBytes = mixinBytes;
- this.validationClassNode = this.getClassNode(0);
+ this.classNode = this.getClassNode(0);
this.classInfo = classInfo;
}
ValidationState(byte[] mixinBytes) {
this.mixinBytes = mixinBytes;
- this.validationClassNode = this.getClassNode(0);
- this.classInfo = ClassInfo.fromClassNode(this.validationClassNode);
+ this.classNode = this.getClassNode(0);
+ this.classInfo = ClassInfo.fromClassNode(this.classNode);
}
/**
@@ -161,11 +161,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
if (!new HashSet(this.softImplements).equals(new HashSet(this.previous.softImplements))) {
throw new MixinReloadException(MixinInfo.this, "Cannot change soft interfaces");
}
- List targets = MixinInfo.this.readTargetClasses(this.validationClassNode, true);
+ List targets = MixinInfo.this.readTargetClasses(this.classNode, true);
if (!new HashSet(targets).equals(new HashSet(MixinInfo.this.getTargets0()))) {
throw new MixinReloadException(MixinInfo.this, "Cannot change target classes");
}
- int priority = MixinInfo.this.readPriority(this.validationClassNode);
+ int priority = MixinInfo.this.readPriority(this.classNode);
if (priority != MixinInfo.this.getPriority()) {
throw new MixinReloadException(MixinInfo.this, "Cannot change mixin priority");
}
@@ -270,7 +270,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
void validate() {
try {
- ClassNode classNode = this.uninitialisedState.validationClassNode;
+ ClassNode classNode = this.uninitialisedState.classNode;
this.uninitialisedState.detachedSuper = this.validateTargetClasses(classNode);
this.validateMixin(this.uninitialisedState);
this.readImplementations(this.uninitialisedState);
@@ -280,7 +280,7 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
} else {
new MixinPreProcessor(this, classNode).prepare();
}
- this.uninitialisedState.validationClassNode = null;
+ this.uninitialisedState.classNode = null;
// the state is now fully initialised and validated
this.validationState = this.uninitialisedState;
} finally {
@@ -392,14 +392,18 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
if (!state.classInfo.isProbablyStatic()) {
throw new InvalidMixinException(this, "Inner class mixin must be declared static");
}
+
+ if (state.classNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) {
+ throw new InvalidMixinException(this, "Unsupported mixin class version " + state.classNode.version);
+ }
// 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 : state.validationClassNode.fields) {
+ for (FieldNode field : state.classNode.fields) {
this.checkRemappable(Shadow.class, field.name, ASMHelper.getVisibleAnnotation(field, Shadow.class));
}
- for (MethodNode method : state.validationClassNode.methods) {
+ for (MethodNode method : state.classNode.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)) {
@@ -420,9 +424,9 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* Read and process any {@link Implements} annotations on the mixin
*/
private void readImplementations(ValidationState state) {
- state.interfaces.addAll(state.validationClassNode.interfaces);
+ state.interfaces.addAll(state.classNode.interfaces);
- AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(state.validationClassNode, Implements.class);
+ AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(state.classNode, Implements.class);
if (implementsAnnotation == null) {
return;
}
@@ -449,11 +453,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
* config.
*/
private void readInnerClasses(ValidationState state) {
- for (InnerClassNode inner : state.validationClassNode.innerClasses) {
+ for (InnerClassNode inner : state.classNode.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 + "$")) {
+ || inner.name.startsWith(state.classNode.name + "$")) {
state.syntheticInnerClasses.add(inner.name);
} else {
throw new InvalidMixinException(this, "Unhandled synthetic inner class found: " + inner.name);
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java
index 53a4c4aa..769da82d 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessor.java
@@ -130,7 +130,6 @@ class MixinPreProcessor {
MixinTargetContext createContextFor(ClassNode target) {
this.prepare();
MixinTargetContext context = new MixinTargetContext(this.mixin, this.classNode, target);
- target.version = Math.max(this.classNode.version, target.version);
this.attach(context);
return context;
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index 4b66f66f..51bd7c61 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -36,6 +36,8 @@ import org.spongepowered.asm.lib.Handle;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.*;
+import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
+import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.mixin.injection.struct.Target;
@@ -99,6 +101,12 @@ public class MixinTargetContext implements IReferenceMapperContext {
* True if this mixin's superclass is detached from the target superclass
*/
private final boolean detachedSuper;
+
+ /**
+ * Minimum class version required to apply this mixin, target class will be
+ * upgraded if the version is below this value
+ */
+ private int minRequiredClassVersion = CompatibilityLevel.JAVA_6.classVersion();
/**
* ctor
@@ -114,6 +122,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
this.targetClassInfo = ClassInfo.forName(target.name);
this.inheritsFromMixin = mixin.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy();
this.detachedSuper = !this.classNode.superName.equals(this.targetClass.superName);
+ this.requireVersion(classNode.version);
}
/**
@@ -192,6 +201,13 @@ public class MixinTargetContext implements IReferenceMapperContext {
public ClassInfo getTargetClassInfo() {
return this.targetClassInfo;
}
+
+ /**
+ * Get the minimum required class version for this mixin
+ */
+ public int getMinRequiredClassVersion() {
+ return this.minRequiredClassVersion;
+ }
/**
* Find the corresponding class type for the supplied mixin class in this
@@ -352,6 +368,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
* @param dynInsn Insn to transform
*/
private void transformInvokeDynamicNode(MethodNode method, Iterator iter, InvokeDynamicInsnNode dynInsn) {
+ this.requireVersion(Opcodes.V1_7);
dynInsn.desc = this.transformMethodDescriptor(dynInsn.desc);
dynInsn.bsm = this.transformHandle(method, iter, dynInsn.bsm);
for (int i = 0; i < dynInsn.bsmArgs.length; i++) {
@@ -608,6 +625,23 @@ public class MixinTargetContext implements IReferenceMapperContext {
return target;
}
+ /**
+ * Mark this mixin as requiring the specified class version in the context
+ * of the current target
+ *
+ * @param version version to require
+ */
+ protected void requireVersion(int version) {
+ this.minRequiredClassVersion = Math.max(this.minRequiredClassVersion, version);
+
+ // This validation is done on the mixin beforehand, however it's still
+ // possible that an upstream transformer can inject java 7 instructions
+ // without updating the class version.
+ if (version > MixinEnvironment.getCompatibilityLevel().classVersion()) {
+ throw new InvalidMixinException(this, "Unsupported mixin class version " + version);
+ }
+ }
+
/**
* Get the mixin info for this mixin
*/
@@ -725,4 +759,5 @@ public class MixinTargetContext implements IReferenceMapperContext {
public void postApply(String transformedName, ClassNode targetClass) {
this.mixin.postApply(transformedName, targetClass);
}
+
}
diff --git a/src/main/java/org/spongepowered/asm/util/JavaVersion.java b/src/main/java/org/spongepowered/asm/util/JavaVersion.java
new file mode 100644
index 00000000..342d6dfc
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/util/JavaVersion.java
@@ -0,0 +1,55 @@
+/*
+ * This file is part of Mixin, licensed under the MIT License (MIT).
+ *
+ * Copyright (c) SpongePowered
+ * Copyright (c) contributors
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.spongepowered.asm.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Small helper to resolve the current java version
+ */
+public abstract class JavaVersion {
+
+ private static double current = 0.0;
+
+ private JavaVersion() {}
+
+ public static double current() {
+ if (JavaVersion.current == 0.0) {
+ JavaVersion.current = JavaVersion.resolveCurrentVersion();
+ }
+ return JavaVersion.current;
+ }
+
+ private static double resolveCurrentVersion() {
+ String version = System.getProperty("java.version");
+ Matcher matcher = Pattern.compile("[0-9]+\\.[0-9]+").matcher(version);
+ if (matcher.find()) {
+ return Double.parseDouble(matcher.group());
+ }
+ return 1.6;
+ }
+
+}
From 8438e29533089a2bbad840d0ba3a2d0f579dd853 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 17 Nov 2015 15:53:59 +0000
Subject: [PATCH 027/169] Resolve methods in interfaces if supported?
---
.../asm/mixin/transformer/ClassInfo.java | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
index 5c851ea6..1be6b324 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
@@ -43,6 +43,7 @@ import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.FrameNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
+import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type;
import com.google.common.collect.ImmutableList;
@@ -1202,6 +1203,16 @@ public class ClassInfo extends TreeInfo {
}
}
}
+
+ if (this.isInterface || MixinEnvironment.getCompatibilityLevel().resolveMethodsInInterfaces()) {
+ for (String implemented : this.interfaces) {
+ ClassInfo iface = ClassInfo.forName(implemented);
+ M member = iface.findInHierarchy(name, desc, true, traversal.next(), flags & ~ClassInfo.INCLUDE_PRIVATE, type);
+ if (member != null) {
+ return member;
+ }
+ }
+ }
return null;
}
From e0e00da2762b7cfb31602bf5f5ed557e8e53cfbf Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 17 Nov 2015 15:54:42 +0000
Subject: [PATCH 028/169] Version bump to 0.4.7
---
gradle.properties | 2 +-
src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/gradle.properties b/gradle.properties
index a8b235bd..699cd8cc 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -4,5 +4,5 @@ packaging=jar
description=Mixin
url=https://www.spongepowered.org
organization=SpongePowered
-buildVersion=0.4.6
+buildVersion=0.4.7
buildType=SNAPSHOT
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java
index e48bcec4..e516137d 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java
@@ -60,7 +60,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
- public static final String VERSION = "0.4.6";
+ public static final String VERSION = "0.4.7";
/**
* Blackboard key where the subsystem version will be stored to indicate
From bd93ef2806557bd8b25b5f5e2509c8d9a81c3237 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Thu, 19 Nov 2015 02:05:41 +0000
Subject: [PATCH 029/169] Add mixed-in interfaces to target class metadata
---
.../org/spongepowered/asm/mixin/transformer/MixinApplicator.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
index c571d41b..77d6fd19 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
@@ -224,6 +224,7 @@ public class MixinApplicator {
for (String interfaceName : mixin.getInterfaces()) {
if (!this.targetClass.interfaces.contains(interfaceName)) {
this.targetClass.interfaces.add(interfaceName);
+ mixin.getTargetClassInfo().addInterface(interfaceName);
}
}
}
From 3a25ffa10fd2e459153133e52e98e58764d7881b Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Thu, 19 Nov 2015 13:25:33 +0000
Subject: [PATCH 030/169] Collapse vestigial if
---
.../asm/mixin/transformer/MixinApplicator.java | 14 ++++++--------
1 file changed, 6 insertions(+), 8 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
index 77d6fd19..1efe2b3f 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicator.java
@@ -524,14 +524,12 @@ public class MixinApplicator {
MethodNode ctor = null;
for (MethodNode mixinMethod : mixin.getMethods()) {
- if (Constants.INIT.equals(mixinMethod.name)) {
- if (MixinApplicator.hasLineNumbers(mixinMethod)) {
- if (ctor == null) {
- ctor = mixinMethod;
- } else {
- // Not an error condition, just weird
- this.logger.warn(String.format("Mixin %s has multiple constructors, %s was selected\n", mixin, ctor.desc));
- }
+ if (Constants.INIT.equals(mixinMethod.name) && MixinApplicator.hasLineNumbers(mixinMethod)) {
+ if (ctor == null) {
+ ctor = mixinMethod;
+ } else {
+ // Not an error condition, just weird
+ this.logger.warn(String.format("Mixin %s has multiple constructors, %s was selected\n", mixin, ctor.desc));
}
}
}
From f32d67a23c7086cb79f24d03abdd474544180872 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Sat, 21 Nov 2015 02:20:16 +0000
Subject: [PATCH 031/169] Handle gaps in local variable table when failing over
to surrogates
---
.../asm/mixin/injection/callback/CallbackInjector.java | 4 ++--
.../org/spongepowered/asm/mixin/injection/struct/Target.java | 3 ++-
src/main/java/org/spongepowered/asm/util/Locals.java | 3 ++-
3 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
index e8512fda..726629d6 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
@@ -422,8 +422,8 @@ public class CallbackInjector extends Injector {
private String generateBadLVTMessage(final Callback callback) {
int position = callback.target.method.instructions.indexOf(callback.node);
List expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
- List found = CallbackInjector.summariseLocals(callback.localTypes, callback.frameSize);
- String message = String.format("LVT in %s::%s has incompatible changes at opcode %d in callback %s%s.\nExpected: %s\n Found:%s",
+ List found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), callback.frameSize);
+ String message = String.format("LVT in %s::%s has incompatible changes at opcode %d in callback %s%s.\nExpected: %s\n Found: %s",
this.classNode.name, callback.target.method.name, position, this.methodNode.name, this.methodNode.desc, expected, found);
return message;
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java
index 210a36ea..6737f297 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java
@@ -255,9 +255,10 @@ public class Target {
}
String descriptor = this.callbackDescriptor.substring(0, this.callbackDescriptor.indexOf(')'));
- for (int l = startIndex; l < locals.length && l < (startIndex + extra); l++) {
+ for (int l = startIndex; l < locals.length && extra > 0; l++) {
if (locals[l] != null) {
descriptor += locals[l].getDescriptor();
+ extra--;
}
}
diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java
index d1cf5feb..04dc4323 100644
--- a/src/main/java/org/spongepowered/asm/util/Locals.java
+++ b/src/main/java/org/spongepowered/asm/util/Locals.java
@@ -72,9 +72,10 @@ public class Locals {
*/
public static void loadLocals(Type[] locals, InsnList insns, int pos, int limit) {
limit += pos;
- for (; pos < locals.length && pos < limit; pos++) {
+ for (; pos < locals.length && limit > 0; pos++) {
if (locals[pos] != null) {
insns.add(new VarInsnNode(locals[pos].getOpcode(Opcodes.ILOAD), pos));
+ limit--;
}
}
}
From 237efbc625e5e3184509251858f8deca4d30b420 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Mon, 23 Nov 2015 12:33:12 +0000
Subject: [PATCH 032/169] Minor housekeeping
---
.../spongepowered/tools/agent/MixinAgent.java | 75 ++++++++++++-------
.../tools/agent/MixinAgentClassLoader.java | 4 +-
.../asm/mixin/transformer/MixinInfo.java | 10 +--
3 files changed, 54 insertions(+), 35 deletions(-)
diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java
index 85132c6f..156a2252 100644
--- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java
+++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java
@@ -57,39 +57,17 @@ public class MixinAgent implements IHotSwap {
if (classBeingRedefined == null) {
return null;
}
+
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 (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);
+ List targets = this.reloadMixin(className, classfileBuffer);
+ if (targets == null || !this.reApplyMixins(targets)) {
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);
@@ -98,6 +76,47 @@ public class MixinAgent implements IHotSwap {
return MixinAgent.ERROR_BYTECODE;
}
}
+
+ private List reloadMixin(String className, byte[] classfileBuffer) {
+ MixinAgent.logger.info("Redefining mixin {}", className);
+ try {
+ return MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer);
+ } catch (MixinReloadException e) {
+ MixinAgent.logger.error("Mixin {} cannot be reloaded, needs a restart to be applied: {} ", e.getMixinInfo(), e.getMessage());
+ } catch (Throwable th) {
+ // catch everything as otherwise it is ignored
+ MixinAgent.logger.error("Error while finding targets for mixin " + className, th);
+ }
+ return null;
+ }
+
+ /**
+ * Re-apply all mixins to the supplied list of target classes.
+ *
+ * @param targets Target classes to re-transform
+ * @return true if all targets were transformed, false if transformation
+ * failed
+ */
+ private boolean reApplyMixins(List targets) {
+ 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 {} bytecode is not registered", targetName);
+ return false;
+ }
+ targetBytecode = MixinAgent.this.classTransformer.transform(null, targetName, targetBytecode);
+ MixinAgent.instrumentation.redefineClasses(new ClassDefinition(targetClass, targetBytecode));
+ } catch (Throwable th) {
+ MixinAgent.logger.error("Error while re-transforming target class " + target, th);
+ return false;
+ }
+ }
+ return true;
+ }
}
/**
@@ -169,7 +188,7 @@ public class MixinAgent implements IHotSwap {
if (!MixinAgent.instrumentation.isRedefineClassesSupported()) {
MixinAgent.logger.error("The instrumentation doesn't support re-definition of classes");
}
- for (MixinAgent agent:agents) {
+ for (MixinAgent agent : MixinAgent.agents) {
agent.initTransformer();
}
}
diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java
index 5eaa2946..eb9ea2fc 100644
--- a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java
+++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java
@@ -60,7 +60,7 @@ class MixinAgentClassLoader extends ClassLoader {
* @param name Name of the fake class
*/
void addMixinClass(String name) {
- MixinAgentClassLoader.logger.debug("Mixin class " + name + " added to class loader");
+ MixinAgentClassLoader.logger.debug("Mixin class {} added to class loader", name);
try {
byte[] bytes = this.materialise(name);
Class> clazz = this.defineClass(name, bytes, 0, bytes.length);
@@ -69,7 +69,7 @@ class MixinAgentClassLoader extends ClassLoader {
clazz.newInstance();
this.mixins.put(clazz, bytes);
} catch (Throwable e) {
- logger.catching(e);
+ MixinAgentClassLoader.logger.catching(e);
}
}
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 4b3dd05b..9ce92e85 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
@@ -225,6 +225,11 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
*/
private final transient IMixinConfigPlugin plugin;
+ /**
+ * The environment phase in which this mixin was initialised
+ */
+ private final transient Phase phase;
+
/**
* Holds state that currently is not fully initialised or validated
*/
@@ -235,11 +240,6 @@ class MixinInfo extends TreeInfo implements Comparable, IMixinInfo {
*/
private transient ValidationState validationState;
- /**
- * The environment phase in which this mixin was initialised
- */
- private final transient Phase phase;
-
/**
* Internal ctor, called by {@link MixinConfig}
*
From c804069f5c3577192cfe295f9dbdbcbd6b36993f Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Mon, 23 Nov 2015 22:57:01 +0000
Subject: [PATCH 033/169] Rethrow spurious NPE as something more meaningful
---
.../org/spongepowered/asm/mixin/transformer/ClassInfo.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
index 1be6b324..3ab1a80b 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
@@ -1207,6 +1207,9 @@ public class ClassInfo extends TreeInfo {
if (this.isInterface || MixinEnvironment.getCompatibilityLevel().resolveMethodsInInterfaces()) {
for (String implemented : this.interfaces) {
ClassInfo iface = ClassInfo.forName(implemented);
+ if (iface == null) {
+ throw new RuntimeException(new ClassNotFoundException(implemented));
+ }
M member = iface.findInHierarchy(name, desc, true, traversal.next(), flags & ~ClassInfo.INCLUDE_PRIVATE, type);
if (member != null) {
return member;
From 1d3a5345e968cba6c9c3988ca8eb2b0312da065d Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Mon, 23 Nov 2015 22:57:43 +0000
Subject: [PATCH 034/169] Add some simple validation (idiot checking) to
MemberInfo
---
.../tools/obfuscation/AnnotatedMixin.java | 13 ++++
.../asm/launch/MixinTweakContainer.java | 2 +-
.../mixin/injection/struct/InjectionInfo.java | 2 +-
.../injection/struct/InjectionPointData.java | 4 +-
.../InvalidMemberDescriptorException.java | 43 ++++++++++++
.../mixin/injection/struct/MemberInfo.java | 68 +++++++++++++++++++
6 files changed, 128 insertions(+), 4 deletions(-)
create mode 100644 src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
index 656a8ff0..7e154ffb 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
@@ -47,6 +47,7 @@ import javax.tools.Diagnostic.Kind;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import org.spongepowered.asm.mixin.Mixin;
+import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.ConstraintParser;
@@ -497,6 +498,12 @@ class AnnotatedMixin {
if (targetMember.name == null) {
return;
}
+
+ try {
+ targetMember.validate();
+ } catch (InvalidMemberDescriptorException ex) {
+ this.mixins.printMessage(Kind.ERROR, ex.getMessage(), method, inject);
+ }
if (targetMember.desc != null) {
this.validateReferencedTarget(method, inject, targetMember, "@Inject");
@@ -562,6 +569,12 @@ class AnnotatedMixin {
return;
}
+ try {
+ targetMember.validate();
+ } catch (InvalidMemberDescriptorException ex) {
+ this.mixins.printMessage(Kind.ERROR, ex.getMessage(), element, inject);
+ }
+
MemberInfo remappedReference = null;
if (targetMember.isField()) {
String obfField = this.mixins.getObfField(targetMember.toSrg());
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java b/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java
index a5809cb6..d140042a 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java
@@ -34,7 +34,7 @@ import net.minecraft.launchwrapper.LaunchClassLoader;
/**
- * A collection of {@link IMixinLaunchAgent launch agents)
+ * A collection of {@link IMixinLaunchAgent} launch agents)
*/
public class MixinTweakContainer {
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java
index 3170d598..a3880925 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java
@@ -139,7 +139,7 @@ public abstract class InjectionInfo {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " is missing 'at' value(s)");
}
- MemberInfo targetMember = MemberInfo.parse(method, this.mixin);
+ MemberInfo targetMember = MemberInfo.parseAndValidate(method, this.mixin);
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
throw new InvalidInjectionException(this, type + " annotation on " + this.method.name + " specifies a target class '"
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java
index 57222c07..ffd148ae 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java
@@ -102,7 +102,7 @@ public class InjectionPointData {
}
public MemberInfo get(String key) {
- return MemberInfo.parse(this.get(key, ""), this.mixin);
+ return MemberInfo.parseAndValidate(this.get(key, ""), this.mixin);
}
private int parseInt(String string, int defaultValue) {
@@ -122,7 +122,7 @@ public class InjectionPointData {
}
public MemberInfo getTarget() {
- return MemberInfo.parse(this.target, this.mixin);
+ return MemberInfo.parseAndValidate(this.target, this.mixin);
}
public int getOrdinal() {
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java
new file mode 100644
index 00000000..3b01deb4
--- /dev/null
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java
@@ -0,0 +1,43 @@
+/*
+ * 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.injection.struct;
+
+public class InvalidMemberDescriptorException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ public InvalidMemberDescriptorException(String message) {
+ super(message);
+ }
+
+ public InvalidMemberDescriptorException(Throwable cause) {
+ super(cause);
+ }
+
+ public InvalidMemberDescriptorException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
index 2019777f..943827f8 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.struct;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
+import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AbstractInsnNode;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
@@ -257,6 +258,50 @@ public class MemberInfo {
public boolean isField() {
return this.desc != null && !this.desc.startsWith("(");
}
+
+ /**
+ * Perform ultra-simple validation of the descriptor, checks that the parts
+ * of the descriptor are basically sane.
+ *
+ * @return fluent
+ *
+ * @throws InvalidMemberDescriptorException if any validation check fails
+ */
+ public MemberInfo validate() throws InvalidMemberDescriptorException {
+ // Extremely naive class name validation, just to spot really egregious errors
+ if (this.owner != null && !this.owner.matches("(?i)^[\\w\\p{Sc}/]+$")) {
+ throw new InvalidMemberDescriptorException("Invalid owner: " + this.owner);
+ }
+
+ // Also naive validation, we're looking for stupid errors here
+ if (this.name != null && !this.name.matches("(?i)^[\\w\\p{Sc}]+>?$")) {
+ throw new InvalidMemberDescriptorException("Invalid name: " + this.name);
+ }
+
+ if (this.desc != null) {
+ if (!this.desc.matches("^(\\([\\w\\[/;]*\\))?\\[?[\\w/;]+$")) {
+ throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc);
+ }
+ if (this.isField()) {
+ if (!this.desc.equals(Type.getType(this.desc).getDescriptor())) {
+ throw new InvalidMemberDescriptorException("Invalid field type in descriptor: " + this.desc);
+ }
+ } else {
+ try {
+ Type.getArgumentTypes(this.desc);
+ } catch (Exception ex) {
+ throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc);
+ }
+
+ String retString = this.desc.substring(this.desc.indexOf(')') + 1);
+ if (!retString.equals(Type.getType(retString).getDescriptor())) {
+ throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc);
+ }
+ }
+ }
+
+ return this;
+ }
/**
* Test whether this MemberInfo matches the supplied values. Null values are
@@ -338,6 +383,27 @@ public class MemberInfo {
return new MemberInfo(this, methodData, setOwner);
}
+ /**
+ * Parse a MemberInfo from a string and perform validation
+ *
+ * @param string String to parse MemberInfo from
+ * @return parsed MemberInfo
+ */
+ public static MemberInfo parseAndValidate(String string) throws InvalidMemberDescriptorException {
+ return MemberInfo.parse(string, null, null).validate();
+ }
+
+ /**
+ * Parse a MemberInfo from a string and perform validation
+ *
+ * @param string String to parse MemberInfo from
+ * @param context Context to use for reference mapping
+ * @return parsed MemberInfo
+ */
+ public static MemberInfo parseAndValidate(String string, IReferenceMapperContext context) throws InvalidMemberDescriptorException {
+ return MemberInfo.parse(string, context.getReferenceMapper(), context.getClassRef()).validate();
+ }
+
/**
* Parse a MemberInfo from a string
*
@@ -371,6 +437,8 @@ public class MemberInfo {
String desc = null;
String owner = null;
+ name = name.replaceAll("\\s", "");
+
if (refMapper != null) {
name = refMapper.remap(mixinClass, name);
}
From 6c59b7b7a6e6b5f5a85e81e23ecd6953249b6f60 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Mon, 23 Nov 2015 22:57:59 +0000
Subject: [PATCH 035/169] Have AP report Java 8 support
---
.../tools/obfuscation/MixinProcessor.java | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java
index 880d1290..9d899129 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java
@@ -27,6 +27,7 @@ package org.spongepowered.tools.obfuscation;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
+import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
@@ -70,4 +71,15 @@ public abstract class MixinProcessor extends AbstractProcessor {
this.mixins.onPassCompleted();
}
+ @Override
+ public SourceVersion getSupportedSourceVersion() {
+ try {
+ return SourceVersion.valueOf("RELEASE_8");
+ } catch (IllegalArgumentException ex) {
+ // Java 8 not supported
+ }
+
+ return super.getSupportedSourceVersion();
+ }
+
}
From 650a753af795e7c2592c6ab450ae0aa722b7a7fd Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 24 Nov 2015 01:45:05 +0000
Subject: [PATCH 036/169] Descriptors can have currency symbols too
---
.../spongepowered/asm/mixin/injection/struct/MemberInfo.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
index 943827f8..d5c3f40e 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java
@@ -279,7 +279,7 @@ public class MemberInfo {
}
if (this.desc != null) {
- if (!this.desc.matches("^(\\([\\w\\[/;]*\\))?\\[?[\\w/;]+$")) {
+ if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[?[\\w\\p{Sc}/;]+$")) {
throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc);
}
if (this.isField()) {
From 6322cffe8b561d2eb8c7c3c02ee32390bedf6ecc Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 24 Nov 2015 12:30:19 +0000
Subject: [PATCH 037/169] Fix off-by-n error in Locals
---
src/main/java/org/spongepowered/asm/util/Locals.java | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java
index 04dc4323..f9ad8b31 100644
--- a/src/main/java/org/spongepowered/asm/util/Locals.java
+++ b/src/main/java/org/spongepowered/asm/util/Locals.java
@@ -71,7 +71,6 @@ public class Locals {
* @param pos Start position
*/
public static void loadLocals(Type[] locals, InsnList insns, int pos, int limit) {
- limit += pos;
for (; pos < locals.length && limit > 0; pos++) {
if (locals[pos] != null) {
insns.add(new VarInsnNode(locals[pos].getOpcode(Opcodes.ILOAD), pos));
From 519b9c6da12472c395907a37f6117b8cc55b64ac Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 24 Nov 2015 13:08:27 +0000
Subject: [PATCH 038/169] Fix stack calculation error in RedirectInjector when
capturing args
---
.../asm/mixin/injection/invoke/RedirectInjector.java | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
index 0a0675d7..f17302db 100644
--- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
+++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java
@@ -97,9 +97,12 @@ public class RedirectInjector extends InvokeInjector {
InsnList insns = new InsnList();
int extraLocals = ASMHelper.getArgsSize(stackVars) + 1;
+ int extraStack = 1; // Normally only need 1 extra stack pos to store target ref
int[] argMap = this.storeArgs(target, stackVars, insns, 0);
if (injectTargetParams) {
- extraLocals += ASMHelper.getArgsSize(target.arguments);
+ int argSize = ASMHelper.getArgsSize(target.arguments);
+ extraLocals += argSize;
+ extraStack += argSize;
argMap = Ints.concat(argMap, target.argIndices);
}
this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
@@ -107,6 +110,6 @@ public class RedirectInjector extends InvokeInjector {
target.insns.insertBefore(node, insns);
target.insns.remove(node);
target.addToLocals(extraLocals);
- target.addToStack(1);
+ target.addToStack(extraStack);
}
}
From 6fa0432fccec3b0a28248384f21083f62eca7120 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Tue, 24 Nov 2015 14:06:32 +0000
Subject: [PATCH 039/169] Use implementing class in static binding when
resolving default methods
---
.../asm/mixin/transformer/ClassInfo.java | 34 +++++++++++++++++--
.../mixin/transformer/MixinTargetContext.java | 2 +-
2 files changed, 33 insertions(+), 3 deletions(-)
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
index 3ab1a80b..3ac64fa6 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
@@ -245,6 +245,10 @@ public class ClassInfo extends TreeInfo {
// Abstract because this has to be static in order to contain the enum
public abstract ClassInfo getOwner();
+
+ public ClassInfo getImplementor() {
+ return this.getOwner();
+ }
public int getAccess() {
return this.modifiers;
@@ -352,6 +356,31 @@ public class ClassInfo extends TreeInfo {
return super.equals(obj);
}
}
+
+ /**
+ * A method resolved in an interface via a class, return the member
+ * wrapped so that the implementing class can be retrieved.
+ */
+ public class InterfaceMethod extends Method {
+
+ private final ClassInfo owner;
+
+ public InterfaceMethod(Member member) {
+ super(member);
+ this.owner = member.getOwner();
+ }
+
+ @Override
+ public ClassInfo getOwner() {
+ return this.owner;
+ }
+
+ @Override
+ public ClassInfo getImplementor() {
+ return ClassInfo.this;
+ }
+
+ }
/**
* A field
@@ -1177,6 +1206,7 @@ public class ClassInfo extends TreeInfo {
* @param type Type of member to search for (field or method)
* @return the discovered member or null if the member could not be resolved
*/
+ @SuppressWarnings("unchecked")
private M findInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, int flags, Type type) {
if (includeThisClass) {
M member = this.findMember(name, desc, flags, type);
@@ -1204,7 +1234,7 @@ public class ClassInfo extends TreeInfo {
}
}
- if (this.isInterface || MixinEnvironment.getCompatibilityLevel().resolveMethodsInInterfaces()) {
+ if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().resolveMethodsInInterfaces())) {
for (String implemented : this.interfaces) {
ClassInfo iface = ClassInfo.forName(implemented);
if (iface == null) {
@@ -1212,7 +1242,7 @@ public class ClassInfo extends TreeInfo {
}
M member = iface.findInHierarchy(name, desc, true, traversal.next(), flags & ~ClassInfo.INCLUDE_PRIVATE, type);
if (member != null) {
- return member;
+ return this.isInterface ? member : (M)new InterfaceMethod(member);
}
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
index 51bd7c61..b8b54eff 100644
--- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
+++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java
@@ -498,7 +498,7 @@ public class MixinTargetContext implements IReferenceMapperContext {
throw new InvalidMixinException(this, "Invalid " + methodRef + " in " + this + " resolved " + superMethod.getOwner()
+ " but is mixin.");
}
- methodRef.setOwner(superMethod.getOwner().getName());
+ methodRef.setOwner(superMethod.getImplementor().getName());
} else if (ClassInfo.forName(methodRef.getOwner()).isMixin()) {
throw new MixinTransformerError("Error resolving " + methodRef + " in " + this);
}
From 34dab7d1d57d02fcd1bf59f0d2235ea035e1b4b2 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Wed, 25 Nov 2015 00:41:45 +0000
Subject: [PATCH 040/169] Validate against raw types when validating super
because mirror sucks
---
.../org/spongepowered/tools/MirrorUtils.java | 17 +++++++++++++++++
.../obfuscation/validation/TargetValidator.java | 9 +++------
2 files changed, 20 insertions(+), 6 deletions(-)
diff --git a/src/ap/java/org/spongepowered/tools/MirrorUtils.java b/src/ap/java/org/spongepowered/tools/MirrorUtils.java
index fff3cf40..937d2b01 100644
--- a/src/ap/java/org/spongepowered/tools/MirrorUtils.java
+++ b/src/ap/java/org/spongepowered/tools/MirrorUtils.java
@@ -29,6 +29,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
@@ -204,4 +205,20 @@ public abstract class MirrorUtils {
}
return reference.toString();
}
+
+ public static boolean isAssignable(ProcessingEnvironment processingEnv, TypeMirror targetType, TypeMirror superClass) {
+ boolean assignable = processingEnv.getTypeUtils().isAssignable(targetType, superClass);
+ if (!assignable && targetType instanceof DeclaredType && superClass instanceof DeclaredType) {
+ TypeMirror rawTargetType = MirrorUtils.toRawType(processingEnv, (DeclaredType)targetType);
+ TypeMirror rawSuperType = MirrorUtils.toRawType(processingEnv, (DeclaredType)superClass);
+ return processingEnv.getTypeUtils().isAssignable(rawTargetType, rawSuperType);
+ }
+
+ return assignable;
+ }
+
+ private static TypeMirror toRawType(ProcessingEnvironment processingEnv, DeclaredType targetType) {
+ return processingEnv.getElementUtils().getTypeElement(((TypeElement)targetType.asElement()).getQualifiedName()).asType();
+ }
+
}
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java
index 06bb658e..3fc429fd 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/validation/TargetValidator.java
@@ -34,6 +34,7 @@ import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
+import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.IOptionProvider;
import org.spongepowered.tools.obfuscation.MixinValidator;
import org.spongepowered.tools.obfuscation.TypeHandle;
@@ -79,7 +80,7 @@ public class TargetValidator extends MixinValidator {
}
private boolean validateSuperClass(TypeMirror targetType, TypeMirror superClass) {
- if (this.isAssignable(targetType, superClass)) {
+ if (MirrorUtils.isAssignable(this.processingEnv, targetType, superClass)) {
return true;
}
@@ -106,15 +107,11 @@ public class TargetValidator extends MixinValidator {
private boolean checkMixinsFor(TypeMirror targetType, TypeMirror superClass) {
for (TypeMirror mixinType : this.getMixinsTargeting(targetType)) {
- if (this.isAssignable(mixinType, superClass)) {
+ if (MirrorUtils.isAssignable(this.processingEnv, mixinType, superClass)) {
return true;
}
}
return false;
}
-
- protected final boolean isAssignable(TypeMirror targetType, TypeMirror superClass) {
- return this.processingEnv.getTypeUtils().isAssignable(targetType, superClass);
- }
}
From 5814ea195775fa24d6efc52491a61994bd0facab Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Wed, 25 Nov 2015 15:07:26 +0000
Subject: [PATCH 041/169] Store target info between compiles to support
cross-project supermixins
---
.../tools/obfuscation/AnnotatedMixin.java | 13 +
.../tools/obfuscation/AnnotatedMixins.java | 29 +-
.../tools/obfuscation/TargetMap.java | 249 ++++++++++++++++++
.../tools/obfuscation/TypeHandle.java | 12 +
.../tools/obfuscation/TypeReference.java | 114 ++++++++
5 files changed, 411 insertions(+), 6 deletions(-)
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
index 7e154ffb..5425fde1 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
@@ -225,6 +225,11 @@ class AnnotatedMixin {
*/
private final TypeElement mixin;
+ /**
+ * Mixin class
+ */
+ private final TypeHandle handle;
+
/**
* Specified targets
*/
@@ -265,6 +270,7 @@ class AnnotatedMixin {
this.annotation = MirrorUtils.getAnnotation(type, Mixin.class);
this.mixins = mixins;
this.mixin = type;
+ this.handle = new TypeHandle(type);
this.classRef = type.getQualifiedName().toString().replace('.', '/');
TypeHandle primaryTarget = this.initTargets();
@@ -358,6 +364,13 @@ class AnnotatedMixin {
return this.mixin;
}
+ /**
+ * Get the type handle for the mixin class
+ */
+ public TypeHandle getHandle() {
+ return this.handle;
+ }
+
/**
* Get the mixin's targets
*/
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
index 7b880e03..e8ded263 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
@@ -80,6 +80,8 @@ import net.minecraftforge.srg2source.rangeapplier.SrgContainer;
*/
class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
+ private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid";
+
static enum CompilerEnvironment {
/**
* Default environment
@@ -144,6 +146,11 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
*/
private final Map tokenCache = new HashMap();
+ /**
+ * Serialisable mixin target map
+ */
+ private final TargetMap targets;
+
/**
* SRG container for mcp->srg mappings
*/
@@ -167,6 +174,7 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
private AnnotatedMixins(ProcessingEnvironment processingEnv) {
this.env = this.detectEnvironment(processingEnv);
this.processingEnv = processingEnv;
+ this.targets = this.initTargetMap();
this.printMessage(Kind.NOTE, "SpongePowered Mixin Annotation Processor v" + MixinBootstrap.VERSION);
@@ -182,6 +190,12 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
this.initTokenCache(this.getOption("tokens"));
}
+ protected TargetMap initTargetMap() {
+ TargetMap targets = TargetMap.create(System.getProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY));
+ System.setProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY, targets.getSessionId());
+ return targets;
+ }
+
private void initTokenCache(String tokens) {
if (tokens != null) {
Pattern tokenPattern = Pattern.compile("^([A-Z0-9\\-_\\.]+)=([0-9]+)$");
@@ -384,6 +398,7 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
if (!this.mixins.containsKey(name)) {
AnnotatedMixin mixin = new AnnotatedMixin(this, mixinType);
+ this.targets.registerTargets(mixin);
mixin.runValidators(ValidationPass.EARLY, this.validators);
this.mixins.put(name, mixin);
this.mixinsForPass.add(mixin);
@@ -411,12 +426,10 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
public Collection getMixinsTargeting(TypeElement targetType) {
List minions = new ArrayList();
- for (AnnotatedMixin mixin : this.mixins.values()) {
- for (TypeHandle mixinTarget : mixin.getTargets()) {
- if (targetType.equals(mixinTarget.getElement())) {
- minions.add(mixin.getMixin().asType());
- break;
- }
+ for (TypeReference mixin : this.targets.getMixinsTargeting(targetType)) {
+ TypeHandle handle = mixin.getHandle(this.processingEnv);
+ if (handle != null) {
+ minions.add(handle.getType());
}
}
@@ -530,6 +543,10 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
* Called from each AP when a pass is completed
*/
public void onPassCompleted() {
+ if (!"true".equalsIgnoreCase(this.getOption("disableTargetExport"))) {
+ this.targets.write(true);
+ }
+
for (AnnotatedMixin mixin : this.mixinsForPass) {
mixin.runValidators(ValidationPass.LATE, this.validators);
}
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java b/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java
new file mode 100644
index 00000000..188d006f
--- /dev/null
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java
@@ -0,0 +1,249 @@
+/*
+ * 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.obfuscation;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.lang.model.element.TypeElement;
+
+/**
+ * Serialisable map of classes to their associated mixins, used so that we can
+ * pass target information for supermixins from one compiler session to another
+ */
+public class TargetMap extends HashMap> {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Session ID, used to identify the temp file
+ */
+ private final String sessionId;
+
+ /**
+ * Create a new TargetMap with a session ID based on the current system time
+ */
+ private TargetMap() {
+ this(String.valueOf(System.currentTimeMillis()));
+ }
+
+ /**
+ * Create a TargetMap with the specified session ID
+ *
+ * @param sessionId
+ */
+ private TargetMap(String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ /**
+ * Get the session ID
+ */
+ public String getSessionId() {
+ return this.sessionId;
+ }
+
+ /**
+ * Register target classes for the specified mixin
+ *
+ * @param mixin mixin to add targets for
+ */
+ public void registerTargets(AnnotatedMixin mixin) {
+ this.registerTargets(mixin.getTargets(), mixin.getHandle());
+ }
+
+ /**
+ * Register target classes for the supplied mixin
+ *
+ * @param targets List of targets
+ * @param mixin Mixin class
+ */
+ public void registerTargets(List targets, TypeHandle mixin) {
+ for (TypeHandle target : targets) {
+ this.addMixin(target, mixin);
+ }
+ }
+
+ /**
+ * Register the specified mixin against the specified target
+ *
+ * @param target Target class
+ * @param mixin Mixin class
+ */
+ public void addMixin(TypeHandle target, TypeHandle mixin) {
+ this.addMixin(target.getReference(), mixin.getReference());
+ }
+
+ /**
+ * Register the specified mixin against the specified target
+ *
+ * @param target Target class
+ * @param mixin Mixin class
+ */
+ public void addMixin(TypeReference target, TypeReference mixin) {
+ Set mixins = this.getMixinsFor(target);
+ mixins.add(mixin);
+ }
+
+ /**
+ * Get mixin classes which target the specified class
+ *
+ * @param target Target class
+ * @return Collection of mixins registered as targetting the specified class
+ */
+ public Collection getMixinsTargeting(TypeElement target) {
+ return this.getMixinsTargeting(new TypeHandle(target));
+ }
+
+ /**
+ * Get mixin classes which target the specified class
+ *
+ * @param target Target class
+ * @return Collection of mixins registered as targetting the specified class
+ */
+ public Collection getMixinsTargeting(TypeHandle target) {
+ return this.getMixinsTargeting(target.getReference());
+ }
+
+ /**
+ * Get mixin classes which target the specified class
+ *
+ * @param target Target class
+ * @return Collection of mixins registered as targetting the specified class
+ */
+ public Collection getMixinsTargeting(TypeReference target) {
+ return Collections.unmodifiableCollection(this.getMixinsFor(target));
+ }
+
+ /**
+ * Get mixin set for specified class
+ *
+ * @param target Target class
+ * @return Set of mixins registered as targetting the specified class
+ */
+ private Set getMixinsFor(TypeReference target) {
+ Set mixins = this.get(target);
+ if (mixins == null) {
+ mixins = new HashSet();
+ this.put(target, mixins);
+ }
+ return mixins;
+ }
+
+ /**
+ * Write this target map to temporary session file
+ *
+ * @param temp Set "delete on exit" for the file
+ */
+ public void write(boolean temp) {
+ ObjectOutputStream oos = null;
+ FileOutputStream fout = null;
+ try {
+ File sessionFile = TargetMap.getSessionFile(this.sessionId);
+ if (temp) {
+ sessionFile.deleteOnExit();
+ }
+ fout = new FileOutputStream(sessionFile, true);
+ oos = new ObjectOutputStream(fout);
+ oos.writeObject(this);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ } finally {
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+ }
+ }
+
+ /**
+ * Attemp to deserialise a TargetMap from the specified file
+ *
+ * @param sessionFile File to read
+ * @return deserialised map or null if deserialisation failed
+ */
+ private static TargetMap read(File sessionFile) {
+ ObjectInputStream objectinputstream = null;
+ FileInputStream streamIn = null;
+ try {
+ streamIn = new FileInputStream(sessionFile);
+ objectinputstream = new ObjectInputStream(streamIn);
+ TargetMap map = (TargetMap)objectinputstream.readObject();
+ return map;
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if(objectinputstream != null){
+ try {
+ objectinputstream .close();
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Create a TargetMap for the specified session id. Generate new map if
+ * the session id is invalid or the file cannot be read. Session ID can be
+ * null
+ *
+ * @param sessionId session to deserialise, can be null to create new
+ * session
+ * @return new TargetMap
+ */
+ public static TargetMap create(String sessionId) {
+ if (sessionId != null) {
+ File sessionFile = TargetMap.getSessionFile(sessionId);
+ if (sessionFile.exists()) {
+ TargetMap map = TargetMap.read(sessionFile);
+ if (map != null) {
+ return map;
+ }
+ }
+ }
+
+ return new TargetMap();
+ }
+
+ private static File getSessionFile(String sessionId) {
+ File tempDir = new File(System.getProperty("java.io.tmpdir"));
+ return new File(tempDir, String.format("mixin-targetdb-%s.tmp", sessionId));
+ }
+}
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java
index 8950ae9c..90fa5725 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/TypeHandle.java
@@ -63,6 +63,11 @@ public class TypeHandle {
* Actual type element, this is null for inaccessible classes
*/
private final TypeElement element;
+
+ /**
+ * Reference to this handle, for serialisation
+ */
+ private TypeReference reference;
/**
* Ctor for imaginary elements, require the enclosing package and the FQ
@@ -154,6 +159,13 @@ public class TypeHandle {
public boolean isImaginary() {
return this.element == null;
}
+
+ public TypeReference getReference() {
+ if (this.reference == null) {
+ this.reference = new TypeReference(this);
+ }
+ return this.reference;
+ }
public String findDescriptor(MemberInfo memberInfo) {
String desc = memberInfo.desc;
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java b/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java
new file mode 100644
index 00000000..c7d792d6
--- /dev/null
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java
@@ -0,0 +1,114 @@
+/*
+ * 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.obfuscation;
+
+import java.io.Serializable;
+
+import javax.annotation.processing.ProcessingEnvironment;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * Soft wrapper for a {@link TypeHandle} so that we can serialise it
+ */
+public class TypeReference implements Serializable, Comparable {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Class name, used to recreate the handle on the other side
+ */
+ private final String name;
+
+ /**
+ * Transient handle, not serialised, regenerated when required
+ */
+ private transient TypeHandle handle;
+
+ /**
+ * Create a new soft wrapper for the specified type handle
+ *
+ * @param handle handle to wrap
+ */
+ public TypeReference(TypeHandle handle) {
+ this.name = handle.getName();
+ this.handle = handle;
+ }
+
+ /**
+ * Get the class name (internal format)
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * Get the FQ class name (dotted format)
+ */
+ public String getClassName() {
+ return this.name.replace('/', '.');
+ }
+
+ /**
+ * Fetch or attempt to generate the type handle
+ *
+ * @param processingEnv environment to create handle if it needs to be
+ * regenerated
+ * @return type handle
+ */
+ public TypeHandle getHandle(ProcessingEnvironment processingEnv) {
+ if (this.handle == null) {
+ TypeElement element = processingEnv.getElementUtils().getTypeElement(getClassName());
+ try {
+ this.handle = new TypeHandle(element);
+ } catch (Exception ex) {
+ // Class probably doesn't exist in scope :/
+ ex.printStackTrace();
+ }
+ }
+
+ return this.handle;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("TypeReference[%s]", this.name);
+ }
+
+ @Override
+ public int compareTo(TypeReference other) {
+ return other == null ? -1 : this.name.compareTo(other.name);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ return other instanceof TypeReference && this.compareTo((TypeReference)other) == 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return this.name.hashCode();
+ }
+
+}
From 9bad1f5c970b19cdb3e9e748c4d9745c8ec62dac Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Thu, 26 Nov 2015 17:08:04 +0000
Subject: [PATCH 042/169] Don't raise no-obf error for @Inject if remappable
ats exist, fixes #80
---
.../tools/obfuscation/AnnotatedMixin.java | 46 +++++---
.../tools/obfuscation/AnnotatedMixins.java | 20 +++-
.../tools/obfuscation/TargetMap.java | 4 +-
.../tools/obfuscation/TypeReference.java | 2 +-
.../tools/obfuscation/struct/Message.java | 110 ++++++++++++++++++
5 files changed, 156 insertions(+), 26 deletions(-)
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
index 5425fde1..401427bb 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
@@ -56,6 +56,7 @@ import org.spongepowered.asm.util.ConstraintViolationException;
import org.spongepowered.asm.util.InvalidConstraintException;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass;
+import org.spongepowered.tools.obfuscation.struct.Message;
/**
@@ -504,12 +505,17 @@ class AnnotatedMixin {
/**
* Register a {@link org.spongepowered.asm.mixin.injection.Inject} method
+ *
+ * @param method Callback method
+ * @param inject Inject annotation
+ * @param remap
+ * @return
*/
- public void registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) {
+ public Message registerInjector(ExecutableElement method, AnnotationMirror inject, boolean remap) {
String originalReference = MirrorUtils.getAnnotationValue(inject, "method");
MemberInfo targetMember = MemberInfo.parse(originalReference);
if (targetMember.name == null) {
- return;
+ return null;
}
try {
@@ -518,68 +524,71 @@ class AnnotatedMixin {
this.mixins.printMessage(Kind.ERROR, ex.getMessage(), method, inject);
}
+ String type = "@" + inject.getAnnotationType().asElement().getSimpleName() + "";
if (targetMember.desc != null) {
- this.validateReferencedTarget(method, inject, targetMember, "@Inject");
+ this.validateReferencedTarget(method, inject, targetMember, type);
}
- if (!remap || !this.validateSingleTarget("@Inject", method)) {
- return;
+ if (!remap || !this.validateSingleTarget(type, method)) {
+ return null;
}
String desc = this.targetType.findDescriptor(targetMember);
if (desc == null) {
if (this.targetType.isImaginary()) {
- this.mixins.printMessage(Kind.WARNING, "@Inject target requires method signature because enclosing type information is unavailable",
+ this.mixins.printMessage(Kind.WARNING, type + " target requires method signature because enclosing type information is unavailable",
method, inject);
} else if (!Constants.INIT.equals(targetMember.name)) {
- this.mixins.printMessage(Kind.WARNING, "Unable to determine signature for @Inject target method", method, inject);
+ this.mixins.printMessage(Kind.WARNING, "Unable to determine signature for " + type + " target method", method, inject);
}
- return;
+ return null;
}
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc));
if (obfMethod == null) {
Kind error = Constants.INIT.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR;
- this.mixins.printMessage(error, "No obfuscation mapping for @Inject target " + targetMember.name, method, inject);
- return;
+ return new Message(error, "No obfuscation mapping for " + type + " target " + targetMember.name, method, inject);
}
String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
MemberInfo remappedReference = new MemberInfo(obfName, this.targetRef, obfMethod.sig, false);
this.mixins.getReferenceMapper().addMapping(this.classRef, originalReference, remappedReference.toString());
+ return null;
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.At} annotation
* and process the references
*/
- public void registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) {
+ public int registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) {
if (!AnnotatedMixins.getRemapValue(at)) {
- return;
+ return 0;
}
String type = MirrorUtils.getAnnotationValue(at, "value");
String target = MirrorUtils.getAnnotationValue(at, "target");
- this.remapReference(type + ".", target, element, inject, at);
+ int remapped = this.remapReference(type + ".", target, element, inject, at) ? 1 : 0;
// Pattern for replacing references in args, not used yet
// if ("SOMETYPE".equals(type)) {
// Map args = AnnotatedMixin.getAtArgs(at);
// this.remapReference(type + ".args[target]", args.get("target"));
// }
+
+ return remapped;
}
- private void remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) {
+ private boolean remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) {
if (target == null) {
- return;
+ return false;
}
MemberInfo targetMember = MemberInfo.parse(target);
if (!targetMember.isFullyQualified()) {
String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature");
this.mixins.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing, element, inject);
- return;
+ return false;
}
try {
@@ -593,7 +602,7 @@ class AnnotatedMixin {
String obfField = this.mixins.getObfField(targetMember.toSrg());
if (obfField == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target + "'", element, inject);
- return;
+ return false;
}
remappedReference = MemberInfo.fromSrgField(obfField, targetMember.desc);
} else {
@@ -602,12 +611,13 @@ class AnnotatedMixin {
if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) {
this.mixins.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target + "'", element, inject);
}
- return;
+ return false;
}
remappedReference = targetMember.remapUsing(obfMethod, false);
}
this.mixins.getReferenceMapper().addMapping(this.classRef, target, remappedReference.toString());
+ return true;
}
/**
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
index e8ded263..febeab46 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
@@ -65,6 +65,7 @@ import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass;
+import org.spongepowered.tools.obfuscation.struct.Message;
import org.spongepowered.tools.obfuscation.validation.ParentValidator;
import org.spongepowered.tools.obfuscation.validation.TargetValidator;
@@ -497,12 +498,14 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
public void registerInjector(TypeElement mixinType, ExecutableElement method, AnnotationMirror inject) {
AnnotatedMixin mixinClass = this.getMixin(mixinType);
if (mixinClass == null) {
- this.printMessage(Kind.ERROR, "Found @Inject annotation on a non-mixin method", method);
+ String type = "@" + inject.getAnnotationType().asElement().getSimpleName() + "";
+ this.printMessage(Kind.ERROR, "Found " + type + " annotation on a non-mixin method", method);
return;
}
boolean remap = this.shouldRemap(mixinClass, inject);
- mixinClass.registerInjector(method, inject, remap);
+ Message errorMessage = mixinClass.registerInjector(method, inject, remap);
+ int remappedAts = 0;
if (remap) {
Object ats = MirrorUtils.getAnnotationValue(inject, "at");
@@ -514,21 +517,28 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
at = ((AnnotationValue)at).getValue();
}
if (at instanceof AnnotationMirror) {
- mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at);
+ remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at);
} else {
this.printMessage(Kind.WARNING, "No annotation mirror on " + at.getClass().getName());
}
}
} else if (ats instanceof AnnotationMirror) {
- mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats);
+ remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats);
} else if (ats instanceof AnnotationValue) {
// Fix for JDT
Object mirror = ((AnnotationValue)ats).getValue();
if (mirror instanceof AnnotationMirror) {
- mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror);
+ remappedAts += mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror);
}
}
}
+
+ // The annotation was *not* marked as remap=false and failed so we
+ // checked for remappable @At annotations, if that failed as well then
+ // we raise the original error.
+ if (remappedAts == 0 && errorMessage != null) {
+ errorMessage.sendTo(this);
+ }
}
/**
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java b/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java
index 188d006f..0e5c472a 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/TargetMap.java
@@ -53,7 +53,7 @@ public class TargetMap extends HashMap> {
private final String sessionId;
/**
- * Create a new TargetMap with a session ID based on the current system time
+ * Create a new TargetMap with a session ID based on the current system time
*/
private TargetMap() {
this(String.valueOf(System.currentTimeMillis()));
@@ -208,7 +208,7 @@ public class TargetMap extends HashMap> {
} catch (Exception e) {
e.printStackTrace();
} finally {
- if(objectinputstream != null){
+ if (objectinputstream != null) {
try {
objectinputstream .close();
} catch (IOException ex) {
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java b/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java
index c7d792d6..9e14f807 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/TypeReference.java
@@ -79,7 +79,7 @@ public class TypeReference implements Serializable, Comparable {
*/
public TypeHandle getHandle(ProcessingEnvironment processingEnv) {
if (this.handle == null) {
- TypeElement element = processingEnv.getElementUtils().getTypeElement(getClassName());
+ TypeElement element = processingEnv.getElementUtils().getTypeElement(this.getClassName());
try {
this.handle = new TypeHandle(element);
} catch (Exception ex) {
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java b/src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java
new file mode 100644
index 00000000..4c67ce92
--- /dev/null
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java
@@ -0,0 +1,110 @@
+/*
+ * 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.obfuscation.struct;
+
+import javax.annotation.processing.Messager;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.tools.Diagnostic;
+
+public class Message {
+
+ private Diagnostic.Kind kind;
+ private CharSequence msg;
+ private final Element element;
+ private final AnnotationMirror annotation;
+ private final AnnotationValue value;
+
+ public Message(Diagnostic.Kind kind, CharSequence msg) {
+ this(kind, msg, null, null, null);
+ }
+
+ public Message(Diagnostic.Kind kind, CharSequence msg, Element element) {
+ this(kind, msg, element, null, null);
+ }
+
+ public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation) {
+ this(kind, msg, element, annotation, null);
+ }
+
+ public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value) {
+ this.kind = kind;
+ this.msg = msg;
+ this.element = element;
+ this.annotation = annotation;
+ this.value = value;
+ }
+
+ public Message sendTo(Messager messager) {
+ if (this.value != null) {
+ messager.printMessage(this.kind, this.msg, this.element, this.annotation, this.value);
+ } else if (this.annotation != null) {
+ messager.printMessage(this.kind, this.msg, this.element, this.annotation);
+ } else if (this.element != null) {
+ messager.printMessage(this.kind, this.msg, this.element);
+ } else {
+ messager.printMessage(this.kind, this.msg);
+ }
+ return this;
+ }
+
+
+ public Diagnostic.Kind getKind() {
+ return this.kind;
+ }
+
+
+ public Message setKind(Diagnostic.Kind kind) {
+ this.kind = kind;
+ return this;
+ }
+
+
+ public CharSequence getMsg() {
+ return this.msg;
+ }
+
+
+ public Message setMsg(CharSequence msg) {
+ this.msg = msg;
+ return this;
+ }
+
+
+ public Element getElement() {
+ return this.element;
+ }
+
+
+ public AnnotationMirror getAnnotation() {
+ return this.annotation;
+ }
+
+
+ public AnnotationValue getValue() {
+ return this.value;
+ }
+}
From bc4219660112e703b5b211418568583518033c80 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Thu, 3 Dec 2015 02:34:46 +0000
Subject: [PATCH 043/169] Minor fixes
---
.../tools/obfuscation/AnnotatedMixin.java | 6 ++++--
.../obfuscation/InjectionObfuscationProcessor.java | 8 ++------
.../tools/obfuscation/MixinProcessor.java | 13 +++++++++++++
.../obfuscation/TargetObfuscationProcessor.java | 7 +------
.../asm/launch/MixinLaunchAgentFML.java | 3 +--
.../asm/launch/MixinTweakContainer.java | 7 ++++++-
.../spongepowered/asm/mixin/MixinEnvironment.java | 2 +-
7 files changed, 28 insertions(+), 18 deletions(-)
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
index 401427bb..3083d2d4 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
@@ -550,8 +550,10 @@ class AnnotatedMixin {
return new Message(error, "No obfuscation mapping for " + type + " target " + targetMember.name, method, inject);
}
- String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
- MemberInfo remappedReference = new MemberInfo(obfName, this.targetRef, obfMethod.sig, false);
+ int slashPos = obfMethod.name.lastIndexOf('/');
+ String obfName = obfMethod.name.substring(slashPos + 1);
+ String obfOwner = obfMethod.name.substring(0, slashPos);
+ MemberInfo remappedReference = new MemberInfo(obfName, obfOwner, obfMethod.sig, false);
this.mixins.getReferenceMapper().addMapping(this.classRef, originalReference, remappedReference.toString());
return null;
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java
index e07acb5a..2dbd81ac 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/InjectionObfuscationProcessor.java
@@ -29,9 +29,6 @@ import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.annotation.processing.SupportedOptions;
-import javax.annotation.processing.SupportedSourceVersion;
-import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
@@ -39,6 +36,7 @@ import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
+import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.Redirect;
@@ -48,14 +46,12 @@ import org.spongepowered.tools.MirrorUtils;
* Annotation processor which finds {@link Inject} and {@link At} annotations in
* mixin classes and generates SRG mappings
*/
-@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({
"org.spongepowered.asm.mixin.injection.Inject",
"org.spongepowered.asm.mixin.injection.ModifyArg",
"org.spongepowered.asm.mixin.injection.Redirect",
"org.spongepowered.asm.mixin.injection.At"
})
-@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile" })
public class InjectionObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
@@ -66,7 +62,7 @@ public class InjectionObfuscationProcessor extends MixinProcessor {
@Override
public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
- return false;
+ return true;
}
this.processMixins(roundEnv);
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java
index 9d899129..0184fdc8 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinProcessor.java
@@ -24,6 +24,8 @@
*/
package org.spongepowered.tools.obfuscation;
+import java.util.Set;
+
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
@@ -35,7 +37,13 @@ import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.Mixin;
+import com.google.common.collect.ImmutableSet;
+
public abstract class MixinProcessor extends AbstractProcessor {
+
+ private static final Set supportedOptions = ImmutableSet.of(
+ "reobfSrgFile", "outSrgFile", "outRefMapFile", "disableTargetValidator"
+ );
/**
* Mixin info manager
@@ -82,4 +90,9 @@ public abstract class MixinProcessor extends AbstractProcessor {
return super.getSupportedSourceVersion();
}
+ @Override
+ public Set getSupportedOptions() {
+ return MixinProcessor.supportedOptions;
+ }
+
}
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java
index fdbd7ff3..53201a87 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationProcessor.java
@@ -28,9 +28,6 @@ import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.annotation.processing.SupportedOptions;
-import javax.annotation.processing.SupportedSourceVersion;
-import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
@@ -47,9 +44,7 @@ import org.spongepowered.tools.MirrorUtils;
* Annotation processor which finds {@link Shadow} and {@link Overwrite}
* annotations in mixin classes and generates SRG mappings
*/
-@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.Mixin", "org.spongepowered.asm.mixin.Shadow", "org.spongepowered.asm.mixin.Overwrite" })
-@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile", "disableTargetValidator" })
public class TargetObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
@@ -60,7 +55,7 @@ public class TargetObfuscationProcessor extends MixinProcessor {
@Override
public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
- return false;
+ return true;
}
this.processMixins(roundEnv);
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java b/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java
index 099b0778..c39d1460 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinLaunchAgentFML.java
@@ -91,9 +91,8 @@ public class MixinLaunchAgentFML extends MixinLaunchAgentAbstract {
return this.injectCorePlugin();
} catch (Exception ex) {
- ex.printStackTrace();
+ return null;
}
- return null;
}
/**
diff --git a/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java b/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java
index d140042a..2bf79fa4 100644
--- a/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java
+++ b/src/main/java/org/spongepowered/asm/launch/MixinTweakContainer.java
@@ -29,6 +29,9 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.List;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
@@ -46,6 +49,8 @@ public class MixinTweakContainer {
MixinTweakContainer.agentClasses.add("org.spongepowered.asm.launch.MixinLaunchAgentDefault");
}
+ private final Logger logger = LogManager.getLogger("mixin");
+
private final URI uri;
private final List agents = new ArrayList();
@@ -61,7 +66,7 @@ public class MixinTweakContainer {
IMixinLaunchAgent agent = ctor.newInstance(uri);
this.agents.add(agent);
} catch (Exception ex) {
- ex.printStackTrace();
+ this.logger.catching(ex);
}
}
}
diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
index b1294206..6973e578 100644
--- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
+++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java
@@ -211,7 +211,7 @@ public class MixinEnvironment implements ITokenProvider {
return name;
}
- name = this.getSideName("com.mumfrey.liteloader.core.LiteLoader", "getEnvironmentType");
+ name = this.getSideName("com.mumfrey.liteloader.launch.LiteLoaderTweaker", "getEnvironmentType");
if (name != null) {
return name;
}
From 03744c86a097daba18b16e9ee5d347f7eb1ad473 Mon Sep 17 00:00:00 2001
From: Mumfrey
Date: Fri, 4 Dec 2015 01:45:43 +0000
Subject: [PATCH 044/169] AP support for gradle plugin, version bump to 0.4.8
---
gradle.properties | 2 +-
.../tools/obfuscation/AnnotatedMixin.java | 87 +++---
.../tools/obfuscation/AnnotatedMixins.java | 269 ++++++-----------
.../obfuscation/ITypeHandleProvider.java | 31 ++
.../tools/obfuscation/MixinProcessor.java | 8 +-
.../tools/obfuscation/ObfuscationData.java | 52 ++++
.../tools/obfuscation/ObfuscationType.java | 81 +++++
.../tools/obfuscation/SupportedOptions.java | 55 ++++
.../TargetObfuscationEnvironment.java | 279 ++++++++++++++++++
.../validation/TargetValidator.java | 3 +-
.../asm/launch/MixinBootstrap.java | 2 +-
11 files changed, 635 insertions(+), 234 deletions(-)
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/ITypeHandleProvider.java
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationData.java
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java
create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/TargetObfuscationEnvironment.java
diff --git a/gradle.properties b/gradle.properties
index 699cd8cc..71e0f17d 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -4,5 +4,5 @@ packaging=jar
description=Mixin
url=https://www.spongepowered.org
organization=SpongePowered
-buildVersion=0.4.7
+buildVersion=0.4.8
buildType=SNAPSHOT
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
index 3083d2d4..a90eb314 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java
@@ -259,12 +259,12 @@ class AnnotatedMixin {
/**
* Stored (ordered) field mappings
*/
- private final Set fieldMappings = new LinkedHashSet();
+ private final Map> fieldMappings = new HashMap>();
/**
* Stored (ordered) method mappings
*/
- private final Set methodMappings = new LinkedHashSet();
+ private final Map> methodMappings = new HashMap>();
public AnnotatedMixin(AnnotatedMixins mixins, TypeElement type) {
@@ -284,6 +284,11 @@ class AnnotatedMixin {
}
this.remap = AnnotatedMixins.getRemapValue(this.annotation) && this.targets.size() > 0;
+
+ for (ObfuscationType obfType : ObfuscationType.values()) {
+ this.fieldMappings.put(obfType, new LinkedHashSet());
+ this.methodMappings.put(obfType, new LinkedHashSet());
+ }
}
AnnotatedMixin runValidators(ValidationPass pass, Collection validators) {
@@ -389,15 +394,15 @@ class AnnotatedMixin {
/**
* Get stored field mappings
*/
- public Set getFieldMappings() {
- return this.fieldMappings;
+ public Set getFieldMappings(ObfuscationType type) {
+ return this.fieldMappings.get(type);
}
/**
* Get stored method mappings
*/
- public Set getMethodMappings() {
- return this.methodMappings;
+ public Set getMethodMappings(ObfuscationType type) {
+ return this.methodMappings.get(type);
}
/**
@@ -437,9 +442,9 @@ class AnnotatedMixin {
String mcpName = method.getSimpleName().toString();
String mcpSignature = MirrorUtils.generateSignature(method);
- MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + mcpName, mcpSignature));
+ ObfuscationData obfMethodData = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + mcpName, mcpSignature));
- if (obfMethod == null) {
+ if (obfMethodData.isEmpty()) {
Kind error = Kind.ERROR;
try {
@@ -455,9 +460,12 @@ class AnnotatedMixin {
this.mixins.printMessage(error, "No obfuscation mapping for @Overwrite method", method);
return;
}
-
- String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
- this.addMethodMapping(mcpName, obfName, mcpSignature, obfMethod.sig);
+
+ for (ObfuscationType type : obfMethodData) {
+ MethodData obfMethod = obfMethodData.get(type);
+ String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
+ this.addMethodMapping(type, mcpName, obfName, mcpSignature, obfMethod.sig);
+ }
}
/**
@@ -471,14 +479,17 @@ class AnnotatedMixin {
return;
}
- String obfField = this.mixins.getObfField(this.targetRef + "/" + name);
+ ObfuscationData obfFieldData = this.mixins.getObfField(this.targetRef + "/" + name);
- if (obfField == null) {
+ if (obfFieldData.isEmpty()) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field, shadow);
return;
}
- this.addFieldMapping(name.setObfuscatedName(obfField));
+ for (ObfuscationType type : obfFieldData) {
+ String fieldName = obfFieldData.get(type);
+ this.addFieldMapping(type, name.setObfuscatedName(fieldName));
+ }
}
/**
@@ -493,14 +504,17 @@ class AnnotatedMixin {
}
String mcpSignature = MirrorUtils.generateSignature(method);
- MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + name, mcpSignature));
+ ObfuscationData obfMethodData = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + name, mcpSignature));
- if (obfMethod == null) {
+ if (obfMethodData.isEmpty()) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method", method, shadow);
return;
}
- this.addMethodMapping(name.setObfuscatedName(obfMethod.name), mcpSignature, obfMethod.sig);
+ for (ObfuscationType type : obfMethodData) {
+ MethodData obfMethod = obfMethodData.get(type);
+ this.addMethodMapping(type, name.setObfuscatedName(obfMethod.name), mcpSignature, obfMethod.sig);
+ }
}
/**
@@ -544,18 +558,13 @@ class AnnotatedMixin {
return null;
}
- MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc));
- if (obfMethod == null) {
+ ObfuscationData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc));
+ if (obfMethod.isEmpty()) {
Kind error = Constants.INIT.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR;
return new Message(error, "No obfuscation mapping for " + type + " target " + targetMember.name, method, inject);
}
- int slashPos = obfMethod.name.lastIndexOf('/');
- String obfName = obfMethod.name.substring(slashPos + 1);
- String obfOwner = obfMethod.name.substring(0, slashPos);
- MemberInfo remappedReference = new MemberInfo(obfName, obfOwner, obfMethod.sig, false);
-
- this.mixins.getReferenceMapper().addMapping(this.classRef, originalReference, remappedReference.toString());
+ this.mixins.addMethodMapping(this.classRef, originalReference, obfMethod);
return null;
}
@@ -599,50 +608,46 @@ class AnnotatedMixin {
this.mixins.printMessage(Kind.ERROR, ex.getMessage(), element, inject);
}
- MemberInfo remappedReference = null;
if (targetMember.isField()) {
- String obfField = this.mixins.getObfField(targetMember.toSrg());
- if (obfField == null) {
+ ObfuscationData obfFieldData = this.mixins.getObfField(targetMember.toSrg());
+ if (obfFieldData.isEmpty()) {
this.mixins.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target + "'", element, inject);
return false;
}
- remappedReference = MemberInfo.fromSrgField(obfField, targetMember.desc);
+ this.mixins.addFieldMapping(this.classRef, target, targetMember, obfFieldData);
} else {
- MethodData obfMethod = this.mixins.getObfMethod(targetMember);
- if (obfMethod == null) {
+ ObfuscationData obfMethodData = this.mixins.getObfMethod(targetMember);
+ if (obfMethodData.isEmpty()) {
if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) {
this.mixins.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target + "'", element, inject);
}
- return false;
}
- remappedReference = targetMember.remapUsing(obfMethod, false);
+ this.mixins.addMethodMapping(this.classRef, target, targetMember, obfMethodData);
}
-
- this.mixins.getReferenceMapper().addMapping(this.classRef, target, remappedReference.toString());
return true;
}
/**
* Add a field mapping to the local table
*/
- private void addFieldMapping(ShadowElementName name) {
+ private void addFieldMapping(ObfuscationType type, ShadowElementName name) {
String mapping = String.format("FD: %s %s", this.classRef + "/" + name.name(), this.classRef + "/" + name.obfuscated());
- this.fieldMappings.add(mapping);
+ this.fieldMappings.get(type).add(mapping);
}
/**
* Add a method mapping to the local table
*/
- private void addMethodMapping(ShadowElementName name, String mcpSignature, String obfSignature) {
- this.addMethodMapping(name.name(), name.obfuscated(), mcpSignature, obfSignature);
+ private void addMethodMapping(ObfuscationType type, ShadowElementName name, String mcpSignature, String obfSignature) {
+ this.addMethodMapping(type, name.name(), name.obfuscated(), mcpSignature, obfSignature);
}
/**
* Add a method mapping to the local table
*/
- private void addMethodMapping(String mcpName, String obfName, String mcpSignature, String obfSignature) {
+ private void addMethodMapping(ObfuscationType type, String mcpName, String obfName, String mcpSignature, String obfSignature) {
String mapping = String.format("MD: %s %s %s %s", this.classRef + "/" + mcpName, mcpSignature, this.classRef + "/" + obfName, obfSignature);
- this.methodMappings.add(mapping);
+ this.methodMappings.get(type).add(mapping);
}
/**
diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
index febeab46..156d24f9 100644
--- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
+++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java
@@ -24,18 +24,13 @@
*/
package org.spongepowered.tools.obfuscation;
-import java.io.File;
-import java.io.IOException;
import java.io.InputStream;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
-import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -50,7 +45,6 @@ import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
-import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;
@@ -61,7 +55,6 @@ import javax.tools.StandardLocation;
import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
-import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.IMixinValidator.ValidationPass;
@@ -72,14 +65,13 @@ import org.spongepowered.tools.obfuscation.validation.TargetValidator;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
-import net.minecraftforge.srg2source.rangeapplier.SrgContainer;
/**
* Mixin info manager, stores all of the mixin info during processing and also
* manages access to the srgs
*/
-class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
+class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider, ITypeHandleProvider {
private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid";
@@ -118,24 +110,9 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
private final List mixinsForPass = new ArrayList();
/**
- * Name of the resource to write generated srgs to
+ * Target obfuscation environments
*/
- private final String outSrgFileName;
-
- /**
- * Name of the resource to write remapped refs to
- */
- private final String outRefMapFileName;
-
- /**
- * File containing the reobfd srgs
- */
- private final String reobfSrgFileName;
-
- /**
- * Reference mapper for reference mapping
- */
- private final ReferenceMapper refMapper = new ReferenceMapper();
+ private final List targetEnvironments = new ArrayList();
/**
* Rule validators
@@ -152,17 +129,6 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
*/
private final TargetMap targets;
- /**
- * SRG container for mcp->srg mappings
- */
- private SrgContainer srgs;
-
- /**
- * True once we've tried to initialise the srgs, initially false so that we
- * can do srg init lazily
- */
- private boolean initDone;
-
/**
* Properties file used to specify options when AP options cannot be
* configured via the build script (eg. when using AP with MCP)
@@ -178,10 +144,12 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
this.targets = this.initTargetMap();
this.printMessage(Kind.NOTE, "SpongePowered Mixin Annotation Processor v" + MixinBootstrap.VERSION);
-
- this.reobfSrgFileName = this.getOption("reobfSrgFile");
- this.outSrgFileName = this.getOption("outSrgFile");
- this.outRefMapFileName = this.getOption("outRefMapFile");
+
+ for (ObfuscationType obfType : ObfuscationType.values()) {
+ if (obfType.isSupported(this)) {
+ this.targetEnvironments.add(new TargetObfuscationEnvironment(obfType, this, this, this));
+ }
+ }
this.validators = ImmutableList.of(
new ParentValidator(processingEnv, this, this),
@@ -267,123 +235,103 @@ class AnnotatedMixins implements Messager, ITokenProvider, IOptionProvider {
return CompilerEnvironment.JAVAC;
}
- /**
- * Lazy initialisation for srgs, so that we only initialise the srgs if
- * they're actually required.
- */
- private boolean initSrgs() {
- if (!this.initDone) {
- this.initDone = true;
-
- if (this.reobfSrgFileName == null) {
- this.printMessage(Kind.ERROR, "The reobfSrgFile argument was not supplied, obfuscation processing will not occur");
- return false;
- }
-
- try {
- File reobfSrgFile = new File(this.reobfSrgFileName);
- this.printMessage(Kind.NOTE, "Loading SRGs from " + reobfSrgFile.getAbsolutePath());
- this.srgs = new SrgContainer().readSrg(reobfSrgFile);
- } catch (Exception ex) {
- ex.printStackTrace();
- this.printMessage(Kind.ERROR, "The specified SRG file could not be read, processing cannot continue");
- this.srgs = null;
- }
- }
-
- return this.srgs != null;
- }
-
/**
* Write out generated srgs
*/
public void writeSrgs() {
- if (this.outSrgFileName == null) {
- return;
+ for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
+ targetEnv.writeSrgs(this.processingEnv.getFiler(), this.mixins);
}
-
- Set fieldMappings = new LinkedHashSet();
- Set methodMappings = new LinkedHashSet();
-
- for (AnnotatedMixin mixin : this.mixins.values()) {
- fieldMappings.addAll(mixin.getFieldMappings());
- methodMappings.addAll(mixin.getMethodMappings());
- }
-
- PrintWriter writer = null;
-
- try {
- writer = this.openFileWriter(this.outSrgFileName, "output SRGs");
- for (String fieldMapping : fieldMappings) {
- writer.println(fieldMapping);
- }
- for (String methodMapping : methodMappings) {
- writer.println(methodMapping);
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- if (writer != null) {
- try {
- writer.close();
- } catch (Exception ex) {
- // oh well
- }
- }
- }
- }
-
- /**
- * Open a writer for an output file
- */
- private PrintWriter openFileWriter(String fileName, String description) throws IOException {
- if (fileName.matches("^.*[\\\\/:].*$")) {
- File outSrgFile = new File(fileName);
- outSrgFile.getParentFile().mkdirs();
- this.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath());
- return new PrintWriter(outSrgFile);
- }
-
- Filer filer = this.processingEnv.getFiler();
- FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
- this.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath());
- return new PrintWriter(outSrg.openWriter());
}
/**
* Write out stored mappings
*/
public void writeRefs() {
- if (this.outRefMapFileName == null) {
- return;
+ for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
+ targetEnv.writeRefs(this.processingEnv.getFiler());
}
+ }
+
+ public ObfuscationData getObfMethod(MemberInfo method) {
+ ObfuscationData data = new ObfuscationData();
- PrintWriter writer = null;
-
- try {
- writer = this.openFileWriter(this.outRefMapFileName, "refmap");
- this.refMapper.write(writer);
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- if (writer != null) {
- try {
- writer.close();
- } catch (Exception ex) {
- // oh well
- }
+ for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
+ MethodData obfMethod = targetEnv.getObfMethod(method);
+ if (obfMethod != null) {
+ data.add(targetEnv.getType(), obfMethod);
}
}
+ return data;
}
/**
- * Get the reference mapper
+ * Get an obfuscation mapping for a method
*/
- public ReferenceMapper getReferenceMapper() {
- return this.refMapper;
+ public ObfuscationData getObfMethod(MethodData method) {
+ ObfuscationData data = new ObfuscationData();
+
+ for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
+ MethodData obfMethod = targetEnv.getObfMethod(method);
+ if (obfMethod != null) {
+ data.add(targetEnv.getType(), obfMethod);
+ }
+ }
+
+ return data;
+ }
+
+ /**
+ * Get an obfuscation mapping for a field
+ */
+ public ObfuscationData getObfField(String field) {
+ ObfuscationData data = new ObfuscationData();
+
+ for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
+ String obfField = targetEnv.getObfField(field);
+ if (obfField != null) {
+ data.add(targetEnv.getType(), obfField);
+ }
+ }
+
+ return data;
+ }
+
+ void addMethodMapping(String className, String reference, ObfuscationData obfMethodData) {
+ for (TargetObfuscationEnvironment targetEnv : this.targetEnvironments) {
+ MethodData obfMethod = obfMethodData.get(targetEnv.getType());
+ if (obfMethod != null) {
+ int slashPos = obfMethod.name.lastIndexOf('/');
+ String obfName = obfMethod.name.substring(slashPos + 1);
+ String obfOwner = obfMethod.name.substring(0, slashPos);
+ MemberInfo remappedReference = new MemberInfo(obfName, obfOwner, obfMethod.sig, false);
+ targetEnv.getReferenceMapper().addMapping(className, reference, remappedReference.toString());
+ }
+ }
}
+ void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData