Merge remote-tracking branch 'sponge/master'

# Conflicts:
#	build.gradle
#	gradle.properties
#	gradle/wrapper/gradle-wrapper.properties
#	src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java
This commit is contained in:
modmuss50 committed 2021-08-14 14:45:50 +01:00
commit 45917bee6b
77 files changed
+2714 -610

No files matched your search

@@ -66,7 +66,7 @@ public abstract class MixinBootstrap {
/**
* Subsystem version
*/
public static final String VERSION = "0.8.3";
public static final String VERSION = "0.8.4";
/**
* Transformer factory
@@ -24,18 +24,25 @@
*/
package org.spongepowered.asm.launch.platform;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.spongepowered.asm.util.JavaVersion;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
/**
* "Main" attribute cache for a URI container, mainly to avoid constantly
@@ -54,8 +61,8 @@ public final class MainAttributes {
this.attributes = new Attributes();
}
private MainAttributes(File jar) {
this.attributes = MainAttributes.getAttributes(jar);
private MainAttributes(URI codeSource) {
this.attributes = MainAttributes.getAttributes(codeSource);
}
/**
@@ -72,20 +79,42 @@ public final class MainAttributes {
return null;
}
private static Attributes getAttributes(File codeSource) {
/**
* Retrieve the value of attribute with the specified name, or null if not
* present
*
* @param name attribute name
* @return attribute value or null if not present
*/
public final String get(Name name) {
if (this.attributes != null) {
return this.attributes.getValue(name);
}
return null;
}
private static Attributes getAttributes(URI codeSource) {
if (codeSource == null) {
return null;
}
if (codeSource.isFile()) {
Attributes attributes = MainAttributes.getJarAttributes(codeSource);
if (attributes != null) {
return attributes;
if ("file".equals(codeSource.getScheme())) {
File file = new File(codeSource);
if (file.isFile()) {
Attributes attributes = MainAttributes.getJarAttributes(file);
if (attributes != null) {
return attributes;
}
} else if (file.isDirectory()) {
Attributes attributes = MainAttributes.getDirAttributes(file);
if (attributes != null) {
return attributes;
}
}
}
if (codeSource.isDirectory()) {
Attributes attributes = MainAttributes.getDirAttributes(codeSource);
} else if (JavaVersion.current() >= JavaVersion.JAVA_7) {
// Can try getting the resource using nio if we are on Java 7 or later
Attributes attributes = MainAttributes.getNioAttributes(codeSource);
if (attributes != null) {
return attributes;
}
@@ -119,7 +148,7 @@ public final class MainAttributes {
private static Attributes getDirAttributes(File dir) {
File manifestFile = new File(dir, JarFile.MANIFEST_NAME);
if (manifestFile.isFile()) {
ByteSource source = Files.asByteSource(manifestFile);
ByteSource source = com.google.common.io.Files.asByteSource(manifestFile);
InputStream inputStream = null;
try {
inputStream = source.openBufferedStream();
@@ -140,7 +169,35 @@ public final class MainAttributes {
return null;
}
private static Attributes getNioAttributes(URI uri) {
try {
Path manifestPath = Paths.get(uri).resolve(JarFile.MANIFEST_NAME);
BufferedInputStream inputStream = null;
try {
inputStream = new BufferedInputStream(java.nio.file.Files.newInputStream(manifestPath));
Manifest manifest = new Manifest(inputStream);
return manifest.getMainAttributes();
} catch (IOException ex) {
// be quiet checkstyle
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
// ignore
}
}
} catch (FileSystemNotFoundException ex) {
// No FS available?
ex.printStackTrace();
} catch (InvalidPathException ex) {
ex.printStackTrace();
}
return null;
}
/**
* Create a MainAttributes instance for the supplied jar file
@@ -161,7 +218,7 @@ public final class MainAttributes {
public static MainAttributes of(URI uri) {
MainAttributes attributes = MainAttributes.instances.get(uri);
if (attributes == null) {
attributes = new MainAttributes(new File(uri));
attributes = new MainAttributes(uri);
MainAttributes.instances.put(uri, attributes);
}
return attributes;
@@ -42,11 +42,6 @@ public class ContainerHandleURI implements IContainerHandle {
*/
private final URI uri;
/**
* File containing this tweaker
*/
private final File file;
/**
* "Main" manifest attributes from the container
*/
@@ -54,7 +49,6 @@ public class ContainerHandleURI implements IContainerHandle {
public ContainerHandleURI(URI uri) {
this.uri = uri;
this.file = this.uri != null ? new File(this.uri) : null;
this.attributes = MainAttributes.of(uri);
}
@@ -68,8 +62,9 @@ public class ContainerHandleURI implements IContainerHandle {
/**
* Get the container file
*/
@Deprecated
public File getFile() {
return this.file;
return this.uri != null && "file".equals(this.uri.getScheme()) ? new File(this.uri) : null;
}
/* (non-Javadoc)
@@ -62,6 +62,13 @@ public class ContainerHandleVirtual implements IContainerHandle {
this.name = name;
}
/**
* Get the name of this container
*/
public String getName() {
return this.name;
}
/**
* Set a virtual attribute on this virtual container
*
@@ -603,7 +603,7 @@ public final class MixinEnvironment implements ITokenProvider {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.7;
return JavaVersion.current() >= JavaVersion.JAVA_7;
}
},
@@ -615,7 +615,7 @@ public final class MixinEnvironment implements ITokenProvider {
@Override
boolean isSupported() {
return JavaVersion.current() >= 1.8;
return JavaVersion.current() >= JavaVersion.JAVA_8;
}
},
@@ -628,7 +628,7 @@ public final class MixinEnvironment implements ITokenProvider {
@Override
boolean isSupported() {
return JavaVersion.current() >= 9.0;
return JavaVersion.current() >= JavaVersion.JAVA_8 && ASM.isAtLeastVersion(6);
}
},
@@ -641,7 +641,7 @@ public final class MixinEnvironment implements ITokenProvider {
@Override
boolean isSupported() {
return JavaVersion.current() >= 10.0;
return JavaVersion.current() >= JavaVersion.JAVA_10 && ASM.isAtLeastVersion(6, 1);
}
},
@@ -654,7 +654,105 @@ public final class MixinEnvironment implements ITokenProvider {
@Override
boolean isSupported() {
return JavaVersion.current() >= 11.0;
return JavaVersion.current() >= JavaVersion.JAVA_11 && ASM.isAtLeastVersion(7);
}
},
/**
* Java 12 or above is required
*/
JAVA_12(12, Opcodes.V12, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_12 && ASM.isAtLeastVersion(7);
}
},
/**
* Java 13 or above is required
*/
JAVA_13(13, Opcodes.V13, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_13 && ASM.isAtLeastVersion(7);
}
},
/**
* Java 14 or above is required. Records are a preview feature in this
* release.
*/
JAVA_14(14, Opcodes.V14, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS
| LanguageFeatures.RECORDS) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_14 && ASM.isAtLeastVersion(8);
}
},
/**
* Java 15 or above is required. Records and sealed classes are preview
* features in this release.
*/
JAVA_15(15, Opcodes.V15, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS
| LanguageFeatures.RECORDS | LanguageFeatures.SEALED_CLASSES) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_15 && ASM.isAtLeastVersion(9);
}
},
/**
* Java 16 or above is required
*/
JAVA_16(16, Opcodes.V16, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS
| LanguageFeatures.RECORDS | LanguageFeatures.SEALED_CLASSES) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_16 && ASM.isAtLeastVersion(9);
}
},
/**
* Java 17 or above is required
*/
JAVA_17(17, Opcodes.V17, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS
| LanguageFeatures.RECORDS | LanguageFeatures.SEALED_CLASSES) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_17 && ASM.isAtLeastVersion(9, 1);
}
},
/**
* Java 18 or above is required
*/
JAVA_18(18, Opcodes.V18, LanguageFeatures.METHODS_IN_INTERFACES | LanguageFeatures.PRIVATE_SYNTHETIC_METHODS_IN_INTERFACES
| LanguageFeatures.PRIVATE_METHODS_IN_INTERFACES | LanguageFeatures.NESTING | LanguageFeatures.DYNAMIC_CONSTANTS
| LanguageFeatures.RECORDS | LanguageFeatures.SEALED_CLASSES) {
@Override
boolean isSupported() {
return JavaVersion.current() >= JavaVersion.JAVA_18 && ASM.isAtLeastVersion(9, 2);
}
},
@@ -762,7 +860,7 @@ public final class MixinEnvironment implements ITokenProvider {
* PR #500 which demonstrates that the nature of compatibility levels
* in mixin are not understood that well.</p>
*/
public static CompatibilityLevel MAX_SUPPORTED = CompatibilityLevel.JAVA_11;
public static CompatibilityLevel MAX_SUPPORTED = CompatibilityLevel.JAVA_13;
private final int ver;
@@ -1114,7 +1212,7 @@ public final class MixinEnvironment implements ITokenProvider {
printer.kv("Internal Version", version);
printer.kv("Java Version", "%s (supports compatibility %s)", JavaVersion.current(), CompatibilityLevel.getSupportedVersions());
printer.kv("Default Compatibility Level", MixinEnvironment.getCompatibilityLevel());
printer.kv("Detected ASM API Version", ASM.getApiVersionString());
printer.kv("Detected ASM Version", ASM.getVersionString());
printer.kv("Detected ASM Supports Java", ASM.getClassVersionString()).hr();
printer.kv("Service Name", serviceName);
printer.kv("Mixin Service Class", this.service.getClass().getName());
@@ -1525,7 +1623,11 @@ public final class MixinEnvironment implements ITokenProvider {
return MixinEnvironment.compatibility;
}
private static CompatibilityLevel getMinCompatibilityLevel() {
/**
* Get the minimum (default) compatibility level supported by the current
* service
*/
public static CompatibilityLevel getMinCompatibilityLevel() {
CompatibilityLevel minLevel = MixinService.getService().getMinCompatibilityLevel();
return minLevel == null ? CompatibilityLevel.DEFAULT : minLevel;
}
@@ -1547,7 +1649,10 @@ public final class MixinEnvironment implements ITokenProvider {
CompatibilityLevel currentLevel = MixinEnvironment.getCompatibilityLevel();
if (level != currentLevel && level.isAtLeast(currentLevel)) {
if (!level.isSupported()) {
throw new IllegalArgumentException("The requested compatibility level " + level + " could not be set. Level is not supported");
throw new IllegalArgumentException(String.format(
"The requested compatibility level %s could not be set. Level is not supported by the active JRE or ASM version (Java %s, %s)",
level, JavaVersion.current(), ASM.getVersionString()
));
}
IMixinService service = MixinService.getService();
@@ -0,0 +1,101 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.extensibility;
public interface IActivityContext {
public interface IActivity {
/**
* End this activity (and any descendants) and begin the next activity
* using the same activity handle
*
* @param descriptionFormat New activity description format
* @param args New activity description args
*/
void next(String descriptionFormat, Object... args);
/**
* End this activity (and any descendants) and begin the next activity
* using the same activity handle
*
* @param description New activity description
*/
void next(String description);
/**
* End this activity and remove it (and any descendants)
*/
void end();
/**
* Append text to the activity description
*
* @param textFormat Format for text to append
* @param args Format args
*/
void append(String textFormat, Object...args);
/**
* Append text to the activity description
*
* @param text Text to append
*/
void append(String text);
}
/**
* Convert this activity stack to a string representation using the
* specified glue string
*
* @param glue glue string
* @return string representation of this activity stack
*/
public abstract String toString(String glue);
/**
* Begin a new activity (push it onto this activity stack)
*
* @param descriptionFormat Activity description format
* @param args format args
* @return new activity handle
*/
public abstract IActivity begin(String descriptionFormat, Object... args);
/**
* Begin a new activity (push it onto this activity stack)
*
* @param description Activity description
* @return new activity handle
*/
public abstract IActivity begin(String description);
/**
* Clear the activity stack
*/
public abstract void clear();
}
@@ -88,5 +88,33 @@ public interface IMixinConfig {
* @return target classes of mixins in this config
*/
public abstract Set<String> getTargets();
/**
* Decorate this config with arbitrary metadata for debugging or
* compatibility purposes
*
* @param key meta key
* @param value meta value
* @param <V> value type
* @throws IllegalArgumentException if the specified key exists already
*/
public abstract <V> void decorate(String key, V value);
/**
* Get whether this node is decorated with the specified key
*
* @param key meta key
* @return true if the specified decoration exists
*/
public abstract boolean hasDecoration(String key);
/**
* Get the specified decoration
*
* @param key meta key
* @param <V> value type
* @return decoration value or null if absent
*/
public abstract <V> V getDecoration(String key);
}
@@ -42,17 +42,17 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* method invocation within the target method(s). To affect multiple arguments
* of an invocation all at once, use {@link ModifyArgs} instead.
*
* <p>Use this injector when a method contains an method invocation and you wish
* to change a single value being <em>passed to</em> that method. If you need to
* alter an argument <em>received by</em> a target method, use {@link
* ModifyVariable} instead.</p>
* <p>Use this injector when a (target) method contains an method invocation
* (the subject) and you wish to change a single value being <em>passed to</em>
* that subject method. If you need to alter an argument <em>received by</em> a
* target method, use {@link ModifyVariable} instead.</p>
*
* <p>Consider the following method:</p>
*
* <blockquote><pre><code>private void targetMethod() {
* Entity someEntity = this.obtainEntity();
* float x = 1.0F, y = 3.0F, z = 0.1F;
* someEntity.<ins>setLocation</ins>(x, <ins>y</ins>, z, true);
* someEntity.<ins>setLocation</ins>(x, <ins>y</ins>, z, true); // subject
*}</code></pre>
*</blockquote>
*
@@ -71,7 +71,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <p>The callback consumes the original value of <tt>y</tt> and returns the
* adjusted value.</p>
*
* <p><tt>&#064;ModifyArg</tt> can also consume all of the target method's
* <p><tt>&#064;ModifyArg</tt> can also consume all of the subject method's
* arguments if required, to provide additional context for the callback. In
* this case the arguments of the callback should match the target method:</p>
*
@@ -80,6 +80,9 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* private float adjustYCoord(float x, float y, float z, boolean interpolate) {
* <br />&nbsp; &nbsp; return (x == 0 &amp;&amp; y == 0) ? 0 : y;<br />
* }</code></blockquote>
*
* <p>Note that <tt>&#064;ModifyArg</tt> <em>cannot</em> capture the arguments
* of the <em>target</em> method like some other injectors can
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -49,7 +49,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* <p>This injector works by creating an <em>argument bundle</em> in the form of
* {@link Args} which is passed to your handler method. You can manipulate the
* method arguments via the bundle in your handler method. The bundle is then
* unpacked and the original method is called with the modified arguments.</p>
* unpacked and the original subject method is called with the modified
* arguments.</p>
*
* <p>Since the argument bundle is created for every invocation of the target
* method, and primitive types must undergo boxing and unboxing, this injector
@@ -66,7 +67,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* </ul>
*
* <p>Methods decorated with this injector should return <tt>void</tt> and
* return either:</p>
* consume either:</p>
*
* <ul>
* <li>A single argument of type {@link Args}</li>
@@ -454,7 +454,7 @@ public class CallbackInjector extends Injector {
@Override
protected void preInject(Target target, InjectionNode node) {
if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
if ((this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) && !node.hasDecoration(CallbackInjector.LOCALS_KEY)) {
LocalVariableNode[] locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget());
for (int j = 0; j < locals.length; j++) {
if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) {
@@ -34,7 +34,7 @@ import org.objectweb.asm.tree.InsnList;
* instances so that custom InjectionPoint implementations cannot modify the
* insn list whilst inspecting it.
*/
class InsnListReadOnly extends InsnList {
public class InsnListReadOnly extends InsnList {
private InsnList insnList;
@@ -131,8 +131,8 @@ public class BeforeLoadLocal extends LocalVariableInjectionPoint {
this.varNode = node;
}
void check(Target target, Collection<AbstractInsnNode> nodes, AbstractInsnNode insn) {
Context context = new Context(BeforeLoadLocal.this.returnType, BeforeLoadLocal.this.discriminator.isArgsOnly(), target, insn);
void check(InjectionInfo info, Target target, Collection<AbstractInsnNode> nodes, AbstractInsnNode insn) {
Context context = new Context(info, BeforeLoadLocal.this.returnType, BeforeLoadLocal.this.discriminator.isArgsOnly(), target, insn);
int local = SearchState.INVALID_IMPLICIT;
try {
@@ -207,13 +207,13 @@ public class BeforeLoadLocal extends LocalVariableInjectionPoint {
while (iter.hasNext()) {
AbstractInsnNode insn = iter.next();
if (state.isPendingCheck()) {
state.check(target, nodes, insn);
state.check(info, target, nodes, insn);
} else if (insn instanceof VarInsnNode && insn.getOpcode() == this.opcode && (this.ordinal == -1 || !state.success())) {
state.register((VarInsnNode)insn);
if (this.opcodeAfter) {
state.setPendingCheck();
} else {
state.check(target, nodes, insn);
state.check(info, target, nodes, insn);
}
}
}
@@ -36,6 +36,7 @@ import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
@@ -65,17 +66,17 @@ public class LocalVariableDiscriminator {
/**
* Ordinal value of this local variable type
*/
int ord = 0;
private int ord = -1;
/**
* Local variable name
*/
String name;
final String name;
/**
* Local variable type
*/
Type type;
final Type type;
public Local(String name, Type type) {
this.name = name;
@@ -87,8 +88,24 @@ public class LocalVariableDiscriminator {
return String.format("Local[ordinal=%d, name=%s, type=%s]", this.ord, this.name, this.type);
}
void setOrdinal(int ordinal) {
if (this.ord > -1 && this.ord != ordinal) {
throw new IllegalStateException("Attempted to reset ordinal for computed local");
}
this.ord = ordinal;
}
int getOrdinal() {
return this.ord;
}
}
/**
* Injection info
*/
final InjectionInfo info;
/**
* Target method for this context
*/
@@ -121,7 +138,8 @@ public class LocalVariableDiscriminator {
*/
private final boolean isStatic;
public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
public Context(InjectionInfo info, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
this.info = info;
this.isStatic = Bytecode.isStatic(target.method);
this.returnType = returnType;
this.target = target;
@@ -166,7 +184,7 @@ public class LocalVariableDiscriminator {
if (this.locals[l] != null) {
ordinal = ordinalMap.get(this.locals[l].type);
ordinalMap.put(this.locals[l].type, ordinal = Integer.valueOf(ordinal == null ? 0 : ordinal.intValue() + 1));
this.locals[l].ord = ordinal.intValue();
this.locals[l].setOrdinal(ordinal.intValue());
}
}
}
@@ -189,7 +207,7 @@ public class LocalVariableDiscriminator {
if (local != null) {
Type localType = local.type;
String localName = local.name;
int ordinal = local.ord;
int ordinal = local.getOrdinal();
String candidate = this.returnType.equals(localType) ? "YES" : "-";
printer.add("[%3d] [%3d] %30s %-50s %s", l, ordinal, SignaturePrinter.getTypeName(localType, false), localName, candidate);
} else if (l > 0) {
@@ -366,7 +384,7 @@ public class LocalVariableDiscriminator {
continue;
}
if (this.ordinal > -1) {
if (this.ordinal == local.ord) {
if (this.ordinal == local.getOrdinal()) {
return index;
}
continue;
@@ -67,8 +67,8 @@ public class ModifyVariableInjector extends Injector {
*/
final InsnList insns = new InsnList();
public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
super(returnType, argsOnly, target, node);
public Context(InjectionInfo info, Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
super(info, returnType, argsOnly, target, node);
}
}
@@ -93,11 +93,6 @@ public class ModifyVariableInjector extends Injector {
abstract boolean find(InjectionInfo info, InsnList insns, Collection<AbstractInsnNode> nodes, Target target);
}
/**
* Decorator key for Context decoration
*/
private static final String LOCALS_CONTEXT_KEY = "localcontext";
/**
* True to consider only method args
@@ -142,10 +137,27 @@ public class ModifyVariableInjector extends Injector {
}
}
/**
* Generate a key which uniquely identifies the combination of return type,
* frame type and target injection node so that injectors targetting the
* same instruction still get unique contexts.
*
* @param target Target method
* @param node Target node
* @return Key for storing/retrieving the injector context decoration
*/
protected String getTargetNodeKey(Target target, InjectionNode node) {
return String.format("localcontext(%s,%s,#%s)", this.returnType, this.discriminator.isArgsOnly() ? "argsOnly" : "fullFrame", node.getId());
}
@Override
protected void preInject(Target target, InjectionNode node) {
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
node.<Context>decorate(ModifyVariableInjector.LOCALS_CONTEXT_KEY, context);
String key = this.getTargetNodeKey(target, node);
if (node.hasDecoration(key)) {
return; // already have a suitable context
}
Context context = new Context(this.info, this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
node.<Context>decorate(key, context);
}
/**
@@ -157,13 +169,22 @@ public class ModifyVariableInjector extends Injector {
throw new InvalidInjectionException(this.info, "Variable modifier target for " + this + " was removed by another injector");
}
Context context = node.<Context>getDecoration(ModifyVariableInjector.LOCALS_CONTEXT_KEY);
Context context = node.<Context>getDecoration(this.getTargetNodeKey(target, node));
if (context == null) {
throw new InjectionError(String.format(
"%s injector target is missing CONTEXT decoration for %s. PreInjection failure or illegal internal state change",
this.annotationType, this.info));
}
// If the context is being reused (because two identical injectors are targetting this node)
// then the insns SHOULD have been drained by the previous insertBefore. If the list hasn't
// been cleared for some reason then something probably went wrong during the previous inject
if (context.insns.size() > 0) {
throw new InjectionError(String.format(
"%s injector target has contaminated CONTEXT decoration for %s. Check for previous errors.",
this.annotationType, this.info));
}
if (this.discriminator.printLVT()) {
this.printLocals(target, context);
}
@@ -265,7 +265,7 @@ public final class DescriptorResolver {
}
public static IResolvedDescriptor resolve(IAnnotationHandle desc, ISelectorContext context) {
return new Descriptor(Collections.emptySet(), desc, context);
return new Descriptor(Collections.<String>emptySet(), desc, context);
}
/**
@@ -24,9 +24,9 @@
*/
package org.spongepowered.asm.mixin.injection.throwables;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
@@ -37,70 +37,70 @@ public class InvalidInjectionException extends InvalidMixinException {
private static final long serialVersionUID = 2L;
private final InjectionInfo info;
private final ISelectorContext selectorContext;
public InvalidInjectionException(IMixinContext context, String message) {
super(context, message);
this.info = null;
this.selectorContext = null;
}
public InvalidInjectionException(IMixinContext context, String message, ActivityStack activityContext) {
public InvalidInjectionException(IMixinContext context, String message, IActivityContext activityContext) {
super(context, message, activityContext);
this.info = null;
this.selectorContext = null;
}
public InvalidInjectionException(InjectionInfo info, String message) {
super(info.getMixin(), message);
this.info = info;
public InvalidInjectionException(ISelectorContext selectorContext, String message) {
super(selectorContext.getMixin(), message);
this.selectorContext = selectorContext;
}
public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) {
super(info.getMixin(), message, activityContext);
this.info = info;
public InvalidInjectionException(ISelectorContext selectorContext, String message, IActivityContext activityContext) {
super(selectorContext.getMixin(), message, activityContext);
this.selectorContext = selectorContext;
}
public InvalidInjectionException(IMixinContext context, Throwable cause) {
super(context, cause);
this.info = null;
this.selectorContext = null;
}
public InvalidInjectionException(IMixinContext context, Throwable cause, ActivityStack activityContext) {
public InvalidInjectionException(IMixinContext context, Throwable cause, IActivityContext activityContext) {
super(context, cause, activityContext);
this.info = null;
this.selectorContext = null;
}
public InvalidInjectionException(InjectionInfo info, Throwable cause) {
super(info.getMixin(), cause);
this.info = info;
public InvalidInjectionException(ISelectorContext selectorContext, Throwable cause) {
super(selectorContext.getMixin(), cause);
this.selectorContext = selectorContext;
}
public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) {
super(info.getMixin(), cause, activityContext);
this.info = info;
public InvalidInjectionException(ISelectorContext selectorContext, Throwable cause, IActivityContext activityContext) {
super(selectorContext.getMixin(), cause, activityContext);
this.selectorContext = selectorContext;
}
public InvalidInjectionException(IMixinContext context, String message, Throwable cause) {
super(context, message, cause);
this.info = null;
this.selectorContext = null;
}
public InvalidInjectionException(IMixinContext context, String message, Throwable cause, ActivityStack activityContext) {
public InvalidInjectionException(IMixinContext context, String message, Throwable cause, IActivityContext activityContext) {
super(context, message, cause, activityContext);
this.info = null;
this.selectorContext = null;
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) {
super(info.getMixin(), message, cause);
this.info = info;
public InvalidInjectionException(ISelectorContext selectorContext, String message, Throwable cause) {
super(selectorContext.getMixin(), message, cause);
this.selectorContext = selectorContext;
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) {
super(info.getMixin(), message, cause, activityContext);
this.info = info;
public InvalidInjectionException(ISelectorContext selectorContext, String message, Throwable cause, IActivityContext activityContext) {
super(selectorContext.getMixin(), message, cause, activityContext);
this.selectorContext = selectorContext;
}
public InjectionInfo getInjectionInfo() {
return this.info;
public ISelectorContext getContext() {
return this.selectorContext;
}
}
@@ -24,7 +24,7 @@
*/
package org.spongepowered.asm.mixin.throwables;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
import org.spongepowered.asm.mixin.transformer.ClassInfo;
/**
@@ -42,7 +42,7 @@ public class ClassMetadataNotFoundException extends MixinException {
super(message);
}
public ClassMetadataNotFoundException(String message, ActivityStack context) {
public ClassMetadataNotFoundException(String message, IActivityContext context) {
super(message, context);
}
@@ -50,7 +50,7 @@ public class ClassMetadataNotFoundException extends MixinException {
super(cause);
}
public ClassMetadataNotFoundException(Throwable cause, ActivityStack context) {
public ClassMetadataNotFoundException(Throwable cause, IActivityContext context) {
super(cause, context);
}
@@ -58,7 +58,7 @@ public class ClassMetadataNotFoundException extends MixinException {
super(message, cause);
}
public ClassMetadataNotFoundException(String message, Throwable cause, ActivityStack context) {
public ClassMetadataNotFoundException(String message, Throwable cause, IActivityContext context) {
super(message, cause, context);
}
@@ -24,6 +24,7 @@
*/
package org.spongepowered.asm.mixin.throwables;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
/**
@@ -39,7 +40,7 @@ public class MixinException extends RuntimeException {
super(message);
}
public MixinException(String message, ActivityStack context) {
public MixinException(String message, IActivityContext context) {
super(message);
this.activityDescriptor = context != null ? context.toString() : null;
}
@@ -48,7 +49,7 @@ public class MixinException extends RuntimeException {
super(cause);
}
public MixinException(Throwable cause, ActivityStack context) {
public MixinException(Throwable cause, IActivityContext context) {
super(cause);
this.activityDescriptor = context != null ? context.toString() : null;
}
@@ -57,7 +58,7 @@ public class MixinException extends RuntimeException {
super(message, cause);
}
public MixinException(String message, Throwable cause, ActivityStack context) {
public MixinException(String message, Throwable cause, IActivityContext context) {
super(message, cause);
this.activityDescriptor = context != null ? context.toString() : null;
}
@@ -67,7 +68,7 @@ public class MixinException extends RuntimeException {
*
* @param upstreamContext Upstream activity stack to decorate
*/
public void prepend(ActivityStack upstreamContext) {
public void prepend(IActivityContext upstreamContext) {
String strContext = upstreamContext.toString();
this.activityDescriptor = this.activityDescriptor != null ? strContext + ActivityStack.GLUE_STRING + this.activityDescriptor
: ActivityStack.GLUE_STRING + strContext;
@@ -24,17 +24,19 @@
*/
package org.spongepowered.asm.mixin.transformer;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
/**
* Tracker for processors which want to express their activity stack on crash in
* a user-readable way.
*/
public class ActivityStack {
public class ActivityStack implements IActivityContext {
/**
* An activity node in the activity stack (yes it's actually a doubly-linked
* list).
*/
public class Activity {
public class Activity implements IActivity {
/**
* Description of this activity
@@ -56,6 +58,7 @@ public class ActivityStack {
*
* @param text Text to append
*/
@Override
public void append(String text) {
this.description = this.description != null ? this.description + text : text;
}
@@ -66,6 +69,7 @@ public class ActivityStack {
* @param textFormat Format for text to append
* @param args Format args
*/
@Override
public void append(String textFormat, Object...args) {
this.append(String.format(textFormat, args));
}
@@ -73,6 +77,7 @@ public class ActivityStack {
/**
* End this activity and remove it (and any descendants)
*/
@Override
public void end() {
// Cannot end head or ended activity
if (this.last != null) {
@@ -87,6 +92,7 @@ public class ActivityStack {
*
* @param description New activity description
*/
@Override
public void next(String description) {
if (this.next != null) {
this.next.end();
@@ -101,6 +107,7 @@ public class ActivityStack {
* @param descriptionFormat New activity description format
* @param args New activity description args
*/
@Override
public void next(String descriptionFormat, Object... args) {
if (descriptionFormat == null) {
descriptionFormat = "null";
@@ -133,6 +140,7 @@ public class ActivityStack {
/**
* Clear the activity stack
*/
@Override
public void clear() {
this.tail = this.head;
this.head.next = null;
@@ -144,7 +152,8 @@ public class ActivityStack {
* @param description Activity description
* @return new activity handle
*/
public Activity begin(String description) {
@Override
public IActivity begin(String description) {
return this.tail = new Activity(this.tail, description != null ? description : "null");
}
@@ -155,7 +164,8 @@ public class ActivityStack {
* @param args format args
* @return new activity handle
*/
public Activity begin(String descriptionFormat, Object... args) {
@Override
public IActivity begin(String descriptionFormat, Object... args) {
if (descriptionFormat == null) {
descriptionFormat = "null";
}
@@ -182,6 +192,7 @@ public class ActivityStack {
* @param glue glue string
* @return string representation of this activity stack
*/
@Override
public String toString(String glue) {
if (this.head.description == null && this.head.next == null) {
return "Unknown";
@@ -29,6 +29,7 @@ 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;
@@ -42,6 +43,7 @@ import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.InnerClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.Final;
@@ -56,12 +58,15 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.ClassSignature;
import org.spongepowered.asm.util.LanguageFeatures;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.asm.ClassNodeAdapter;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
@@ -236,11 +241,11 @@ public final class ClassInfo {
this.size = size;
}
FrameData(int index, FrameNode frameNode) {
FrameData(int index, FrameNode frameNode, int initialFrameSize) {
this.index = index;
this.type = frameNode.type;
this.locals = frameNode.local != null ? frameNode.local.size() : 0;
this.size = Locals.computeFrameSize(frameNode);
this.size = Locals.computeFrameSize(frameNode, initialFrameSize);
}
/* (non-Javadoc)
@@ -522,7 +527,7 @@ public final class ClassInfo {
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
if (insn instanceof FrameNode) {
frames.add(new FrameData(method.instructions.indexOf(insn), (FrameNode)insn));
frames.add(new FrameData(method.instructions.indexOf(insn), (FrameNode)insn, Bytecode.getFirstNonArgLocalIndex(method)));
}
}
return frames;
@@ -689,6 +694,11 @@ public final class ClassInfo {
* Outer class name
*/
private final String outerName;
/**
* True if this in an inner class
*/
private final boolean isInner;
/**
* True either if this is not an inner class or if it is an inner class but
@@ -768,6 +778,16 @@ public final class ClassInfo {
* Mixins which have been applied this class
*/
private Set<MixinInfo> appliedMixins;
/**
* Declared nest host
*/
private String nestHost;
/**
* Declared nest members
*/
private Set<String> nestMembers;
/**
* Private constructor used to initialise the ClassInfo for {@link Object}
@@ -776,6 +796,7 @@ public final class ClassInfo {
this.name = ClassInfo.JAVA_LANG_OBJECT;
this.superName = null;
this.outerName = null;
this.isInner = false;
this.isProbablyStatic = true;
this.initialisers = ImmutableSet.<Method>of(
new Method("<init>", "()V")
@@ -818,7 +839,6 @@ public final class ClassInfo {
this.fields = new HashSet<Field>();
this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
this.interfaces = new HashSet<String>();
this.access = classNode.access;
this.isMixin = classNode instanceof MixinClassNode;
this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null;
this.mixins = this.isMixin ? Collections.<MixinInfo>emptySet() : new HashSet<MixinInfo>();
@@ -837,7 +857,7 @@ public final class ClassInfo {
isProbablyStatic = false;
if (outerName == null) {
outerName = field.desc;
if (outerName != null && outerName.startsWith("L")) {
if (outerName != null && outerName.startsWith("L") && outerName.endsWith(";")) {
outerName = outerName.substring(1, outerName.length() - 1);
}
}
@@ -848,9 +868,32 @@ public final class ClassInfo {
}
this.isProbablyStatic = isProbablyStatic;
this.outerName = outerName;
this.methodMapper = new MethodMapper(MixinEnvironment.getCurrentEnvironment(), this);
this.signature = ClassSignature.ofLazy(classNode);
int access = classNode.access;
boolean isInner = outerName != null;
for (InnerClassNode innerClass : classNode.innerClasses) {
if (this.name.equals(innerClass.name)) {
access = innerClass.access;
isInner = true;
outerName = innerClass.outerName;
}
}
this.access = access;
this.isInner = isInner;
this.outerName = outerName;
if (MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING)) {
this.nestHost = ClassNodeAdapter.getNestHostClass(classNode);
List<String> nestMembers = ClassNodeAdapter.getNestMembers(classNode);
if (nestMembers != null) {
this.nestMembers = new LinkedHashSet<String>();
this.nestMembers.addAll(nestMembers);
}
}
} finally {
timer.end();
}
@@ -927,6 +970,42 @@ public final class ClassInfo {
public boolean isPublic() {
return (this.access & Opcodes.ACC_PUBLIC) != 0;
}
/**
* Get whether this class is really public (only valid for inner classes
* which may be "public" themselves but aren't actually visible because
* their enclosing type is package-private for example.
*/
public boolean isReallyPublic() {
boolean isPublic = this.isPublic();
if (!this.isInner || !isPublic) {
return isPublic;
}
ClassInfo outer = this;
while (outer != null && outer.outerName != null) {
outer = ClassInfo.forName(outer.outerName);
if (outer != null && !outer.isPublic()) {
return false;
}
}
return true;
}
/**
* Get whether this class has ACC_PROTECTED (only valid for inner classes)
*/
public boolean isProtected() {
return (this.access & Opcodes.ACC_PROTECTED) != 0;
}
/**
* Get whether this class has ACC_PRIVATE (only valid for inner classes)
*/
public boolean isPrivate() {
return (this.access & Opcodes.ACC_PRIVATE) != 0;
}
/**
* Get whether this class has ACC_ABSTRACT
@@ -953,7 +1032,7 @@ public final class ClassInfo {
* Get whether this class is an inner class
*/
public boolean isInner() {
return this.outerName != null;
return this.isInner;
}
/**
@@ -1058,7 +1137,36 @@ public final class ClassInfo {
public ClassSignature getSignature() {
return this.signature.wake();
}
/**
* Return the nest host declared in the class
*/
public String getNestHost() {
return this.nestHost;
}
/**
* Get nest members declared in the class
*/
public Set<String> getNestMembers() {
return this.nestMembers != null ? Collections.<String>unmodifiableSet(this.nestMembers) : Collections.<String>emptySet();
}
/**
* Resolve the nest host for inner classes of this class. If the class
* itself has a nest host, the host is returned so that members can be added
* to it. If the class itself <em>is</em> a nest host (already has nest
* members) or is neither a nest host or member (eg. per the specification
* is already a nest host with itself as the sole member) then this method
* simply returns this ClassInfo.
*/
public ClassInfo resolveNestHost() {
if (!Strings.isNullOrEmpty(this.nestHost)) {
return ClassInfo.forName(this.nestHost);
}
return this;
}
/**
* Class targets
*/
@@ -2045,6 +2153,9 @@ public final class ClassInfo {
* @return common superclass info
*/
private static ClassInfo getCommonSuperClass(ClassInfo type1, ClassInfo type2) {
if (type1 == null || type2 == null) {
return ClassInfo.OBJECT;
}
return ClassInfo.getCommonSuperClass(type1, type2, false);
}
@@ -41,7 +41,8 @@ final class DefaultExtensions {
private DefaultExtensions() {
}
static void create(final MixinEnvironment environment, final Extensions extensions, final SyntheticClassRegistry registry) {
static void create(final MixinEnvironment environment, final Extensions extensions, final SyntheticClassRegistry registry,
final MixinCoprocessorNestHost nestHostCoprocessor) {
IConsumer<ISyntheticClassInfo> registryDelegate = new IConsumer<ISyntheticClassInfo>() {
@Override
public void accept(ISyntheticClassInfo item) {
@@ -50,7 +51,7 @@ final class DefaultExtensions {
};
extensions.add(new ArgsClassGenerator(registryDelegate));
extensions.add(new InnerClassGenerator(registryDelegate));
extensions.add(new InnerClassGenerator(registryDelegate, nestHostCoprocessor));
extensions.add(new ExtensionClassExporter(environment));
extensions.add(new ExtensionCheckClass());
@@ -45,6 +45,9 @@ import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.IConsumer;
import org.spongepowered.asm.util.asm.ASM;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* Class generator which creates unique copies of inner classes within mixins
* which are specialised to the target class.
@@ -63,48 +66,48 @@ final class InnerClassGenerator implements IClassGenerator {
private final IMixinInfo mixin;
/**
* Class name (internal name)
* Target class info
*/
private final String name;
private final ClassInfo targetClassInfo;
/**
* Original class name
*/
private final String originalName;
/**
* Class name (internal name)
*/
private final String name;
/**
* Mixin which owns this inner class
*/
private final MixinInfo owner;
/**
* Mixin target context
*/
private final MixinTargetContext target;
/**
* Name of the owner mixin (class ref)
*/
private final String ownerName;
/**
* Name of the target class (class ref)
* Name of the new nest host based on the target class
*/
private final String targetName;
private final String nestHostName;
/**
* Number of times this inner class has been generated
*/
private int loadCounter;
InnerClassInfo(IMixinInfo mixin, String name, String originalName, MixinInfo owner, MixinTargetContext target) {
InnerClassInfo(IMixinInfo mixin, ClassInfo targetClass, ClassInfo nestHost, String originalName, String name, MixinInfo owner) {
this.mixin = mixin;
this.name = name;
this.targetClassInfo = targetClass;
this.originalName = originalName;
this.name = name;
this.owner = owner;
this.ownerName = owner.getClassRef();
this.target = target;
this.targetName = target.getTargetClassRef();
this.nestHostName = nestHost.getName();
}
@Override
@@ -135,16 +138,20 @@ final class InnerClassGenerator implements IClassGenerator {
return this.owner;
}
MixinTargetContext getTarget() {
return this.target;
}
String getOwnerName() {
return this.ownerName;
}
String getTargetName() {
return this.targetName;
return this.targetClassInfo.getName();
}
ClassInfo getTargetClass() {
return this.targetClassInfo;
}
String getNestHostName() {
return this.nestHostName;
}
void accept(final ClassVisitor classVisitor) throws ClassNotFoundException, IOException {
@@ -176,7 +183,7 @@ final class InnerClassGenerator implements IClassGenerator {
if (this.originalName.equals(key)) {
return this.name;
} else if (this.ownerName.equals(key)) {
return this.targetName;
return this.targetClassInfo.getName();
}
return key;
}
@@ -199,11 +206,22 @@ final class InnerClassGenerator implements IClassGenerator {
private final InnerClassInfo info;
public InnerClassAdapter(ClassVisitor cv, InnerClassInfo info) {
InnerClassAdapter(ClassVisitor cv, InnerClassInfo info) {
super(ASM.API_VERSION, cv, info);
this.info = info;
}
/* (non-Javadoc)
* @see org.objectweb.asm.commons.ClassRemapper
* #visitNestHost(java.lang.String)
*/
@Override
public void visitNestHost(String nestHost) {
// Discard the original nest host and use the resolved nest host
// from the target class
this.cv.visitNestHost(this.info.getNestHostName());
}
/* (non-Javadoc)
* @see org.objectweb.asm.ClassVisitor
* #visitSource(java.lang.String, java.lang.String)
@@ -254,14 +272,21 @@ final class InnerClassGenerator implements IClassGenerator {
* Mapping of generated class names to the respective inner class info
*/
private final Map<String, InnerClassInfo> innerClasses = new HashMap<String, InnerClassInfo>();
/**
* Coprocessor which handles merging nest members into nest hosts which may
* or may not be mixin targets themselves
*/
private final MixinCoprocessorNestHost nestHostCoprocessor;
/**
* Ctor
*
* @param registry sythetic class registry
*/
public InnerClassGenerator(IConsumer<ISyntheticClassInfo> registry) {
public InnerClassGenerator(IConsumer<ISyntheticClassInfo> registry, MixinCoprocessorNestHost nestHostCoprocessor) {
this.registry = registry;
this.nestHostCoprocessor = nestHostCoprocessor;
}
/* (non-Javadoc)
@@ -274,26 +299,48 @@ final class InnerClassGenerator implements IClassGenerator {
}
/**
* Register a mixin inner class against the specified target
*
* @param owner Mixin which owns the original inner class
* @param originalName Original inner class name
* @param context Target class
* @return new name
* @param targetClass Target class name
* @param innerClassName Original inner class name
*/
public String registerInnerClass(MixinInfo owner, String originalName, MixinTargetContext context) {
String id = String.format("%s%s", originalName, context);
String ref = this.innerClassNames.get(id);
if (ref == null) {
ref = InnerClassGenerator.getUniqueReference(originalName, context);
InnerClassInfo info = new InnerClassInfo(owner, ref, originalName, owner, context);
this.innerClassNames.put(id, ref);
this.innerClasses.put(ref, info);
this.registry.accept(info);
InnerClassGenerator.logger.debug("Inner class {} in {} on {} gets unique name {}", originalName, owner.getClassRef(),
context.getTargetClassRef(), ref);
void registerInnerClass(MixinInfo owner, ClassInfo targetClass, String innerClassName) {
String coordinate = String.format("%s:%s:%s", owner, innerClassName, targetClass.getName());
String uniqueName = this.innerClassNames.get(coordinate);
if (uniqueName != null) {
return;
}
return ref;
uniqueName = InnerClassGenerator.getUniqueReference(innerClassName, targetClass);
ClassInfo nestHost = targetClass.resolveNestHost();
InnerClassInfo info = new InnerClassInfo(owner, targetClass, nestHost, innerClassName, uniqueName, owner);
this.innerClassNames.put(coordinate, uniqueName);
this.innerClasses.put(uniqueName, info);
this.registry.accept(info);
InnerClassGenerator.logger.debug("Inner class {} in {} on {} gets unique name {}",
innerClassName, owner.getClassRef(), targetClass, uniqueName);
this.nestHostCoprocessor.registerNestMember(nestHost.getClassName(), uniqueName);
}
/**
* Get a BiMap of inner classes for the specified mixin+target combination
* so that references to the inner class can be remapped during application
*
* @param owner Mixin which owns the original inner class
* @param targetName Target class name
* @return BiMap of original (mixin) inner class names to conformed class
* names
*/
BiMap<String, String> getInnerClasses(MixinInfo owner, String targetName) {
BiMap<String, String> innerClasses = HashBiMap.<String, String>create();
for (InnerClassInfo innerClass : this.innerClasses.values()) {
if (innerClass.getMixin() == owner && targetName.equals(innerClass.getTargetName())) {
innerClasses.put(innerClass.getOriginalName(), innerClass.getName());
}
}
return innerClasses;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.ext.IClassGenerator
* #generate(java.lang.String, org.objectweb.asm.tree.ClassNode)
@@ -334,15 +381,15 @@ final class InnerClassGenerator implements IClassGenerator {
* multiple mixins, each remapped class gets a unique name.
*
* @param originalName Original inner class name
* @param context Target context
* @param targetClass Target class
* @return unique class name
*/
private static String getUniqueReference(String originalName, MixinTargetContext context) {
private static String getUniqueReference(String originalName, ClassInfo targetClass) {
String name = originalName.substring(originalName.lastIndexOf('$') + 1);
if (name.matches("^[0-9]+$")) {
name = "Anonymous";
}
return String.format("%s$%s$%s", context.getTargetClassRef(), name, UUID.randomUUID().toString().replace("-", ""));
return String.format("%s$%s$%s", targetClass, name, UUID.randomUUID().toString().replace("-", ""));
}
}
@@ -109,7 +109,7 @@ class MixinApplicatorInterface extends MixinApplicatorStandard {
}
}
} catch (InvalidInjectionException ex) {
String description = ex.getInjectionInfo() != null ? ex.getInjectionInfo().toString() : "Injection";
String description = ex.getContext() != null ? ex.getContext().toString() : "Injection";
throw new InvalidInterfaceMixinException(mixin, description + " is not supported in interface mixin");
}
}
@@ -41,6 +41,7 @@ import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.extensibility.IActivityContext.IActivity;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -50,7 +51,6 @@ import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.throwables.MixinError;
import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExporter;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
@@ -64,7 +64,6 @@ import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Bytecode.DelegateInitialiser;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.ConstraintParser;
import org.spongepowered.asm.util.LanguageFeatures;
import org.spongepowered.asm.util.ConstraintParser.Constraint;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
@@ -95,6 +94,7 @@ class MixinApplicatorStandard {
* Passes the mixin applicator applies to each mixin
*/
enum ApplicatorPass {
/**
* Main pass, mix in methods, fields, interfaces etc
*/
@@ -109,12 +109,14 @@ class MixinApplicatorStandard {
* Apply injectors from previous pass
*/
INJECT
}
/**
* Strategy for injecting initialiser insns
*/
enum InitialiserInjectionMode {
/**
* Default mode, attempts to place initialisers after all other
* competing initialisers in the target ctor
@@ -126,12 +128,14 @@ class MixinApplicatorStandard {
* invocation
*/
SAFE
}
/**
* Internal struct for representing a range
*/
class Range {
/**
* Start of the range
*/
@@ -196,6 +200,7 @@ class MixinApplicatorStandard {
public String toString() {
return String.format("Range[%d-%d,%d,valid=%s)", this.start, this.end, this.marker, this.isValid());
}
}
/**
@@ -302,8 +307,8 @@ class MixinApplicatorStandard {
this.activities.clear();
try {
Activity activity = this.activities.begin("PreApply Phase");
Activity preApplyActivity = this.activities.begin("Mixin");
IActivity activity = this.activities.begin("PreApply Phase");
IActivity preApplyActivity = this.activities.begin("Mixin");
for (MixinTargetContext context : mixinContexts) {
preApplyActivity.next(context.toString());
(current = context).preApply(this.targetName, this.targetClass);
@@ -313,7 +318,7 @@ class MixinApplicatorStandard {
for (ApplicatorPass pass : ApplicatorPass.values()) {
activity.next("%s Applicator Phase", pass);
Section timer = this.profiler.begin("pass", pass.name().toLowerCase(Locale.ROOT));
Activity applyActivity = this.activities.begin("Mixin");
IActivity applyActivity = this.activities.begin("Mixin");
for (Iterator<MixinTargetContext> iter = mixinContexts.iterator(); iter.hasNext();) {
current = iter.next();
applyActivity.next(current.toString());
@@ -332,7 +337,7 @@ class MixinApplicatorStandard {
}
activity.next("PostApply Phase");
Activity postApplyActivity = this.activities.begin("Mixin");
IActivity postApplyActivity = this.activities.begin("Mixin");
for (Iterator<MixinTargetContext> iter = mixinContexts.iterator(); iter.hasNext();) {
current = iter.next();
postApplyActivity.next(current.toString());
@@ -365,7 +370,7 @@ class MixinApplicatorStandard {
* @param mixin Mixin to apply
*/
protected final void applyMixin(MixinTargetContext mixin, ApplicatorPass pass) {
Activity activity = this.activities.begin("Apply");
IActivity activity = this.activities.begin("Apply");
switch (pass) {
case MAIN:
activity.next("Apply Signature");
@@ -382,8 +387,6 @@ class MixinApplicatorStandard {
this.applyMethods(mixin);
activity.next("Apply Initialisers");
this.applyInitialisers(mixin);
activity.next("Apply Nesting");
this.applyNesting(mixin);
break;
case PREINJECT:
@@ -505,7 +508,7 @@ class MixinApplicatorStandard {
* @param mixin mixin target context
*/
protected void applyMethods(MixinTargetContext mixin) {
Activity activity = this.activities.begin("?");
IActivity activity = this.activities.begin("?");
for (MethodNode shadow : mixin.getShadowMethods()) {
activity.next("@Shadow %s:%s", shadow.desc, shadow.name);
this.applyShadowMethod(mixin, shadow);
@@ -535,7 +538,7 @@ class MixinApplicatorStandard {
this.mergeMethod(mixin, mixinMethod);
} else if (Constants.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
Activity activity = this.activities.begin("Merge CLINIT insns");
IActivity activity = this.activities.begin("Merge CLINIT insns");
this.appendInsns(mixin, mixinMethod);
activity.end();
}
@@ -1030,30 +1033,6 @@ class MixinApplicatorStandard {
private static String fieldKey(FieldInsnNode fieldNode) {
return String.format("%s:%s", fieldNode.desc, fieldNode.name);
}
/**
* Apply nesting attributes from the mixin to the target.
*
* <p><strong>NOT YET SUPPORTED!</strong></p>
*/
protected void applyNesting(MixinTargetContext mixin) {
String nestHostClass = mixin.getNestHostClass();
List<String> nestMembers = mixin.getNestMembers();
if ((nestHostClass == null && nestMembers == null) || (nestMembers != null && nestMembers.size() == 0)) {
return;
}
if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING)) {
// Shouldn't get here because we should error out during the initial scan, but you never know
throw new InvalidMixinException(mixin,
String.format("%s contains nesting information but the current compatibility level does not support class nesting attributes",
mixin));
}
// TODO Nesting not done yet, just log an error for now that we're not applying these attributes
this.logger.error("NESTING not supported in this version of Mixin. {} nesting attributes will not be applied to the target", mixin);
}
/**
* Scan for injector methods and injection points
@@ -53,6 +53,7 @@ import org.spongepowered.asm.mixin.refmap.IClassReferenceMapper;
import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.mixin.refmap.ReferenceMapper;
import org.spongepowered.asm.mixin.refmap.RemappingReferenceMapper;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
@@ -384,6 +385,11 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
*/
private transient int warnedClassVersion = 0;
/**
* Service decorations on this config
*/
private transient Map<String, Object> decorations;
/**
* Spawn via GSON, no public ctor for you
*/
@@ -531,14 +537,20 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
throw new MixinInitialisationError(String.format("Mixin config %s requires compatibility level %s which is prohibited by %s",
this.name, this.compatibilityLevel, currentLevel));
}
CompatibilityLevel minCompatibilityLevel = MixinEnvironment.getMinCompatibilityLevel();
if (this.compatibilityLevel.isLessThan(minCompatibilityLevel)) {
this.logger.log(this.verboseLogging ? Level.INFO : Level.DEBUG,
"Compatibility level {} specified by {} is lower than the default level supported by the current mixin service ({}).",
this.compatibilityLevel, this, minCompatibilityLevel);
}
// Required level is higher than highest version we support, this possibly
// means that a shaded mixin dependency has been usurped by an old version,
// or the mixin author is trying to elevate the compatibility level beyond
// the versions currently supported
if (CompatibilityLevel.MAX_SUPPORTED.isLessThan(this.compatibilityLevel)) {
Level logLevel = this.verboseLogging ? Level.WARN : Level.DEBUG;
this.logger.log(logLevel,
this.logger.log(this.verboseLogging ? Level.WARN : Level.DEBUG,
"Compatibility level {} specified by {} is higher than the maximum level supported by this version of mixin ({}).",
this.compatibilityLevel, this, CompatibilityLevel.MAX_SUPPORTED);
}
@@ -757,20 +769,20 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* either the <em>hasMixinsFor()</em> or <em>getMixinsFor()</em> methods.
* </p>
*/
void prepare() {
void prepare(Extensions extensions) {
if (this.prepared) {
return;
}
this.prepared = true;
this.prepareMixins("mixins", this.mixinClasses, false);
this.prepareMixins("mixins", this.mixinClasses, false, extensions);
switch (this.env.getSide()) {
case CLIENT:
this.prepareMixins("client", this.mixinClassesClient, false);
this.prepareMixins("client", this.mixinClassesClient, false, extensions);
break;
case SERVER:
this.prepareMixins("server", this.mixinClassesServer, false);
this.prepareMixins("server", this.mixinClassesServer, false, extensions);
break;
case UNKNOWN:
//$FALL-THROUGH$
@@ -780,10 +792,10 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
void postInitialise() {
void postInitialise(Extensions extensions) {
if (this.plugin != null) {
List<String> pluginMixins = this.plugin.getMixins();
this.prepareMixins("companion plugin", pluginMixins, true);
this.prepareMixins("companion plugin", pluginMixins, true, extensions);
}
for (Iterator<MixinInfo> iter = this.mixins.iterator(); iter.hasNext();) {
@@ -815,7 +827,7 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
private void prepareMixins(String collectionName, List<String> mixinClasses, boolean ignorePlugin) {
private void prepareMixins(String collectionName, List<String> mixinClasses, boolean ignorePlugin, Extensions extensions) {
if (mixinClasses == null) {
return;
}
@@ -838,7 +850,7 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
MixinInfo mixin = null;
try {
this.pendingMixins.add(mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, ignorePlugin));
this.pendingMixins.add(mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, ignorePlugin, extensions));
MixinConfig.globalMixinList.add(fqMixinClass);
} catch (InvalidMixinException ex) {
if (this.required) {
@@ -1114,6 +1126,50 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
return Collections.<String>unmodifiableSet(this.unhandledTargets);
}
/**
* Decorate this config with arbitrary metadata for debugging or
* compatibility purposes
*
* @param key meta key
* @param value meta value
* @param <V> value type
* @throws IllegalArgumentException if the specified key exists already
*/
@Override
public <V> void decorate(String key, V value) {
if (this.decorations == null) {
this.decorations = new HashMap<String, Object>();
}
if (this.decorations.containsKey(key)) {
throw new IllegalArgumentException(String.format("Decoration with key '%s' already exists on config %s", key, this));
}
this.decorations.put(key, value);
}
/**
* Get whether this node is decorated with the specified key
*
* @param key meta key
* @return true if the specified decoration exists
*/
@Override
public boolean hasDecoration(String key) {
return this.decorations != null && this.decorations.get(key) != null;
}
/**
* Get the specified decoration
*
* @param key meta key
* @param <V> value type
* @return decoration value or null if absent
*/
@Override
@SuppressWarnings("unchecked")
public <V> V getDecoration(String key) {
return (V) (this.decorations == null ? null : this.decorations.get(key));
}
/**
* Get the logging level for this config
*/
@@ -0,0 +1,171 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.transformer.MixinConfig.IListener;
/**
* Coprocessors are parts of the mixin pipeline which aren't involved in
* applying mixins but handle other transformation tasks <em>required</em> by
* mixins.
*
* <p>Such tasks as {@link MixinCoprocessorAccessor making accessor mixins
* loadable (and transforming the accessors therein)}, {@link
* MixinCoprocessorSyntheticInner exposing synthetic inner classes to all
* consumers} and {@link MixinCoprocessorNestHost applying nest member
* attributes to nest hosts which may themselves not be mixin targets} are
* handled by different coprocessors.</p>
*
* <p>These classes were previously encapsulated in a single companion class
* called <tt>MixinPostProcessor</tt>, but the mixture of responsibilities of
* that class made its role unclear and slightly schizophrenic.</p>
*/
abstract class MixinCoprocessor implements IListener {
/**
* The result of a specific coprocessor's action on a supplied class,
* effectively a tuple of <tt>transformed</tt> and <tt>passthrough</tt>
* which combines the normal <tt>transformed</tt> flag (which is returned to
* the service so it knows whether the supplied class was altered or not)
* and a second flag which indicates whether the class is eligible for
* processing by the mixin pipeline: Results with <tt>passthrough</tt> set
* will <b>not</b> be processed further by the mixin processor.
*/
enum ProcessResult {
/**
* This coprocessor does not take any action for the specified class
*/
NONE(false, false),
/**
* This coprocessor acted on the supplied bytecode, but does not change
* the flow of the main mixin processor pipeline
*/
TRANSFORMED(false, true),
/**
* This coprocessor did not transform the supplied bytecode, and mixins
* should not be applied to this class
*/
PASSTHROUGH_NONE(true, false),
/**
* This coprocessor acted on the supplied bytecode, and mixins should
* not be applied to this class
*/
PASSTHROUGH_TRANSFORMED(true, true);
private boolean passthrough;
private boolean transformed;
private ProcessResult(boolean passthrough, boolean transformed) {
this.passthrough = passthrough;
this.transformed = transformed;
}
boolean isPassthrough() {
return this.passthrough;
}
boolean isTransformed() {
return this.transformed;
}
/**
* Combine this result with the supplied result
*/
ProcessResult with(ProcessResult other) {
if (other == this) {
return this;
}
return ProcessResult.of(this.passthrough || other.passthrough, this.transformed || other.transformed);
}
/**
* Return a result which represents the supplied tuple of attributes
*/
static ProcessResult of(boolean passthrough, boolean transformed) {
if (passthrough) {
return transformed ? ProcessResult.PASSTHROUGH_TRANSFORMED : ProcessResult.PASSTHROUGH_NONE;
}
return transformed ? ProcessResult.TRANSFORMED : ProcessResult.NONE;
}
}
/**
* Coprocessor name, for debugging only
*/
abstract String getName();
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinConfig.IListener
* #onPrepare(org.spongepowered.asm.mixin.transformer.MixinInfo)
*/
@Override
public void onPrepare(MixinInfo mixin) {
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.MixinConfig.IListener
* #onInit(org.spongepowered.asm.mixin.transformer.MixinInfo)
*/
@Override
public void onInit(MixinInfo mixin) {
}
/**
* Process the supplied class. If the class is transformed, or should be
* passed through (rather than treated as a mixin target) then this is
* indicated by the return value
*
* @param className Name of the target class
* @param classNode Classnode of the target class
* @return result indicating whether the class was transformed, and whether
* or not to passthrough instead of apply mixins
*/
ProcessResult process(String className, ClassNode classNode) {
return ProcessResult.NONE;
}
/**
* Perform postprocessing actions on the supplied class. This is called for
* all classes. For passthrough classes and classes which are not mixin
* targets this is called immediately after {@link process} is completed for
* all coprocessors. For mixin targets this is called after mixins are
* applied.
*
* @param className Name of the target class
* @param classNode Classnode of the target class
* @return true if the coprocessor applied any transformations
*/
boolean postProcess(String className, ClassNode classNode) {
return false;
}
}
@@ -25,15 +25,12 @@
package org.spongepowered.asm.mixin.transformer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
@@ -47,126 +44,55 @@ import org.spongepowered.asm.mixin.transformer.meta.MixinProxy;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Bytecode.Visibility;
import org.spongepowered.asm.util.LanguageFeatures;
import org.spongepowered.asm.util.Bytecode.Visibility;
/**
* Performs post-processing tasks required for certain classes which pass
* through the mixin transformer, such as transforming synthetic inner classes
* and populating accessor methods in accessor mixins.
* This coprocessor handles transformations to accessor mixins themselves as
* they are classloaded. Besides ensuring that the interface is public, its
* primary responsibility is to transform the decorated accessor methods into
* proxies for the target members.
*/
class MixinPostProcessor implements MixinConfig.IListener {
class MixinCoprocessorAccessor extends MixinCoprocessor {
/**
* Transformer session ID
*/
private final String sessionId;
/**
* Synthetic inner classes in mixins
*/
private final Set<String> syntheticInnerClasses = new HashSet<String>();
protected final String sessionId;
/**
* Accessor mixins
*/
private final Map<String, MixinInfo> accessorMixins = new HashMap<String, MixinInfo>();
/**
* Loadable classes within mixin packages
*/
private final Set<String> loadable = new HashSet<String>();
MixinPostProcessor(String sessionId) {
MixinCoprocessorAccessor(String sessionId) {
this.sessionId = sessionId;
}
@Override
public void onInit(MixinInfo mixin) {
for (String innerClass : mixin.getSyntheticInnerClasses()) {
this.registerSyntheticInner(innerClass.replace('/', '.'));
}
String getName() {
return "accessor";
}
@Override
public void onPrepare(MixinInfo mixin) {
String className = mixin.getClassName();
if (mixin.isLoadable()) {
this.registerLoadable(className);
}
if (mixin.isAccessor()) {
this.registerAccessor(mixin);
}
}
void registerSyntheticInner(String className) {
this.syntheticInnerClasses.add(className);
}
void registerLoadable(String className) {
this.loadable.add(className);
}
void registerAccessor(MixinInfo mixin) {
this.registerLoadable(mixin.getClassName());
this.accessorMixins.put(mixin.getClassName(), mixin);
}
/**
* Get whether the specified class can be piped through the postprocessor
* rather than being classloaded normally
*
* @param className Class name to check
* @return True if the specified class name has been registered for post-
* processing
*/
boolean canProcess(String className) {
return this.syntheticInnerClasses.contains(className) || this.loadable.contains(className);
}
public boolean processClass(String name, ClassNode classNode) {
if (this.syntheticInnerClasses.contains(name)) {
this.processSyntheticInner(classNode);
return true;
}
if (this.accessorMixins.containsKey(name)) {
MixinInfo mixin = this.accessorMixins.get(name);
return this.processAccessor(classNode, mixin);
}
return false;
}
/**
* "Pass through" a synthetic inner class. Transforms package-private
* members in the class into public so that they are accessible from their
* new home in the target class
*/
private void processSyntheticInner(ClassNode classNode) {
classNode.access |= Opcodes.ACC_PUBLIC;
for (FieldNode field : classNode.fields) {
if ((field.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
field.access |= Opcodes.ACC_PUBLIC;
}
}
for (MethodNode method : classNode.methods) {
if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
method.access |= Opcodes.ACC_PUBLIC;
}
}
}
private boolean processAccessor(ClassNode classNode, MixinInfo mixin) {
if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)) {
return false;
@Override
ProcessResult process(String className, ClassNode classNode) {
if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.METHODS_IN_INTERFACES)
|| !this.accessorMixins.containsKey(className)) {
return ProcessResult.NONE;
}
MixinInfo mixin = this.accessorMixins.get(className);
boolean transformed = false;
MixinClassNode mixinClassNode = mixin.getClassNode(0);
ClassInfo targetClass = mixin.getTargets().get(0);
@@ -185,7 +111,7 @@ class MixinPostProcessor implements MixinConfig.IListener {
AnnotationNode invoker = methodNode.getVisibleAnnotation(Invoker.class);
if (accessor != null || invoker != null) {
Method method = this.getAccessorMethod(mixin, methodNode, targetClass);
MixinPostProcessor.createProxy(methodNode, targetClass, method);
MixinCoprocessorAccessor.createProxy(methodNode, targetClass, method);
Annotations.setVisible(methodNode, MixinProxy.class, "sessionId", this.sessionId);
classNode.methods.add(methodNode);
transformed = true;
@@ -193,11 +119,11 @@ class MixinPostProcessor implements MixinConfig.IListener {
}
if (!transformed) {
return false;
return ProcessResult.NONE;
}
Bytecode.replace(mixinClassNode, classNode);
return true;
return ProcessResult.PASSTHROUGH_TRANSFORMED;
}
private Method getAccessorMethod(MixinInfo mixin, MethodNode methodNode, ClassInfo targetClass) throws MixinTransformerError {
@@ -0,0 +1,108 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
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.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.util.LanguageFeatures;
import org.spongepowered.asm.util.asm.ClassNodeAdapter;
/**
* In Java 11 and above, access control semantics for inner members are reified
* in the concept of nesting, where an "outermost" class becomes a "nest host"
* for all nested classes. Since a mixin can be applied to an inner class, the
* process of adding any inner classes of mixins to the nest is not as simple as
* having the target class become the nest host. Thus the nest host of conformed
* inner classes is resolved during the <em>prepare</em> phase so that any
* classes which need to have their nests expanded can be processed accordingly.
*
* <p>This coprocessor therefore processes all classes regardless of whether
* they are mixin targets or not, in order to add any additional nest members
* where a mixin targets the class, or one of its existing nest members.</p>
*/
class MixinCoprocessorNestHost extends MixinCoprocessor {
/**
* Classes which are nest hosts with new members injected by mixins
*/
private final Map<String, Set<String>> nestHosts = new HashMap<String, Set<String>>();
MixinCoprocessorNestHost() {
}
void registerNestMember(String hostName, String memberName) {
Set<String> nestMembers = this.nestHosts.get(hostName);
if (nestMembers == null) {
this.nestHosts.put(hostName, nestMembers = new HashSet<String>());
}
nestMembers.add(memberName);
}
@Override
String getName() {
return "nesthost";
}
@Override
boolean postProcess(String className, ClassNode classNode) {
if (!this.nestHosts.containsKey(className)) {
return false;
}
Set<String> newMembers = this.nestHosts.get(className);
if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeatures.NESTING) || newMembers.isEmpty()) {
return false;
}
String nestHost = ClassNodeAdapter.getNestHostClass(classNode);
if (nestHost != null) {
throw new MixinTransformerError(String.format("Nest host candidate %s is a nest member", classNode.name));
}
List<String> nestMembers = ClassNodeAdapter.getNestMembers(classNode);
if (nestMembers == null) {
// If there are currently no nest members, just set the ones we have
nestMembers = new ArrayList<String>(newMembers);
} else {
// Otherwise add all the new members
LinkedHashSet<String> combinedMembers = new LinkedHashSet<String>(nestMembers);
combinedMembers.addAll(newMembers);
nestMembers.clear();
nestMembers.addAll(combinedMembers);
}
ClassNodeAdapter.setNestMembers(classNode, nestMembers);
return true;
}
}
@@ -0,0 +1,67 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.tree.ClassNode;
/**
* Passthrough coprocessor which simply keeps track of classes which are
* loadable.
*/
class MixinCoprocessorPassthrough extends MixinCoprocessor {
/**
* Loadable classes within mixin packages
*/
private final Set<String> loadable = new HashSet<String>();
MixinCoprocessorPassthrough() {
}
@Override
String getName() {
return "passthrough";
}
@Override
public void onPrepare(MixinInfo mixin) {
if (mixin.isLoadable()) {
this.registerLoadable(mixin.getClassName());
}
}
void registerLoadable(String className) {
this.loadable.add(className);
}
@Override
ProcessResult process(String className, ClassNode classNode) {
return this.loadable.contains(className) ? ProcessResult.PASSTHROUGH_NONE : ProcessResult.NONE;
}
}
@@ -0,0 +1,99 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
/**
* Coprocessor which handles synthetic inner classes in mixins. Since synthetic
* inner classes are usually just switch tables, it is reasonably safe to share
* them amongst all mixin targets. Therefore the class is simply transformed so
* that all members are public.
*
* <p>Nest based-access control could potentially be used where a mixin has a
* single target, and Java 11 or higher is in use, but at the moment it's more
* straightforward to just make everything public.</p>
*/
class MixinCoprocessorSyntheticInner extends MixinCoprocessor {
/**
* Synthetic inner classes in mixins
*/
private final Set<String> syntheticInnerClasses = new HashSet<String>();
MixinCoprocessorSyntheticInner() {
}
@Override
String getName() {
return "syntheticinner";
}
@Override
public void onInit(MixinInfo mixin) {
for (String innerClass : mixin.getSyntheticInnerClasses()) {
this.registerSyntheticInner(innerClass.replace('/', '.'));
}
}
void registerSyntheticInner(String className) {
this.syntheticInnerClasses.add(className);
}
/**
* "Pass through" a synthetic inner class. Transforms package-private
* members in the class into public so that they are accessible from their
* new home in the target class
*/
@Override
ProcessResult process(String className, ClassNode classNode) {
if (!this.syntheticInnerClasses.contains(className)) {
return ProcessResult.NONE;
}
classNode.access |= Opcodes.ACC_PUBLIC;
for (FieldNode field : classNode.fields) {
if ((field.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
field.access |= Opcodes.ACC_PUBLIC;
}
}
for (MethodNode method : classNode.methods) {
if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
method.access |= Opcodes.ACC_PUBLIC;
}
}
return ProcessResult.PASSTHROUGH_TRANSFORMED;
}
}
@@ -0,0 +1,89 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.transformer.MixinCoprocessor.ProcessResult;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
/**
* Convenience list of coprocessors
*/
class MixinCoprocessors extends ArrayList<MixinCoprocessor> {
private static final long serialVersionUID = 1L;
/**
* Profiler
*/
private final Profiler profiler;
MixinCoprocessors() {
this.profiler = MixinEnvironment.getProfiler();
}
/**
* Process the supplied class using all registered coprocessors. If the
* class is transformed, or should be passed through (rather than treated as
* a mixin target) then this is indicated by the return value.
*
* @param className Name of the target class
* @param classNode Classnode of the target class
* @return result indicating whether the class was transformed, and whether
* or not to passthrough instead of apply mixins
*/
ProcessResult process(String className, ClassNode classNode) {
Section timer = this.profiler.begin("coprocessor");
ProcessResult result = ProcessResult.NONE;
for (MixinCoprocessor coprocessor : this) {
result = coprocessor.process(className, classNode).with(result);
}
timer.end();
return result;
}
/**
* Perform postprocessing actions on the supplied class using all registered
* coprocessors.
*
* @param className Name of the target class
* @param classNode Classnode of the target class
* @return true if the coprocessor applied any transformations
*/
boolean postProcess(String className, ClassNode classNode) {
Section timer = this.profiler.begin("coprocessor");
boolean transformed = false;
for (MixinCoprocessor coprocessor : this) {
transformed |= coprocessor.postProcess(className, classNode);
}
timer.end();
return transformed;
}
}
@@ -62,6 +62,7 @@ import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException;
@@ -319,7 +320,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
void validate(SubType type, List<ClassInfo> targetClasses) {
MixinClassNode classNode = this.getValidationClassNode();
MixinPreProcessorStandard preProcessor = type.createPreProcessor(classNode).prepare();
MixinPreProcessorStandard preProcessor = type.createPreProcessor(classNode).prepare(MixinInfo.this.getExtensions());
for (ClassInfo target : targetClasses) {
preProcessor.conform(target);
}
@@ -439,7 +440,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
}
protected void validateChanges(SubType type, List<ClassInfo> targetClasses) {
type.createPreProcessor(this.validationClassNode).prepare();
type.createPreProcessor(this.validationClassNode).prepare(MixinInfo.this.getExtensions());
}
}
@@ -817,6 +818,11 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
* Strict target checks enabled
*/
private final transient boolean strict;
/**
* Transformer extensions manager
*/
private final transient Extensions extensions;
/**
* Holds state that currently is not fully initialised or validated
@@ -837,7 +843,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
* @param ignorePlugin true to prevent the plugin from filtering targets of
* this mixin
*/
MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean ignorePlugin) {
MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean ignorePlugin, Extensions extensions) {
this.service = service;
this.parent = parent;
this.name = name;
@@ -845,6 +851,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
this.plugin = plugin;
this.phase = parent.getEnvironment().getPhase();
this.strict = parent.getEnvironment().getOption(Option.DEBUG_TARGETS);
this.extensions = extensions;
// Read the class bytes and transform
try {
@@ -1018,7 +1025,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
return null;
}
this.type.validateTarget(target.name, targetInfo);
if (target.isPrivate && targetInfo.isPublic() && !this.isVirtual()) {
if (target.isPrivate && targetInfo.isReallyPublic() && !this.isVirtual()) {
this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this), true);
}
return targetInfo;
@@ -1262,6 +1269,13 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
Set<String> getInterfaces() {
return this.getState().getInterfaces();
}
/**
* Get transformer extensions
*/
Extensions getExtensions() {
return this.extensions;
}
/**
* Get a new mixin target context object for the specified target
@@ -1272,7 +1286,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
MixinTargetContext createContextFor(TargetClassContext target) {
MixinClassNode classNode = this.getClassNode(ClassReader.EXPAND_FRAMES);
Section preTimer = this.profiler.begin("pre");
MixinTargetContext context = this.type.createPreProcessor(classNode).prepare().createContextFor(target);
MixinTargetContext context = this.type.createPreProcessor(classNode).prepare(this.extensions).createContextFor(target);
preTimer.end();
return context;
}
@@ -1337,7 +1351,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Called immediately before the mixin is applied to targetClass
*/
public void preApply(String transformedName, ClassNode targetClass) {
public void preApply(String transformedName, ClassNode targetClass) throws Exception {
if (this.plugin.isAvailable()) {
Section pluginTimer = this.profiler.begin("plugin");
try {
@@ -1351,7 +1365,7 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Called immediately after the mixin is applied to targetClass
*/
public void postApply(String transformedName, ClassNode targetClass) {
public void postApply(String transformedName, ClassNode targetClass) throws Exception {
if (this.plugin.isAvailable()) {
Section pluginTimer = this.profiler.begin("plugin");
try {
@@ -40,19 +40,20 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.extensibility.IActivityContext.IActivity;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.struct.MemberRef;
import org.spongepowered.asm.mixin.throwables.ClassMetadataNotFoundException;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ClassInfo.SearchType;
import org.spongepowered.asm.mixin.transformer.ClassInfo.TypeLookup;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinPreProcessorException;
@@ -163,7 +164,7 @@ class MixinPreProcessorStandard {
*
* @return Prepared classnode
*/
final MixinPreProcessorStandard prepare() {
final MixinPreProcessorStandard prepare(Extensions extensions) {
if (this.prepared) {
return this;
}
@@ -173,17 +174,19 @@ class MixinPreProcessorStandard {
this.activities.clear();
Section prepareTimer = this.profiler.begin("prepare");
try {
Activity activity = this.activities.begin("Prepare method");
IActivity activity = this.activities.begin("Prepare inner classes");
this.prepareInnerClasses(extensions);
activity.next("Prepare method");
for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod);
Activity methodActivity = this.activities.begin(mixinMethod.toString());
IActivity methodActivity = this.activities.begin(mixinMethod.toString());
this.prepareMethod(mixinMethod, method);
methodActivity.end();
}
activity.next("Prepare field");
for (FieldNode mixinField : this.classNode.fields) {
Activity fieldActivity = this.activities.begin(String.format("%s:%s", mixinField.name, mixinField.desc));
IActivity fieldActivity = this.activities.begin(String.format("%s:%s", mixinField.name, mixinField.desc));
this.prepareField(mixinField);
fieldActivity.end();
}
@@ -197,6 +200,16 @@ class MixinPreProcessorStandard {
return this;
}
protected void prepareInnerClasses(Extensions extensions) {
InnerClassGenerator icg = extensions.<InnerClassGenerator>getGenerator(InnerClassGenerator.class);
for (String targetClassName : this.mixin.getDeclaredTargetClasses()) {
ClassInfo targetClassInfo = ClassInfo.forName(targetClassName);
for (String innerClass : this.mixin.getInnerClasses()) {
icg.registerInnerClass(this.mixin, targetClassInfo, innerClass);
}
}
}
protected void prepareMethod(MixinMethodNode mixinMethod, Method method) {
this.prepareShadow(mixinMethod, method);
this.prepareSoftImplements(mixinMethod, method);
@@ -239,7 +252,7 @@ class MixinPreProcessorStandard {
for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) {
if (mixinMethod.isInjector()) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
Activity methodActivity = this.activities.begin("Conform injector %s", mixinMethod);
IActivity methodActivity = this.activities.begin("Conform injector %s", mixinMethod);
this.conformInjector(target, mixinMethod, method);
methodActivity.end();
}
@@ -282,7 +295,7 @@ class MixinPreProcessorStandard {
try {
// Perform context-sensitive attachment phase
Section timer = this.profiler.begin("methods");
Activity activity = this.activities.begin("Attach method");
IActivity activity = this.activities.begin("Attach method");
this.attachMethods(context);
timer = timer.next("fields");
activity.next("Attach field");
@@ -304,7 +317,7 @@ class MixinPreProcessorStandard {
}
protected void attachMethods(MixinTargetContext context) {
Activity methodActivity = this.activities.begin("?");
IActivity methodActivity = this.activities.begin("?");
for (Iterator<MixinMethodNode> iter = this.classNode.mixinMethods.iterator(); iter.hasNext();) {
MixinMethodNode mixinMethod = iter.next();
methodActivity.next(mixinMethod.toString());
@@ -579,7 +592,7 @@ class MixinPreProcessorStandard {
}
protected void attachFields(MixinTargetContext context) {
Activity fieldActivity = this.activities.begin("?");
IActivity fieldActivity = this.activities.begin("?");
for (Iterator<FieldNode> iter = this.classNode.getFields().iterator(); iter.hasNext();) {
FieldNode mixinField = iter.next();
fieldActivity.next("%s:%s", mixinField.name, mixinField.desc);
@@ -710,12 +723,12 @@ class MixinPreProcessorStandard {
* accesses in the mixin
*/
protected void transform(MixinTargetContext context) {
Activity methodActivity = this.activities.begin("method");
IActivity methodActivity = this.activities.begin("method");
for (MethodNode mixinMethod : this.classNode.methods) {
methodActivity.next("Method %s", mixinMethod);
for (Iterator<AbstractInsnNode> iter = mixinMethod.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
Activity activity = this.activities.begin(Bytecode.getOpcodeName(insn));
IActivity activity = this.activities.begin(Bytecode.getOpcodeName(insn));
if (insn instanceof MethodInsnNode) {
this.transformMethod((MethodInsnNode)insn);
} else if (insn instanceof FieldInsnNode) {
@@ -730,7 +743,7 @@ class MixinPreProcessorStandard {
}
protected void transformInvokeDynamic(InvokeDynamicInsnNode invokeDynamicNode) {
Activity activity = this.activities.begin("%s%s", invokeDynamicNode.name, invokeDynamicNode.desc);
IActivity activity = this.activities.begin("%s::%s%s", invokeDynamicNode.owner, invokeDynamicNode.name, invokeDynamicNode.desc);
Section metaTimer = this.profiler.begin("meta");
MemberRef.Handle ref = new MemberRef.Handle(invokeDynamicNode.bsm);
@@ -760,7 +773,7 @@ class MixinPreProcessorStandard {
}
protected void transformMemberReference(MemberRef ref) {
Activity activity = this.activities.begin("%s::%s%s", ref.getOwner(), ref.getName(), ref.getDesc());
IActivity activity = this.activities.begin("%s::%s:%s", ref.getOwner(), ref.getName(), ref.getDesc());
Section metaTimer = this.profiler.begin("meta");
ClassInfo owner = ClassInfo.forDescriptor(ref.getOwner(), TypeLookup.DECLARED_TYPE);
@@ -49,10 +49,10 @@ import org.spongepowered.asm.mixin.throwables.MixinApplyError;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.throwables.MixinPrepareError;
import org.spongepowered.asm.mixin.transformer.MixinConfig.IListener;
import org.spongepowered.asm.mixin.transformer.MixinCoprocessor.ProcessResult;
import org.spongepowered.asm.mixin.transformer.MixinInfo.Variant;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.mixin.transformer.ext.IHotSwap;
import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckClass.ValidationFailedException;
import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExporter;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.IllegalClassLoadError;
@@ -185,7 +185,7 @@ class MixinProcessor {
/**
* Postprocessor for passthrough
*/
private final MixinPostProcessor postProcessor;
private final MixinCoprocessors coprocessors = new MixinCoprocessors();
/**
* Profiler
@@ -220,12 +220,16 @@ class MixinProcessor {
/**
* ctor
*/
MixinProcessor(MixinEnvironment environment, Extensions extensions, IHotSwap hotSwapper) {
MixinProcessor(MixinEnvironment environment, Extensions extensions, IHotSwap hotSwapper, MixinCoprocessorNestHost nestHostCoprocessor) {
this.lock = this.service.getReEntranceLock();
this.extensions = extensions;
this.hotSwapper = hotSwapper;
this.postProcessor = new MixinPostProcessor(this.sessionId);
this.coprocessors.add(new MixinCoprocessorPassthrough());
this.coprocessors.add(new MixinCoprocessorSyntheticInner());
this.coprocessors.add(new MixinCoprocessorAccessor(this.sessionId));
this.coprocessors.add(nestHostCoprocessor);
this.profiler = MixinEnvironment.getProfiler();
this.auditTrail = this.service.getAuditTrail();
@@ -292,18 +296,21 @@ class MixinProcessor {
}
}
boolean success = false;
boolean transformed = false;
try {
if (this.postProcessor.canProcess(name)) {
ProcessResult result = this.coprocessors.process(name, targetClassNode);
transformed |= result.isTransformed();
if (result.isPassthrough()) {
for (MixinCoprocessor coprocessor : this.coprocessors) {
transformed |= coprocessor.postProcess(name, targetClassNode);
}
if (this.auditTrail != null) {
this.auditTrail.onPostProcess(name);
}
Section postTimer = this.profiler.begin("postprocessor");
success = this.postProcessor.processClass(name, targetClassNode);
postTimer.end();
this.extensions.export(environment, name, false, targetClassNode);
return success;
return transformed;
}
MixinConfig packageOwnedByConfig = null;
@@ -322,7 +329,7 @@ class MixinProcessor {
// AMS - Temp passthrough for injection points and dynamic selectors. Moving to service in 0.9
ClassInfo targetInfo = ClassInfo.fromClassNode(targetClassNode);
if (targetInfo.hasSuperClass(InjectionPoint.class) || targetInfo.hasSuperClass(ITargetSelectorDynamic.class)) {
return false;
return transformed;
}
throw new IllegalClassLoadError(this.getInvalidClassError(name, targetClassNode, packageOwnedByConfig));
@@ -353,18 +360,31 @@ class MixinProcessor {
}
try {
// Tree for target class
Section timer = this.profiler.begin("read");
TargetClassContext context = new TargetClassContext(environment, this.extensions, this.sessionId,
name, targetClassNode, mixins);
timer.end();
this.applyMixins(environment, context);
TargetClassContext context = new TargetClassContext(environment, this.extensions, this.sessionId, name, targetClassNode, mixins);
context.applyMixins();
transformed |= this.coprocessors.postProcess(name, targetClassNode);
if (context.isExported()) {
this.extensions.export(environment, context.getClassName(), context.isExportForced(), context.getClassNode());
}
for (InvalidMixinException suppressed : context.getSuppressedExceptions()) {
this.handleMixinApplyError(context.getClassName(), suppressed, environment);
}
this.transformedCount++;
success = true;
transformed = true;
} catch (InvalidMixinException th) {
this.dumpClassOnFailure(name, targetClassNode, environment);
this.handleMixinApplyError(name, th, environment);
}
} else {
// No mixins, but still need to run postProcess stage of coprocessors
if (this.coprocessors.postProcess(name, targetClassNode)) {
transformed = true;
this.extensions.export(environment, name, false, targetClassNode);
}
}
} catch (MixinTransformerError er) {
throw er;
@@ -375,7 +395,7 @@ class MixinProcessor {
this.lock.pop();
mixinTimer.end();
}
return success;
return transformed;
}
private String getInvalidClassError(String name, ClassNode targetClassNode, MixinConfig ownedByConfig) {
@@ -440,7 +460,7 @@ class MixinProcessor {
this.selectConfigs(environment);
this.extensions.select(environment);
int totalMixins = this.prepareConfigs(environment);
int totalMixins = this.prepareConfigs(environment, this.extensions);
this.currentEnvironment = environment;
this.transformedCount = 0;
@@ -493,12 +513,14 @@ class MixinProcessor {
* @param environment Environment
* @return total number of mixins initialised
*/
private int prepareConfigs(MixinEnvironment environment) {
private int prepareConfigs(MixinEnvironment environment, Extensions extensions) {
int totalMixins = 0;
final IHotSwap hotSwapper = this.hotSwapper;
for (MixinConfig config : this.pendingConfigs) {
config.addListener(this.postProcessor);
for (MixinCoprocessor coprocessor : this.coprocessors) {
config.addListener(coprocessor);
}
if (hotSwapper != null) {
config.addListener(new IListener() {
@Override
@@ -515,7 +537,7 @@ class MixinProcessor {
for (MixinConfig config : this.pendingConfigs) {
try {
MixinProcessor.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount());
config.prepare();
config.prepare(extensions);
totalMixins += config.getMixinCount();
} catch (InvalidMixinException ex) {
this.handleMixinPrepareError(config, ex, environment);
@@ -543,7 +565,7 @@ class MixinProcessor {
for (MixinConfig config : this.pendingConfigs) {
try {
config.postInitialise();
config.postInitialise(this.extensions);
} catch (InvalidMixinException ex) {
this.handleMixinPrepareError(config, ex, environment);
} catch (Exception ex) {
@@ -559,37 +581,6 @@ class MixinProcessor {
return totalMixins;
}
/**
* Apply mixins for specified target class to the class described by the
* supplied byte array.
*
* @param environment current environment
* @param context target class context
*/
private void applyMixins(MixinEnvironment environment, TargetClassContext context) {
Section timer = this.profiler.begin("preapply");
this.extensions.preApply(context);
timer = timer.next("apply");
context.applyMixins();
timer = timer.next("postapply");
boolean export = false;
try {
this.extensions.postApply(context);
export = true;
} catch (ValidationFailedException ex) {
MixinProcessor.logger.info(ex.getMessage());
// If verify is enabled and failed, write out the bytecode to allow us to inspect it
export |= context.isExportForced() || environment.getOption(Option.DEBUG_EXPORT);
}
timer.end();
if (export) {
this.extensions.export(this.currentEnvironment, context.getClassName(), context.isExportForced(), context.getClassNode());
}
for (InvalidMixinException suppressed : context.getSuppressedExceptions()) {
this.handleMixinApplyError(context.getClassName(), suppressed, environment);
}
}
private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError {
this.handleMixinError(config.getName(), ex, environment, ErrorPhase.PREPARE);
}
@@ -654,7 +645,7 @@ class MixinProcessor {
try {
MixinProcessor.logger.info("Instancing error handler class {}", handlerClassName);
Class<?> handlerClass = this.service.getClassProvider().findClass(handlerClassName, true);
IMixinErrorHandler handler = (IMixinErrorHandler)handlerClass.newInstance();
IMixinErrorHandler handler = (IMixinErrorHandler)handlerClass.getDeclaredConstructor().newInstance();
if (handler != null) {
handlers.add(handler);
}
@@ -49,6 +49,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.extensibility.IActivityContext.IActivity;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.gen.AccessorInfo;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -62,7 +63,6 @@ import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.mixin.struct.MemberRef;
import org.spongepowered.asm.mixin.struct.SourceMap.File;
import org.spongepowered.asm.mixin.throwables.ClassMetadataNotFoundException;
import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.ClassInfo.SearchType;
@@ -82,7 +82,6 @@ import org.spongepowered.asm.util.asm.ASM;
import org.spongepowered.asm.util.asm.ClassNodeAdapter;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* This object keeps track of data for applying a mixin to a specific target
@@ -132,7 +131,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
/**
*
*/
private final BiMap<String, String> innerClasses = HashBiMap.<String, String>create();
private final BiMap<String, String> innerClasses;
/**
* Shadow method list
@@ -203,10 +202,8 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
this.sessionId = context.getSessionId();
this.requireVersion(classNode.version);
InnerClassGenerator icg = context.getExtensions().getGenerator(InnerClassGenerator.class);
for (String innerClass : this.mixin.getInnerClasses()) {
this.innerClasses.put(innerClass, icg.registerInnerClass(this.mixin, innerClass, this));
}
InnerClassGenerator icg = context.getExtensions().<InnerClassGenerator>getGenerator(InnerClassGenerator.class);
this.innerClasses = icg.getInnerClasses(this.mixin, this.getTargetClassRef());
}
/**
@@ -445,7 +442,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
this.activities.clear();
try {
Activity activity = this.activities.begin("Validate");
IActivity activity = this.activities.begin("Validate");
this.validateMethod(method);
activity.next("Transform Descriptor");
this.transformDescriptor(method);
@@ -460,7 +457,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
AbstractInsnNode lastInsn = null;
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
Activity insnActivity = this.activities.begin(Bytecode.getOpcodeName(insn) + " ");
IActivity insnActivity = this.activities.begin(Bytecode.getOpcodeName(insn) + " ");
if (insn instanceof MethodInsnNode) {
MethodInsnNode methodNode = (MethodInsnNode)insn;
@@ -537,7 +534,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
return;
}
Activity localVarActivity = this.activities.begin("?");
IActivity localVarActivity = this.activities.begin("?");
for (LocalVariableNode local : method.localVariables) {
if (local == null || local.desc == null) {
continue;
@@ -947,7 +944,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
}
private String transformSingleDescriptor(String desc, boolean isObject) {
Activity descriptorActivity = this.activities.begin("desc=%s", desc);
IActivity descriptorActivity = this.activities.begin("desc=%s", desc);
boolean isArray = false;
String type = desc;
while (type.startsWith("[") || type.startsWith("L")) {
@@ -1217,6 +1214,13 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
List<String> getNestMembers() {
return ClassNodeAdapter.getNestMembers(this.classNode);
}
/**
* Get the map of inner classes to remapped inner classes
*/
BiMap<String, String> getInnerClasses() {
return this.innerClasses;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IReferenceMapperContext
@@ -1233,7 +1237,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
* @param transformedName Target class's transformed name
* @param targetClass Target class
*/
void preApply(String transformedName, ClassNode targetClass) {
void preApply(String transformedName, ClassNode targetClass) throws Exception {
this.mixin.preApply(transformedName, targetClass);
}
@@ -1247,7 +1251,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
this.activities.clear();
try {
Activity activity = this.activities.begin("Validating Injector Groups");
IActivity activity = this.activities.begin("Validating Injector Groups");
this.injectorGroups.validateAll();
activity.next("Plugin Post-Application");
this.mixin.postApply(transformedName, targetClass);
@@ -1300,10 +1304,10 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
try {
this.injectors.clear();
Activity prepareActivity = this.activities.begin("?");
IActivity prepareActivity = this.activities.begin("?");
for (MethodNode method : this.mergedMethods) {
prepareActivity.next("%s%s", method.name, method.desc);
Activity methodActivity = this.activities.begin("Parse");
IActivity methodActivity = this.activities.begin("Parse");
InjectionInfo injectInfo = InjectionInfo.parse(this, method);
if (injectInfo == null) {
continue;
@@ -1337,22 +1341,22 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
this.activities.clear();
try {
Activity applyActivity = this.activities.begin("PreInject");
Activity preInjectActivity = this.activities.begin("?");
IActivity applyActivity = this.activities.begin("PreInject");
IActivity preInjectActivity = this.activities.begin("?");
for (InjectionInfo injectInfo : this.injectors) {
preInjectActivity.next(injectInfo.toString());
injectInfo.preInject();
}
applyActivity.next("Inject");
Activity injectActivity = this.activities.begin("?");
IActivity injectActivity = this.activities.begin("?");
for (InjectionInfo injectInfo : this.injectors) {
injectActivity.next(injectInfo.toString());
injectInfo.inject();
}
applyActivity.next("PostInject");
Activity postInjectActivity = this.activities.begin("?");
IActivity postInjectActivity = this.activities.begin("?");
for (InjectionInfo injectInfo : this.injectors) {
postInjectActivity.next(injectInfo.toString());
injectInfo.postInject();
@@ -1378,22 +1382,22 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
List<MethodNode> methods = new ArrayList<MethodNode>();
try {
Activity accessorActivity = this.activities.begin("Locate");
Activity locateActivity = this.activities.begin("?");
IActivity accessorActivity = this.activities.begin("Locate");
IActivity locateActivity = this.activities.begin("?");
for (AccessorInfo accessor : this.accessors) {
locateActivity.next(accessor.toString());
accessor.locate();
}
accessorActivity.next("Validate");
Activity validateActivity = this.activities.begin("?");
IActivity validateActivity = this.activities.begin("?");
for (AccessorInfo accessor : this.accessors) {
validateActivity.next(accessor.toString());
accessor.validate();
}
accessorActivity.next("Generate");
Activity generateActivity = this.activities.begin("?");
IActivity generateActivity = this.activities.begin("?");
for (AccessorInfo accessor : this.accessors) {
generateActivity.next(accessor.toString());
MethodNode generated = accessor.generate();
@@ -76,6 +76,12 @@ final class MixinTransformer extends TreeTransformer implements IMixinTransforme
* Hotswap agent, if available
*/
private final IHotSwap hotSwapper;
/**
* Coprocessor which handles merging nest members into nest hosts which may
* or may not be mixin targets themselves
*/
private final MixinCoprocessorNestHost nestHostCoprocessor;
/**
* Mixin processor which actually manages application of mixins
@@ -102,11 +108,12 @@ final class MixinTransformer extends TreeTransformer implements IMixinTransforme
this.extensions = new Extensions(this.syntheticClassRegistry);
this.hotSwapper = this.initHotSwapper(environment);
this.nestHostCoprocessor = new MixinCoprocessorNestHost();
this.processor = new MixinProcessor(environment, this.extensions, this.hotSwapper);
this.processor = new MixinProcessor(environment, this.extensions, this.hotSwapper, this.nestHostCoprocessor);
this.generator = new MixinClassGenerator(environment, this.extensions);
DefaultExtensions.create(environment, this.extensions, this.syntheticClassRegistry);
DefaultExtensions.create(environment, this.extensions, this.syntheticClassRegistry, this.nestHostCoprocessor);
}
private IHotSwap initHotSwapper(MixinEnvironment environment) {
@@ -135,7 +135,7 @@ class PluginHandle {
/**
* Called immediately before the mixin is applied to targetClass
*/
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, MixinInfo mixinInfo) {
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, MixinInfo mixinInfo) throws Exception {
if (this.plugin == null) {
return;
}
@@ -166,7 +166,7 @@ class PluginHandle {
/**
* Called immediately after the mixin is applied to targetClass
*/
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, MixinInfo mixinInfo) {
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, MixinInfo mixinInfo) throws Exception {
if (this.plugin == null) {
return;
}
@@ -46,10 +46,13 @@ import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.struct.SourceMap;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext;
import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckClass.ValidationFailedException;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.ClassSignature;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
/**
* Struct for containing target class information during mixin application
@@ -70,6 +73,11 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte
* Mixin transformer extensions
*/
private final Extensions extensions;
/**
* Profiler
*/
private final Profiler profiler;
/**
* Transformer session ID
@@ -130,15 +138,22 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte
*/
private boolean applied;
/**
* True if this class is eligible for export. That is, it was successfully
* applied or if validation failed and export is enabled.
*/
private boolean export;
/**
* True if this class is decorated with an {@link Debug} annotation which
* instructs an export
*/
private boolean forceExport;
TargetClassContext(MixinEnvironment env, Extensions extensions, String sessionId, String name, ClassNode classNode, SortedSet<MixinInfo> mixins) {
this.env = env;
this.extensions = extensions;
this.profiler = MixinEnvironment.getProfiler();
this.sessionId = sessionId;
this.className = name;
this.classNode = classNode;
@@ -158,6 +173,10 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte
return this.applied;
}
boolean isExported() {
return this.export;
}
boolean isExportForced() {
return this.forceExport;
}
@@ -331,22 +350,55 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte
}
return target;
}
/**
* Apply mixins to this class
* Apply mixins for this target class
*/
void applyMixins() {
if (this.applied) {
throw new IllegalStateException("Mixins already applied to target class " + this.className);
}
this.applied = true;
Section timer = this.profiler.begin("preapply");
this.preApply();
timer = timer.next("apply");
this.apply();
timer = timer.next("postapply");
this.postApply();
timer.end();
}
/**
* Run extensions before apply
*/
private void preApply() {
this.extensions.preApply(this);
}
/**
* Apply mixins to this class
*/
private void apply() {
MixinApplicatorStandard applicator = this.createApplicator();
applicator.apply(this.mixins);
this.applySignature();
this.upgradeMethods();
this.checkMerges();
}
/**
* Run extensions after apply
*/
private void postApply() {
try {
this.extensions.postApply(this);
this.export = true;
} catch (ValidationFailedException ex) {
MixinProcessor.logger.info(ex.getMessage());
// If verify is enabled and failed, write out the bytecode to allow us to inspect it
this.export |= this.forceExport || this.env.getOption(Option.DEBUG_EXPORT);
}
}
private MixinApplicatorStandard createApplicator() {
if (this.classInfo.isInterface()) {
@@ -24,10 +24,10 @@
*/
package org.spongepowered.asm.mixin.transformer.throwables;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
/**
* Thrown by the mixin validator when a mixin fails a pre-flight check
@@ -43,7 +43,7 @@ public class InvalidMixinException extends MixinException {
this.mixin = mixin;
}
public InvalidMixinException(IMixinInfo mixin, String message, ActivityStack activityContext) {
public InvalidMixinException(IMixinInfo mixin, String message, IActivityContext activityContext) {
super(message, activityContext);
this.mixin = mixin;
}
@@ -52,7 +52,7 @@ public class InvalidMixinException extends MixinException {
this(context.getMixin(), message);
}
public InvalidMixinException(IMixinContext context, String message, ActivityStack activityContext) {
public InvalidMixinException(IMixinContext context, String message, IActivityContext activityContext) {
this(context.getMixin(), message, activityContext);
}
@@ -61,7 +61,7 @@ public class InvalidMixinException extends MixinException {
this.mixin = mixin;
}
public InvalidMixinException(IMixinInfo mixin, Throwable cause, ActivityStack activityContext) {
public InvalidMixinException(IMixinInfo mixin, Throwable cause, IActivityContext activityContext) {
super(cause, activityContext);
this.mixin = mixin;
}
@@ -70,7 +70,7 @@ public class InvalidMixinException extends MixinException {
this(context.getMixin(), cause);
}
public InvalidMixinException(IMixinContext context, Throwable cause, ActivityStack activityContext) {
public InvalidMixinException(IMixinContext context, Throwable cause, IActivityContext activityContext) {
this(context.getMixin(), cause, activityContext);
}
@@ -79,7 +79,7 @@ public class InvalidMixinException extends MixinException {
this.mixin = mixin;
}
public InvalidMixinException(IMixinInfo mixin, String message, Throwable cause, ActivityStack activityContext) {
public InvalidMixinException(IMixinInfo mixin, String message, Throwable cause, IActivityContext activityContext) {
super(message, cause, activityContext);
this.mixin = mixin;
}
@@ -89,7 +89,7 @@ public class InvalidMixinException extends MixinException {
this.mixin = context.getMixin();
}
public InvalidMixinException(IMixinContext context, String message, Throwable cause, ActivityStack activityContext) {
public InvalidMixinException(IMixinContext context, String message, Throwable cause, IActivityContext activityContext) {
super(message, cause, activityContext);
this.mixin = context.getMixin();
}
@@ -24,6 +24,7 @@
*/
package org.spongepowered.asm.mixin.transformer.throwables;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
@@ -39,7 +40,7 @@ public class MixinApplicatorException extends InvalidMixinException {
super(context, message, (ActivityStack)null);
}
public MixinApplicatorException(IMixinInfo context, String message, ActivityStack activityContext) {
public MixinApplicatorException(IMixinInfo context, String message, IActivityContext activityContext) {
super(context, message, activityContext);
}
@@ -47,7 +48,7 @@ public class MixinApplicatorException extends InvalidMixinException {
super(context, message, (ActivityStack)null);
}
public MixinApplicatorException(IMixinContext context, String message, ActivityStack activityContext) {
public MixinApplicatorException(IMixinContext context, String message, IActivityContext activityContext) {
super(context, message, activityContext);
}
@@ -55,7 +56,7 @@ public class MixinApplicatorException extends InvalidMixinException {
super(mixin, message, cause, (ActivityStack)null);
}
public MixinApplicatorException(IMixinInfo mixin, String message, Throwable cause, ActivityStack activityContext) {
public MixinApplicatorException(IMixinInfo mixin, String message, Throwable cause, IActivityContext activityContext) {
super(mixin, message, cause, activityContext);
}
@@ -63,7 +64,7 @@ public class MixinApplicatorException extends InvalidMixinException {
super(mixin, message, cause, (ActivityStack)null);
}
public MixinApplicatorException(IMixinContext mixin, String message, Throwable cause, ActivityStack activityContext) {
public MixinApplicatorException(IMixinContext mixin, String message, Throwable cause, IActivityContext activityContext) {
super(mixin, message, cause, activityContext);
}
@@ -71,7 +72,7 @@ public class MixinApplicatorException extends InvalidMixinException {
super(mixin, cause, (ActivityStack)null);
}
public MixinApplicatorException(IMixinInfo mixin, Throwable cause, ActivityStack activityContext) {
public MixinApplicatorException(IMixinInfo mixin, Throwable cause, IActivityContext activityContext) {
super(mixin, cause, activityContext);
}
@@ -79,7 +80,7 @@ public class MixinApplicatorException extends InvalidMixinException {
super(mixin, cause, (ActivityStack)null);
}
public MixinApplicatorException(IMixinContext mixin, Throwable cause, ActivityStack activityContext) {
public MixinApplicatorException(IMixinContext mixin, Throwable cause, IActivityContext activityContext) {
super(mixin, cause, activityContext);
}
@@ -24,8 +24,8 @@
*/
package org.spongepowered.asm.mixin.transformer.throwables;
import org.spongepowered.asm.mixin.extensibility.IActivityContext;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
/**
* Exception indicating a problem during pre-processing
@@ -34,11 +34,11 @@ public class MixinPreProcessorException extends MixinException {
private static final long serialVersionUID = 1L;
public MixinPreProcessorException(String message, ActivityStack context) {
public MixinPreProcessorException(String message, IActivityContext context) {
super(message, context);
}
public MixinPreProcessorException(String message, Throwable cause, ActivityStack context) {
public MixinPreProcessorException(String message, Throwable cause, IActivityContext context) {
super(message, cause, context);
}
@@ -32,6 +32,71 @@ import java.util.regex.Pattern;
*/
public abstract class JavaVersion {
/**
* Version number for Java 6
*/
public static final double JAVA_6 = 1.6;
/**
* Version number for Java 7
*/
public static final double JAVA_7 = 1.7;
/**
* Version number for Java 8
*/
public static final double JAVA_8 = 1.8;
/**
* Version number for Java 9
*/
public static final double JAVA_9 = 9.0;
/**
* Version number for Java 10
*/
public static final double JAVA_10 = 10.0;
/**
* Version number for Java 11
*/
public static final double JAVA_11 = 11.0;
/**
* Version number for Java 12
*/
public static final double JAVA_12 = 12.0;
/**
* Version number for Java 13
*/
public static final double JAVA_13 = 13.0;
/**
* Version number for Java 14
*/
public static final double JAVA_14 = 14.0;
/**
* Version number for Java 15
*/
public static final double JAVA_15 = 15.0;
/**
* Version number for Java 16
*/
public static final double JAVA_16 = 16.0;
/**
* Version number for Java 17
*/
public static final double JAVA_17 = 17.0;
/**
* Version number for Java 18
*/
public static final double JAVA_18 = 18.0;
private static double current = 0.0;
private JavaVersion() {}
@@ -69,6 +69,16 @@ public final class LanguageFeatures {
*/
public static final int DYNAMIC_CONSTANTS = 16;
/**
* Record types
*/
public static final int RECORDS = 32;
/**
* Sealed classes (permitted subclasses)
*/
public static final int SEALED_CLASSES = 64;
/**
* Utility class
*/
@@ -25,6 +25,7 @@
package org.spongepowered.asm.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -68,6 +69,192 @@ public final class Locals {
}
/**
* A local variable entry which is "dead" (has been removed from the known
* frame) but is being retained in the computed frame as a ghost so that we
* can decide whether we want to include it in the final frame or not.
*
* <p>Zombie nodes are currently only persisted for 1 instruction, so in the
* cases where there is a frame node followed directly by the candidate insn
* the zombies will be returned as valid results, but otherwise culled.</p>
*/
static class ZombieLocalVariableNode extends LocalVariableNode {
static final char CHOP = 'C';
static final char TRIM = 'X';
/**
* Progenitor of this zombie, to allow "resurrection" (am I stretching
* this metaphor too far?)
*/
final LocalVariableNode ancestor;
final char type;
/**
* Number of instructions the zombie has "lived" for, incremented by the
* state machine loop
*/
int lifetime;
/**
* Number of frames which have elapsed for this zombie, incremented by
* the state machine loop when a frame node is encountered
*/
int frames;
ZombieLocalVariableNode(LocalVariableNode ancestor, char type) {
super(ancestor.name, ancestor.desc, ancestor.signature, ancestor.start, ancestor.end, ancestor.index);
this.ancestor = ancestor;
this.type = type;
}
boolean checkResurrect(Settings settings) {
int insnThreshold = this.type == ZombieLocalVariableNode.CHOP ? settings.choppedInsnThreshold : settings.trimmedInsnThreshold;
if (insnThreshold > -1 && this.lifetime > insnThreshold) {
return false;
}
int frameThreshold = this.type == ZombieLocalVariableNode.CHOP ? settings.choppedFrameThreshold : settings.trimmedFrameThreshold;
return frameThreshold == -1 || this.frames <= frameThreshold;
}
static ZombieLocalVariableNode of(LocalVariableNode ancestor, char type) {
if (ancestor instanceof ZombieLocalVariableNode) {
return (ZombieLocalVariableNode)ancestor;
}
return ancestor != null ? new ZombieLocalVariableNode(ancestor, type) : null;
}
@Override
public String toString() {
return String.format("Z(%s,%-2d)", this.type, this.lifetime);
}
}
/**
* Settings for <tt>getLocalsAt</tt> containing the tunable options for the
* algorithm. This exists for two purposes: Firstly, wrapping tunables up in
* a single object for convenience, but secondly providing some level of
* forward compatibility for platforms that which to provide <em>backward
* </em> compatibility to their own consumers. The {@link #flagsCustom}
* field is* provided as a way of encoding arbitrary options that downstream
* projects may wish to use to tune their own implementations. The {@link
* #flags} field is reserved for mixin internal flags to be added at a later
* date.
*/
public static class Settings {
/**
* When an incoming frame contains TOP entries, these are nearly always
* bogus. If we previously knew the local in that slot, resurrect it.
* Only resurrects TRIM zombies.
*/
public static int RESURRECT_FOR_BOGUS_TOP = 0x01;
/**
* When a LOAD grows the frame, resurrect any zombies in the exposed
* portion of the frame, based on the thresholds configured.
*/
public static int RESURRECT_EXPOSED_ON_LOAD = 0x02;
/**
* When a STORE grows the frame, resurrect any zombies in the exposed
* portion of the frame, based on the thresholds configured.
*/
public static int RESURRECT_EXPOSED_ON_STORE = 0x04;
/**
* Default flags
*/
public static int DEFAULT_FLAGS = Settings.RESURRECT_FOR_BOGUS_TOP | Settings.RESURRECT_EXPOSED_ON_LOAD | Settings.RESURRECT_EXPOSED_ON_STORE;
/**
* Default settings. CHOP zombies can be resurrected for 1 frame, TRIM
* zombies can be resurrected forever
*/
public static Settings DEFAULT = new Settings(Settings.DEFAULT_FLAGS, 0, -1, 1, -1, -1);
/**
* Reserved flags for Mixin
*/
final int flags;
/**
* Platform-specific flags
*/
final int flagsCustom;
/**
* Number of instructions that a CHOPped local is eligible for
* resurrection, -1 to ignore, 0 for none
*/
final int choppedInsnThreshold;
/**
* Number of frames that a CHOPped local is eligible for resurrection,
* -1 to ignore, 0 for none
*/
final int choppedFrameThreshold;
/**
* Number of instructions that a TRIMmed local is eligible for
* resurrection, -1 to ignore, 0 for none
*/
final int trimmedInsnThreshold;
/**
* Number of frames that a TRIMmed local is eligible for resurrection,
* -1 to ignore, 0 for none
*/
final int trimmedFrameThreshold;
/**
* @param flags Mixin flags
* @param flagsCustom Platform-specific flags
* @param insnThreshold Number of instructions that a local (regardless
* of death reason) is eligible for resurrection, -1 to ignore,
* 0 for none
* @param frameThreshold Number of frames that a local (regardless of
* death reason) is eligible for resurrection,-1 to ignore, 0 for
* none
*/
public Settings(int flags, int flagsCustom, int insnThreshold, int frameThreshold) {
this(flags, flagsCustom, insnThreshold, frameThreshold, insnThreshold, frameThreshold);
}
/**
* @param flags Mixin flags
* @param flagsCustom Platform-specific flags
* @param choppedInsnThreshold Number of instructions that a CHOPped
* local is eligible for resurrection, -1 to ignore, 0 for none
* @param choppedFrameThreshold Number of frames that a CHOPped local is
* eligible for resurrection,-1 to ignore, 0 for none
* @param trimmedInsnThreshold Number of instructions that a TRIMmed#
* local is eligible for resurrection, -1 to ignore, 0 for none
* @param trimmedFrameThreshold Number of frames that a TRIMmed local is
* eligible for resurrection, -1 to ignore, 0 for none
*/
public Settings(int flags, int flagsCustom, int choppedInsnThreshold, int choppedFrameThreshold, int trimmedInsnThreshold,
int trimmedFrameThreshold) {
this.flags = flags;
this.flagsCustom = flagsCustom;
this.choppedInsnThreshold = choppedInsnThreshold;
this.choppedFrameThreshold = choppedFrameThreshold;
this.trimmedInsnThreshold = trimmedInsnThreshold;
this.trimmedFrameThreshold = trimmedFrameThreshold;
}
boolean hasFlags(int flags) {
return (this.flags & flags) == flags;
}
boolean hasCustomFlags(int flagsCustom) {
return (this.flagsCustom & flagsCustom) == flagsCustom;
}
}
/**
* Frame type names just for the purposes of debug printing
*/
@@ -145,6 +332,53 @@ public final class Locals {
* specified location
*/
public static LocalVariableNode[] getLocalsAt(ClassNode classNode, MethodNode method, AbstractInsnNode node) {
return Locals.getLocalsAt(classNode, method, node, Settings.DEFAULT);
}
/**
* <p>Attempts to identify available locals at an arbitrary point in the
* bytecode specified by node.</p>
*
* <p>This method builds an approximate view of the locals available at an
* arbitrary point in the bytecode by examining the following features in
* the bytecode:</p>
* <ul>
* <li>Any available stack map frames</li>
* <li>STORE opcodes</li>
* <li>The local variable table</li>
* </ul>
*
* <p>Inference proceeds by walking the bytecode from the start of the
* method looking for stack frames and STORE opcodes. When either of these
* is encountered, an attempt is made to cross-reference the values in the
* stack map or STORE opcode with the value in the local variable table
* which covers the code range. Stack map frames overwrite the entire
* simulated local variable table with their own value types, STORE opcodes
* overwrite only the local slot to which they pertain. Values in the
* simulated locals array are spaced according to their size (unlike the
* representation in FrameNode) and this TOP, NULL and UNINTITIALIZED_THIS
* opcodes will be represented as null values in the simulated frame.</p>
*
* <p>This code does not currently simulate the prescribed JVM behaviour
* where overwriting the second slot of a DOUBLE or LONG actually
* invalidates the DOUBLE or LONG stored in the previous location, so we
* have to hope (for now) that this behaviour isn't emitted by the compiler
* or any upstream transformers. I may have to re-think this strategy if
* this situation is encountered in the wild.</p>
*
* @param classNode ClassNode containing the method, used to initialise the
* implicit "this" reference in simple methods with no stack frames
* @param method MethodNode to explore
* @param node Node indicating the position at which to determine the locals
* state. The locals will be enumerated UP TO the specified node, so
* bear in mind that if the specified node is itself a STORE opcode,
* then we will be looking at the state of the locals PRIOR to its
* invocation
* @param settings Tunable settings for the state machine
* @return A sparse array containing a view (hopefully) of the locals at the
* specified location
*/
public static LocalVariableNode[] getLocalsAt(ClassNode classNode, MethodNode method, AbstractInsnNode node, Settings settings) {
for (int i = 0; i < 3 && (node instanceof LabelNode || node instanceof LineNumberNode); i++) {
AbstractInsnNode nextNode = Locals.nextNode(method.instructions, node);
if (nextNode instanceof FrameNode) { // Do not ffwd over frames
@@ -177,7 +411,7 @@ public final class Locals {
local += argType.getSize();
}
int initialFrameSize = local;
final int initialFrameSize = local;
int frameSize = local;
int frameIndex = -1;
int lastFrameSize = local;
@@ -186,6 +420,18 @@ public final class Locals {
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
AbstractInsnNode insn = iter.next();
// Tick the zombies
for (int l = 0; l < frame.length; l++) {
if (frame[l] instanceof ZombieLocalVariableNode) {
ZombieLocalVariableNode zombie = (ZombieLocalVariableNode)frame[l];
zombie.lifetime++;
if (insn instanceof FrameNode) {
zombie.frames++;
}
}
}
if (storeInsn != null) {
LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var);
frame[storeInsn.var] = storedLocal;
@@ -194,6 +440,9 @@ public final class Locals {
&& Type.getType(storedLocal.desc).getSize() == 2) {
frame[storeInsn.var + 1] = null; // TOP
knownFrameSize = Math.max(knownFrameSize, storeInsn.var + 2);
if (settings.hasFlags(Settings.RESURRECT_EXPOSED_ON_STORE)) {
Locals.resurrect(frame, knownFrameSize, settings);
}
}
storeInsn = null;
}
@@ -205,21 +454,21 @@ public final class Locals {
break handleFrame;
}
int frameNodeSize = Locals.computeFrameSize(frameNode);
int frameNodeSize = Locals.computeFrameSize(frameNode, initialFrameSize);
FrameData frameData = frameIndex < frames.size() ? frames.get(frameIndex) : null;
if (frameData != null) {
if (frameData.type == Opcodes.F_FULL) {
knownFrameSize = lastFrameSize = frameSize = Math.min(frameNodeSize, frameData.size);
knownFrameSize = lastFrameSize = frameSize = Math.max(initialFrameSize, Math.min(frameNodeSize, frameData.size));
} else {
frameSize = Locals.getAdjustedFrameSize(frameSize, frameData);
frameSize = Locals.getAdjustedFrameSize(frameSize, frameData, initialFrameSize);
}
} else {
frameSize = Locals.getAdjustedFrameSize(frameSize, frameNode);
frameSize = Locals.getAdjustedFrameSize(frameSize, frameNode, initialFrameSize);
}
// Sanity check
if (frameSize < 0) {
if (frameSize < initialFrameSize) {
throw new IllegalStateException(String.format("Locals entered an invalid state evaluating %s::%s%s at instruction %d (%s). "
+ "Initial frame size is %d, calculated a frame size of %d with %s", classNode.name, method.name, method.desc,
method.instructions.indexOf(insn), Bytecode.describeNode(insn, false), initialFrameSize, frameSize, frameData));
@@ -228,7 +477,7 @@ public final class Locals {
if ((frameData == null && (frameNode.type == Opcodes.F_CHOP || frameNode.type == Opcodes.F_NEW))
|| (frameData != null && frameData.type == Opcodes.F_CHOP)) {
for (int framePos = frameSize; framePos < frame.length; framePos++) {
frame[framePos] = null;
frame[framePos] = ZombieLocalVariableNode.of(frame[framePos], ZombieLocalVariableNode.CHOP);
}
knownFrameSize = lastFrameSize = frameSize;
break handleFrame;
@@ -249,7 +498,14 @@ public final class Locals {
boolean is32bitValue = localType == Opcodes.INTEGER || localType == Opcodes.FLOAT;
boolean is64bitValue = localType == Opcodes.DOUBLE || localType == Opcodes.LONG;
if (localType == Opcodes.TOP) {
// Do nothing, explicit TOP entries are pretty much always bogus, and real ones are handled below
// Explicit TOP entries are pretty much always bogus, but depending on our resurrection
// strategy we may want to resurrect eligible zombies here. Real TOP entries are handled below
if (frame[framePos] instanceof ZombieLocalVariableNode && settings.hasFlags(Settings.RESURRECT_FOR_BOGUS_TOP)) {
ZombieLocalVariableNode zombie = (ZombieLocalVariableNode)frame[framePos];
if (zombie.type == ZombieLocalVariableNode.TRIM) {
frame[framePos] = zombie.ancestor;
}
}
} else if (isMarkerType) {
frame[framePos] = null;
} else if (is32bitValue || is64bitValue) {
@@ -268,7 +524,7 @@ public final class Locals {
if (framePos < knownFrameSize) {
frame[framePos] = Locals.getLocalVariableAt(classNode, method, insn, framePos);
} else {
frame[framePos] = null;
frame[framePos] = ZombieLocalVariableNode.of(frame[framePos], ZombieLocalVariableNode.TRIM);
}
}
} else if (localType instanceof LabelNode) {
@@ -279,17 +535,20 @@ public final class Locals {
}
}
} else if (insn instanceof VarInsnNode) {
VarInsnNode varNode = (VarInsnNode) insn;
VarInsnNode varInsn = (VarInsnNode)insn;
boolean isLoad = insn.getOpcode() >= Opcodes.ILOAD && insn.getOpcode() <= Opcodes.SALOAD;
if (isLoad) {
frame[varNode.var] = Locals.getLocalVariableAt(classNode, method, insn, varNode.var);
int varSize = frame[varNode.var].desc != null ? Type.getType(frame[varNode.var].desc).getSize() : 1;
knownFrameSize = Math.max(knownFrameSize, varNode.var + varSize);
frame[varInsn.var] = Locals.getLocalVariableAt(classNode, method, insn, varInsn.var);
int varSize = frame[varInsn.var].desc != null ? Type.getType(frame[varInsn.var].desc).getSize() : 1;
knownFrameSize = Math.max(knownFrameSize, varInsn.var + varSize);
if (settings.hasFlags(Settings.RESURRECT_EXPOSED_ON_LOAD)) {
Locals.resurrect(frame, knownFrameSize, settings);
}
} else {
// Update the LVT for the opcode AFTER this one, since we always want to know
// the frame state BEFORE the *current* instruction to match the contract of
// injection points
storeInsn = varNode;
storeInsn = varInsn;
}
}
@@ -297,10 +556,18 @@ public final class Locals {
break;
}
}
// Null out any "unknown" or mixin-provided locals
for (int l = 0; l < frame.length; l++) {
if (frame[l] != null && frame[l].desc == null || frame[l] instanceof SyntheticLocalVariableNode) {
if (frame[l] instanceof ZombieLocalVariableNode) {
ZombieLocalVariableNode zombie = (ZombieLocalVariableNode)frame[l];
// preserve zombies where the frame node which culled them was immediately prior to
// the matched instruction, or *was itself* the matched instruction, the returned
// frame will contain the original node (the zombie ancestor)
frame[l] = (zombie.lifetime > 1) ? null : zombie.ancestor;
}
if ((frame[l] != null && frame[l].desc == null) || frame[l] instanceof SyntheticLocalVariableNode) {
frame[l] = null;
}
}
@@ -308,6 +575,25 @@ public final class Locals {
return frame;
}
/**
* Walks the supplied <tt>frame</tt> up to the specified <tt>knownFrameSize
* </tt> and resurrects any zombies that meet the required criteria
*
* @param frame Frame to walk
* @param knownFrameSize Known frame size in which to resurrect
* @param settings Resurrection settings
*/
private static void resurrect(LocalVariableNode[] frame, int knownFrameSize, Settings settings) {
for (int l = 0; l < knownFrameSize && l < frame.length; l++) {
if (frame[l] instanceof ZombieLocalVariableNode) {
ZombieLocalVariableNode zombie = (ZombieLocalVariableNode)frame[l];
if (zombie.checkResurrect(settings)) {
frame[l] = zombie.ancestor;
}
}
}
}
/**
* Attempts to locate the appropriate entry in the local variable table for
* the specified local variable index at the location specified by node.
@@ -380,7 +666,7 @@ public final class Locals {
if (method.localVariables.isEmpty()) {
return Locals.getGeneratedLocalVariableTable(classNode, method);
}
return method.localVariables;
return Collections.<LocalVariableNode>unmodifiableList(method.localVariables);
}
/**
@@ -399,7 +685,7 @@ public final class Locals {
localVars = Locals.generateLocalVariableTable(classNode, method);
Locals.calculatedLocalVariables.put(methodId, localVars);
return localVars;
return Collections.<LocalVariableNode>unmodifiableList(localVars);
}
/**
@@ -548,10 +834,11 @@ public final class Locals {
*
* @param currentSize current frame size
* @param frameNode frame entry
* @param initialFrameSize Method initial frame size
* @return new frame size
*/
private static int getAdjustedFrameSize(int currentSize, FrameNode frameNode) {
return Locals.getAdjustedFrameSize(currentSize, frameNode.type, Locals.computeFrameSize(frameNode));
private static int getAdjustedFrameSize(int currentSize, FrameNode frameNode, int initialFrameSize) {
return Locals.getAdjustedFrameSize(currentSize, frameNode.type, Locals.computeFrameSize(frameNode, initialFrameSize), initialFrameSize);
}
/**
@@ -561,10 +848,11 @@ public final class Locals {
*
* @param currentSize current frame size
* @param frameData frame entry
* @param initialFrameSize Method initial frame size
* @return new frame size
*/
private static int getAdjustedFrameSize(int currentSize, FrameData frameData) {
return Locals.getAdjustedFrameSize(currentSize, frameData.type, frameData.size);
private static int getAdjustedFrameSize(int currentSize, FrameData frameData, int initialFrameSize) {
return Locals.getAdjustedFrameSize(currentSize, frameData.type, frameData.size, initialFrameSize);
}
/**
@@ -575,17 +863,18 @@ public final class Locals {
* @param currentSize current frame size
* @param type frame entry type
* @param size frame entry size
* @param initialFrameSize Method initial frame size
* @return new frame size
*/
private static int getAdjustedFrameSize(int currentSize, int type, int size) {
private static int getAdjustedFrameSize(int currentSize, int type, int size, int initialFrameSize) {
switch (type) {
case Opcodes.F_NEW:
case Opcodes.F_FULL:
return size;
return Math.max(initialFrameSize, size);
case Opcodes.F_APPEND:
return currentSize + size;
case Opcodes.F_CHOP:
return currentSize - size;
return Math.max(initialFrameSize, currentSize - size);
case Opcodes.F_SAME:
case Opcodes.F_SAME1:
return currentSize;
@@ -599,11 +888,12 @@ public final class Locals {
* supplied frame node
*
* @param frameNode frame node with locals to compute
* @param initialFrameSize Method initial frame size
* @return size of frame node locals
*/
public static int computeFrameSize(FrameNode frameNode) {
public static int computeFrameSize(FrameNode frameNode, int initialFrameSize) {
if (frameNode.local == null) {
return 0;
return initialFrameSize;
}
int size = 0;
for (Object local : frameNode.local) {
@@ -613,7 +903,7 @@ public final class Locals {
size++;
}
}
return size;
return Math.max(initialFrameSize, size);
}
/**
@@ -125,10 +125,6 @@ public class SignaturePrinter {
this.returnType = returnType;
this.argTypes = argTypes;
this.argNames = argNames;
if (this.argTypes.length > this.argNames.length) {
throw new IllegalArgumentException(String.format("Types array length must not exceed names array length! (names=%d, types=%d)",
this.argNames.length, this.argTypes.length));
}
}
/**
@@ -225,7 +221,8 @@ public class SignaturePrinter {
}
}
try {
String name = typesOnly ? null : Strings.isNullOrEmpty(this.argNames[var]) ? "unnamed" + var : this.argNames[var];
String name = typesOnly ? null : var < this.argNames.length && !Strings.isNullOrEmpty(this.argNames[var])
? this.argNames[var] : "unnamed" + var;
this.appendType(sb, this.argTypes[var], name);
} catch (Exception ex) {
// System.err.printf("\n\n>>> argTypes=%d, argNames=%d\n\n", this.argTypes.length, this.argNames.length);
@@ -83,6 +83,41 @@ public final class VersionNumber implements Comparable<VersionNumber>, Serializa
this.suffix = suffix != null ? suffix : "";
}
/**
* Get the major version from this version number
*/
public short getMajor() {
return (short)(this.value >> 48);
}
/**
* Get the minor version from this version number
*/
public short getMinor() {
return (short)(this.value >> 32 & Short.MAX_VALUE);
}
/**
* Get the patch from this version number
*/
public short getPatch() {
return (short)(this.value >> 16 & Short.MAX_VALUE);
}
/**
* Get the revision from this version number
*/
public short getRevision() {
return (short)(this.value & Short.MAX_VALUE);
}
/**
* Get the suffix from this version
*/
public String getSuffix() {
return this.suffix;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@@ -25,8 +25,11 @@
package org.spongepowered.asm.util.asm;
import java.lang.reflect.Field;
import java.util.jar.Attributes;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.launch.platform.MainAttributes;
import org.spongepowered.asm.util.VersionNumber;
/**
* Utility methods for determining ASM version and other version-specific
@@ -36,6 +39,11 @@ public final class ASM {
private static int majorVersion = 5;
private static int minorVersion = 0;
// Implementation versions, only available from ASM
private static int implMinorVersion = 0;
private static int patchVersion = 0;
private static String maxVersion = "FALLBACK";
private static int maxClassVersion = Opcodes.V1_6;
@@ -60,6 +68,32 @@ public final class ASM {
return ASM.majorVersion >= majorVersion;
}
/**
* Get whether the current ASM API is at least the specified version
* (including minor version when it's relevant)
*
* @param majorVersion major version to check for (eg. 6)
* @param minorVersion minor version to check for
*/
public static boolean isAtLeastVersion(int majorVersion, int minorVersion) {
return ASM.majorVersion >= majorVersion && (ASM.majorVersion > majorVersion || ASM.implMinorVersion >= minorVersion);
}
/**
* Get whether the current ASM API is at least the specified version
* (including minor version and patch version when it's relevant)
*
* @param majorVersion major version to check for (eg. 6)
* @param minorVersion minor version to check for
* @param patchVersion patch version to check for
*/
public static boolean isAtLeastVersion(int majorVersion, int minorVersion, int patchVersion) {
if (ASM.majorVersion == majorVersion) {
return ASM.implMinorVersion >= minorVersion && (ASM.implMinorVersion > minorVersion || ASM.patchVersion >= patchVersion);
}
return ASM.majorVersion > majorVersion;
}
/**
* Get the major API version
*/
@@ -75,12 +109,22 @@ public final class ASM {
}
/**
* Get the ASM API version as a string (mostly for debugging and the banner)
* Get the ASM API version as a string (mostly for debugging)
*
* @return ASM API version as string
*/
public static String getApiVersionString() {
return String.format("ASM %d.%d (%s)", ASM.majorVersion, ASM.minorVersion, ASM.maxVersion);
return String.format("%d.%d", ASM.majorVersion, ASM.minorVersion);
}
/**
* Get the ASM version as a string (mostly for debugging and the banner)
*
* @return ASM library version as string
*/
public static String getVersionString() {
return String.format("ASM %d.%d%s (%s)",
ASM.majorVersion, ASM.implMinorVersion, ASM.patchVersion > 0 ? "." + ASM.patchVersion : "", ASM.maxVersion);
}
/**
@@ -115,7 +159,9 @@ public final class ASM {
private static int detectVersion() {
int apiVersion = Opcodes.ASM4;
VersionNumber packageVersion = ASM.getPackageVersion(Opcodes.class);
for (Field field : Opcodes.class.getDeclaredFields()) {
if (field.getType() != Integer.TYPE) {
continue;
@@ -135,7 +181,12 @@ public final class ASM {
if (!experimental) {
apiVersion = version;
ASM.majorVersion = major;
ASM.minorVersion = minor;
ASM.minorVersion = ASM.implMinorVersion = minor;
if (packageVersion.getMajor() == major && minor == 0) {
ASM.implMinorVersion = packageVersion.getMinor();
ASM.patchVersion = packageVersion.getPatch();
}
}
}
} else if (name.matches("V([0-9_]+)")) {
@@ -158,4 +209,18 @@ public final class ASM {
return apiVersion;
}
private static VersionNumber getPackageVersion(Class<?> clazz) {
String implVersion = clazz.getPackage().getImplementationVersion();
if (implVersion != null) {
return VersionNumber.parse(implVersion);
}
try {
MainAttributes manifest = MainAttributes.of(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
return VersionNumber.parse(manifest.get(Attributes.Name.IMPLEMENTATION_VERSION));
} catch (Exception ex) {
return VersionNumber.NONE;
}
}
}
@@ -110,6 +110,7 @@ public final class ClassNodeAdapter {
public static void setNestMembers(ClassNode classNode, List<String> nestMembers) {
if (ASM.isAtLeastVersion(7)) {
classNode.nestMembers = nestMembers;
return;
}
if (ClassNodeAdapter.fdNestMembers == null || ClassNodeAdapter.notSupported) {