Merge remote-tracking branch 'remotes/upstream/0.8' into fabric-0.8

# Conflicts:
#	build.gradle
#	src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java
#	src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java
This commit is contained in:
modmuss50 committed 2019-11-03 12:11:33 +00:00
commit 57eefe4e22
66 files changed
+2081 -806

No files matched your search

+6
View File
@@ -97,10 +97,16 @@ plugin developed by [DemonWav](https://github.com/demonwav).
<li>Fixed issue in LVT generator folded in from FabricMC</li>
<li>Fail-fast when a <tt>final</tt> method is accidentally hidden
by a mixin</li>
<li>Fix the appearance of stray <tt>CallbackInfo</tt> instances in
local capture injector LVTs</li>
</ul>
</li>
<li>Apache Commons-IO Dependency removed</li>
<li>Renamed shaded ASM removed</li>
<li>Improved resolution of local variables for local variable capture
injections</li>
<li><tt>&#064;Coerce</tt> on callback injectors and redirects can now
resolve super interfaces including mixed-in interfaces</li>
</ul>
</td>
</tr>
+16 -10
View File
@@ -109,15 +109,15 @@ dependencies {
def guava = 'com.google.guava:guava:21.0' // from mc1.12 onwards
def log4j2 = 'org.apache.logging.log4j:log4j-core:2.0-beta9'
compile guava
compile log4j2
implementation guava
implementation log4j2
compile 'com.google.code.gson:gson:2.2.4'
if (Float.parseFloat(asmVersion) < 6) {
compile "org.ow2.asm:asm-debug-all:$asmVersion"
}
compile "org.ow2.asm:asm-tree:$asmVersion"
compile "org.ow2.asm:asm-commons:$asmVersion"
compile "org.ow2.asm:asm-util:$asmVersion"
implementation "org.ow2.asm:asm-tree:$asmVersion"
implementation "org.ow2.asm:asm-commons:$asmVersion"
implementation "org.ow2.asm:asm-util:$asmVersion"
thinJar "org.ow2.asm:asm-tree:$asmVersion"
thinJar "org.ow2.asm:asm-util:$asmVersion"
@@ -133,18 +133,22 @@ dependencies {
// AP extension example
exampleCompile configurations.compile
exampleImplementation configurations.implementation
// Fernflower decompiler
fernflowerCompile configurations.compile
fernflowerImplementation configurations.implementation
fernflowerCompile 'org.jetbrains:intellij-fernflower:1.0.0.9'
// LegacyLauncher service
launchwrapperCompile configurations.compile
launchwrapperImplementation configurations.implementation
launchwrapperCompile ('net.minecraft:launchwrapper:1.11') {
exclude module: 'lwjgl'
}
modlauncherCompile configurations.compile
modlauncherImplementation configurations.implementation
modlauncherCompile 'net.sf.jopt-simple:jopt-simple:5.0.4'
modlauncherCompile "org.ow2.asm:asm-tree:$modlauncherAsmVersion"
modlauncherCompile "org.ow2.asm:asm-commons:$modlauncherAsmVersion"
@@ -155,7 +159,8 @@ dependencies {
// agent
agentCompile configurations.compile
agentImplementation configurations.implementation
// asm bridge
bridgeCompile log4j2
bridgeCompile "org.ow2.asm:asm-commons:$legacyForgeAsmVersion"
@@ -271,12 +276,12 @@ build.dependsOn(shadowJar)
if (project.doSignJar) {
// Define signjar task
task signJar() {
inputs.files(jar.outputs)
outputs.files jar.outputs.files.collect {
inputs.files(stagingJar.outputs)
outputs.files stagingJar.outputs.files.collect {
new File(it.parent, it.name.replace('-unsigned', ''))
}
doLast {
jar.outputs.files.each {
stagingJar.outputs.files.each {
ant.signjar(
alias: project.keyStoreCert,
jar: it,
@@ -285,7 +290,8 @@ if (project.doSignJar) {
storepass: project.keyStoreSecret,
keypass: project.keyStoreSecret,
tsaurl: project.timestampAuthority,
preservelastmodified: 'true'
preservelastmodified: 'true',
verbose: true
)
}
}
@@ -182,8 +182,8 @@ public class MixinAgent implements IHotSwap {
}
@Override
public void registerTargetClass(String name, byte[] bytecode) {
MixinAgent.classLoader.addTargetClass(name, bytecode);
public void registerTargetClass(String name, ClassNode classNode) {
MixinAgent.classLoader.addTargetClass(name, classNode);
}
/**
@@ -228,4 +228,5 @@ public class MixinAgent implements IHotSwap {
public static void agentmain(String arg, Instrumentation instrumentation) {
MixinAgent.init(instrumentation);
}
}
@@ -33,6 +33,7 @@ import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.util.Constants;
@@ -78,10 +79,23 @@ class MixinAgentClassLoader extends ClassLoader {
* Registers the bytecode for a class targeted by a mixin
*
* @param name Name of the target clas
* @param bytecode Bytecode of the target class
* @param classNode ASM tree node of the target class
*/
void addTargetClass(String name, byte[] bytecode) {
this.targets.put(name, bytecode);
void addTargetClass(String name, ClassNode classNode) {
synchronized (this.targets) {
if (this.targets.containsKey(name)) {
return;
}
try {
ClassWriter cw = new ClassWriter(0);
classNode.accept(cw);
this.targets.put(name, cw.toByteArray());
} catch (Exception ex) {
MixinAgentClassLoader.logger.error("Error storing original class bytecode for {} in mixin hotswap agent. {}: {}",
name, ex.getClass().getName(), ex.getMessage());
MixinAgentClassLoader.logger.debug(ex);
}
}
}
/**
@@ -101,7 +115,9 @@ class MixinAgentClassLoader extends ClassLoader {
* @return Original bytecode
*/
byte[] getOriginalTargetBytecode(String name) {
return this.targets.get(name);
synchronized (this.targets) {
return this.targets.get(name);
}
}
/**
@@ -127,4 +143,5 @@ class MixinAgentClassLoader extends ClassLoader {
cw.visitEnd();
return cw.toByteArray();
}
}
@@ -28,7 +28,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.processing.Messager;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
@@ -44,6 +43,7 @@ import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjector;
import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerOverwrite.AnnotatedElementOverwrite;
import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass;
@@ -68,7 +68,7 @@ class AnnotatedMixin {
/**
* Messager
*/
private final Messager messager;
private final IMessagerSuppressible messager;
/**
* Type handle provider
@@ -215,21 +215,22 @@ class AnnotatedMixin {
// Private targets, referenced by name
try {
for (String privateTarget : this.annotation.<String>getList("targets")) {
TypeHandle type = this.typeProvider.getTypeHandle(privateTarget);
for (String softTarget : this.annotation.<String>getList("targets")) {
TypeHandle type = this.typeProvider.getTypeHandle(softTarget);
if (this.targets.contains(type)) {
continue;
}
if (this.virtual) {
type = this.typeProvider.getSimulatedHandle(privateTarget, this.mixin.asType());
type = this.typeProvider.getSimulatedHandle(softTarget, this.mixin.asType());
} else if (type == null) {
this.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this);
this.printMessage(Kind.ERROR, "Mixin target " + softTarget + " could not be found", this);
return null;
} else if (type.isPublic()) {
this.printMessage(Kind.WARNING, "Mixin target " + privateTarget + " is public and must be specified in value", this);
SuppressedBy suppressedBy = (type.getPackage().isUnnamed()) ? SuppressedBy.DEFAULT_PACKAGE : null;
this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " is public and must be specified in value", this, suppressedBy);
return null;
}
this.addSoftTarget(type, privateTarget);
this.addSoftTarget(type, softTarget);
if (primaryTarget == null) {
primaryTarget = type;
}
@@ -251,6 +252,13 @@ class AnnotatedMixin {
private void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) {
this.messager.printMessage(kind, msg, this.mixin, this.annotation.asMirror());
}
/**
* Print a suppressible message to the AP messager
*/
private void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin, SuppressedBy suppressedBy) {
this.messager.printMessage(kind, msg, this.mixin, this.annotation.asMirror(), suppressedBy);
}
private void addSoftTarget(TypeHandle type, String reference) {
ObfuscationData<String> obfClassData = this.obf.getDataProvider().getObfClass(type);
@@ -374,7 +374,7 @@ abstract class AnnotatedMixinElementHandler {
this.ap.printMessage(Kind.ERROR, ex.getMessage(), method, annotation.asMirror());
}
} catch (InvalidConstraintException ex) {
this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation.asMirror(), "constraints");
this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation.asMirror(), SuppressedBy.CONSTRAINTS);
}
}
@@ -421,7 +421,7 @@ abstract class AnnotatedMixinElementHandler {
this.validateMethodVisibility(method, annotation, type, target, targetMethod);
}
} else if (!merge) {
this.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation, "target");
this.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation, SuppressedBy.TARGET);
}
}
}
@@ -436,9 +436,11 @@ abstract class AnnotatedMixinElementHandler {
Visibility visMethod = TypeUtils.getVisibility(method);
String visibility = "visibility of " + visTarget + " method in " + target;
if (visTarget.ordinal() > visMethod.ordinal()) {
this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation, "visibility");
this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation,
SuppressedBy.VISIBILITY);
} else if (visTarget == Visibility.PRIVATE && visMethod.ordinal() > visTarget.ordinal()) {
this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation, "visibility");
this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation,
SuppressedBy.VISIBILITY);
}
}
@@ -469,7 +471,8 @@ abstract class AnnotatedMixinElementHandler {
}
if (targetField == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, annotation.asMirror(), "target");
this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, annotation.asMirror(),
SuppressedBy.TARGET);
}
}
}
@@ -493,12 +496,13 @@ abstract class AnnotatedMixinElementHandler {
MethodHandle targetMethod = target.findMethod(nameRef.getName(), signature);
if (targetMethod == null) {
this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(), "target");
this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(),
SuppressedBy.TARGET);
}
}
}
private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation, String suppressedBy) {
private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation, SuppressedBy suppressedBy) {
if (annotation == null) {
this.ap.printMessage(kind, msg, e, suppressedBy);
} else {
@@ -45,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorExcep
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException;
import org.spongepowered.tools.obfuscation.ext.SpecialPackages;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor.CompilerEnvironment;
import org.spongepowered.tools.obfuscation.interfaces.IReferenceManager;
@@ -292,9 +293,9 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
String desc = member.toCtorDesc();
MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V");
ObfuscationData<MappingMethod> remapped = this.obf.getDataProvider().getRemappedMethod(m);
if (remapped.isEmpty()) {
if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) {
this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(),
elem.getAnnotation().asMirror(), "mapping");
elem.getAnnotation().asMirror(), SuppressedBy.MAPPING);
return;
}
@@ -345,19 +346,21 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
if (targetMember.isField()) {
ObfuscationData<MappingField> obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember);
if (obfFieldData.isEmpty()) {
this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(),
errorsOn, "mapping");
if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) {
this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(),
errorsOn, SuppressedBy.MAPPING);
}
return;
}
this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData);
} else {
ObfuscationData<MappingMethod> obfMethodData = this.obf.getDataProvider().getObfMethodRecursive(targetMember);
if (obfMethodData.isEmpty()) {
if (targetMember.getOwner() == null || !targetMember.getOwner().startsWith("java/lang/")) {
if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) {
this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(),
errorsOn, "mapping");
return;
errorsOn, SuppressedBy.MAPPING);
}
return;
}
this.obf.getReferenceManager().addMethodMapping(this.classRef, reference, targetMember, obfMethodData);
}
@@ -86,16 +86,16 @@ class AnnotatedMixinElementHandlerOverwrite extends AnnotatedMixinElementHandler
String javadoc = this.ap.getJavadocProvider().getJavadoc(elem.getElement());
if (javadoc == null) {
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", elem.getElement(), "overwrite");
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", elem.getElement(), SuppressedBy.OVERWRITE);
return;
}
if (!javadoc.toLowerCase(Locale.ROOT).contains("@author")) {
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", elem.getElement(), "overwrite");
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", elem.getElement(), SuppressedBy.OVERWRITE);
}
if (!javadoc.toLowerCase(Locale.ROOT).contains("@reason")) {
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", elem.getElement(), "overwrite");
this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", elem.getElement(), SuppressedBy.OVERWRITE);
}
}
}
@@ -59,6 +59,7 @@ import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.util.ITokenProvider;
import org.spongepowered.asm.util.VersionNumber;
import org.spongepowered.tools.obfuscation.interfaces.IJavadocProvider;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator;
@@ -83,6 +84,8 @@ import com.google.common.collect.ImmutableList.Builder;
final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITypeHandleProvider, IJavadocProvider {
private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid";
private static final String RECOMMENDED_MIXINGRADLE_VERSION = "0.7";
/**
* Singleton instances for each ProcessingEnvironment
@@ -143,6 +146,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
this.processingEnv = processingEnv;
this.printMessage(Kind.NOTE, "SpongePowered MIXIN Annotation Processor Version=" + MixinBootstrap.VERSION);
this.checkPluginVersion(this.getOption(SupportedOptions.PLUGIN_VERSION));
this.targets = this.initTargetMap();
this.obf = new ObfuscationManager(this);
@@ -152,10 +156,28 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
new ParentValidator(this),
new TargetValidator(this)
);
this.initTokenCache(this.getOption(SupportedOptions.TOKENS));
}
/**
* If MixinGradle is in use, check the version. This will allow us to notify
* the user if the version of MixinGradle is out of date relative to the
* Mixin library version
*/
private void checkPluginVersion(String version) {
if (version == null) {
return;
}
VersionNumber pluginVersion = VersionNumber.parse(version);
VersionNumber recommendedVersion = VersionNumber.parse(AnnotatedMixins.RECOMMENDED_MIXINGRADLE_VERSION);
if (pluginVersion.compareTo(recommendedVersion) < 0) {
this.printMessage(Kind.WARNING, String.format("MixinGradle version %s is out of date. Update to the recommended version %s",
pluginVersion, recommendedVersion));
}
}
protected TargetMap initTargetMap() {
TargetMap targets = TargetMap.create(System.getProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY));
System.setProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY, targets.getSessionId());
@@ -513,11 +535,11 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
return annotation.getBoolean("remap", mixinClass.remap());
}
private static boolean shouldSuppress(Element element, String suppressedBy) {
private static boolean shouldSuppress(Element element, SuppressedBy suppressedBy) {
if (element == null || suppressedBy == null) {
return false;
}
if (AnnotationHandle.of(element, SuppressWarnings.class).<String>getList().contains(suppressedBy)) {
if (AnnotationHandle.of(element, SuppressWarnings.class).<String>getList().contains(suppressedBy.getToken())) {
return true;
}
return AnnotatedMixins.shouldSuppress(element.getEnclosingElement(), suppressedBy);
@@ -545,7 +567,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
* Print a message to the AP messager
*/
@Override
public void printMessage(Kind kind, CharSequence msg, Element element, String suppressedBy) {
public void printMessage(Kind kind, CharSequence msg, Element element, SuppressedBy suppressedBy) {
if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) {
this.processingEnv.getMessager().printMessage(kind, msg, element);
}
@@ -563,7 +585,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
* Print a message to the AP messager
*/
@Override
public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, String suppressedBy) {
public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, SuppressedBy suppressedBy) {
if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) {
this.processingEnv.getMessager().printMessage(kind, msg, element, annotation);
}
@@ -581,7 +603,8 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider
* Print a message to the AP messager
*/
@Override
public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value, String suppressedBy) {
public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value,
SuppressedBy suppressedBy) {
if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) {
this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value);
}
@@ -46,6 +46,7 @@ public final class SupportedOptions {
public static final String DEFAULT_OBFUSCATION_ENV = "defaultObfuscationEnv";
public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile";
public static final String MAPPING_TYPES = "mappingTypes";
public static final String PLUGIN_VERSION = "pluginVersion";
private SupportedOptions() {}
@@ -0,0 +1,81 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
/**
* A centralised list of tokens supported by the AP for use in
* {@link SuppressWarnings} annotations. Collected here mainly for
* self-documentation purposes.
*/
public enum SuppressedBy {
/**
* Suppress warnings for constraint violations
*/
CONSTRAINTS("constraints"),
/**
* Suppress warnings about overwrite visibility upgrading/downgrading target
* visibility
*/
VISIBILITY("visibility"),
/**
* Suppress warnings when an injector target cannot be found
*/
TARGET("target"),
/**
* Suppress warnings when a class, method or field mapping cannot be located
*/
MAPPING("mapping"),
/**
* Suppress warnings for when an <tt>&#064;Overwrite</tt> method is missing
* javadoc, or author or reason tags
*/
OVERWRITE("overwrite"),
/**
* Suppress warnings when a mixin target specified by name is located in the
* default package
*/
DEFAULT_PACKAGE("default-package");
private final String token;
private SuppressedBy(String token) {
this.token = token;
}
/**
* Get the string token which is used in the {@link SuppressWarnings}
* annotation
*/
public String getToken() {
return this.token;
}
}
@@ -0,0 +1,80 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.ext;
import java.util.HashSet;
import java.util.Set;
/**
* Centralised registry of packages with special handling by the AP. This is
* public and centralised
*/
public final class SpecialPackages {
private static final Set<String> suppressWarningsForPackages = new HashSet<String>();
static {
SpecialPackages.addExcludedPackage("java.");
SpecialPackages.addExcludedPackage("javax.");
SpecialPackages.addExcludedPackage("sun.");
SpecialPackages.addExcludedPackage("com.sun.");
}
private SpecialPackages() {
}
/**
* Add a package to exclude from remapping warnings. This only suppresses
* warnings if a mapping is not found and does not attempt to short-circuit
* the mapping process. Thus if a mapping is present for the element in
* question then the behaviour is preserved. Adding a package here simply
* suppresses warnings if no mapping is found.
*
* @param packageName Package name, including trailing period or slash
*/
public static final void addExcludedPackage(String packageName) {
String internalName = packageName.replace('.', '/');
if (!internalName.endsWith("/")) {
internalName += "/";
}
SpecialPackages.suppressWarningsForPackages.add(internalName);
}
/**
* Check whether a package is in the exclusion set.
*
* @param internalName Internal class or package name
* @return true if warnings for the supplied package should be suppressed
*/
public static boolean isExcludedPackage(String internalName) {
for (String prefix : SpecialPackages.suppressWarningsForPackages) {
if (internalName.startsWith(prefix)) {
return true;
}
}
return false;
}
}
@@ -30,6 +30,8 @@ import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic;
import org.spongepowered.tools.obfuscation.SuppressedBy;
/**
* An extended {@link Messager} which supports messages that can be suppressed
* using the standard Java {@link SuppressWarnings} annotation.
@@ -46,7 +48,7 @@ public interface IMessagerSuppressible extends Messager {
* @param suppressedBy the {@link SuppressWarnings} value which will silence
* this message
*/
void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, String suppressedBy);
void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, SuppressedBy suppressedBy);
/**
* Prints a message of the specified kind at the location of the
@@ -59,7 +61,7 @@ public interface IMessagerSuppressible extends Messager {
* @param suppressedBy the {@link SuppressWarnings} value which will silence
* this message
*/
void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, String suppressedBy);
void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, SuppressedBy suppressedBy);
/**
* Prints a message of the specified kind at the location of the
@@ -74,7 +76,7 @@ public interface IMessagerSuppressible extends Messager {
* @param suppressedBy the {@link SuppressWarnings} value which will silence
* this message
*/
void printMessage(Diagnostic.Kind kind,CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v, String suppressedBy);
void printMessage(Diagnostic.Kind kind,CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v, SuppressedBy suppressedBy);
}
@@ -66,7 +66,7 @@ public class MappingWriterTSrg extends MappingWriterSrg {
@Override
protected String formatFieldMapping(Pair<MappingField> field) {
return String.format("%s %s %s %s", field.from.getOwner(), field.from.getSimpleName(), field.to.getSimpleName());
return String.format("%s %s %s", field.from.getOwner(), field.from.getSimpleName(), field.to.getSimpleName());
}
@Override
@@ -29,6 +29,8 @@ import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.spongepowered.asm.service.IClassTracker;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
@@ -37,7 +39,7 @@ import net.minecraft.launchwrapper.LaunchClassLoader;
* them to perform some validation tasks, and insert entries for mixin "classes"
* into the invalid classes set.
*/
final class LaunchClassLoaderUtil {
final class LaunchClassLoaderUtil implements IClassTracker {
private static final String CACHED_CLASSES_FIELD = "cachedClasses";
private static final String INVALID_CLASSES_FIELD = "invalidClasses";
@@ -67,7 +69,7 @@ final class LaunchClassLoaderUtil {
this.classLoaderExceptions = LaunchClassLoaderUtil.<Set<String>>getField(classLoader, LaunchClassLoaderUtil.CLASS_LOADER_EXCEPTIONS_FIELD);
this.transformerExceptions = LaunchClassLoaderUtil.<Set<String>>getField(classLoader, LaunchClassLoaderUtil.TRANSFORMER_EXCEPTIONS_FIELD);
}
/**
* Get the classloader
*/
@@ -82,10 +84,27 @@ final class LaunchClassLoaderUtil {
* @param name class name
* @return true if the class name exists in the cache
*/
boolean isClassLoaded(String name) {
@Override
public boolean isClassLoaded(String name) {
return this.cachedClasses.containsKey(name);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getClassRestrictions(
* java.lang.String)
*/
@Override
public String getClassRestrictions(String className) {
String restrictions = "";
if (this.isClassClassLoaderExcluded(className, null)) {
restrictions = "PACKAGE_CLASSLOADER_EXCLUSION";
}
if (this.isClassTransformerExcluded(className, null)) {
restrictions = (restrictions.length() > 0 ? restrictions + "," : "") + "PACKAGE_TRANSFORMER_EXCLUSION";
}
return restrictions;
}
/**
* Get whether the specified name or transformedName exist in either of the
* exclusion lists
@@ -143,7 +162,8 @@ final class LaunchClassLoaderUtil {
*
* @param name class name
*/
void registerInvalidClass(String name) {
@Override
public void registerInvalidClass(String name) {
if (this.invalidClasses != null) {
this.invalidClasses.add(name);
}
@@ -52,8 +52,10 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.service.IClassBytecodeProvider;
import org.spongepowered.asm.service.IClassProvider;
import org.spongepowered.asm.service.IClassTracker;
import org.spongepowered.asm.service.ILegacyClassTransformer;
import org.spongepowered.asm.service.ITransformer;
import org.spongepowered.asm.service.ITransformerProvider;
import org.spongepowered.asm.service.MixinServiceAbstract;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.perf.Profiler;
@@ -72,7 +74,7 @@ import net.minecraft.launchwrapper.Launch;
/**
* Mixin service for launchwrapper
*/
public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements IClassProvider, IClassBytecodeProvider {
public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements IClassProvider, IClassBytecodeProvider, ITransformerProvider {
// Blackboard keys
public static final Keys BLACKBOARD_KEY_TWEAKCLASSES = Keys.of("TweakClasses");
@@ -259,6 +261,22 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getTransformerProvider()
*/
@Override
public ITransformerProvider getTransformerProvider() {
return this;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getClassTracker()
*/
@Override
public IClassTracker getClassTracker() {
return this.classLoaderUtil;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IClassProvider#findClass(
* java.lang.String)
@@ -315,40 +333,6 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I
return Launch.classLoader.getResourceAsStream(name);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#registerInvalidClass(
* java.lang.String)
*/
@Override
public void registerInvalidClass(String className) {
this.classLoaderUtil.registerInvalidClass(className);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#isClassLoaded(
* java.lang.String)
*/
@Override
public boolean isClassLoaded(String className) {
return this.classLoaderUtil.isClassLoaded(className);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getClassRestrictions(
* java.lang.String)
*/
@Override
public String getClassRestrictions(String className) {
String restrictions = "";
if (this.classLoaderUtil.isClassClassLoaderExcluded(className, null)) {
restrictions = "PACKAGE_CLASSLOADER_EXCLUSION";
}
if (this.classLoaderUtil.isClassTransformerExcluded(className, null)) {
restrictions = (restrictions.length() > 0 ? restrictions + "," : "") + "PACKAGE_TRANSFORMER_EXCLUSION";
}
return restrictions;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IClassProvider#getClassPath()
*/
@@ -43,4 +43,5 @@ public @interface Implements {
* @return list of interfaces to implement
*/
public Interface[] value();
}
@@ -24,15 +24,15 @@
*/
package org.spongepowered.asm.mixin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* I'm probably going to the special hell for this
* This annotation is used to define information for a soft-implemented
* interface. See {@link Implements} for details.
*/
@Target(ElementType.TYPE)
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.CLASS)
public @interface Interface {
@@ -47,6 +47,7 @@ import org.spongepowered.asm.mixin.transformer.IMixinTransformer;
import org.spongepowered.asm.obfuscation.RemapperChain;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.ITransformer;
import org.spongepowered.asm.service.ITransformerProvider;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.service.MixinServiceAbstract;
import org.spongepowered.asm.util.CompareUtil;
@@ -1066,6 +1067,20 @@ public final class MixinEnvironment implements ITokenProvider {
return mixinConfigs;
}
/**
* Add a mixin configuration to the blackboard
*
* @param config Name of configuration resource to add
* @return fluent interface
* @deprecated use Mixins::addConfiguration instead
*/
@Deprecated
public MixinEnvironment addConfiguration(String config) {
MixinEnvironment.logger.warn("MixinEnvironment::addConfiguration is deprecated and will be removed. Use Mixins::addConfiguration instead!");
Mixins.addConfiguration(config, this);
return this;
}
void registerConfig(String config) {
List<String> configs = this.getMixinConfigs();
if (!configs.contains(config)) {
@@ -1301,7 +1316,8 @@ public final class MixinEnvironment implements ITokenProvider {
@Deprecated
public List<ITransformer> getTransformers() {
MixinEnvironment.logger.warn("MixinEnvironment::getTransformers is deprecated!");
return (List<ITransformer>)this.service.getTransformers();
ITransformerProvider transformers = this.service.getTransformerProvider();
return transformers != null ? (List<ITransformer>)transformers.getTransformers() : Collections.<ITransformer>emptyList();
}
/**
@@ -1313,7 +1329,10 @@ public final class MixinEnvironment implements ITokenProvider {
@Deprecated
public void addTransformerExclusion(String name) {
MixinEnvironment.logger.warn("MixinEnvironment::addTransformerExclusion is deprecated!");
this.service.addTransformerExclusion(name);
ITransformerProvider transformers = this.service.getTransformerProvider();
if (transformers != null) {
transformers.addTransformerExclusion(name);
}
}
/* (non-Javadoc)
@@ -125,4 +125,5 @@ public @interface Shadow {
* @return Aliases for this member
*/
public String[] aliases() default { };
}
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.points.*;
@@ -44,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.points.*;
* should be consulted for the meaning of the argument to that particular class.
* A general description of each parameter is provided below.
*/
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.RUNTIME)
public @interface At {
@@ -33,13 +33,16 @@ import java.lang.annotation.Target;
* <p>This annotation has two usages applicable to Callback Injectors (defined
* using {@link Inject &#064;Inject}. For local capture injectors, it indicates
* that the injector should coerce top-level primitive types (int) to covariant
* types defined on the handler. For other injectors, it can be used on a
* reference type to indicate that the intended type is covariant over the
* argument type (or that the argument type is contravariant on the target class
* type). This can be used for multi-target injectors with a bounded type
* argument on the class or target method.</p>
* types defined on the handler. It can also be used on a reference type to
* indicate that the intended type is covariant over the argument type (or that
* the argument type is contravariant on the target class type). This can be
* used for multi-target injectors with a bounded type argument on the class or
* target method. It is also acceptable to use an interface directly or
* indirectly implemented by the relevant class, including interfaces applied by
* other mixins.</p>
*
* <p>During LVT generation it is not always possible to inflect the exact local
* <p><tt>&#064;Coerce</tt> also has an important usage with primitive types. It
* is not always possible during LVT generation to determine the exact local
* type for types represented internally as integers, for example booleans and
* shorts. However adding a surrogate for these cases is overkill when the type
* is known for certain by the injector. Since the bytecode for all types stored
@@ -56,8 +59,15 @@ import java.lang.annotation.Target;
* indicate that an incoming parameter can be consumed as a valid supertype, up
* to and including {@link Object}. This is particularly useful when an argument
* on the target method invocation is inaccessible or unknown.</p>
*
* <p>Since Mixin <tt>0.8</tt> it is also possible to use <tt>&#064;Coerce</tt>
* on the return type of a <em>field gettter</em> or <em>method invocation</em>
* redirector. To do so simply annotate the method itself. Note that doing so
* will cast the return type back to the original return type as part of the
* injection, so the object must be of an appropriate type regardless of
* visibility.</p>
*/
@Target({ ElementType.PARAMETER })
@Target({ ElementType.PARAMETER, ElementType.METHOD })
public @interface Coerce {
}
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.objectweb.asm.Opcodes;
@@ -39,6 +40,7 @@ import org.objectweb.asm.Opcodes;
* appropriate argument. Specifying values of different types will cause an
* error to be raised by the injector.</p>
*/
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.RUNTIME)
public @interface Constant {
@@ -31,6 +31,7 @@ import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
@@ -41,6 +42,65 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* Specifies that this mixin method should inject a callback (or
* callback<b>s</b>) to itself in the target method(s) identified by
* {@link #method}.
*
* <p>Callbacks are simple injectors which simply inject a call to the decorated
* method (the <em>handler</em>) in the <em>target</em> method (or methods)
* selected by the selectors specified in {@link #method}. Callback Injectors
* can also capture arguments and local variables from the <em>target</em> for
* use in the handler.</p>
*
* <p>Callback handler methods should always return <tt>void</tt> and should
* have the same <tt>static</tt>-ness as their target (though it is allowable to
* have a <tt>static</tt> callback injected into an instance method, and for
* obvious reasons the inverse is not permitted).</p>
*
* <h3>Basic usage</h3>
*
* <p>The simplest usage of <tt>&#064;Inject</tt> captures no context from the
* target scope. This is particularly useful if the injector is targetting
* multiple methods with different signatures. In this case only the
* {@link CallbackInfo} (or {@link CallbackInfoReturnable} as appropriate) is
* required.</p>
*
* <blockquote><tt>private void onSomeEvent(CallbackInfo ci)</tt></blockquote>
*
* <h3>Capture target arguments</h3>
*
* <p>Callbacks can also capture the arguments passed to the target method. To
* do so specify the target arguments before the {@link CallbackInfo}:</p>
*
* <blockquote><tt>private void onSomeEvent(int arg1, String arg2,
* CallbackInfo ci)</tt></blockquote>
*
* <h3>Surrogate methods</h3>
*
* <p>If injecting into multiple methods with different target arguments it is
* obviously possible to ignore the target arguments (see "Basic Usage" above)
* but this may be unsuitable if arguments from the target are required. If you
* need to inject into multiple methods but also wish to capture method
* arguments you may provide a <em>surrogate</em> method with the alternative
* signature. In fact you may provide as many surrogates as required by the
* injection. Surrogate methods much have the same name as the handler method
* and must be decorated with {@link Surrogate}. A surrogate may also be
* required where the LVT of a method with <em>local capture</em> (see below) is
* known to change between different environments or injection points.</p>
*
* <h3>Capture local variables</h3>
*
* <p>In addition to capturing the target method arguments, it may be desirable
* to capture locally-scoped variables from the target method at the point of
* injection. This is usually executed in two stages:</p>
*
* <ol>
* <li>Set the {@link #locals()} value of your injection to
* {@link LocalCapture#PRINT} and run the application.</li>
* <li>When the injector is processed, a listing of the LVT is produced
* accompanied by a generated signature for your handler method including
* the discovered args. Modify your handler signature accordingly.</li>
* </ol>
*
* <p>For more details see {@link #locals()}.</p>
*
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -114,6 +174,13 @@ public @interface Inject {
* surrogate targets for the orphaned injector by annotating them with an
* {@link Surrogate} annotation.</p>
*
* <p>You can improve the robustness of your local capture injection by only
* specifying locals up to the last variable you wish to use. For example if
* the target LVT contains <tt>&lt;int, int, int, float, String&gt;</tt> and
* you only need the <tt>float</tt> value, you can choose to omit the unused
* <tt>String</tt> and changes to the LVT beyond that point will not affect
* your injection.</p>
*
* <p>It is also important to nominate the failure behaviour to follow when
* local capture fails and so all {@link LocalCapture} behaviours which
* specify a capture action imply a particular behaviour for handling
@@ -63,6 +63,10 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* type exists in the target LVT, then capture will succeed. However, if more
* than one variable of the required type is encountered in the LVT then an
* {@link InvalidInjectionException} is thrown.</p>
*
* <p>Like other injectors, the callback signature can optionally include the
* target method arguments by simply appending them to the handler method
* signature.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@@ -87,9 +91,7 @@ public @interface ModifyVariable {
/**
* An {@link At} annotation which describes the {@link InjectionPoint} in
* the target method. The specified {@link InjectionPoint} <i>must only</i>
* return {@link org.objectweb.asm.tree.MethodInsnNode} instances
* and an exception will be thrown if this is not the case.
* the target method.
*
* @return {@link At} which identifies the target method invocation
*/
@@ -31,6 +31,8 @@ import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
import org.spongepowered.asm.mixin.injection.points.BeforeInvoke;
import org.spongepowered.asm.mixin.injection.points.BeforeNew;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
@@ -41,7 +43,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* method call, field access or object construction (via the <tt>new</tt>
* keyword) to the method decorated with this annotation.</p>
*
* <h4>Method Redirect Mode</h4>
* <h3>Method Redirect Mode</h3>
*
* <p>The handler method signature must match the hooked method precisely
* <b>but</b> prepended with an arg of the owning object's type to accept the
@@ -65,7 +67,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* </blockquote>
*
* <p>For obvious reasons this does not apply for static methods, for static
* methods it is sufficient that the signature simply match the hooked method.
* methods it is sufficient that the signature simply match the redirected
* method.
* </p>
*
* <p>It is also possible to capture the arguments of the target method in
@@ -78,7 +81,12 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* int someInt, String someString)</pre>
* </blockquote>
*
* <h4>Field Access Redirect Mode</h4>
* <p>All arguments of a method redirect handler, and the return type, can be
* decorated with {@link Coerce} if - for example - a package-private class
* needs to be coerced to a duck interface or to (for example) <tt>Object</tt>.
* </p>
*
* <h3>Field Access Redirect Mode</h3>
*
* <p>The handler method signature varies depending on whether the redirector is
* handling a field <b>write</b> (<tt>PUTFIELD</tt>, <tt>PUTSTATIC</tt>) or a
@@ -91,21 +99,22 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* </tr>
* <tr>
* <td>Read static field (<tt>GETSTATIC</tt>)</td>
* <td><code>private <b>FieldType</b> getFieldValue()</code></td>
* <td><code>private static <b>FieldType</b> getFieldValue()</code></td>
* </tr>
* <tr>
* <td>Read instance field (<tt>GETFIELD</tt>)</td>
* <td><code>private <b>FieldType</b> getFieldValue(<b>OwnerType</b>
* owner)</code></td>
* owner)</code></td>
* </tr>
* <tr>
* <td>Write static field (<tt>PUTSTATIC</tt>)</td>
* <td><code>private void setFieldValue(<b>FieldType</b> value)</code></td>
* <td><code>private static void setFieldValue(<b>FieldType</b> value)
* </code></td>
* </tr>
* <tr>
* <td>Write instance field (<tt>PUTFIELD</tt>)</td>
* <td><code>private void setFieldValue(<b>OwnerType</b>
* owner, <b>FieldType</b> value)</code></td>
* owner, <b>FieldType</b> value)</code></td>
* </tr>
* </table>
*
@@ -114,7 +123,13 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* the code above this would be the <em>someInt</em> and <em>someString</em>
* arguments) by appending the arguments to the method signature.</p>
*
* <h4>Array Element Access Redirect Mode</h4>
* <p>All arguments of a field redirect handler, including the field type
* itself, can be decorated with {@link Coerce} if - for example - a
* package-private class needs to be coerced to a duck interface or to (for
* example) <tt>Object</tt>.
* </p>
*
* <h3>Array Element Access Redirect Mode</h3>
*
* <p>For fields of an array type, it is possible to redirect the access to the
* actual array field itself using the behaviour above. However it is also
@@ -155,7 +170,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* {@link BeforeFieldAccess BeforeFieldAccess args} for details
* on matching array accesses using the <tt>FIELD</tt> injection point.</p>
*
* <h4>Array Length Redirect Mode</h4>
* <h3>Array Length Redirect Mode</h3>
*
* <p>For fields of an array type, it is possible to redirect the call to the
* builtin pseudo-property <tt>length</tt>. To do so, specify the argument
@@ -174,28 +189,105 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint;
* private <b>int</b> getLength(<b>ElementType</b>[][] array, int baseDim)
* </code></blockquote>
*
* <h4>Constructor Redirect Mode</h4>
* <h3>New Object Redirect Mode (Factory Mode)</h3>
*
* <p>Redirecting object creation requires redirection of the <tt>NEW</tt>
* operation and constructor call. Your handler method should target the <tt>NEW
* </tt> opcode using the {@link BeforeNew} Injection Point and construct an
* appropriate object. The factory method <b>must return a new object</b> and
* <b>must not</b> return <tt>null</tt> since the contract of the <tt>new</tt>
* opcode does not allow for the possibility of <tt>null</tt>. Your factory may
* throw an exception however.</p>
*
* <p>Note that {@link BeforeNew} differs from {@link BeforeInvoke} in that the
* shape of <tt>target</tt> should contain <em>only</em> an <tt>owner</tt> (to
* target any ctor of the specified class) or <em>only</em> a <tt>descriptor
* </tt> consisting of the constructor descriptor with the return type changed
* from <tt>void</tt> (<tt>V</tt>) to the type of object being constructed. In
* other words to redirect an object creation for an object <tt>Foo</tt>:</p>
*
* <blockquote><pre>package baz.bar;
*
*class Foo {
* private final int x, y;
*
* // ctor we wish to hook
* Foo(int x, int y) {
* this.x = x;
* this.y = y;
* }
*}</pre>
* </blockquote>
*
* <p>Valid signatures for this ctor would be:</p>
*
* <ul>
* <li><tt>Lbaz/bar/Foo;</tt> - valid because Foo only has one ctor</li>
* <li><tt>(II)Lbaz/bar/Foo;</tt> - includes signature of specific ctor</li>
* </ul>
*
* <p>The handler method signature must match the constructor being redirected
* and the return type must match the type of object being constructed. For
* example to redirect the following constructor call:</p>
* example to redirect the following object creation call:</p>
*
* <blockquote><pre>public void baz(int someInt, String someString) {
* <blockquote><pre>public void exampleFunc(String someString, int dx, int dy) {
* // Hooking this constructor
* Foo someObject = new Foo("bar");
* Foo someFoo = new Foo(dx * 10, dy * 10);
*}</pre>
* </blockquote>
*
* <p>The signature of the handler method should be:</p>
*
* <blockquote>
* <pre>public Foo constructFoo(String arg1)</pre>
* <pre>public Foo constructFoo(int x, int y)</pre>
* </blockquote>
*
* <p>Note that like other redirectors, it is possible to capture the target
* method's arguments by appending them to the handler method's signature.</p>
* method's arguments by appending them to the handler method's signature:</p>
*
* <h4>A note on <tt>static</tt> modifiers for handler methods</h4>
* <blockquote>
* <tt>public Foo constructFoo(int x, int y, String someString, int dx,
* int dy)</tt>
* </blockquote>
*
* <h3><tt>instanceof</tt> Redirect Mode</h3>
*
* <p>An <tt>instanceof</tt> check is a boolean operation where an object on the
* stack is compared with a class literal compiled directly into the bytecode.
* The check can be redirected in one of two ways: logic redirection or class
* type redirection. For the following example code:</p>
*
* <blockquote><pre>if (reference instanceof Foo) {</pre></blockquote>
*
* <p>To perform a <em>logic redirection</em>, use a handler with the following
* signature returning <tt>boolean</tt>:</p>
*
* <blockquote><pre>public boolean onInstanceOf(Object reference, Class clFoo) {
* return reference instanceof ADifferentClass;
*}</pre></blockquote>
*
* <p>Note that the entire check is moved into the redirect method, and the
* <tt>boolean</tt> return value is used in place of the previous <tt>instanceof
* </tt> check. To perform a <em>class type redirection</em> instead, construct
* your handler as follows:</p>
*
* <blockquote><pre>public Class onInstanceOf(Object reference, Class clFoo) {
* return ADifferentClass.class;
*}</pre></blockquote>
*
* <p>Note that this results in the injected code being less efficient, because
* the <tt>instanceof</tt> opcode is replaced with discrete code similar to <tt>
* reference != null && yourClass.isAssignableFrom(reference.getClass())</tt> in
* the target method body.</p>
*
* <p>The arguments to an <tt>instanceof</tt> redirect handler <b>must always be
* <tt>Object, Class</tt> even if the variable type is known</b>. This is
* because the type of variable on the stack cannot be determined without
* relatively expensive analysis, which is redundant given the redirect
* handler's role. If you need to cast-down the reference then you should do so
* inside your handler method.</p>
*
* <h3>A note on <tt>static</tt> modifiers for handler methods</h3>
*
* <p>In general, when declaring a redirect handler the <tt>static</tt> modifier
* of the handler method must always match the target method. The exception to
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
@@ -123,6 +124,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
* can distinguish different slices using {@link #id} and then specify the slice
* to use in the {@link At#slice} argument.</p>
*/
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.RUNTIME)
public @interface Slice {
@@ -170,7 +170,7 @@ public class CallbackInjector extends Injector {
this.node = node;
this.locals = locals;
this.localTypes = locals != null ? new Type[locals.length] : null;
this.frameSize = Bytecode.getFirstNonArgLocalIndex(target.arguments, !CallbackInjector.this.isStatic());
this.frameSize = Bytecode.getFirstNonArgLocalIndex(target.arguments, !target.isStatic);
List<String> argNames = null;
if (locals != null) {
@@ -190,7 +190,8 @@ public class CallbackInjector extends Injector {
}
// Calc number of args for the handler method, additional 1 is to ignore the CallbackInfo arg
this.extraArgs = Math.max(0, Bytecode.getFirstNonArgLocalIndex(this.handler) - (this.frameSize + 1));
Type[] handlerArgs = Type.getArgumentTypes(this.handler.desc);
this.extraArgs = Math.max(0, handlerArgs.length - target.arguments.length - 1);
this.argNames = argNames != null ? argNames.toArray(new String[argNames.size()]) : null;
this.canCaptureLocals = captureLocals && locals != null && locals.length > this.frameSize;
this.isAtReturn = this.node.getCurrentTarget() instanceof InsnNode && this.isValueReturnOpcode(this.node.getCurrentTarget().getOpcode());
@@ -426,6 +427,11 @@ public class CallbackInjector extends Injector {
if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) {
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/")) {
locals[j] = null;
}
}
}
this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals()));
@@ -523,8 +529,11 @@ public class CallbackInjector extends Injector {
*/
private String generateBadLVTMessage(final Callback callback) {
int position = callback.target.indexOf(callback.node);
List<String> expected = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), callback.target.arguments.length + 1);
List<String> found = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
List<String> expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1);
List<String> found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0));
if (expected.equals(found)) {
return String.format("Invalid descriptor on %s! Expected %s but found %s", this.info, callback.getDescriptor(), this.methodNode.desc);
}
return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s",
callback.target, position, this, expected, found);
}
@@ -558,7 +567,7 @@ public class CallbackInjector extends Injector {
private void printLocals(final Callback callback) {
Type[] args = Type.getArgumentTypes(callback.getDescriptorWithAllLocals());
SignaturePrinter methodSig = new SignaturePrinter(callback.target.method, callback.argNames);
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, callback.target.returnType, args, callback.argNames);
SignaturePrinter handlerSig = new SignaturePrinter(this.info.getMethodName(), callback.target.returnType, args, callback.argNames);
handlerSig.setModifiers(this.methodNode);
PrettyPrinter printer = new PrettyPrinter();
@@ -566,7 +575,7 @@ public class CallbackInjector extends Injector {
printer.kv("Target Method", methodSig);
printer.kv("Target Max LOCALS", callback.target.getMaxLocals());
printer.kv("Initial Frame Size", callback.frameSize);
printer.kv("Callback Name", this.methodNode.name);
printer.kv("Callback Name", this.info.getMethodName());
printer.kv("Instruction", "%s %s", callback.node.getClass().getSimpleName(),
Bytecode.getOpcodeName(callback.node.getCurrentTarget().getOpcode()));
printer.hr();
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin.injection.code;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
@@ -37,28 +38,29 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.*;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.transformer.ClassInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal;
import org.spongepowered.asm.mixin.transformer.ClassInfo.TypeLookup;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.SignaturePrinter;
import org.spongepowered.asm.util.Bytecode.DelegateInitialiser;
import com.google.common.collect.ObjectArrays;
/**
* Base class for bytecode injectors
*/
@@ -101,6 +103,66 @@ public abstract class Injector {
}
/**
* Redirection data bundle base. No this isn't meant to be pretty, it's a
* way of passing a bunch of state around the injector without having dumb
* method signatures.
*/
public static class InjectorData {
/**
* Redirect target
*/
public final Target target;
/**
* Mutable description. The bundle is be passed to different types of
* handler and the handler decorates the bundle with a description of
* the <em>type</em> of injection, purely for use in error messages.
*/
public String description;
/**
* When passing through {@link RedirectInjector#validateParams} this
* switch determines whether coercion is supported for both the primary
* handler args and captured target args, or for target args only.
*/
public boolean allowCoerceArgs;
/**
* Number of arguments to capture from the target, determined by the
* number of extra args on the handler method
*/
public int captureTargetArgs = 0;
/**
* True if the method itself is decorated with {@link Coerce} and the
* return type is coerced. Instructs the injector to add a CHECKCAST
* following the handler.
*/
public boolean coerceReturnType = false;
public InjectorData(Target target) {
this(target, "handler");
}
public InjectorData(Target target, String description) {
this(target, description, true);
}
public InjectorData(Target target, String description, boolean allowCoerceArgs) {
this.target = target;
this.description = description;
this.allowCoerceArgs = allowCoerceArgs;
}
@Override
public String toString() {
return this.description;
}
}
/**
* Log more things
*/
@@ -160,7 +222,7 @@ public abstract class Injector {
@Override
public String toString() {
return String.format("%s::%s", this.classNode.name, this.methodNode.name);
return String.format("%s::%s", this.classNode.name, this.info.getMethodName());
}
/**
@@ -350,7 +412,204 @@ public abstract class Injector {
this.info.addCallbackInvocation(handler);
return insn;
}
/**
* @param args handler arguments
* @param insns InsnList to inject insns into
* @param argMap Mapping of args to local variables
* @return injected insn node
*/
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) {
return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
}
/**
* @param args handler arguments
* @param insns InsnList to inject insns into
* @param argMap Mapping of args to local variables
* @param startArg Starting arg to consume
* @param endArg Ending arg to consume
* @return injected insn node
*/
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) {
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
this.pushArgs(args, insns, argMap, startArg, endArg);
return this.invokeHandler(insns);
}
/**
* Store args on the stack starting at the end and working back to position
* specified by start, return the generated argMap
*
* @param target target method
* @param args argument types
* @param insns instruction list to generate insns into
* @param start Starting index
* @return the generated argmap
*/
protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) {
int[] argMap = target.generateArgMap(args, start);
this.storeArgs(args, insns, argMap, start, args.length);
return argMap;
}
/**
* Store args on the stack to their positions allocated based on argMap
*
* @param args argument types
* @param insns instruction list to generate insns into
* @param argMap generated argmap containing local indices for all args
* @param start Starting index
* @param end Ending index
*/
protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
for (int arg = end - 1; arg >= start; arg--) {
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg]));
}
}
/**
* Load args onto the stack from their positions allocated in argMap
*
* @param args argument types
* @param insns instruction list to generate insns into
* @param argMap generated argmap containing local indices for all args
* @param start Starting index
* @param end Ending index
*/
protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
this.pushArgs(args, insns, argMap, start, end, null);
}
/**
* Load args onto the stack from their positions allocated in argMap
*
* @param args argument types
* @param insns instruction list to generate insns into
* @param argMap generated argmap containing local indices for all args
* @param start Starting index
* @param end Ending index
*/
protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end, Extension extension) {
for (int arg = start; arg < end && arg < args.length; arg++) {
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg]));
if (extension != null) {
extension.add(args[arg].getSize());
}
}
}
/**
* Collects all the logic from old validateParams/checkDescriptor so that we
* can consistently apply coercion logic to method params, and also provide
* more detailed errors when something doesn't line up.
*
* <p>The supplied return type and argument list will be verified first. Any
* arguments on the handler beyond the base arguments consume arguments from
* the target. The flag <tt>allowCoerceArgs</tt> on the <tt>redirect</tt>
* instance determines whether coercion is supported for the base args and
* return type, coercion is always allowed for captured target args.</p>
*
* <p>Following validation, the <tt>captureTargetArgs</tt> and
* <tt>coerceReturnType</tt> values will be set on the bundle and the
* calling injector function should adjust itself accordingly.</p>
*
* @param injector Data bundle for the injector
* @param returnType Return type for the handler, must not be null
* @param args Array of handler args, must not be null
*/
protected final void validateParams(InjectorData injector, Type returnType, Type... args) {
String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext());
int argIndex = 0;
try {
injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs);
for (Type arg : args) {
if (arg != null) {
this.checkCoerce(argIndex, arg, description, injector.allowCoerceArgs);
argIndex++;
}
}
if (argIndex == this.methodArgs.length) {
return;
}
for (int targetArg = 0; targetArg < injector.target.arguments.length && argIndex < this.methodArgs.length; targetArg++, argIndex++) {
this.checkCoerce(argIndex, injector.target.arguments[targetArg], description, true);
injector.captureTargetArgs++;
}
} catch (InvalidInjectionException ex) {
String expected = this.methodArgs.length > args.length
? Bytecode.generateDescriptor(returnType, ObjectArrays.concat(args, injector.target.arguments, Type.class))
: Bytecode.generateDescriptor(returnType, args);
throw new InvalidInjectionException(this.info, String.format("%s. Handler signature: %s Expected signature: %s", ex.getMessage(),
this.methodNode.desc, expected));
}
if (argIndex < this.methodArgs.length) {
Type[] extraArgs = Arrays.copyOfRange(this.methodArgs, argIndex, this.methodArgs.length);
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Found %d unexpected additional method arguments: %s",
description, this.methodArgs.length - argIndex, new SignaturePrinter(extraArgs).getFormattedArgs()));
}
}
/**
* Called inside {@link #validateParams} but can also be used directly. This
* method checks whether the supplied type is compatible with the specified
* handler argument, apply coercion logic where necessary.
*
* @param index Handler argument index, pass in a negative value (by
* convention -1) to specify handler return type
* @param toType Desired type based on the injector contract
* @param description human-readable description of the handler method, used
* in raised exception
* @param allowCoercion True if coercion logic can be applied to this
* argument, false to only allow a precise match
* @return <tt>false</tt> if the argument matched perfectly, <tt>true</tt>
* if coercion is required for the argument
*/
protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) {
Type fromType = index < 0 ? this.returnType : this.methodArgs[index];
if (index >= this.methodArgs.length) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Not enough arguments: expected argument type %s at index %d",
description, SignaturePrinter.getTypeName(toType), index));
}
AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index);
boolean isReturn = index < 0;
String argType = isReturn ? "return" : "argument";
Object argIndex = isReturn ? "" : " at index " + index;
if (fromType.equals(toType)) {
if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex,
SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType));
}
return false;
}
if (coerce == null || !allowCoercion) {
String coerceWarning = coerce != null ? ". @Coerce not allowed here" : "";
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Found unexpected %s type %s%s, expected %s%s", description, argType,
SignaturePrinter.getTypeName(fromType), argIndex, SignaturePrinter.getTypeName(toType), coerceWarning));
}
boolean canCoerce = Injector.canCoerce(fromType, toType);
if (!canCoerce) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Cannot @Coerce %s type %s%s to %s", description, argType,
SignaturePrinter.getTypeName(toType), argIndex, SignaturePrinter.getTypeName(fromType)));
}
return true;
}
/**
* Throw an exception. The exception class must have a string which takes a
* string argument
@@ -376,7 +635,12 @@ public abstract class Injector {
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
*/
public static boolean canCoerce(Type from, Type to) {
if (from.getSort() == Type.OBJECT && to.getSort() == Type.OBJECT) {
int fromSort = from.getSort();
int toSort = to.getSort();
if (fromSort >= Type.ARRAY && toSort >= Type.ARRAY && fromSort == toSort) {
if (fromSort == Type.ARRAY && from.getDimensions() != to.getDimensions()) {
return false;
}
return Injector.canCoerce(ClassInfo.forType(from, TypeLookup.ELEMENT_TYPE), ClassInfo.forType(to, TypeLookup.ELEMENT_TYPE));
}
@@ -421,7 +685,7 @@ public abstract class Injector {
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
*/
private static boolean canCoerce(ClassInfo from, ClassInfo to) {
return from != null && to != null && (to == from || to.hasSuperClass(from));
return from != null && to != null && (to == from || to.hasSuperClass(from, Traversal.ALL, true));
}
}
@@ -26,17 +26,12 @@ package org.spongepowered.asm.mixin.injection.invoke;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
/**
@@ -95,74 +90,4 @@ public abstract class InvokeInjector extends Injector {
*/
protected abstract void injectAtInvoke(Target target, InjectionNode node);
/**
* @param args handler arguments
* @param insns InsnList to inject insns into
* @param argMap Mapping of args to local variables
* @return injected insn node
*/
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) {
return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length);
}
/**
* @param args handler arguments
* @param insns InsnList to inject insns into
* @param argMap Mapping of args to local variables
* @param startArg Starting arg to consume
* @param endArg Ending arg to consume
* @return injected insn node
*/
protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) {
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
this.pushArgs(args, insns, argMap, startArg, endArg);
return this.invokeHandler(insns);
}
/**
* Store args on the stack starting at the end and working back to position
* specified by start, return the generated argMap
*
* @param target target method
* @param args argument types
* @param insns instruction list to generate insns into
* @param start Starting index
* @return the generated argmap
*/
protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) {
int[] argMap = target.generateArgMap(args, start);
this.storeArgs(args, insns, argMap, start, args.length);
return argMap;
}
/**
* Store args on the stack to their positions allocated based on argMap
*
* @param args argument types
* @param insns instruction list to generate insns into
* @param argMap generated argmap containing local indices for all args
* @param start Starting index
* @param end Ending index
*/
protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
for (int arg = end - 1; arg >= start; arg--) {
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg]));
}
}
/**
* Load args onto the stack from their positions allocated in argMap
* @param args argument types
* @param insns instruction list to generate insns into
* @param argMap generated argmap containing local indices for all args
* @param start Starting index
* @param end Ending index
*/
protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) {
for (int arg = start; arg < end; arg++) {
insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg]));
}
}
}
@@ -33,6 +33,7 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.code.Injector;
@@ -76,6 +77,12 @@ public class ModifyConstantInjector extends RedirectInjector {
}
AbstractInsnNode targetNode = node.getCurrentTarget();
if (targetNode instanceof TypeInsnNode) {
this.checkTargetModifiers(target, false);
this.injectTypeConstantModifier(target, (TypeInsnNode)targetNode);
return;
}
if (targetNode instanceof JumpInsnNode) {
this.checkTargetModifiers(target, false);
this.injectExpandedConstantModifier(target, (JumpInsnNode)targetNode);
@@ -88,10 +95,19 @@ public class ModifyConstantInjector extends RedirectInjector {
return;
}
throw new InvalidInjectionException(this.info, this.annotationType + " annotation is targetting an invalid insn in "
+ target + " in " + this);
throw new InvalidInjectionException(this.info, String.format("%s annotation is targetting an invalid insn in %s in %s",
this.annotationType, target, this));
}
private void injectTypeConstantModifier(Target target, TypeInsnNode typeNode) {
int opcode = typeNode.getOpcode();
if (opcode != Opcodes.INSTANCEOF) {
throw new InvalidInjectionException(this.info, String.format("%s annotation does not support %s insn in %s in %s",
this.annotationType, Bytecode.getOpcodeName(opcode), target, this));
}
this.injectAtInstanceOf(target, typeNode);
}
/**
* Injects a constant modifier at an implied-zero
*
@@ -101,8 +117,8 @@ public class ModifyConstantInjector extends RedirectInjector {
private void injectExpandedConstantModifier(Target target, JumpInsnNode jumpNode) {
int opcode = jumpNode.getOpcode();
if (opcode < Opcodes.IFLT || opcode > Opcodes.IFLE) {
throw new InvalidInjectionException(this.info, this.annotationType + " annotation selected an invalid opcode "
+ Bytecode.getOpcodeName(opcode) + " in " + target + " in " + this);
throw new InvalidInjectionException(this.info, String.format("%s annotation selected an invalid opcode %s in %s in %s",
this.annotationType, Bytecode.getOpcodeName(opcode), target, this));
}
Extension extraStack = target.extendStack();
@@ -130,17 +146,16 @@ public class ModifyConstantInjector extends RedirectInjector {
}
private AbstractInsnNode invokeConstantHandler(Type constantType, Target target, Extension extraStack, InsnList before, InsnList after) {
final String handlerDesc = Bytecode.generateDescriptor(constantType, constantType);
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
InjectorData handler = new InjectorData(target, "constant modifier");
this.validateParams(handler, constantType, constantType);
if (!this.isStatic) {
before.insert(new VarInsnNode(Opcodes.ALOAD, 0));
extraStack.add();
}
if (withArgs) {
this.pushArgs(target.arguments, after, target.getArgIndices(), 0, target.arguments.length);
extraStack.add(target.arguments);
if (handler.captureTargetArgs > 0) {
this.pushArgs(target.arguments, after, target.getArgIndices(), 0, handler.captureTargetArgs, extraStack);
}
return this.invokeHandler(after);
@@ -33,24 +33,22 @@ import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess;
import org.spongepowered.asm.mixin.injection.points.BeforeNew;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.struct.Target;
import org.spongepowered.asm.mixin.injection.struct.Target.Extension;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.SignaturePrinter;
import com.google.common.base.Joiner;
import com.google.common.collect.ObjectArrays;
import com.google.common.primitives.Ints;
@@ -90,6 +88,11 @@ import com.google.common.primitives.Ints;
*/
public class RedirectInjector extends InvokeInjector {
private static final String GET_CLASS_METHOD = "getClass";
private static final String IS_ASSIGNABLE_FROM_METHOD = "isAssignableFrom";
private static final String NPE = "java/lang/NullPointerException";
private static final String KEY_NOMINATORS = "nominators";
private static final String KEY_FUZZ = "fuzz";
private static final String KEY_OPCODE = "opcode";
@@ -129,36 +132,94 @@ public class RedirectInjector extends InvokeInjector {
public static final String KEY = "ctor";
public boolean wildcard = false;
boolean wildcard = false;
public int injected = 0;
int injected = 0;
InvalidInjectionException lastException;
public void throwOrCollect(InvalidInjectionException ex) {
if (!this.wildcard) {
throw ex;
}
this.lastException = ex;
}
}
/**
* Data bundle for invoke redirectors
*/
static class RedirectedInvoke {
static class RedirectedInvokeData extends InjectorData {
final Target target;
final MethodInsnNode node;
final Type returnType;
final Type[] args;
final Type[] locals;
final Type[] targetArgs;
final Type[] handlerArgs;
boolean captureTargetArgs = false;
RedirectedInvoke(Target target, MethodInsnNode node) {
this.target = target;
RedirectedInvokeData(Target target, MethodInsnNode node) {
super(target);
this.node = node;
this.returnType = Type.getReturnType(node.desc);
this.args = Type.getArgumentTypes(node.desc);
this.locals = node.getOpcode() == Opcodes.INVOKESTATIC
? this.args
: ObjectArrays.concat(Type.getType("L" + node.owner + ";"), this.args);
this.targetArgs = Type.getArgumentTypes(node.desc);
this.handlerArgs = node.getOpcode() == Opcodes.INVOKESTATIC
? this.targetArgs
: ObjectArrays.concat(Type.getObjectType(node.owner), this.targetArgs);
}
}
/**
* Data bundle for field redirectors
*/
static class RedirectedFieldData extends InjectorData {
final FieldInsnNode node;
final int opcode;
final Type owner;
final Type type;
final int dimensions;
final boolean isStatic;
final boolean isGetter;
final boolean isSetter;
// This is actually the return type for array access, might be int for
// array length redirectors
Type elementType;
int extraDimensions = 1;
RedirectedFieldData(Target target, FieldInsnNode node) {
super(target);
this.node = node;
this.opcode = node.getOpcode();
this.owner = Type.getObjectType(node.owner);
this.type = Type.getType(node.desc);
this.dimensions = (this.type.getSort() == Type.ARRAY) ? this.type.getDimensions() : 0;
this.isStatic = this.opcode == Opcodes.GETSTATIC || this.opcode == Opcodes.PUTSTATIC;
this.isGetter = this.opcode == Opcodes.GETSTATIC || this.opcode == Opcodes.GETFIELD;
this.isSetter = this.opcode == Opcodes.PUTSTATIC || this.opcode == Opcodes.PUTFIELD;
this.description = this.isGetter ? "field getter" : this.isSetter ? "field setter" : "handler";
}
int getTotalDimensions() {
return this.dimensions + this.extraDimensions;
}
Type[] getArrayArgs(Type... extra) {
int dimensions = this.getTotalDimensions();
Type[] args = new Type[dimensions + extra.length];
for (int i = 0; i < args.length; i++) {
args[i] = i == 0 ? this.type : i < dimensions ? Type.INT_TYPE : extra[dimensions - i];
}
return args;
}
}
/**
* Meta is used to decorate the target node with information about this
* injection
*/
protected Meta meta;
private Map<BeforeNew, ConstructorRedirectData> ctorRedirectors = new HashMap<BeforeNew, ConstructorRedirectData>();
@@ -268,13 +329,20 @@ public class RedirectInjector extends InvokeInjector {
return;
}
if (node.getCurrentTarget() instanceof TypeInsnNode && node.getCurrentTarget().getOpcode() == Opcodes.NEW) {
if (!this.isStatic && target.isStatic) {
throw new InvalidInjectionException(this.info, String.format(
"non-static callback method %s has a static target which is not supported", this));
if (node.getCurrentTarget() instanceof TypeInsnNode) {
int opcode = node.getCurrentTarget().getOpcode();
if (opcode == Opcodes.NEW) {
if (!this.isStatic && target.isStatic) {
throw new InvalidInjectionException(this.info, String.format(
"non-static callback method %s has a static target which is not supported", this));
}
this.injectAtConstructor(target, node);
return;
} else if (opcode == Opcodes.INSTANCEOF) {
this.checkTargetModifiers(target, false);
this.injectAtInstanceOf(target, node);
return;
}
this.injectAtConstructor(target, node);
return;
}
throw new InvalidInjectionException(this.info, String.format("%s annotation on is targetting an invalid insn in %s in %s",
@@ -297,7 +365,8 @@ public class RedirectInjector extends InvokeInjector {
if (node.getOriginalTarget() instanceof TypeInsnNode && node.getOriginalTarget().getOpcode() == Opcodes.NEW) {
ConstructorRedirectData meta = node.<ConstructorRedirectData>getDecoration(ConstructorRedirectData.KEY);
if (meta.wildcard && meta.injected == 0) {
throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target));
throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target),
meta.lastException);
}
}
}
@@ -307,150 +376,99 @@ public class RedirectInjector extends InvokeInjector {
*/
@Override
protected void injectAtInvoke(Target target, InjectionNode node) {
RedirectedInvoke invoke = new RedirectedInvoke(target, (MethodInsnNode)node.getCurrentTarget());
RedirectedInvokeData invoke = new RedirectedInvokeData(target, (MethodInsnNode)node.getCurrentTarget());
this.validateParams(invoke);
this.validateParams(invoke, invoke.returnType, invoke.handlerArgs);
InsnList insns = new InsnList();
Extension extraLocals = target.extendLocals().add(invoke.locals).add(1);
Extension extraLocals = target.extendLocals().add(invoke.handlerArgs).add(1);
Extension extraStack = target.extendStack().add(1); // Normally only need 1 extra stack pos to store target ref
int[] argMap = this.storeArgs(target, invoke.locals, insns, 0);
if (invoke.captureTargetArgs) {
int argSize = Bytecode.getArgsSize(target.arguments);
int[] argMap = this.storeArgs(target, invoke.handlerArgs, insns, 0);
if (invoke.captureTargetArgs > 0) {
int argSize = Bytecode.getArgsSize(target.arguments, 0, invoke.captureTargetArgs);
extraLocals.add(argSize);
extraStack.add(argSize);
// No need to truncate target arg indices, pushArgs ignores args which don't exist
argMap = Ints.concat(argMap, target.getArgIndices());
}
AbstractInsnNode insn = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
target.replaceNode(invoke.node, insn, insns);
AbstractInsnNode champion = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap);
if (invoke.coerceReturnType && invoke.returnType.getSort() >= Type.ARRAY) {
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, invoke.returnType.getInternalName()));
}
target.replaceNode(invoke.node, champion, insns);
extraLocals.apply();
extraStack.apply();
}
/**
* Perform validation of an invoke handler parameters, each parameter in the
* handler must match the expected type or be annotated with {@link Coerce}
* and be a supported supertype of the incoming type.
*
* @param invoke invocation being redirected
*/
protected void validateParams(RedirectedInvoke invoke) {
int argc = this.methodArgs.length;
String description = String.format("%s handler method %s", this.annotationType, this);
if (!invoke.returnType.equals(this.returnType)) {
throw new InvalidInjectionException(this.info, String.format("%s has an invalid signature. Expected return type %s found %s",
description, this.returnType, invoke.returnType));
}
for (int index = 0; index < argc; index++) {
Type toType = null;
if (index >= this.methodArgs.length) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Not enough arguments found for capture of target method args, expected %d but found %d",
description, argc, this.methodArgs.length));
}
Type fromType = this.methodArgs[index];
if (index < invoke.locals.length) {
toType = invoke.locals[index];
} else {
invoke.captureTargetArgs = true;
argc = Math.max(argc, invoke.locals.length + invoke.target.arguments.length);
int arg = index - invoke.locals.length;
if (arg >= invoke.target.arguments.length) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Found unexpected additional target argument with type %s at index %d",
description, fromType, index));
}
toType = invoke.target.arguments[arg];
}
AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index);
if (fromType.equals(toType)) {
if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) {
Injector.logger.warn("Redundant @Coerce on {} argument {}, {} is identical to {}", description, index, toType, fromType);
}
continue;
}
boolean canCoerce = Injector.canCoerce(fromType, toType);
if (coerce == null) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Found unexpected argument type %s at index %d, expected %s",
description, fromType, index, toType));
}
if (!canCoerce) {
throw new InvalidInjectionException(this.info, String.format(
"%s has an invalid signature. Cannot @Coerce argument type %s at index %d to %s",
description, toType, index, fromType));
}
}
}
/**
* Redirect a field get or set operation, or an array element access
*/
private void injectAtFieldAccess(Target target, InjectionNode node) {
final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget();
final int opCode = fieldNode.getOpcode();
final Type ownerType = Type.getType("L" + fieldNode.owner + ";");
final Type fieldType = Type.getType(fieldNode.desc);
RedirectedFieldData field = new RedirectedFieldData(target, (FieldInsnNode)node.getCurrentTarget());
int targetDimensions = (fieldType.getSort() == Type.ARRAY) ? fieldType.getDimensions() : 0;
int handlerDimensions = (this.returnType.getSort() == Type.ARRAY) ? this.returnType.getDimensions() : 0;
if (handlerDimensions > targetDimensions) {
if (handlerDimensions > field.dimensions) {
throw new InvalidInjectionException(this.info, "Dimensionality of handler method is greater than target array on " + this);
} else if (handlerDimensions == 0 && targetDimensions > 0) {
} else if (handlerDimensions == 0 && field.dimensions > 0) {
int fuzz = node.<Integer>getDecoration(RedirectInjector.KEY_FUZZ).intValue();
int opcode = node.<Integer>getDecoration(RedirectInjector.KEY_OPCODE).intValue();
this.injectAtArrayField(target, fieldNode, opCode, ownerType, fieldType, fuzz, opcode);
this.injectAtArrayField(field, fuzz, opcode);
} else {
this.injectAtScalarField(target, fieldNode, opCode, ownerType, fieldType);
this.injectAtScalarField(field);
}
}
/**
* Redirect an array element access
*/
private void injectAtArrayField(Target target, FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType, int fuzz, int opcode) {
Type elementType = fieldType.getElementType();
if (opCode != Opcodes.GETSTATIC && opCode != Opcodes.GETFIELD) {
private void injectAtArrayField(RedirectedFieldData field, int fuzz, int opcode) {
Type elementType = field.type.getElementType();
if (field.opcode != Opcodes.GETSTATIC && field.opcode != Opcodes.GETFIELD) {
throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for array access %s",
Bytecode.getOpcodeName(opCode), this.info));
Bytecode.getOpcodeName(field.opcode), this.info));
} else if (this.returnType.getSort() != Type.VOID) {
if (opcode != Opcodes.ARRAYLENGTH) {
opcode = elementType.getOpcode(Opcodes.IALOAD);
}
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, opcode, fuzz);
this.injectAtGetArray(target, fieldNode, varNode, ownerType, fieldType);
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(field.target.insns, field.node, opcode, fuzz);
this.injectAtGetArray(field, varNode);
} else {
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, elementType.getOpcode(Opcodes.IASTORE), fuzz);
this.injectAtSetArray(target, fieldNode, varNode, ownerType, fieldType);
AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(field.target.insns, field.node, elementType.getOpcode(Opcodes.IASTORE), fuzz);
this.injectAtSetArray(field, varNode);
}
}
/**
* Array element read (xALOAD) or array.length (ARRAYLENGTH)
*/
private void injectAtGetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) {
String handlerDesc = RedirectInjector.getGetArrayHandlerDescriptor(varNode, this.returnType, fieldType);
boolean withArgs = this.checkDescriptor(handlerDesc, target, "array getter");
this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array getter");
private void injectAtGetArray(RedirectedFieldData field, AbstractInsnNode varNode) {
field.description = "array getter";
field.elementType = field.type.getElementType();
if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) {
field.elementType = Type.INT_TYPE;
field.extraDimensions = 0;
}
this.validateParams(field, field.elementType, field.getArrayArgs());
this.injectArrayRedirect(field, varNode, "array getter");
}
/**
* Array element write (xASTORE)
*/
private void injectAtSetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) {
String handlerDesc = Bytecode.generateDescriptor(null, (Object[])RedirectInjector.getArrayArgs(fieldType, 1, fieldType.getElementType()));
boolean withArgs = this.checkDescriptor(handlerDesc, target, "array setter");
this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array setter");
private void injectAtSetArray(RedirectedFieldData field, AbstractInsnNode varNode) {
field.description = "array setter";
Type elementType = field.type.getElementType();
int valueArgIndex = field.getTotalDimensions();
if (this.checkCoerce(valueArgIndex, elementType, String.format("%s array setter method %s from %s",
this.annotationType, this, this.info.getContext()), true)) {
elementType = this.methodArgs[valueArgIndex];
}
this.validateParams(field, Type.VOID_TYPE, field.getArrayArgs(elementType));
this.injectArrayRedirect(field, varNode, "array setter");
}
/**
@@ -459,35 +477,38 @@ public class RedirectInjector extends InvokeInjector {
* actual handler signature, the correct arguments are already on the stack
* thanks to the nature of xALOAD and xASTORE.
*
* @param varNode array access node
* @param type description of access type for use in error messages
* @param target target method
* @param fieldNode field node
* @param varNode array access node
* @param withArgs true if the descriptor includes captured arguments from
* the target method signature
* @param type description of access type for use in error messages
*/
private void injectArrayRedirect(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, boolean withArgs, String type) {
private void injectArrayRedirect(RedirectedFieldData field, AbstractInsnNode varNode, String type) {
if (varNode == null) {
String advice = "";
throw new InvalidInjectionException(this.info, String.format(
"Array element %s on %s could not locate a matching %s instruction in %s. %s",
this.annotationType, this, type, target, advice));
this.annotationType, this, type, field.target, advice));
}
Extension extraStack = target.extendStack();
Extension extraStack = field.target.extendStack();
if (!this.isStatic) {
target.insns.insertBefore(fieldNode, new VarInsnNode(Opcodes.ALOAD, 0));
VarInsnNode loadThis = new VarInsnNode(Opcodes.ALOAD, 0);
field.target.insns.insert(field.node, loadThis);
field.target.insns.insert(loadThis, new InsnNode(Opcodes.SWAP));
extraStack.add();
}
InsnList invokeInsns = new InsnList();
if (withArgs) {
this.pushArgs(target.arguments, invokeInsns, target.getArgIndices(), 0, target.arguments.length);
extraStack.add(target.arguments);
InsnList insns = new InsnList();
if (field.captureTargetArgs > 0) {
this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack);
}
extraStack.apply();
target.replaceNode(varNode, this.invokeHandler(invokeInsns), invokeInsns);
AbstractInsnNode champion = this.invokeHandler(insns);
if (field.coerceReturnType && field.type.getSort() >= Type.ARRAY) {
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, field.elementType.getInternalName()));
}
field.target.replaceNode(varNode, champion, insns);
}
/**
@@ -499,18 +520,19 @@ public class RedirectInjector extends InvokeInjector {
* @param ownerType type of the field owner
* @param fieldType field type
*/
private void injectAtScalarField(Target target, final FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType) {
private void injectAtScalarField(RedirectedFieldData field) {
AbstractInsnNode invoke = null;
InsnList insns = new InsnList();
if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) {
invoke = this.injectAtGetField(insns, target, fieldNode, opCode == Opcodes.GETSTATIC, ownerType, fieldType);
} else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) {
invoke = this.injectAtPutField(insns, target, fieldNode, opCode == Opcodes.PUTSTATIC, ownerType, fieldType);
if (field.isGetter) {
invoke = this.injectAtGetField(field, insns);
} else if (field.isSetter) {
invoke = this.injectAtPutField(field, insns);
} else {
throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for %s", Bytecode.getOpcodeName(opCode), this.info));
throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for %s",
Bytecode.getOpcodeName(field.opcode), this.info));
}
target.replaceNode(fieldNode, invoke, insns);
field.target.replaceNode(field.node, invoke, insns);
}
/**
@@ -519,27 +541,29 @@ public class RedirectInjector extends InvokeInjector {
* possible scenarios based on the possible combinations of static on the
* handler and the field itself.
*/
private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
final String handlerDesc = staticField ? Bytecode.generateDescriptor(fieldType) : Bytecode.generateDescriptor(fieldType, owner);
final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter");
private AbstractInsnNode injectAtGetField(RedirectedFieldData field, InsnList insns) {
this.validateParams(field, field.type, field.isStatic ? null : field.owner);
Extension extraStack = target.extendStack();
Extension extraStack = field.target.extendStack();
if (!this.isStatic) {
extraStack.add();
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
if (!staticField) {
if (!field.isStatic) {
insns.add(new InsnNode(Opcodes.SWAP));
}
}
if (withArgs) {
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length);
extraStack.add(target.arguments);
if (field.captureTargetArgs > 0) {
this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack);
}
extraStack.apply();
return this.invokeHandler(insns);
AbstractInsnNode champion = this.invokeHandler(insns);
if (field.coerceReturnType && field.type.getSort() >= Type.ARRAY) {
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, field.type.getInternalName()));
}
return champion;
}
/**
@@ -548,60 +572,33 @@ public class RedirectInjector extends InvokeInjector {
* possible scenarios based on the possible combinations of static on the
* handler and the field itself.
*/
private AbstractInsnNode injectAtPutField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) {
String handlerDesc = staticField ? Bytecode.generateDescriptor(null, fieldType) : Bytecode.generateDescriptor(null, owner, fieldType);
boolean withArgs = this.checkDescriptor(handlerDesc, target, "setter");
private AbstractInsnNode injectAtPutField(RedirectedFieldData field, InsnList insns) {
this.validateParams(field, Type.VOID_TYPE, field.isStatic ? null : field.owner, field.type);
Extension extraStack = target.extendStack();
Extension extraStack = field.target.extendStack();
if (!this.isStatic) {
if (staticField) {
if (field.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
} else {
extraStack.add();
int marshallVar = target.allocateLocals(fieldType.getSize());
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ISTORE), marshallVar));
int marshallVar = field.target.allocateLocals(field.type.getSize());
insns.add(new VarInsnNode(field.type.getOpcode(Opcodes.ISTORE), marshallVar));
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ILOAD), marshallVar));
insns.add(new VarInsnNode(field.type.getOpcode(Opcodes.ILOAD), marshallVar));
}
}
if (withArgs) {
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length);
extraStack.add(target.arguments);
if (field.captureTargetArgs > 0) {
this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack);
}
extraStack.apply();
return this.invokeHandler(insns);
}
/**
* Check that the handler descriptor matches the calculated descriptor for
* the access being redirected.
*
* @param desc computed descriptor
* @param target target method
* @param type redirector type in human-readable text, for error messages
* @return true if the descriptor was found and includes target method args,
* false if the descriptor was found and does not capture target args
*/
protected boolean checkDescriptor(String desc, Target target, String type) {
if (this.methodNode.desc.equals(desc)) {
return false;
}
int pos = desc.indexOf(')');
String alternateDesc = String.format("%s%s%s", desc.substring(0, pos), Joiner.on("").join(target.arguments), desc.substring(pos));
if (this.methodNode.desc.equals(alternateDesc)) {
return true;
}
throw new InvalidInjectionException(this.info, String.format("%s method %s %s has an invalid signature. Expected %s but found %s",
this.annotationType, type, this, desc, this.methodNode.desc));
}
protected void injectAtConstructor(Target target, InjectionNode node) {
ConstructorRedirectData meta = node.<ConstructorRedirectData>getDecoration(ConstructorRedirectData.KEY);
@@ -616,22 +613,19 @@ public class RedirectInjector extends InvokeInjector {
final MethodInsnNode initNode = target.findInitNodeFor(newNode);
if (initNode == null) {
if (!meta.wildcard) {
throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target));
}
meta.throwOrCollect(new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s",
this.annotationType, target)));
return;
}
// True if the result of the object construction is being assigned
boolean isAssigned = dupNode.getOpcode() == Opcodes.DUP;
String desc = initNode.desc.replace(")V", ")L" + newNode.desc + ";");
boolean withArgs = false;
RedirectedInvokeData ctor = new RedirectedInvokeData(target, initNode);
ctor.description = "factory";
try {
withArgs = this.checkDescriptor(desc, target, "constructor");
this.validateParams(ctor, Type.getObjectType(newNode.desc), ctor.targetArgs);
} catch (InvalidInjectionException ex) {
if (!meta.wildcard) {
throw ex;
}
meta.throwOrCollect(ex);
return;
}
@@ -647,25 +641,21 @@ public class RedirectInjector extends InvokeInjector {
Extension extraStack = target.extendStack();
InsnList insns = new InsnList();
if (withArgs) {
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length);
extraStack.add(target.arguments);
if (ctor.captureTargetArgs > 0) {
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, ctor.captureTargetArgs, extraStack);
}
this.invokeHandler(insns);
if (ctor.coerceReturnType) {
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, newNode.desc));
}
extraStack.apply();
if (isAssigned) {
// Do a null-check following the redirect to ensure that the handler
// didn't return null. Since NEW cannot return null, this would break
// the contract of the target method!
LabelNode nullCheckSucceeded = new LabelNode();
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded));
this.throwException(insns, "java/lang/NullPointerException", String.format("%s constructor handler %s returned null for %s",
this.annotationType, this, newNode.desc.replace('/', '.')));
insns.add(nullCheckSucceeded);
extraStack.add();
this.doNullCheck(insns, extraStack, "constructor handler", newNode.desc.replace('/', '.'));
} else {
// Result is not assigned, so just pop it from the operand stack
insns.add(new InsnNode(Opcodes.POP));
@@ -676,20 +666,118 @@ public class RedirectInjector extends InvokeInjector {
meta.injected++;
}
private static String getGetArrayHandlerDescriptor(AbstractInsnNode varNode, Type returnType, Type fieldType) {
if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) {
return Bytecode.generateDescriptor(Type.INT_TYPE, (Object[])RedirectInjector.getArrayArgs(fieldType, 0));
}
return Bytecode.generateDescriptor(returnType, (Object[])RedirectInjector.getArrayArgs(fieldType, 1));
protected void injectAtInstanceOf(Target target, InjectionNode node) {
this.injectAtInstanceOf(target, (TypeInsnNode)node.getCurrentTarget());
}
private static Type[] getArrayArgs(Type fieldType, int extraDimensions, Type... extra) {
int dimensions = fieldType.getDimensions() + extraDimensions;
Type[] args = new Type[dimensions + extra.length];
for (int i = 0; i < args.length; i++) {
args[i] = i == 0 ? fieldType : i < dimensions ? Type.INT_TYPE : extra[dimensions - i];
protected void injectAtInstanceOf(Target target, TypeInsnNode typeNode) {
if (this.returnType.getSort() == Type.BOOLEAN) {
this.redirectInstanceOf(target, typeNode, false);
return;
}
return args;
if (this.returnType.equals(Type.getType(Constants.CLASS_DESC))) {
this.redirectInstanceOf(target, typeNode, true);
return;
}
// This syntax is neat but the inconsistency might be a step too far
// if (this.returnType.getSort() >= Type.ARRAY) {
// this.modifyInstanceOfType(target, typeNode);
// return;
// }
throw new InvalidInjectionException(this.info, String.format("%s on %s has an invalid signature. Found unexpected return type %s. INSTANCEOF"
+ " handler expects (Ljava/lang/Object;Ljava/lang/Class;)Z or (Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Class;",
this.annotationType, this, SignaturePrinter.getTypeName(this.returnType)));
}
private void redirectInstanceOf(Target target, TypeInsnNode typeNode, boolean dynamic) {
Extension extraStack = target.extendStack();
final InsnList insns = new InsnList();
InjectorData handler = new InjectorData(target, "instanceof handler", false /* do not coerce args */);
this.validateParams(handler, this.returnType, Type.getType(Constants.OBJECT_DESC), Type.getType(Constants.CLASS_DESC));
if (dynamic) {
insns.add(new InsnNode(Opcodes.DUP));
extraStack.add();
}
if (!this.isStatic) {
insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
insns.add(new InsnNode(Opcodes.SWAP));
extraStack.add();
}
// Add the class type from the original instanceof check
insns.add(new LdcInsnNode(Type.getObjectType(typeNode.desc)));
extraStack.add();
if (handler.captureTargetArgs > 0) {
this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, handler.captureTargetArgs, extraStack);
}
AbstractInsnNode champion = this.invokeHandler(insns);
if (dynamic) {
// First null-check the class value returned by the handler, if it's
// null then the rest is going to go badly
this.doNullCheck(insns, extraStack, "instanceof handler", "class type");
// Now do a null-check on the reference and isAssignableFrom check
this.checkIsAssignableFrom(insns, extraStack);
}
target.replaceNode(typeNode, champion, insns);
extraStack.apply();
}
private void checkIsAssignableFrom(final InsnList insns, Extension extraStack) {
LabelNode objectIsNull = new LabelNode();
LabelNode checkComplete = new LabelNode();
// Swap the values (we duped the ref above) and check for null. If
// the reference is null, load FALSE per the contract of instanceof
insns.add(new InsnNode(Opcodes.SWAP));
insns.add(new InsnNode(Opcodes.DUP));
extraStack.add();
insns.add(new JumpInsnNode(Opcodes.IFNULL, objectIsNull));
// If it's not null, call getClass on the reference and then use
// isAssignableFrom on the result
insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Constants.OBJECT, RedirectInjector.GET_CLASS_METHOD,
"()" + Constants.CLASS_DESC, false));
insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Constants.CLASS, RedirectInjector.IS_ASSIGNABLE_FROM_METHOD,
"(" + Constants.CLASS_DESC + ")Z", false));
insns.add(new JumpInsnNode(Opcodes.GOTO, checkComplete));
insns.add(objectIsNull);
insns.add(new InsnNode(Opcodes.POP)); // remove ref
insns.add(new InsnNode(Opcodes.POP)); // remove class
insns.add(new InsnNode(Opcodes.ICONST_0));
insns.add(checkComplete);
extraStack.add();
}
// private void modifyInstanceOfType(Target target, TypeInsnNode typeNode) {
// if (this.methodArgs.length > 0) {
// throw new InvalidInjectionException(this.info, String.format("%s on %s has an invalid signature. Found %d unexpected additional method"
// + "arguments, expected 0. INSTANCEOF handler expects ()Lthe/replacement/Type; or (Ljava/lang/Object;Ljava/lang/Class;)Z",
// this.annotationType, this, this.methodArgs.length));
// }
//
// // Already know that returnType is an object or array so no need to check again
// typeNode.desc = this.returnType.getInternalName();
// this.info.addCallbackInvocation(this.methodNode);
// }
private void doNullCheck(InsnList insns, Extension extraStack, String type, String value) {
LabelNode nullCheckSucceeded = new LabelNode();
insns.add(new InsnNode(Opcodes.DUP));
insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded));
this.throwException(insns, RedirectInjector.NPE, String.format("%s %s %s returned null for %s",
this.annotationType, type, this, value));
insns.add(nullCheckSucceeded);
extraStack.add();
}
}
@@ -41,6 +41,7 @@ import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Locals;
import org.spongepowered.asm.util.PrettyPrinter;
import org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable;
import org.spongepowered.asm.util.SignaturePrinter;
/**
@@ -54,7 +55,7 @@ public class LocalVariableDiscriminator {
* Discriminator context information, wraps all relevant information about
* a target location for use when performing discrimination
*/
public static class Context implements org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable {
public static class Context implements IPrettyPrintable {
/**
* Information about a local variable in the LVT, used during
@@ -147,21 +147,18 @@ public class ModifyVariableInjector extends Injector {
Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget());
if (this.discriminator.printLVT()) {
this.printLocals(context);
this.printLocals(target, context);
}
String handlerDesc = Bytecode.getDescriptor(new Type[] { this.returnType }, this.returnType);
if (!handlerDesc.equals(this.methodNode.desc)) {
throw new InvalidInjectionException(this.info, "Variable modifier " + this + " has an invalid signature, expected " + handlerDesc
+ " but found " + this.methodNode.desc);
}
InjectorData handler = new InjectorData(target, "handler", false);
this.validateParams(handler, this.returnType, this.returnType);
Extension extraStack = target.extendStack();
try {
int local = this.discriminator.findLocal(context);
if (local > -1) {
this.inject(context, extraStack, local);
this.inject(context, handler, extraStack, local);
}
} catch (InvalidImplicitDiscriminatorException ex) {
if (this.discriminator.printLVT()) {
@@ -178,17 +175,18 @@ public class ModifyVariableInjector extends Injector {
/**
* Pretty-print local variable information to stderr
*/
private void printLocals(final Context context) {
SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, this.returnType, this.methodArgs, new String[] { "var" });
private void printLocals(Target target, Context context) {
SignaturePrinter handlerSig = new SignaturePrinter(this.info.getMethodName(), this.returnType, this.methodArgs, new String[] { "var" });
handlerSig.setModifiers(this.methodNode);
new PrettyPrinter()
.kvWidth(20)
.kv("Target Class", this.classNode.name.replace('/', '.'))
.kv("Target Method", context.target.method.name)
.kv("Callback Name", this.methodNode.name)
.kv("Callback Name", this.info.getMethodName())
.kv("Capture Type", SignaturePrinter.getTypeName(this.returnType, false))
.kv("Instruction", "%s %s", context.node.getClass().getSimpleName(), Bytecode.getOpcodeName(context.node.getOpcode())).hr()
.kv("Instruction", "[%d] %s %s", target.insns.indexOf(context.node), context.node.getClass().getSimpleName(),
Bytecode.getOpcodeName(context.node.getOpcode())).hr()
.kv("Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)")
.kv("Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal())
.kv("Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex())
@@ -205,7 +203,7 @@ public class ModifyVariableInjector extends Injector {
* @param extraStack stack extension
* @param local local variable to capture
*/
private void inject(final Context context, Extension extraStack, final int local) {
private void inject(final Context context, InjectorData handler, Extension extraStack, final int local) {
if (!this.isStatic) {
context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0));
extraStack.add();
@@ -213,6 +211,11 @@ public class ModifyVariableInjector extends Injector {
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local));
extraStack.add();
if (handler.captureTargetArgs > 0) {
this.pushArgs(handler.target.arguments, context.insns, handler.target.getArgIndices(), 0, handler.captureTargetArgs, extraStack);
}
this.invokeHandler(context.insns);
context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local));
}
@@ -35,7 +35,7 @@ import org.spongepowered.asm.util.asm.ElementNode;
* defining the query parameters. They are used by injectors and other
* components which need to identify a target element using a string.
*
* <h4>Explicit Target Selectors</h4>
* <h3>Explicit Target Selectors</h3>
*
* <p><b>Explicit</b> Target Selectors are handled internally using
* {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the
@@ -43,6 +43,13 @@ import org.spongepowered.asm.util.asm.ElementNode;
*/
public interface ITargetSelector {
/**
* Get the next target selector in this path (or <tt>null</tt> if this
* selector is the last selector in the chain. Called at recurse points in
* the subject in order to match against the child subject.
*/
public abstract ITargetSelector next();
/**
* Configure and return a modified version of this selector by consuming the
* supplied arguments. Results from this method should be idempotent in
@@ -204,6 +204,11 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
* Map of lists of nodes enumerated by calling {@link #prepare}
*/
protected final Map<Target, List<InjectionNode>> targetNodes = new LinkedHashMap<Target, List<InjectionNode>>();
/**
* Number of target methods identified by the injection points
*/
protected int targetCount = 0;
/**
* Bytecode injector
@@ -267,18 +272,18 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
return;
}
String type = "@" + Bytecode.getSimpleName(this.annotation);
List<AnnotationNode> injectionPoints = this.readInjectionPoints(type);
this.findMethods(this.parseTargets(type), type);
this.parseInjectionPoints(injectionPoints);
List<AnnotationNode> injectionPoints = this.readInjectionPoints();
this.parseRequirements();
this.findMethods(this.parseTargets());
this.parseInjectionPoints(injectionPoints);
this.injector = this.parseInjector(this.annotation);
}
protected Set<ITargetSelector> parseTargets(String type) {
protected Set<ITargetSelector> parseTargets() {
List<String> methods = Annotations.<String>getValue(this.annotation, "method", false);
if (methods == null) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", type, this.method.name));
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name",
this.annotationType, this.methodName));
}
Set<ITargetSelector> selectors = new LinkedHashSet<ITargetSelector>();
@@ -286,26 +291,26 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
try {
selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin));
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", type,
this.method.name, method, this.mixin.getReferenceMapper().getStatus()));
throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s",
this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus()));
} catch (TargetNotSupportedException ex) {
throw new InvalidInjectionException(this,
String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.method.name,
ex.getMessage()));
String.format("%s annotation on %s specifies a target class '%s', which is not supported",
this.annotationType, this.methodName, ex.getMessage()));
} catch (InvalidSelectorException ex) {
throw new InvalidInjectionException(this,
String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.method.name,
String.format("%s annotation on %s is decorated with an invalid selector: %s", this.annotationType, this.methodName,
ex.getMessage()));
}
}
return selectors;
}
protected List<AnnotationNode> readInjectionPoints(String type) {
protected List<AnnotationNode> readInjectionPoints() {
List<AnnotationNode> ats = Annotations.<AnnotationNode>getValue(this.annotation, this.atKey, false);
if (ats == null) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", type, this.method.name,
this.atKey));
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)",
this.annotationType, this.methodName, this.atKey));
}
return ats;
}
@@ -384,18 +389,18 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
String dynamicInfo = this.getDynamicInfo();
if ((this.mixin.getEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) {
throw new InvalidInjectionException(this,
String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. %s%s", description,
this.method.name, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, refMapStatus,
dynamicInfo));
String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. Scanned %d target(s). %s%s",
description, this.methodName, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount,
this.targetCount, refMapStatus, dynamicInfo));
} else if (this.injectedCallbackCount < this.requiredCallbackCount) {
throw new InjectionError(
String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded. %s%s", description,
this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, refMapStatus,
dynamicInfo));
String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded. Scanned %d target(s). %s%s",
description, this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount,
this.targetCount, refMapStatus, dynamicInfo));
} else if (this.injectedCallbackCount > this.maxCallbackCount) {
throw new InjectionError(
String.format("Critical injection failure: %s %s%s in %s failed injection check, %d succeeded of %d allowed.%s",
description, this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, dynamicInfo));
description, this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, dynamicInfo));
}
}
@@ -485,9 +490,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
* Finds methods in the target class which match searchFor
*
* @param selectors members to search for
* @param type annotation type
*/
private void findMethods(Set<ITargetSelector> selectors, String type) {
private void findMethods(Set<ITargetSelector> selectors) {
this.targets.clear();
// When remapping refmap is enabled this implies we are in a development
@@ -521,10 +525,20 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
}
if (this.targets.size() == 0) {
this.targetCount = this.targets.size();
if (this.targetCount > 0) {
return;
}
if ((this.mixin.getEnvironment().getOption(Option.DEBUG_INJECTORS) && this.expectedCallbackCount > 0)) {
throw new InvalidInjectionException(this,
String.format("%s annotation on %s could not find any targets matching %s in the target class %s. %s%s",
type, this.method.name, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
String.format("Injection validation failed: %s annotation on %s could not find any targets matching %s in %s. %s%s",
this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()));
} else if (this.requiredCallbackCount > 0) {
throw new InvalidInjectionException(this,
String.format("Critical injection failure: %s annotation on %s could not find any targets matching %s in %s. %s%s",
this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(),
this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()));
}
}
@@ -261,6 +261,11 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec
this.unparsed = null;
}
@Override
public ITargetSelector next() {
return null; // Not supported yet
}
@Override
public String getOwner() {
return this.owner;
@@ -55,8 +55,8 @@ public class ModifyConstantInjectionInfo extends InjectionInfo {
}
@Override
protected List<AnnotationNode> readInjectionPoints(String type) {
List<AnnotationNode> ats = super.readInjectionPoints(type);
protected List<AnnotationNode> readInjectionPoints() {
List<AnnotationNode> ats = super.readInjectionPoints();
if (ats.isEmpty()) {
AnnotationNode c = new AnnotationNode(ModifyConstantInjectionInfo.CONSTANT_ANNOTATION_CLASS);
c.visit("log", Boolean.TRUE);
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.throwables;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.transformer.ActivityStack;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
@@ -43,31 +44,61 @@ public class InvalidInjectionException extends InvalidMixinException {
this.info = null;
}
public InvalidInjectionException(IMixinContext context, String message, ActivityStack activityContext) {
super(context, message, activityContext);
this.info = null;
}
public InvalidInjectionException(InjectionInfo info, String message) {
super(info.getContext(), message);
this.info = info;
}
public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) {
super(info.getContext(), message, activityContext);
this.info = info;
}
public InvalidInjectionException(IMixinContext context, Throwable cause) {
super(context, cause);
this.info = null;
}
public InvalidInjectionException(IMixinContext context, Throwable cause, ActivityStack activityContext) {
super(context, cause, activityContext);
this.info = null;
}
public InvalidInjectionException(InjectionInfo info, Throwable cause) {
super(info.getContext(), cause);
this.info = info;
}
public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) {
super(info.getContext(), cause, activityContext);
this.info = info;
}
public InvalidInjectionException(IMixinContext context, String message, Throwable cause) {
super(context, message, cause);
this.info = null;
}
public InvalidInjectionException(IMixinContext context, String message, Throwable cause, ActivityStack activityContext) {
super(context, message, cause, activityContext);
this.info = null;
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) {
super(info.getContext(), message, cause);
this.info = info;
}
public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) {
super(info.getContext(), message, cause, activityContext);
this.info = info;
}
public InjectionInfo getInjectionInfo() {
return this.info;
}
@@ -30,6 +30,8 @@ import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.asm.MethodNodeEx;
/**
* Information about a special mixin method such as an injector or accessor
@@ -41,6 +43,11 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
*/
protected final AnnotationNode annotation;
/**
* Human-readable annotation type
*/
protected final String annotationType;
/**
* Class
*/
@@ -50,6 +57,11 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
* Annotated method
*/
protected final MethodNode method;
/**
* Original name of the method, if available
*/
protected final String methodName;
/**
* Mixin data
@@ -60,7 +72,9 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
this.mixin = mixin;
this.method = method;
this.annotation = annotation;
this.annotationType = this.annotation != null ? "@" + Bytecode.getSimpleName(this.annotation) : "Undecorated injector";
this.classNode = mixin.getTargetClassNode();
this.methodName = method instanceof MethodNodeEx ? ((MethodNodeEx)this.method).getOriginalName() : method.name;
}
/**
@@ -101,5 +115,12 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext {
public final MethodNode getMethod() {
return this.method;
}
/**
* Get the original name of the method, if available
*/
public String getMethodName() {
return this.methodName;
}
}
@@ -271,9 +271,18 @@ class MixinApplicatorStandard {
final void apply(SortedSet<MixinInfo> mixins) {
List<MixinTargetContext> mixinContexts = new ArrayList<MixinTargetContext>();
for (MixinInfo mixin : mixins) {
this.logger.log(mixin.getLoggingLevel(), "Mixing {} from {} into {}", mixin.getName(), mixin.getParent(), this.targetName);
mixinContexts.add(mixin.createContextFor(this.context));
for (Iterator<MixinInfo> iter = mixins.iterator(); iter.hasNext();) {
MixinInfo mixin = iter.next();
try {
this.logger.log(mixin.getLoggingLevel(), "Mixing {} from {} into {}", mixin.getName(), mixin.getParent(), this.targetName);
mixinContexts.add(mixin.createContextFor(this.context));
} catch (InvalidMixinException ex) {
if (mixin.isRequired()) {
throw ex;
}
this.context.addSuppressed(ex);
iter.remove(); // Do not process this mixin further
}
}
MixinTargetContext current = null;
@@ -292,9 +301,18 @@ class MixinApplicatorStandard {
activity.next("%s Applicator Phase", pass);
Section timer = this.profiler.begin("pass", pass.name().toLowerCase(Locale.ROOT));
Activity applyActivity = this.activities.begin("Mixin");
for (MixinTargetContext context : mixinContexts) {
applyActivity.next(context.toString());
this.applyMixin(current = context, pass);
for (Iterator<MixinTargetContext> iter = mixinContexts.iterator(); iter.hasNext();) {
current = iter.next();
applyActivity.next(current.toString());
try {
this.applyMixin(current, pass);
} catch (InvalidMixinException ex) {
if (current.isRequired()) {
throw ex;
}
this.context.addSuppressed(ex);
iter.remove(); // Do not process this mixin further
}
}
applyActivity.end();
timer.end();
@@ -302,9 +320,18 @@ class MixinApplicatorStandard {
activity.next("PostApply Phase");
Activity postApplyActivity = this.activities.begin("Mixin");
for (MixinTargetContext context : mixinContexts) {
postApplyActivity.next(context.toString());
(current = context).postApply(this.targetName, this.targetClass);
for (Iterator<MixinTargetContext> iter = mixinContexts.iterator(); iter.hasNext();) {
current = iter.next();
postApplyActivity.next(current.toString());
try {
current.postApply(this.targetName, this.targetClass);
} catch (InvalidMixinException ex) {
if (current.isRequired()) {
throw ex;
}
this.context.addSuppressed(ex);
iter.remove();
}
}
activity.end();
} catch (InvalidMixinException ex) {
@@ -161,6 +161,11 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
*/
private final transient Set<String> unhandledTargets = new HashSet<String>();
/**
* Mixins which have been parsed but not yet prepared
*/
private final transient List<MixinInfo> pendingMixins = new ArrayList<MixinInfo>();
/**
* All mixins loaded by this config
*/
@@ -690,7 +695,7 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
}
private void prepareMixins(List<String> mixinClasses, boolean suppressPlugin) {
private void prepareMixins(List<String> mixinClasses, boolean ignorePlugin) {
if (mixinClasses == null) {
return;
}
@@ -705,9 +710,25 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
MixinInfo mixin = null;
try {
mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, suppressPlugin);
this.pendingMixins.add(mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, ignorePlugin));
MixinConfig.globalMixinList.add(fqMixinClass);
} catch (InvalidMixinException ex) {
if (this.required) {
throw ex;
}
this.logger.error(ex.getMessage(), ex);
} catch (Exception ex) {
if (this.required) {
throw new InvalidMixinException(mixin, "Error initialising mixin " + mixin + " - " + ex.getClass() + ": " + ex.getMessage(), ex);
}
this.logger.error(ex.getMessage(), ex);
}
}
for (MixinInfo mixin : this.pendingMixins) {
try {
mixin.parseTargets();
if (mixin.getTargetClasses().size() > 0) {
MixinConfig.globalMixinList.add(fqMixinClass);
for (String targetClass : mixin.getTargetClasses()) {
String targetClassName = targetClass.replace('/', '.');
this.mixinsFor(targetClassName).add(mixin);
@@ -730,6 +751,8 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
this.logger.error(ex.getMessage(), ex);
}
}
this.pendingMixins.clear();
}
void postApply(String transformedName, ClassNode targetClass) {
@@ -971,6 +994,18 @@ final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
return this.mixinMapping.containsKey(targetClass);
}
boolean hasPendingMixinsFor(String targetClass) {
if (this.packageMatch(targetClass)) {
return false;
}
for (MixinInfo pendingMixin : this.pendingMixins) {
if (pendingMixin.hasDeclaredTarget(targetClass)) {
return true;
}
}
return false;
}
/**
* Get mixins for the specified target class
*
@@ -39,6 +39,7 @@ import org.apache.logging.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.MethodVisitor;
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;
@@ -63,17 +64,18 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException;
import org.spongepowered.asm.service.IClassTracker;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.asm.ASM;
import org.spongepowered.asm.util.asm.MethodNodeEx;
import org.spongepowered.asm.util.CompareUtil;
import org.spongepowered.asm.util.perf.Profiler;
import org.spongepowered.asm.util.perf.Profiler.Section;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
/**
@@ -84,22 +86,10 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* A MethodNode in a mixin
*/
class MixinMethodNode extends MethodNode {
private final String originalName;
class MixinMethodNode extends MethodNodeEx {
public MixinMethodNode(int access, String name, String desc, String signature, String[] exceptions) {
super(ASM.API_VERSION, access, name, desc, signature, exceptions);
this.originalName = name;
}
@Override
public String toString() {
return String.format("%s%s", this.originalName, this.desc);
}
public String getOriginalName() {
return this.originalName;
super(access, name, desc, signature, exceptions, MixinInfo.this);
}
public boolean isInjector() {
@@ -121,10 +111,6 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
public AnnotationNode getInjectorAnnotation() {
return InjectionInfo.getInjectorAnnotation(MixinInfo.this, this);
}
public IMixinInfo getOwner() {
return MixinInfo.this;
}
}
@@ -672,9 +658,35 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
}
/**
* Mixin service
* Handle for a declared target on a mixin.
*/
private static final IMixinService classLoaderUtil = MixinService.getService();
static final class DeclaredTarget {
final String name;
final boolean isPrivate;
private DeclaredTarget(String name, boolean isPrivate) {
this.name = name;
this.isPrivate = isPrivate;
}
@Override
public String toString() {
return this.name;
}
static DeclaredTarget of(Object target, MixinInfo info) {
if (target instanceof String) {
String remappedName = info.remapClassName((String)target);
return remappedName != null ? new DeclaredTarget(remappedName, true) : null;
} else if (target instanceof Type) {
return new DeclaredTarget(((Type)target).getClassName(), false);
}
return null;
}
}
/**
* Global order of mixin infos, used to determine ordering between mixins
@@ -719,13 +731,19 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Mixin targets, read from the {@link Mixin} annotation on the mixin class
* but not yet parsed in the current environment
*/
private final List<ClassInfo> targetClasses;
private final transient List<DeclaredTarget> declaredTargets;
/**
* Mixin targets, read from the {@link Mixin} annotation on the mixin class
*/
private final transient List<ClassInfo> targetClasses = new ArrayList<ClassInfo>();
/**
* Names of target classes
*/
private final List<String> targetClassNames;
private final List<String> targetClassNames = new ArrayList<String>();
/**
* Intrinsic order (for sorting mixins with identical priority)
@@ -778,10 +796,10 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
* @param parent configuration which owns this mixin, the parent
* @param name name of this mixin (class name stub)
* @param plugin mixin config companion plugin handle
* @param suppressPlugin true to suppress the plugin from filtering targets
* of this mixin
* @param ignorePlugin true to prevent the plugin from filtering targets of
* this mixin
*/
MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean suppressPlugin) {
MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean ignorePlugin) {
this.service = service;
this.parent = parent;
this.name = name;
@@ -806,15 +824,32 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
// Inject the mixin class name into the LaunchClassLoader's invalid
// classes set so that any classes referencing the mixin directly will
// cause the game to crash
MixinInfo.classLoaderUtil.registerInvalidClass(this.className);
IClassTracker tracker = this.service.getClassTracker();
if (tracker != null) {
tracker.registerInvalidClass(this.className);
}
}
// Read the class bytes and transform
try {
this.priority = this.readPriority(this.pendingState.getClassNode());
this.virtual = this.readPseudo(this.pendingState.getValidationClassNode());
this.targetClasses = this.readTargetClasses(this.pendingState.getValidationClassNode(), suppressPlugin);
this.targetClassNames = Collections.<String>unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction()));
this.declaredTargets = this.readDeclaredTargets(this.pendingState.getValidationClassNode(), ignorePlugin);
} catch (InvalidMixinException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidMixinException(this, ex);
}
}
/**
* Parse the declared targets from the annotation into ClassInfo instances
* and perform initial validation of each target
*/
void parseTargets() {
try {
this.targetClasses.addAll(this.readTargetClasses(this.declaredTargets));
this.targetClassNames.addAll(Lists.transform(this.targetClasses, Functions.toStringFunction()));
} catch (InvalidMixinException ex) {
throw ex;
} catch (Exception ex) {
@@ -839,15 +874,15 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
}
/**
* Read the target class names from the {@link Mixin} annotation
* Read the declared target class names from the {@link Mixin} annotation
*
* @param classNode mixin classnode
* @param suppressPlugin true to suppress plugin filtering targets
* @param ignorePlugin true to suppress plugin filtering targets
* @return target class list read from classNode
*/
protected List<ClassInfo> readTargetClasses(MixinClassNode classNode, boolean suppressPlugin) {
protected List<DeclaredTarget> readDeclaredTargets(MixinClassNode classNode, boolean ignorePlugin) {
if (classNode == null) {
return Collections.<ClassInfo>emptyList();
return Collections.<DeclaredTarget>emptyList();
}
AnnotationNode mixin = Annotations.getInvisible(classNode, Mixin.class);
@@ -855,75 +890,98 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
}
List<ClassInfo> targets = new ArrayList<ClassInfo>();
List<org.objectweb.asm.Type> publicTargets = Annotations.getValue(mixin, "value");
List<String> privateTargets = Annotations.getValue(mixin, "targets");
if (publicTargets != null) {
this.readTargets(targets, Lists.transform(publicTargets, new Function<org.objectweb.asm.Type, String>() {
@Override
public String apply(org.objectweb.asm.Type input) {
return input.getClassName();
}
}), suppressPlugin, false);
}
if (privateTargets != null) {
this.readTargets(targets, Lists.transform(privateTargets, new Function<String, String>() {
@Override
public String apply(String input) {
return MixinInfo.this.getParent().remapClassName(MixinInfo.this.getClassRef(), input);
}
}), suppressPlugin, true);
}
return targets;
}
/**
* Reads a target list into the outTargets list
*/
private void readTargets(Collection<ClassInfo> outTargets, Collection<String> inTargets, boolean suppressPlugin, boolean checkPublic) {
for (String targetRef : inTargets) {
String targetName = targetRef.replace('/', '.');
if (MixinInfo.classLoaderUtil.isClassLoaded(targetName) && !this.isReloading()) {
String message = String.format("Critical problem: %s target %s was loaded too early.", this, targetName);
IClassTracker tracker = this.service.getClassTracker();
List<DeclaredTarget> declaredTargets = new ArrayList<DeclaredTarget>();
for (Object target : this.readTargets(mixin)) {
DeclaredTarget declaredTarget = DeclaredTarget.of(target, this);
if (declaredTarget == null) {
continue;
}
if (tracker != null && tracker.isClassLoaded(declaredTarget.name) && !this.isReloading()) {
String message = String.format("Critical problem: %s target %s was loaded too early.", this, declaredTarget.name);
if (this.parent.isRequired()) {
throw new MixinTargetAlreadyLoadedException(this, message, targetName);
throw new MixinTargetAlreadyLoadedException(this, message, declaredTarget.name);
}
this.logger.error(message);
}
if (this.shouldApplyMixin(suppressPlugin, targetName)) {
ClassInfo targetInfo = this.getTarget(targetName, checkPublic);
if (targetInfo != null && !outTargets.contains(targetInfo)) {
outTargets.add(targetInfo);
targetInfo.addMixin(this);
}
if (this.shouldApplyMixin(ignorePlugin, declaredTarget.name)) {
declaredTargets.add(declaredTarget);
}
}
return declaredTargets;
}
private boolean shouldApplyMixin(boolean suppressPlugin, String targetName) {
/**
* Combine the public and private mixin targets from the supplied annotation
* and return them as an interable collection
*
* @param mixin mixin annotation
* @return target list
*/
private Iterable<Object> readTargets(AnnotationNode mixin) {
Iterable<Object> publicTargets = Annotations.getValue(mixin, "value");
Iterable<Object> privateTargets = Annotations.getValue(mixin, "targets");
if (publicTargets == null && privateTargets == null) {
return Collections.<Object>emptyList();
}
if (publicTargets == null) {
return privateTargets;
}
return privateTargets == null ? publicTargets : Iterables.concat(publicTargets, privateTargets);
}
/**
* Check whether this mixin should apply to the specified taret
*
* @param ignorePlugin true to ignore the config plugin
* @param targetName target class name
* @return true if the mixin should be a pplied
*/
private boolean shouldApplyMixin(boolean ignorePlugin, String targetName) {
Section pluginTimer = this.profiler.begin("plugin");
boolean result = suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className);
boolean result = ignorePlugin || this.plugin.shouldApplyMixin(targetName, this.className);
pluginTimer.end();
return result;
}
private ClassInfo getTarget(String targetName, boolean checkPublic) throws InvalidMixinException {
ClassInfo targetInfo = ClassInfo.forName(targetName);
/**
* Read and parse target classes from the supplied class node
*
* @param classNode class node to parse
* @param ignorePlugin true to ignore the config plugin when deciding
* whether to apply declared targets
* @return new list of target classes
*/
List<ClassInfo> readTargetClasses(MixinClassNode classNode, boolean ignorePlugin) {
return this.readTargetClasses(this.readDeclaredTargets(classNode, ignorePlugin));
}
private List<ClassInfo> readTargetClasses(List<DeclaredTarget> declaredTargets) throws InvalidMixinException {
List<ClassInfo> targetClasses = new ArrayList<ClassInfo>();
for (DeclaredTarget target : declaredTargets) {
ClassInfo targetClass = this.getTargetClass(target);
if (targetClass != null) {
targetClasses.add(targetClass);
targetClass.addMixin(this);
}
}
return targetClasses;
}
private ClassInfo getTargetClass(DeclaredTarget target) throws InvalidMixinException {
ClassInfo targetInfo = ClassInfo.forName(target.name);
if (targetInfo == null) {
if (this.isVirtual()) {
this.logger.debug("Skipping virtual target {} for {}", targetName, this);
this.logger.debug("Skipping virtual target {} for {}", target.name, this);
} else {
this.handleTargetError(String.format("@Mixin target %s was not found %s", targetName, this));
this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this));
}
return null;
}
this.type.validateTarget(targetName, targetInfo);
if (checkPublic && targetInfo.isPublic() && !this.isVirtual()) {
this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", targetName, this));
this.type.validateTarget(target.name, targetInfo);
if (target.isPrivate && targetInfo.isPublic() && !this.isVirtual()) {
this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this));
}
return targetInfo;
}
@@ -964,6 +1022,19 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
return this.pendingState instanceof Reloaded;
}
String remapClassName(String className) {
return this.parent.remapClassName(this.getClassRef(), className);
}
public boolean hasDeclaredTarget(String targetClass) {
for (DeclaredTarget declaredTarget : this.declaredTargets) {
if (targetClass.equals(declaredTarget.name)) {
return true;
}
}
return false;
}
/**
* Current state, either the validated state or the uninitialised state if
* the mixin is initialising for the first time. Should never return null.
@@ -1072,6 +1143,13 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
return this.type.isLoadable();
}
/**
* True if the parent mixin config is marked as required
*/
public boolean isRequired() {
return this.parent.isRequired();
}
/**
* Get the logging level for this mixin
*/
@@ -1095,12 +1173,19 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
return this.getState().createClassNode(flags);
}
/**
* Get the target class names as declared for this mixin
*/
List<String> getDeclaredTargetClasses() {
return Collections.<String>unmodifiableList(Lists.transform(this.declaredTargets, Functions.toStringFunction()));
}
/**
* Get the target class names for this mixin
*/
@Override
public List<String> getTargetClasses() {
return this.targetClassNames;
return Collections.<String>unmodifiableList(this.targetClassNames);
}
/**
@@ -1165,9 +1250,12 @@ class MixinInfo implements Comparable<MixinInfo>, IMixinInfo {
ClassNode classNode = null;
try {
String restrictions = this.service.getClassRestrictions(mixinClassName);
if (restrictions.length() > 0) {
this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName);
IClassTracker tracker = this.service.getClassTracker();
if (tracker != null) {
String restrictions = tracker.getClassRestrictions(mixinClassName);
if (restrictions.length() > 0) {
this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName);
}
}
classNode = this.service.getBytecodeProvider().getClassNode(mixinClassName, true);
} catch (ClassNotFoundException ex) {
@@ -512,10 +512,14 @@ class MixinPreProcessorStandard {
String type = method.isSynthetic() ? "synthetic" : "@Unique";
if (Bytecode.getVisibility(mixinMethod).ordinal() < Visibility.PUBLIC.ordinal()) {
String uniqueName = context.getUniqueName(mixinMethod, false);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming {} method {}{} to {} in {}",
type, mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
mixinMethod.name = method.conform(uniqueName);
if (method.isConformed()) {
mixinMethod.name = method.getName();
} else {
String uniqueName = context.getUniqueName(mixinMethod, false);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming {} method {}{} to {} in {}",
type, mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
mixinMethod.name = method.conform(uniqueName);
}
return false;
}
@@ -597,7 +601,7 @@ class MixinPreProcessorStandard {
target = context.findRemappedField(mixinField);
if (target == null) {
// If this field is a shadow field but is NOT found in the target class, that's bad, mmkay
throw new InvalidMixinException(this.mixin, String.format("Shadow field %s was not located in the target class %s. %s%s",
throw new InvalidMixinException(this.mixin, String.format("@Shadow field %s was not located in the target class %s. %s%s",
mixinField.name, context.getTarget(), context.getReferenceMapper().getStatus(),
MixinPreProcessorStandard.getDynamicInfo(mixinField)));
}
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.lang.reflect.Constructor;
import java.text.DecimalFormat;
import java.util.*;
@@ -53,6 +52,7 @@ import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExpo
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.mixin.transformer.throwables.ReEntrantTransformerError;
import org.spongepowered.asm.service.IMixinService;
import org.spongepowered.asm.service.MixinService;
import org.spongepowered.asm.util.PrettyPrinter;
@@ -131,8 +131,6 @@ public class MixinProcessor {
}
}
private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent";
/**
* Log all the things
@@ -209,36 +207,16 @@ public class MixinProcessor {
/**
* ctor
*/
MixinProcessor(MixinEnvironment environment, Extensions extensions) {
MixinProcessor(MixinEnvironment environment, Extensions extensions, IHotSwap hotSwapper) {
this.lock = this.service.getReEntranceLock();
this.extensions = extensions;
this.hotSwapper = this.initHotSwapper(environment);
this.hotSwapper = hotSwapper;
this.postProcessor = new MixinPostProcessor(this.sessionId);
this.profiler = MixinEnvironment.getProfiler();
}
private IHotSwap initHotSwapper(MixinEnvironment environment) {
if (!environment.getOption(Option.HOT_SWAP)) {
return null;
}
try {
MixinProcessor.logger.info("Attempting to load Hot-Swap agent");
@SuppressWarnings("unchecked")
Class<? extends IHotSwap> clazz =
(Class<? extends IHotSwap>)Class.forName(MixinProcessor.MIXIN_AGENT_CLASS);
Constructor<? extends IHotSwap> ctor = clazz.getDeclaredConstructor(MixinProcessor.class);
return ctor.newInstance(this);
} catch (Throwable th) {
MixinProcessor.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
return null;
}
/**
* Force-load all classes targetted by mixins but not yet applied
*
@@ -282,7 +260,15 @@ public class MixinProcessor {
boolean locked = this.lock.push().check();
Section mixinTimer = this.profiler.begin("mixin");
if (!locked) {
if (locked) {
for (MixinConfig config : this.pendingConfigs) {
if (config.hasPendingMixinsFor(name)) {
ReEntrantTransformerError error = new ReEntrantTransformerError("Re-entrance error.");
MixinProcessor.logger.warn("Re-entrance detected during prepare phase, this will cause serious problems.", error);
throw error;
}
}
} else {
try {
this.checkSelect(environment);
} catch (Exception ex) {
@@ -321,22 +307,22 @@ public class MixinProcessor {
mixins.addAll(config.getMixinsFor(name));
}
}
if (invalidRef) {
throw new NoClassDefFoundError(String.format("%s is a mixin class and cannot be referenced directly", name));
}
if (mixins != null) {
// Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now
if (locked) {
MixinApplyError error = new MixinApplyError("Re-entrance error.");
ReEntrantTransformerError error = new ReEntrantTransformerError("Re-entrance error.");
MixinProcessor.logger.warn("Re-entrance detected, this will cause serious problems.", error);
throw error;
}
if (this.hotSwapper != null) {
// TODO hotswapper
// this.hotSwapper.registerTargetClass(transformedName, basicClass);
this.hotSwapper.registerTargetClass(name, targetClassNode);
}
try {
@@ -353,7 +339,8 @@ public class MixinProcessor {
this.handleMixinApplyError(name, th, environment);
}
}
} catch (MixinTransformerError er) {
throw er;
} catch (Throwable th) {
th.printStackTrace();
this.dumpClassOnFailure(name, targetClassNode, environment);
@@ -539,7 +526,7 @@ public class MixinProcessor {
Section timer = this.profiler.begin("preapply");
this.extensions.preApply(context);
timer = timer.next("apply");
this.apply(context);
context.applyMixins();
timer = timer.next("postapply");
boolean export = false;
try {
@@ -554,15 +541,9 @@ public class MixinProcessor {
if (export) {
this.extensions.export(this.currentEnvironment, context.getClassName(), context.isExportForced(), context.getClassNode());
}
}
/**
* Apply the mixins to the target class
*
* @param context Target class context
*/
private void apply(TargetClassContext context) {
context.applyMixins();
for (InvalidMixinException suppressed : context.getSuppressedExceptions()) {
this.handleMixinApplyError(context.getClassName(), suppressed, environment);
}
}
private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError {
@@ -589,6 +570,7 @@ public class MixinProcessor {
if (environment.getOption(Option.DEBUG_VERBOSE)) {
new PrettyPrinter()
.wrapTo(160)
.add("Invalid Mixin").centre()
.hr('-')
.kvWidth(10)
@@ -602,7 +584,7 @@ public class MixinProcessor {
.addWrapped(" %s", ex.getMessage())
.hr('-')
.add(ex, 8)
.trace(action.logLevel);
.log(action.logLevel);
}
for (IMixinErrorHandler handler : this.getErrorHandlers(mixin.getPhase())) {
@@ -1048,6 +1048,13 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
MixinInfo getInfo() {
return this.mixin;
}
/**
* True if the parent mixin config is marked as required
*/
boolean isRequired() {
return this.mixin.isRequired();
}
/**
* Get the mixin priority
@@ -24,13 +24,16 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.lang.reflect.Constructor;
import java.util.List;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.transformer.ext.Extensions;
import org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry;
import org.spongepowered.asm.mixin.transformer.ext.IHotSwap;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.Constants;
import org.spongepowered.asm.util.asm.ASM;
@@ -40,10 +43,22 @@ import org.spongepowered.asm.util.asm.ASM;
*/
class MixinTransformer extends TreeTransformer implements IMixinTransformer {
private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent";
/**
* Synthetic class registry
*/
private final SyntheticClassRegistry syntheticClassRegistry;
/**
* Transformer extensions
*/
private final Extensions extensions;
/**
* Hotswap agent, if available
*/
private final IHotSwap hotSwapper;
/**
* Mixin processor which actually manages application of mixins
@@ -55,11 +70,6 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer {
*/
private final MixinClassGenerator generator;
/**
* Synthetic class registry
*/
private final SyntheticClassRegistry syntheticClassRegistry;
public MixinTransformer() {
MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment();
@@ -73,13 +83,35 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer {
this.syntheticClassRegistry = new SyntheticClassRegistry();
this.extensions = new Extensions(this.syntheticClassRegistry);
this.hotSwapper = this.initHotSwapper(environment);
this.processor = new MixinProcessor(environment, this.extensions);
this.processor = new MixinProcessor(environment, this.extensions, this.hotSwapper);
this.generator = new MixinClassGenerator(environment, this.extensions);
DefaultExtensions.create(environment, this.extensions, this.syntheticClassRegistry);
}
private IHotSwap initHotSwapper(MixinEnvironment environment) {
if (!environment.getOption(Option.HOT_SWAP)) {
return null;
}
try {
MixinProcessor.logger.info("Attempting to load Hot-Swap agent");
@SuppressWarnings("unchecked")
Class<? extends IHotSwap> clazz =
(Class<? extends IHotSwap>)Class.forName(MixinTransformer.MIXIN_AGENT_CLASS);
Constructor<? extends IHotSwap> ctor = clazz.getDeclaredConstructor(IMixinTransformer.class);
return ctor.newInstance(this);
} catch (Throwable th) {
MixinProcessor.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}",
th.getClass().getSimpleName(), th.getMessage());
}
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.transformer.IMixinTransformer
* #getExtensions()
@@ -24,6 +24,7 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
@@ -45,6 +46,7 @@ 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.throwables.InvalidMixinException;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.ClassSignature;
@@ -116,6 +118,12 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte
* target class.
*/
private final Set<MethodNode> mixinMethods = new HashSet<MethodNode>();
/**
* Exceptions which were suppressed during mixin application because they
* were raised by an optional mixin
*/
private final List<InvalidMixinException> suppressedExceptions = new ArrayList<InvalidMixinException>();
/**
* True once mixins have been applied to this class
@@ -383,4 +391,12 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte
}
}
void addSuppressed(InvalidMixinException ex) {
this.suppressedExceptions.add(ex);
}
List<InvalidMixinException> getSuppressedExceptions() {
return this.suppressedExceptions;
}
}
@@ -24,6 +24,8 @@
*/
package org.spongepowered.asm.mixin.transformer.ext;
import org.objectweb.asm.tree.ClassNode;
/**
* Interface to allow the hot-swap agent to be loaded on-demand
*/
@@ -42,11 +44,11 @@ public interface IHotSwap {
* Registers a class targeted by at least one mixin.
*
* <p>This is used to rollback the target class to a state before the
* mixin's were applied.</p>
* mixins were applied.</p>
*
* @param name Name of the class
* @param bytecode Bytecode of the class before mixin's have been applied
* @param classNode ASM tree of the class before mixins have been applied
*/
public abstract void registerTargetClass(String name, byte[] bytecode);
public abstract void registerTargetClass(String name, ClassNode classNode);
}
@@ -158,7 +158,7 @@ public class ExtensionClassExporter implements IExtension {
File outputFile = new File(this.classExportDir, fileName + ".class");
outputFile.getParentFile().mkdirs();
try {
byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode);
byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode, true);
if (bytecode != null) {
Files.write(bytecode, outputFile);
}
@@ -168,12 +168,22 @@ public class ExtensionClassExporter implements IExtension {
return outputFile;
}
private static byte[] getClassBytes(ClassNode classNode) {
private static byte[] getClassBytes(ClassNode classNode, boolean computeFrames) {
byte[] bytes = null;
try {
MixinClassWriter cw = new MixinClassWriter(ClassWriter.COMPUTE_FRAMES);
MixinClassWriter cw = new MixinClassWriter(computeFrames ? ClassWriter.COMPUTE_FRAMES : 0);
classNode.accept(cw);
bytes = cw.toByteArray();
} catch (NegativeArraySizeException ex) {
// Try again with compute frames turned off, this gives us a better chance
// of successful export when the class is corrupt which - given we are
// exporting for debugging purposes - is worthwhile so that we have a
// the bytecode to inspect!
if (computeFrames) {
ExtensionClassExporter.logger.warn("Exporting class {} with COMPUTE_FRAMES failed! Trying a raw export.", classNode.name);
return ExtensionClassExporter.getClassBytes(classNode, false);
}
ex.printStackTrace();
} catch (Exception ex) {
// well, damn
ex.printStackTrace();
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer.meta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -33,7 +32,7 @@ import java.lang.annotation.Target;
* Decoration annotation used by the mixin inner class generator to mark inner
* classes which have been generated from an existing inner class in a mixin
*/
@Target(ElementType.TYPE)
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.CLASS)
public @interface MixinInner {
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer.meta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -36,7 +35,7 @@ import java.lang.annotation.Target;
* <p>Decoration annotation used by the mixin applicator to mark methods in a
* class which have been added or overwritten by a mixin.</p>
*/
@Target({ ElementType.METHOD })
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.RUNTIME)
public @interface MixinMerged {
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer.meta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -33,7 +32,7 @@ import java.lang.annotation.Target;
* Decoration annotation used by postprocessor to mark methods which have had
* their contents replaced with a proxy.
*/
@Target({ ElementType.METHOD })
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.RUNTIME)
public @interface MixinProxy {
@@ -24,7 +24,6 @@
*/
package org.spongepowered.asm.mixin.transformer.meta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -35,7 +34,7 @@ import java.lang.annotation.Target;
* <p>Decoration annotation used by MixinInfo and MixinPreProcessor to mark
* methods in a mixin which have been renamed prior to being merged.</p>
*/
@Target({ ElementType.METHOD })
@Target({ /* No targets allowed */ })
@Retention(RetentionPolicy.RUNTIME)
public @interface MixinRenamed {
@@ -0,0 +1,46 @@
/*
* 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.throwables;
/**
* Error thrown when transformer re-entrance is detected
*/
public class ReEntrantTransformerError extends MixinTransformerError {
private static final long serialVersionUID = 7073583236491579255L;
public ReEntrantTransformerError(String message) {
super(message);
}
public ReEntrantTransformerError(Throwable cause) {
super(cause);
}
public ReEntrantTransformerError(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,62 @@
/*
* 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.service;
/**
* Class trackers are responsible for interacting with the class loading process
* to for the purposes of tracking class load activity and class load
* restrictions. This service component is entirely optional and services can
* elect to return <tt>null</tt> if the platform does not support this
* functionality.
*/
public interface IClassTracker {
/**
* Register an invalid class with the service classloader
*
* @param className invalid class name
*/
public abstract void registerInvalidClass(String className);
/**
* Check whether the specified class was already loaded by the service
* classloader
*
* @param className class name to check
* @return true if the class was already loaded
*/
public abstract boolean isClassLoaded(String className);
/**
* Check whether the specified class name is subject to any restrictions in
* the context of this service
*
* @param className class name to check
* @return comma-separated list of restrictions, empty string if no
* restrictions apply
*/
public abstract String getClassRestrictions(String className);
}
@@ -97,10 +97,20 @@ public interface IMixinService {
*/
public abstract IClassBytecodeProvider getBytecodeProvider();
// /**
// * Return the synthetic class registry for this service
// */
// public abstract ISyntheticClassRegistry getSyntheticClassRegistry();
/**
* Return the transformer provider for this service. <b>Note that unlike
* other service components, this component is allowed to be <tt>null</tt>
* for services which do not support transformers, or don't support
* interacting with them</b>!
*/
public abstract ITransformerProvider getTransformerProvider();
/**
* Return the class tracker for this service. <b>Note that unlike
* other service components, this component is allowed to be <tt>null</tt>
* for services which do not support this functionality</b>!
*/
public abstract IClassTracker getClassTracker();
/**
* Get additional platform agents for this service
@@ -130,49 +140,6 @@ public interface IMixinService {
*/
public abstract InputStream getResourceAsStream(String name);
/**
* Register an invalid class with the service classloader
*
* @param className invalid class name
*/
public abstract void registerInvalidClass(String className);
/**
* Check whether the specified class was already loaded by the service
* classloader
*
* @param className class name to check
* @return true if the class was already loaded
*/
public abstract boolean isClassLoaded(String className);
/**
* Check whether the specified class name is subject to any restrictions in
* the context of this service
*
* @param className class name to check
* @return comma-separated list of restrictions, empty string if no
* restrictions apply
*/
public abstract String getClassRestrictions(String className);
/**
* Get currently available transformers in the environment
*/
public abstract Collection<ITransformer> getTransformers();
/**
* Get currently available transformers in the environment
*/
public abstract Collection<ITransformer> getDelegatedTransformers();
/**
* Adds a transformer to the transformer exclusions list
*
* @param name Class transformer exclusion to add
*/
public abstract void addTransformerExclusion(String name);
/**
* Get the detected side name for this environment
*/
@@ -0,0 +1,54 @@
/*
* 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.service;
import java.util.Collection;
/**
* Interface for interacting with transforming classloaders. This service
* component is entirely optional and services can elect to return <tt>null</tt>
* if the platform does not support interacting with the transformer chain (or
* doesn't <em>have</em> a transformer chain!)
*/
public interface ITransformerProvider {
/**
* Get currently available transformers in the environment
*/
public abstract Collection<ITransformer> getTransformers();
/**
* Get currently available transformers in the environment
*/
public abstract Collection<ITransformer> getDelegatedTransformers();
/**
* Adds a transformer to the transformer exclusions list
*
* @param name Class transformer exclusion to add
*/
public abstract void addTransformerExclusion(String name);
}
@@ -257,10 +257,14 @@ public final class Annotations {
*
* @param method Source method
* @param annotationClass Type of annotation to search for
* @param paramIndex Index of the parameter to fetch annotation for
* @param paramIndex Index of the parameter to fetch annotation for, or the
* method itself if less than zero
* @return the annotation, or null if not present
*/
public static AnnotationNode getVisibleParameter(MethodNode method, Class<? extends Annotation> annotationClass, int paramIndex) {
if (paramIndex < 0) {
return Annotations.getVisible(method, annotationClass);
}
return Annotations.getParameter(method.visibleParameterAnnotations, Type.getDescriptor(annotationClass), paramIndex);
}
@@ -270,10 +274,14 @@ public final class Annotations {
*
* @param method Source method
* @param annotationClass Type of annotation to search for
* @param paramIndex Index of the parameter to fetch annotation for
* @param paramIndex Index of the parameter to fetch annotation for, or the
* method itself if less than zero
* @return the annotation, or null if not present
*/
public static AnnotationNode getInvisibleParameter(MethodNode method, Class<? extends Annotation> annotationClass, int paramIndex) {
if (paramIndex < 0) {
return Annotations.getInvisible(method, annotationClass);
}
return Annotations.getParameter(method.invisibleParameterAnnotations, Type.getDescriptor(annotationClass), paramIndex);
}
@@ -506,12 +514,16 @@ public final class Annotations {
}
int existingIndex = 0;
for (int pos = 0; pos < annotation.values.size() - 1; pos += 2) {
String keyName = annotation.values.get(pos).toString();
if (key.equals(keyName)) {
existingIndex = pos + 1;
break;
if (annotation.values != null) {
for (int pos = 0; pos < annotation.values.size() - 1; pos += 2) {
String keyName = annotation.values.get(pos).toString();
if (key.equals(keyName)) {
existingIndex = pos + 1;
break;
}
}
} else {
annotation.values = new ArrayList<Object>();
}
if (existingIndex > 0) {
@@ -183,13 +183,15 @@ public final class Bytecode {
Opcodes.LCONST_0, Opcodes.LCONST_1,
Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2,
Opcodes.DCONST_0, Opcodes.DCONST_1,
Opcodes.BIPUSH, // 15
Opcodes.SIPUSH, // 16
Opcodes.LDC, // 17
Opcodes.BIPUSH, // 15
Opcodes.SIPUSH, // 16
Opcodes.LDC, // 17
Opcodes.CHECKCAST, // 18
Opcodes.INSTANCEOF // 19
};
private static final Object[] CONSTANTS_VALUES = {
null,
Type.VOID_TYPE,
Integer.valueOf(-1),
Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5),
Long.valueOf(0L), Long.valueOf(1L),
@@ -538,7 +540,7 @@ public final class Bytecode {
* argument or "this"
*/
public static int getFirstNonArgLocalIndex(MethodNode method) {
return Bytecode.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), (method.access & Opcodes.ACC_STATIC) == 0);
return Bytecode.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), !Bytecode.isStatic(method));
}
/**
@@ -565,15 +567,29 @@ public final class Bytecode {
* @return size of the specified arguments array in terms of stack slots
*/
public static int getArgsSize(Type[] args) {
return Bytecode.getArgsSize(args, 0, args.length);
}
/**
* Get the size of the specified args array in local variable terms (eg.
* doubles and longs take two spaces) using startIndex (inclusive) and
* endIndex (exclusive) to determine which arguments to process.
*
* @param args Method argument types as array
* @param startIndex Start index in the array, not related to arg size
* @param endIndex End index (exclusive) in the array, not related to size
* @return size of the specified arguments array in terms of stack slots
*/
public static int getArgsSize(Type[] args, int startIndex, int endIndex) {
int size = 0;
for (Type type : args) {
size += type.getSize();
for (int index = startIndex; index < args.length && index < endIndex; index++) {
size += args[index].getSize();
}
return size;
}
/**
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate
* for each entry in the args array starting at pos
@@ -588,7 +604,8 @@ public final class Bytecode {
/**
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate
* for each entry in the args array starting at start and ending at end
* for each entry in the args array starting at start (inclusive) and ending
* at end (inclusive)
*
* @param args Argument types
* @param insns Instruction List to inject into
@@ -601,7 +618,8 @@ public final class Bytecode {
/**
* Injects appropriate LOAD opcodes into the supplied InsnList appropriate
* for each entry in the args array starting at start and ending at end
* for each entry in the args array starting at start (inclusive) and ending
* at end (inclusive)
*
* @param args Argument types
* @param insns Instruction List to inject into
@@ -610,18 +628,17 @@ public final class Bytecode {
* @param casts Type casts array
*/
public static void loadArgs(Type[] args, InsnList insns, int start, int end, Type[] casts) {
int pos = start, index = 0;
int pos = start;
for (Type type : args) {
insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), pos));
for (int index = 0; index < args.length; index++) {
insns.add(new VarInsnNode(args[index].getOpcode(Opcodes.ILOAD), pos));
if (casts != null && index < casts.length && casts[index] != null) {
insns.add(new TypeInsnNode(Opcodes.CHECKCAST, casts[index].getInternalName()));
}
pos += type.getSize();
pos += args[index].getSize();
if (end >= start && pos >= end) {
return;
}
index++;
}
}
@@ -646,6 +663,17 @@ public final class Bytecode {
return labels;
}
/**
* Generate a bytecode descriptor from the supplied types.
*
* @param returnType the method return type, can be <tt>null</tt> for
* <tt>void</tt>
* @param args argument types
*/
public static String generateDescriptor(Type returnType, Type... args) {
return Bytecode.generateDescriptor(returnType, (Object[])args);
}
/**
* Generate a bytecode descriptor from the supplied tokens. Each token can
* be a {@link Type}, a {@link Class} or otherwise is converted in-place by
@@ -689,18 +717,18 @@ public final class Bytecode {
* @param args argument types
* @return method descriptor without return type
*/
public static String getDescriptor(Type[] args) {
public static String getDescriptor(Type... args) {
return "(" + Joiner.on("").join(args) + ")";
}
/**
* Generate a method descriptor with the specified types
*
* @param args argument types
* @param returnType return type
* @param args argument types
*
* @return generated method descriptor
*/
public static String getDescriptor(Type[] args, Type returnType) {
public static String getDescriptor(Type returnType, Type... args) {
return Bytecode.getDescriptor(args) + returnType.toString();
}
@@ -783,7 +811,7 @@ public final class Bytecode {
*
* @param insn constant instruction to process
* @return the constant value or <tt>null</tt> if the value cannot be parsed
* (or is null)
* (<tt>null</tt> constant is returned as <tt>Type.VOID_TYPE</tt>)
*/
public static Object getConstant(AbstractInsnNode insn) {
if (insn == null) {
@@ -796,6 +824,11 @@ public final class Bytecode {
return Integer.valueOf(value);
}
throw new IllegalArgumentException("IntInsnNode with invalid opcode " + insn.getOpcode() + " in getConstant");
} else if (insn instanceof TypeInsnNode) {
if (insn.getOpcode() < Opcodes.CHECKCAST) {
return null; // Don't treat NEW and ANEWARRAY as constants
}
return Type.getObjectType(((TypeInsnNode)insn).desc);
}
int index = Ints.indexOf(Bytecode.CONSTANTS_ALL, insn.getOpcode());
@@ -806,8 +839,8 @@ public final class Bytecode {
* Returns the {@link Type} of a particular constant instruction's payload
*
* @param insn constant instruction
* @return type of constant or <tt>null</tt> if it cannot be parsed (or is
* null)
* @return type of constant or <tt>null</tt> if it cannot be parsed (<tt>
* null</tt> constant is returned as <tt>Type.VOID_TYPE</tt>)
*/
public static Type getConstantType(AbstractInsnNode insn) {
if (insn == null) {
@@ -828,6 +861,11 @@ public final class Bytecode {
return Type.getType(Constants.CLASS_DESC);
}
throw new IllegalArgumentException("LdcInsnNode with invalid payload type " + cst.getClass() + " in getConstant");
} else if (insn instanceof TypeInsnNode) {
if (insn.getOpcode() < Opcodes.CHECKCAST) {
return null; // Don't treat NEW and ANEWARRAY as constants
}
return Type.getType(Constants.CLASS_DESC);
}
int index = Ints.indexOf(Bytecode.CONSTANTS_ALL, insn.getOpcode());
@@ -378,6 +378,11 @@ public class PrettyPrinter {
}
/**
* Minimum allowed width
*/
private static final int MIN_WIDTH = 40;
/**
* Horizontal rule
*/
@@ -421,7 +426,8 @@ public class PrettyPrinter {
}
public PrettyPrinter(int width) {
this.width = width;
this.width = Math.max(PrettyPrinter.MIN_WIDTH, width);
this.wrapWidth = this.width - 20;
}
/**
@@ -684,7 +690,7 @@ public class PrettyPrinter {
*/
public PrettyPrinter add(Throwable th, int indent) {
while (th != null) {
this.add("%s: %s", th.getClass().getName(), th.getMessage());
this.addWrapped(" %s: %s", th.getClass().getName(), th.getMessage());
this.add(th.getStackTrace(), indent);
th = th.getCause();
}
@@ -776,14 +782,14 @@ public class PrettyPrinter {
public PrettyPrinter addWrapped(int width, String format, Object... args) {
String indent = "";
String line = String.format(format, args).replace("\t", " ");
Matcher indentMatcher = Pattern.compile("^(\\s+)(.*)$").matcher(line);
if (indentMatcher.matches()) {
Matcher indentMatcher = Pattern.compile("^(\\s+)[^\\s]").matcher(line);
if (indentMatcher.find()) {
indent = indentMatcher.group(1);
}
try {
for (String wrappedLine : this.getWrapped(width, line, indent)) {
this.addLine(wrappedLine);
this.add(wrappedLine);
}
} catch (Exception ex) {
this.add(line);
@@ -795,7 +801,7 @@ public class PrettyPrinter {
List<String> lines = new ArrayList<String>();
while (line.length() > width) {
int wrapPoint = line.lastIndexOf(' ', width);
int wrapPoint = PrettyPrinter.lastBreakIndex(line, width);
if (wrapPoint < 10) {
wrapPoint = width;
}
@@ -811,6 +817,11 @@ public class PrettyPrinter {
return lines;
}
private static int lastBreakIndex(String line, int width) {
int lineBreakPos = line.lastIndexOf('\n', width);
return lineBreakPos > -1 ? lineBreakPos : Math.max(line.lastIndexOf(' ', width), line.lastIndexOf('\t', width));
}
/**
* Add a formatted key/value pair to the output
*
@@ -1099,6 +1110,16 @@ public class PrettyPrinter {
return this.log(logger, Level.INFO);
}
/**
* Write this printer to the specified logger at {@link Level#INFO}
*
* @param level log level
* @return fluent interface
*/
public PrettyPrinter log(Level level) {
return this.log(LogManager.getLogger(PrettyPrinter.getDefaultLoggerName()), level);
}
/**
* Write this printer to the specified logger
*
@@ -85,7 +85,15 @@ public class SignaturePrinter {
public SignaturePrinter(String name, String desc) {
this(name, Type.getReturnType(desc), Type.getArgumentTypes(desc));
}
public SignaturePrinter(Type[] args) {
this(null, null, args);
}
public SignaturePrinter(Type returnType, Type[] args) {
this(null, returnType, args);
}
public SignaturePrinter(String name, Type returnType, Type[] args) {
this.name = name;
this.returnType = returnType;
@@ -193,7 +201,8 @@ public class SignaturePrinter {
*/
@Override
public String toString() {
return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(this.name), false, true).toString();
String name = this.name != null ? this.name : "method";
return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(name), false, true).toString();
}
/**
@@ -254,6 +263,17 @@ public class SignaturePrinter {
}
return sb;
}
/**
* Get the source code name for the specified type
*
* @param type Type to generate a friendly name for
* @return String representation of the specified type, eg "int" for an
* integer primitive or "String" for java.lang.String
*/
public static String getTypeName(Type type) {
return SignaturePrinter.getTypeName(type, false, true);
}
/**
* Get the source code name for the specified type
@@ -277,6 +297,9 @@ public class SignaturePrinter {
* integer primitive or "String" for java.lang.String
*/
public static String getTypeName(Type type, boolean box, boolean fullyQualified) {
if (type == null) {
return "{null?}";
}
switch (type.getSort()) {
case Type.VOID: return box ? "Void" : "void";
case Type.BOOLEAN: return box ? "Boolean" : "boolean";
@@ -0,0 +1,62 @@
/*
* 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.util.asm;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
/**
* MethodNode with some extra convenience functionality
*/
public class MethodNodeEx extends MethodNode {
private final IMixinInfo owner;
private final String originalName;
public MethodNodeEx(int access, String name, String descriptor, String signature, String[] exceptions, IMixinInfo owner) {
super(ASM.API_VERSION, access, name, descriptor, signature, exceptions);
this.originalName = name;
this.owner = owner;
}
@Override
public String toString() {
return String.format("%s%s", this.originalName, this.desc);
}
public String getQualifiedName() {
return String.format("%s::%s", this.owner.getName(), this.originalName);
}
public String getOriginalName() {
return this.originalName;
}
public IMixinInfo getOwner() {
return this.owner;
}
}
@@ -108,4 +108,5 @@ public class MixinTransformationHandler implements IClassProcessor {
}
return transformer.transformClass(environment, classType.getClassName(), classNode);
}
}
@@ -34,7 +34,8 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
import org.spongepowered.asm.mixin.transformer.MixinTransformationHandler;
import org.spongepowered.asm.service.IClassBytecodeProvider;
import org.spongepowered.asm.service.IClassProvider;
import org.spongepowered.asm.service.ITransformer;
import org.spongepowered.asm.service.IClassTracker;
import org.spongepowered.asm.service.ITransformerProvider;
import org.spongepowered.asm.service.MixinServiceAbstract;
import org.spongepowered.asm.util.IConsumer;
@@ -171,6 +172,25 @@ public class MixinServiceModLauncher extends MixinServiceAbstract {
}
return this.bytecodeProvider;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getTransformerProvider()
*/
@Override
public ITransformerProvider getTransformerProvider() {
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getClassTracker()
*/
@Override
public IClassTracker getClassTracker() {
if (this.classTracker == null) {
this.classTracker = new ModLauncherClassTracker();
}
return this.classTracker;
}
/**
* Get (or create) the transformation handler
@@ -181,16 +201,6 @@ public class MixinServiceModLauncher extends MixinServiceAbstract {
}
return this.transformationHandler;
}
/**
* Get (or create) the class tracker
*/
private ModLauncherClassTracker getClassTracker() {
if (this.classTracker == null) {
this.classTracker = new ModLauncherClassTracker();
}
return this.classTracker;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getPlatformAgents()
@@ -219,59 +229,6 @@ public class MixinServiceModLauncher extends MixinServiceAbstract {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#registerInvalidClass(
* java.lang.String)
*/
@Override
public void registerInvalidClass(String className) {
this.getClassTracker().registerInvalidClass(className);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#isClassLoaded(
* java.lang.String)
*/
@Override
public boolean isClassLoaded(String className) {
return this.getClassTracker().isClassLoaded(className);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getClassRestrictions(
* java.lang.String)
*/
@Override
public String getClassRestrictions(String className) {
return this.getClassTracker().getClassRestrictions(className);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#getTransformers()
*/
@Override
public Collection<ITransformer> getTransformers() {
return ImmutableList.<ITransformer>of();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService
* #getDelegatedTransformers()
*/
@Override
public Collection<ITransformer> getDelegatedTransformers() {
return ImmutableList.<ITransformer>of();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IMixinService#addTransformerExclusion(
* java.lang.String)
*/
@Override
public void addTransformerExclusion(String name) {
// TODO ?
}
/**
* Internal method to retrieve the class processors which will be called by
* the launch plugin
@@ -279,7 +236,7 @@ public class MixinServiceModLauncher extends MixinServiceAbstract {
public Collection<IClassProcessor> getProcessors() {
return ImmutableList.<IClassProcessor>of(
this.getTransformationHandler(),
this.getClassTracker()
(IClassProcessor)this.getClassTracker()
);
}
@@ -32,6 +32,7 @@ import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.spongepowered.asm.launch.IClassProcessor;
import org.spongepowered.asm.launch.Phases;
import org.spongepowered.asm.service.IClassTracker;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase;
@@ -40,25 +41,40 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase;
* TCL and class load events so we can report when classes were loaded before
* we could transform them
*/
public class ModLauncherClassTracker implements IClassProcessor {
public class ModLauncherClassTracker implements IClassProcessor, IClassTracker {
private final Set<String> invalidClasses = new HashSet<String>();
private final Set<String> loadedClasses = new HashSet<String>();
void registerInvalidClass(String className) {
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IClassTracker#registerInvalidClass(
* java.lang.String)
*/
@Override
public void registerInvalidClass(String className) {
synchronized (this.invalidClasses) {
this.invalidClasses.add(className);
}
}
boolean isClassLoaded(String className) {
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IClassTracker#isClassLoaded(
* java.lang.String)
*/
@Override
public boolean isClassLoaded(String className) {
synchronized (this.loadedClasses) {
return this.loadedClasses.contains(className);
}
}
String getClassRestrictions(String className) {
/* (non-Javadoc)
* @see org.spongepowered.asm.service.IClassTracker#getClassRestrictions(
* java.lang.String)
*/
@Override
public String getClassRestrictions(String className) {
return ""; // TODO ?
}