diff --git a/README.MD b/README.MD index c862da1d..a9797c48 100644 --- a/README.MD +++ b/README.MD @@ -1,3 +1,4 @@ + ### [![Build Status](http://ci.liteloader.com/view/Other/job/Mixin/badge/icon)](http://ci.liteloader.com/view/Other/job/Mixin/lastSuccessfulBuild/) ![Mixin Logo](docs/logo.png?raw=true) @@ -64,6 +65,54 @@ plugin developed by [DemonWav](https://github.com/demonwav). + + 0.8 + August 2019 + + + + + + 0.7.11 + July 2018 + + + + 0.7.10 June 2018 diff --git a/build.gradle b/build.gradle index 158ef23d..eb85dd86 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ buildscript { } dependencies { classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0' - classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.3' + classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.4' } } @@ -35,9 +35,8 @@ ext.packaging = 'jar' ext.buildNumber = project.hasProperty("buildNumber") ? buildNumber : '0' ext.ciSystem = project.hasProperty("ciSystem") ? ciSystem : 'unknown' ext.commit = project.hasProperty("commit") ? commit : 'unknown' - -// Location to store renamed packages -ext.renamedPackageRoot = new File("build/renamed-packages/") +ext.asmVersion = project.hasProperty("asmVersion") ? asmVersion : '6.2' +ext.legacyForgeAsmVersion = project.hasProperty("legacyForgeAsmVersion") ? asmVersion : '5.0.3' // True to do jar signing task ext.doSignJar = project.hasProperty("keyStorePath") @@ -53,28 +52,30 @@ repositories { name = 'minecraft' url = 'https://libraries.minecraft.net/' } - maven { - name = 'renamed-packages' - url = file(renamedPackageRoot) - } maven { // For fernflower name = 'sponge' url = 'http://repo.spongepowered.org/maven' } + maven { + // For modlauncher + name = 'forge' + url = 'https://files.minecraftforge.net/maven' + } } configurations { deployerJars // maven stuff - asm // renamer input - jarjar // renamer task - - // Exclude non-repackaged ASM so that we don't use it by mistake - compile.exclude module: 'asm-debug-all' + thinJar + stagingJar } // Include annotation processor sourceSet sourceSets { + legacy + main { + compileClasspath += legacy.output + } ap { compileClasspath += main.output } @@ -94,69 +95,29 @@ sourceSets { launchwrapper { compileClasspath += main.output } -} - -// Dependencies for renamed ASM -dependencies { - asm 'org.ow2.asm:asm-debug-all:5.2' - asm 'org.ow2.asm:asm-debug-all:5.2:sources' - jarjar 'com.googlecode.jarjar:jarjar:1.1' -} - -// Task to read ASM library and rename packages -task renamedASM { - outputs.file files(configurations.asm.files.withIndex().collect { file, i -> def dep = configurations.asm.dependencies[i] - new File(new File(renamedPackageRoot, "org/spongepowered/mixin-" + dep.name + "/" + dep.version), "mixin-" + file.name).path - }) - ant { - taskdef ( - name: "jarjar", - classname: "com.tonicsystems.jarjar.JarJarTask", - classpath: configurations.jarjar.asPath, - ) - outputs.files.eachWithIndex { elem, index -> - logger.info "Generating renamed jar {}", elem.name - def inJar = configurations.asm.files[index] - if (elem.name.contains("sources")) { - def tmpDir = new File(temporaryDir, elem.name + ".tmp") - def rootOld = new File(tmpDir, "org/objectweb") - def tmpOld = new File(rootOld, "asm") - def tmpNew = new File(tmpDir, "org/spongepowered/asm/lib") - unzip (src: inJar, dest: tmpDir) - replace (dir: tmpDir, token: "org.objectweb.asm", value: "org.spongepowered.asm.lib") - move (file: tmpOld, tofile: tmpNew) - delete rootOld - jar (destFile: new File(elem.path)) { fileset(dir: tmpDir) } - delete tmpDir - } else { - jarjar (jarfile: elem.path) { - zipfileset (src: inJar) - rule ( - pattern: "org.objectweb.asm.**", - result: "org.spongepowered.asm.lib.@1" - ) - } - } - } + modlauncher { + compileClasspath += main.output + sourceCompatibility = '1.8' + targetCompatibility = '1.8' } - - project.dependencies.add('compile', 'org.spongepowered:mixin-asm-debug-all:5.2') - project.dependencies.add('apCompile', 'org.spongepowered:mixin-asm-debug-all:5.2') - project.dependencies.add('agentCompile', 'org.spongepowered:mixin-asm-debug-all:5.2') - } -eclipseClasspath.dependsOn(renamedASM) // Project dependencies dependencies { - def guava = 'com.google.guava:guava:17.0' + 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 - compile 'commons-io:commons-io:2.4' compile 'com.google.code.gson:gson:2.2.4' - compile files(tasks.renamedASM.outputs.files[0]) // Establish implicit dependency on remapped ASM + compile "org.ow2.asm:asm-tree:$asmVersion" + compile "org.ow2.asm:asm-commons:$asmVersion" + compile "org.ow2.asm:asm-util:$asmVersion" + + thinJar "org.ow2.asm:asm-tree:$asmVersion" + thinJar "org.ow2.asm:asm-util:$asmVersion" + + stagingJar "org.ow2.asm:asm-util:$asmVersion" // Tests // testCompile 'junit:junit:4.11' @@ -164,6 +125,7 @@ dependencies { // testCompile 'org.mockito:mockito-core:1.9.0' // Annotation Processor + apCompile "org.ow2.asm:asm-tree:$asmVersion" apCompile guava // AP extension example @@ -178,22 +140,35 @@ dependencies { // LegacyLauncher service launchwrapperCompile configurations.compile - launchwrapperCompile('net.minecraft:launchwrapper:1.11') { + launchwrapperCompile ('net.minecraft:launchwrapper:1.11') { exclude module: 'lwjgl' } + modlauncherCompile configurations.compile + modlauncherCompile 'net.sf.jopt-simple:jopt-simple:5.0.4' + modlauncherCompile ('cpw.mods:modlauncher:3.2.0') { + exclude module: 'log4j-core' + } + // agent agentCompile configurations.compile // asm bridge bridgeCompile log4j2 - bridgeCompile 'org.ow2.asm:asm-commons:5.0.3' + bridgeCompile "org.ow2.asm:asm-commons:$legacyForgeAsmVersion" + + legacyCompile "org.ow2.asm:asm-tree:$asmVersion" +} + +javadoc { + classpath += sourceSets.legacy.output // why? } // Eclipse eclipse.classpath.plusConfigurations += [ configurations.fernflowerCompile, configurations.launchwrapperCompile, + configurations.modlauncherCompile, configurations.bridgeCompile ] @@ -201,6 +176,7 @@ eclipse.classpath.plusConfigurations += [ idea.module.scopes.COMPILE.plus += [ configurations.fernflowerCompile, configurations.launchwrapperCompile, + configurations.modlauncherCompile, configurations.bridgeCompile ] @@ -240,7 +216,7 @@ checkstyle { // Source compiler configuration tasks.withType(JavaCompile) { - options.compilerArgs += ['-Xlint:all', '-Xlint:-path'] + options.compilerArgs += ['-Xlint:all', '-Xlint:-path', '-proc:none'] options.deprecation = true options.encoding = 'utf8' } @@ -252,37 +228,17 @@ if (JavaVersion.current().isJava8Compatible()) { } } -jar { - // Include annotation processor - from sourceSets.ap.output - - // Include fernflower bridge - from sourceSets.fernflower.output - - // Include hotswap agent - from sourceSets.agent.output - - // Bridge - from sourceSets.bridge.output - - // Launchwrapper - from sourceSets.launchwrapper.output - - // Renamed ASM - from zipTree(tasks.renamedASM.outputs.files[0]).matching { - include 'org/spongepowered/asm/lib/*' - include 'org/spongepowered/asm/lib/commons/*Remapper*' - include 'org/spongepowered/asm/lib/commons/Remapper*' - include 'org/spongepowered/asm/lib/commons/SignatureRemapper*' - include 'org/spongepowered/asm/lib/signature/**' - include 'org/spongepowered/asm/lib/tree/**' - include 'org/spongepowered/asm/lib/util/**' +task stagingJar(type: com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar) { + sourceSets.each { + if (it.name != 'example') { + from it.output + } } - exclude 'org/objectweb/**' + configurations = [project.configurations.stagingJar] // JAR manifest configuration - manifest.mainAttributes( + manifest.attributes( "Built-By": System.properties['user.name'], "Created-By": System.properties['java.vm.version'] + " (" + System.properties['java.vm.vendor'] + ")", "Implementation-Title": name, @@ -298,18 +254,18 @@ jar { if (project.doSignJar) { classifier = 'unsigned' } + + mergeServiceFiles() } +// Clear artifacts because jar will be there by default and we want to use staging jar instead +configurations.archives.artifacts.clear() + task thinJar(type: Jar) { from sourceSets.main.output - from zipTree(tasks.renamedASM.outputs.files[0]) +// from { configurations.thinJar.collect { zipTree(it) } classifier = 'thin' - exclude 'org/objectweb/**' - exclude 'org/spongepowered/asm/lib/commons/**' - exclude 'org/spongepowered/asm/lib/signature/**' - exclude 'org/spongepowered/asm/lib/tree/analysis/**' - exclude 'org/spongepowered/asm/lib/xml/**' exclude 'org/spongepowered/asm/launch/**' exclude 'org/spongepowered/asm/mixin/injection/invoke/**' exclude 'org/spongepowered/asm/mixin/transformer/*.class' @@ -334,7 +290,6 @@ shadowJar { dependencies { include(dependency('com.google.guava:guava')) include(dependency('com.google.code.gson:gson')) - include(dependency('commons-io:commons-io')) include(dependency('org.apache.logging.log4j:log4j-core')) include(dependency('org.apache.logging.log4j:log4j-api')) } @@ -343,13 +298,10 @@ shadowJar { build.dependsOn(shadowJar) if (project.doSignJar) { - // Clear artifacts because jar will be there by default - configurations.archives.artifacts.clear() - // Define signjar task task signJar() { inputs.files(jar.outputs) - outputs.file jar.outputs.files.collect { + outputs.files jar.outputs.files.collect { new File(it.parent, it.name.replace('-unsigned', '')) } doLast { @@ -378,18 +330,10 @@ task timestamp(type: Jar, dependsOn: build) { } task sourceJar(type: Jar) { - from sourceSets.main.java - from sourceSets.main.resources - from sourceSets.ap.java - from sourceSets.ap.resources - from sourceSets.fernflower.java - from sourceSets.fernflower.resources - from sourceSets.agent.java - from sourceSets.agent.resources - from sourceSets.bridge.java - from sourceSets.bridge.resources - from sourceSets.example.java - from sourceSets.example.resources + sourceSets.each { + from it.java + from it.resources + } classifier = "sources" } @@ -401,6 +345,8 @@ task javadocJar(type: Jar, dependsOn: javadoc) { artifacts { if (project.doSignJar) { archives signJar.outputs.files[0] + } else { + archives stagingJar } archives thinJar archives sourceJar @@ -435,7 +381,7 @@ uploadArchives { artifactId = project.archivesBaseName project { name project.archivesBaseName - packaging 'jar' + packaging project.packaging description project.projectName url 'http://www.spongepowered.org/' diff --git a/checkstyle.xml b/checkstyle.xml index 6ba29b3a..a00c9b81 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -128,9 +128,6 @@ - - - diff --git a/gradle.properties b/gradle.properties index 770852b0..c0dd8d2e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,5 +4,7 @@ packaging=jar description=Mixin url=https://www.spongepowered.org organization=SpongePowered -buildVersion=0.7.12 +buildVersion=0.8-preview buildType=SNAPSHOT +asmVersion=6.2 +legacyForgeAsmVersion=5.0.3 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 552180ee..41affa0d 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 736aafb8..7e90c87d 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -34,11 +34,14 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.mixin.transformer.MixinTransformer; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.transformer.IMixinTransformer; import org.spongepowered.asm.mixin.transformer.ext.IHotSwap; import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.util.Bytecode; /** * An agent that re-transforms a mixin's target classes if the mixin has been @@ -61,11 +64,14 @@ public class MixinAgent implements IHotSwap { byte[] mixinBytecode = MixinAgent.classLoader.getFakeMixinBytecode(classBeingRedefined); if (mixinBytecode != null) { - List targets = this.reloadMixin(className, classfileBuffer); + ClassNode classNode = new ClassNode(Bytecode.ASM_API_VERSION); + ClassReader cr = new ClassReader(classfileBuffer); + cr.accept(classNode, ClassReader.EXPAND_FRAMES); + + List targets = this.reloadMixin(className, classNode); if (targets == null || !this.reApplyMixins(targets)) { return MixinAgent.ERROR_BYTECODE; } - return mixinBytecode; } @@ -78,10 +84,10 @@ public class MixinAgent implements IHotSwap { } } - private List reloadMixin(String className, byte[] classfileBuffer) { + private List reloadMixin(String className, ClassNode classNode) { MixinAgent.logger.info("Redefining mixin {}", className); try { - return MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classfileBuffer); + return MixinAgent.this.classTransformer.reload(className.replace('/', '.'), classNode); } catch (MixinReloadException e) { MixinAgent.logger.error("Mixin {} cannot be reloaded, needs a restart to be applied: {} ", e.getMixinInfo(), e.getMessage()); } catch (Throwable th) { @@ -149,7 +155,7 @@ public class MixinAgent implements IHotSwap { /** * MixinTransformer instance to use to transform the mixin's target classes */ - final MixinTransformer classTransformer; + final IMixinTransformer classTransformer; /** * Constructs an agent from a class transformer in which it will use to @@ -158,7 +164,7 @@ public class MixinAgent implements IHotSwap { * @param classTransformer Class transformer that will transform a mixin's * target class */ - public MixinAgent(MixinTransformer classTransformer) { + public MixinAgent(IMixinTransformer classTransformer) { this.classTransformer = classTransformer; MixinAgent.agents.add(this); if (MixinAgent.instrumentation != null) { diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java index 3decd055..192ac448 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java @@ -29,10 +29,10 @@ import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.MethodVisitor; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.util.Constants; diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 53f48b35..b8b0a317 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -33,7 +33,8 @@ import javax.lang.model.element.VariableElement; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -373,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()); + this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation.asMirror(), "constraints"); } } @@ -420,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); + this.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation, "target"); } } } @@ -435,9 +436,9 @@ 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); + this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation, "visibility"); } else if (visTarget == Visibility.PRIVATE && visMethod.ordinal() > visTarget.ordinal()) { - this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation); + this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation, "visibility"); } } @@ -468,7 +469,7 @@ abstract class AnnotatedMixinElementHandler { } if (targetField == null) { - this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, annotation.asMirror()); + this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, annotation.asMirror(), "target"); } } } @@ -477,26 +478,35 @@ abstract class AnnotatedMixinElementHandler { * Checks whether the referenced method exists in all targets and raises * warnings where appropriate */ - protected final void validateReferencedTarget(ExecutableElement method, AnnotationHandle inject, MemberInfo reference, String type) { - String signature = reference.toDescriptor(); + protected final void validateReferencedTarget(ExecutableElement method, AnnotationHandle inject, ITargetSelector reference, String type) { + if (!(reference instanceof ITargetSelectorByName)) { + return; + } + + ITargetSelectorByName nameRef = (ITargetSelectorByName)reference; + String signature = nameRef.toDescriptor(); for (TypeHandle target : this.mixin.getTargets()) { if (target.isImaginary()) { continue; } - MethodHandle targetMethod = target.findMethod(reference.name, signature); + 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()); + this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(), "target"); } } } private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation) { + this.printMessage(kind, msg, e, annotation, null); + } + + private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation, String suppressedBy) { if (annotation == null) { - this.ap.printMessage(kind, msg, e); + this.ap.printMessage(kind, msg, e, suppressedBy); } else { - this.ap.printMessage(kind, msg, e, annotation.asMirror()); + this.ap.printMessage(kind, msg, e, annotation.asMirror(), suppressedBy); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index 71c6fae8..57f46220 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -25,15 +25,18 @@ package org.spongepowered.tools.obfuscation; import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.AccessorInfo; +import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorName; import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorType; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -41,6 +44,7 @@ import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.asm.util.Constants; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; @@ -61,11 +65,11 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH */ static class AnnotatedElementAccessor extends AnnotatedElement { - private final boolean shouldRemap; + protected final boolean shouldRemap; - private final TypeMirror returnType; + protected final TypeMirror returnType; - private String targetName; + protected String targetName; public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { super(element, annotation); @@ -73,6 +77,9 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH this.returnType = this.getElement().getReturnType(); } + public void attach(TypeHandle target) { + } + public boolean shouldRemap() { return this.shouldRemap; } @@ -100,7 +107,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH return TypeUtils.getInternalName(this.getTargetType()); } - public MemberInfo getContext() { + public ITargetSelectorRemappable getContext() { return new MemberInfo(this.getTargetName(), null, this.getAccessorDesc()); } @@ -115,21 +122,66 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH public String getTargetName() { return this.targetName; } + + public TypeMirror getReturnType() { + return this.returnType; + } + + public boolean isStatic() { + return this.element.getModifiers().contains(Modifier.STATIC); + } @Override public String toString() { return this.targetName != null ? this.targetName : ""; } + } /** * Invoker element */ static class AnnotatedElementInvoker extends AnnotatedElementAccessor { + + private AccessorType type = AccessorType.METHOD_PROXY; public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { super(element, annotation, shouldRemap); } + + @Override + public void attach(TypeHandle target) { + this.type = AccessorType.METHOD_PROXY; + if (this.returnType.getKind() != TypeKind.DECLARED) { + return; + } + + String specifiedName = this.getAnnotationValue(); + if (specifiedName != null) { + if (Constants.CTOR.equals(specifiedName) || target.getName().equals(specifiedName.replace('.', '/'))) { + this.type = AccessorType.OBJECT_FACTORY; + } + return; + } + + AccessorName accessorName = AccessorName.of(this.getSimpleName(), false); + if (accessorName == null) { + return; + } + + for (String prefix : AccessorType.OBJECT_FACTORY.getExpectedPrefixes()) { + if (prefix.equals(accessorName.prefix) + && (Constants.CTOR.equals(accessorName.name) || target.getSimpleName().equals(accessorName.name))) { + this.type = AccessorType.OBJECT_FACTORY; + return; + } + } + } + + @Override + public boolean shouldRemap() { + return (this.type == AccessorType.METHOD_PROXY || this.getAnnotationValue() != null) && super.shouldRemap(); + } @Override public String getAccessorDesc() { @@ -138,7 +190,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH @Override public AccessorType getAccessorType() { - return AccessorType.METHOD_PROXY; + return this.type; } @Override @@ -216,7 +268,15 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH elem.setTargetName(targetName); for (TypeHandle target : this.mixin.getTargets()) { - if (elem.getAccessorType() == AccessorType.METHOD_PROXY) { + try { + elem.attach(target); + } catch (Exception ex) { + elem.printMessage(this.ap, Kind.ERROR, ex.getMessage()); + continue; + } + if (elem.getAccessorType() == AccessorType.OBJECT_FACTORY) { + this.registerFactoryForTarget((AnnotatedElementInvoker)elem, target); + } else if (elem.getAccessorType() == AccessorType.METHOD_PROXY) { this.registerInvokerForTarget((AnnotatedElementInvoker)elem, target); } else { this.registerAccessorForTarget(elem, target); @@ -288,6 +348,22 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } } + private void registerFactoryForTarget(AnnotatedElementInvoker elem, TypeHandle target) { + if (!elem.getReturnType().equals(target.getType())) { + throw new RuntimeException("Invalid Factory @Invoker return type, expected " + target.getType()); + } + if (!elem.isStatic()) { + throw new RuntimeException("Factory @Invoker must be static"); + } + + if (!elem.shouldRemap()) { + return; + } + + ObfuscationData obfData = this.obf.getDataProvider().getObfClass(elem.getAnnotationValue().replace('.', '/')); + this.obf.getReferenceManager().addClassMapping(this.mixin.getClassRef(), elem.getAnnotationValue(), obfData); + } + private String getAccessorTargetName(AnnotatedElementAccessor elem) { String value = elem.getAnnotationValue(); if (Strings.isNullOrEmpty(value)) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 732f8b84..5966ba34 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -35,9 +35,13 @@ import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.Coerce; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; @@ -152,18 +156,24 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } for (String reference : elem.getAnnotation().getList("method")) { - MemberInfo targetMember = MemberInfo.parse(reference); - if (targetMember.name == null) { - continue; - } + ITargetSelector targetSelector = TargetSelector.parse(reference); try { - targetMember.validate(); + targetSelector.validate(); } catch (InvalidMemberDescriptorException ex) { elem.printMessage(this.ap, Kind.ERROR, ex.getMessage()); } + + if (!(targetSelector instanceof ITargetSelectorRemappable)) { + continue; + } - if (targetMember.desc != null) { + ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector; + if (targetMember.getName() == null) { + continue; + } + + if (targetMember.getDesc() != null) { this.validateReferencedTarget(elem.getElement(), elem.getAnnotation(), targetMember, elem.toString()); } @@ -179,7 +189,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } } - private boolean registerInjector(AnnotatedElementInjector elem, String reference, MemberInfo targetMember, TypeHandle target) { + private boolean registerInjector(AnnotatedElementInjector elem, String reference, ITargetSelectorRemappable targetMember, TypeHandle target) { String desc = target.findDescriptor(targetMember); if (desc == null) { Kind error = this.mixin.isMultiTarget() ? Kind.ERROR : Kind.WARNING; @@ -194,8 +204,8 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return true; } - String targetName = elem + " target " + targetMember.name; - MappingMethod targetMethod = target.getMappingMethod(targetMember.name, desc); + String targetName = elem + " target " + targetMember.getName(); + MappingMethod targetMethod = target.getMappingMethod(targetMember.getName(), desc); ObfuscationData obfData = this.obf.getDataProvider().getObfMethod(targetMethod); if (obfData.isEmpty()) { if (target.isSimulated()) { @@ -212,17 +222,19 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler IReferenceManager refMap = this.obf.getReferenceManager(); try { // If the original owner is unspecified, and the mixin is multi-target, we strip the owner from the obf mappings - if ((targetMember.owner == null && this.mixin.isMultiTarget()) || target.isSimulated()) { + if ((targetMember.getOwner() == null && this.mixin.isMultiTarget()) || target.isSimulated()) { obfData = AnnotatedMixinElementHandler.stripOwnerData(obfData); } refMap.addMethodMapping(this.classRef, reference, obfData); } catch (ReferenceConflictException ex) { String conflictType = this.mixin.isMultiTarget() ? "Multi-target" : "Target"; - if (elem.hasCoerceArgument() && targetMember.owner == null && targetMember.desc == null) { - MemberInfo oldMember = MemberInfo.parse(ex.getOld()); - MemberInfo newMember = MemberInfo.parse(ex.getNew()); - if (oldMember.name.equals(newMember.name)) { + if (elem.hasCoerceArgument() && targetMember.getOwner() == null && targetMember.getDesc() == null) { + ITargetSelector oldMember = TargetSelector.parse(ex.getOld()); + ITargetSelector newMember = TargetSelector.parse(ex.getNew()); + String oldName = oldMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)oldMember).getName() : oldMember.toString(); + String newName = newMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)newMember).getName() : newMember.toString(); + if (oldName != null && oldName.equals(newName)) { obfData = AnnotatedMixinElementHandler.stripDescriptors(obfData); refMap.setAllowConflicts(true); refMap.addMethodMapping(this.classRef, reference, obfData); @@ -271,31 +283,34 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return; } - MemberInfo member = MemberInfo.parse(reference); - String target = member.toCtorType(); - - if (target != null) { - String desc = member.toCtorDesc(); - MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); - ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); - if (remapped.isEmpty()) { - this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), - elem.getAnnotation().asMirror()); - return; - } - - ObfuscationData mappings = new ObfuscationData(); - for (ObfuscationType type : remapped) { - MappingMethod mapping = remapped.get(type); - if (desc == null) { - mappings.put(type, mapping.getOwner()); - } else { - mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); - } - } + ITargetSelector selector = TargetSelector.parse(reference); + if (selector instanceof ITargetSelectorConstructor) { + ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; + String target = member.toCtorType(); - this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); - } + if (target != null) { + String desc = member.toCtorDesc(); + MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); + ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); + if (remapped.isEmpty()) { + this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), + elem.getAnnotation().asMirror(), "mapping"); + return; + } + + ObfuscationData mappings = new ObfuscationData(); + for (ObfuscationType type : remapped) { + MappingMethod mapping = remapped.get(type); + if (desc == null) { + mappings.put(type, mapping.getOwner()); + } else { + mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); + } + } + + this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); + } + } elem.notifyRemapped(); } @@ -304,13 +319,18 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (reference == null) { return; } - + + ITargetSelector targetSelector = TargetSelector.parse(reference); + if (!(targetSelector instanceof ITargetSelectorRemappable)) { + return; + } + ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector; + // JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work AnnotationMirror errorsOn = (this.ap.getCompilerEnvironment() == CompilerEnvironment.JDT ? elem.getAt() : elem.getAnnotation()).asMirror(); - MemberInfo targetMember = MemberInfo.parse(reference); if (!targetMember.isFullyQualified()) { - String missing = targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature"; + String missing = targetMember.getOwner() == null ? (targetMember.getDesc() == null ? "owner and signature" : "owner") : "signature"; this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorsOn); return; } @@ -326,16 +346,16 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); if (obfFieldData.isEmpty()) { this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn); + errorsOn, "mapping"); return; } this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData); } else { ObfuscationData obfMethodData = this.obf.getDataProvider().getObfMethodRecursive(targetMember); if (obfMethodData.isEmpty()) { - if (targetMember.owner == null || !targetMember.owner.startsWith("java/lang/")) { + if (targetMember.getOwner() == null || !targetMember.getOwner().startsWith("java/lang/")) { this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn); + errorsOn, "mapping"); return; } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java index 6df7e132..1905baf7 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java @@ -25,6 +25,7 @@ package org.spongepowered.tools.obfuscation; import java.lang.reflect.Method; +import java.util.Locale; import javax.lang.model.element.ExecutableElement; import javax.tools.Diagnostic.Kind; @@ -85,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()); + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", elem.getElement(), "overwrite"); return; } - if (!javadoc.toLowerCase().contains("@author")) { - this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", elem.getElement()); + if (!javadoc.toLowerCase(Locale.ROOT).contains("@author")) { + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", elem.getElement(), "overwrite"); } - if (!javadoc.toLowerCase().contains("@reason")) { - this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", elem.getElement()); + if (!javadoc.toLowerCase(Locale.ROOT).contains("@reason")) { + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", elem.getElement(), "overwrite"); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java index 112b7037..ffde81ea 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerShadow.java @@ -24,6 +24,8 @@ */ package org.spongepowered.tools.obfuscation; +import java.util.Locale; + import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.VariableElement; @@ -79,7 +81,7 @@ class AnnotatedMixinElementHandlerShadow extends AnnotatedMixinElementHandler { @Override public String toString() { - return this.getElementType().name().toLowerCase(); + return this.getElementType().name().toLowerCase(Locale.ROOT); } public ShadowElementName setObfuscatedName(IMapping name) { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index e5737a28..45da79de 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; @@ -49,7 +50,6 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; -import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import javax.tools.FileObject; import javax.tools.StandardLocation; @@ -74,6 +74,7 @@ import org.spongepowered.tools.obfuscation.validation.ParentValidator; import org.spongepowered.tools.obfuscation.validation.TargetValidator; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; /** * Mixin info manager, stores all of the mixin info during processing and also @@ -173,7 +174,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider if (tokens != null) { Pattern tokenPattern = Pattern.compile("^([A-Z0-9\\-_\\.]+)=([0-9]+)$"); - String[] tokenValues = tokens.replaceAll("\\s", "").toUpperCase().split("[;,]"); + String[] tokenValues = tokens.replaceAll("\\s", "").toUpperCase(Locale.ROOT).split("[;,]"); for (String tokenValue : tokenValues) { Matcher tokenMatcher = tokenPattern.matcher(tokenValue); if (tokenMatcher.matches()) { @@ -244,6 +245,24 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider return this.getProperties().getProperty(option); } + + @Override + public boolean getOption(String option, boolean defaultValue) { + String value = this.getOption(option); + return value != null ? Boolean.parseBoolean(value) : defaultValue; + } + + @Override + public List getOptions(String option) { + Builder list = ImmutableList.builder(); + String value = this.getOption(option); + if (value != null) { + for (String part : value.split(",")) { + list.add(part); + } + } + return list.build(); + } public Properties getProperties() { if (this.properties == null) { @@ -354,7 +373,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider } AnnotationHandle accessor = AnnotationHandle.of(method, Accessor.class); - mixinClass.registerAccessor(method, accessor, this.shouldRemap(mixinClass, accessor)); + mixinClass.registerAccessor(method, accessor, AnnotatedMixins.shouldRemap(mixinClass, accessor)); } /** @@ -371,7 +390,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider } AnnotationHandle invoker = AnnotationHandle.of(method, Invoker.class); - mixinClass.registerInvoker(method, invoker, this.shouldRemap(mixinClass, invoker)); + mixinClass.registerInvoker(method, invoker, AnnotatedMixins.shouldRemap(mixinClass, invoker)); } /** @@ -388,7 +407,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider } AnnotationHandle overwrite = AnnotationHandle.of(method, Overwrite.class); - mixinClass.registerOverwrite(method, overwrite, this.shouldRemap(mixinClass, overwrite)); + mixinClass.registerOverwrite(method, overwrite, AnnotatedMixins.shouldRemap(mixinClass, overwrite)); } /** @@ -405,7 +424,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider return; } - mixinClass.registerShadow(field, shadow, this.shouldRemap(mixinClass, shadow)); + mixinClass.registerShadow(field, shadow, AnnotatedMixins.shouldRemap(mixinClass, shadow)); } /** @@ -422,7 +441,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider return; } - mixinClass.registerShadow(method, shadow, this.shouldRemap(mixinClass, shadow)); + mixinClass.registerShadow(method, shadow, AnnotatedMixins.shouldRemap(mixinClass, shadow)); } /** @@ -440,7 +459,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider return; } - InjectorRemap remap = new InjectorRemap(this.shouldRemap(mixinClass, inject)); + InjectorRemap remap = new InjectorRemap(AnnotatedMixins.shouldRemap(mixinClass, inject)); mixinClass.registerInjector(method, inject, remap); remap.dispatchPendingMessages(this); } @@ -484,15 +503,25 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider } } - private boolean shouldRemap(AnnotatedMixin mixinClass, AnnotationHandle annotation) { + private static boolean shouldRemap(AnnotatedMixin mixinClass, AnnotationHandle annotation) { return annotation.getBoolean("remap", mixinClass.remap()); } + private static boolean shouldSuppress(Element element, String suppressedBy) { + if (element == null || suppressedBy == null) { + return false; + } + if (AnnotationHandle.of(element, SuppressWarnings.class).getList().contains(suppressedBy)) { + return true; + } + return AnnotatedMixins.shouldSuppress(element.getEnclosingElement(), suppressedBy); + } + /** * Print a message to the AP messager */ @Override - public void printMessage(Diagnostic.Kind kind, CharSequence msg) { + public void printMessage(Kind kind, CharSequence msg) { if (this.env == CompilerEnvironment.JAVAC || kind != Kind.NOTE) { this.processingEnv.getMessager().printMessage(kind, msg); } @@ -502,9 +531,19 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider * Print a message to the AP messager */ @Override - public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element element) { + public void printMessage(Kind kind, CharSequence msg, Element element) { this.processingEnv.getMessager().printMessage(kind, msg, element); } + + /** + * Print a message to the AP messager + */ + @Override + public void printMessage(Kind kind, CharSequence msg, Element element, String suppressedBy) { + if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) { + this.processingEnv.getMessager().printMessage(kind, msg, element); + } + } /** * Print a message to the AP messager @@ -514,6 +553,16 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider this.processingEnv.getMessager().printMessage(kind, msg, element, annotation); } + /** + * Print a message to the AP messager + */ + @Override + public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, String suppressedBy) { + if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) { + this.processingEnv.getMessager().printMessage(kind, msg, element, annotation); + } + } + /** * Print a message to the AP messager */ @@ -522,6 +571,16 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value); } + /** + * Print a message to the AP messager + */ + @Override + public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value, String suppressedBy) { + if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) { + this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value); + } + } + /** * Get a TypeHandle representing another type in the current processing * environment diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java index 00c90eae..15d06480 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinValidator.java @@ -111,8 +111,9 @@ public abstract class MixinValidator implements IMixinValidator { * * @param warning Message * @param element Element to attach the warning to + * @param suppressedBy {@link SuppressWarnings} value to support */ - protected final void warning(String warning, Element element) { + protected final void warning(String warning, Element element, String suppressedBy) { this.messager.printMessage(Kind.WARNING, warning, element); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationDataProvider.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationDataProvider.java index abc6c19a..ba04abb0 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationDataProvider.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationDataProvider.java @@ -26,6 +26,7 @@ package org.spongepowered.tools.obfuscation; import java.util.List; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.IMapping.Type; @@ -62,13 +63,13 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * org.spongepowered.asm.mixin.injection.struct.MemberInfo) */ @Override - public ObfuscationData getObfEntryRecursive(final MemberInfo targetMember) { - MemberInfo currentTarget = targetMember; - ObfuscationData obfTargetNames = this.getObfClass(currentTarget.owner); + public ObfuscationData getObfEntryRecursive(final ITargetSelectorRemappable targetMember) { + ITargetSelectorRemappable currentTarget = targetMember; + ObfuscationData obfTargetNames = this.getObfClass(currentTarget.getOwner()); ObfuscationData obfData = this.getObfEntry(currentTarget); try { while (obfData.isEmpty()) { - TypeHandle targetType = this.ap.getTypeProvider().getTypeHandle(currentTarget.owner); + TypeHandle targetType = this.ap.getTypeProvider().getTypeHandle(currentTarget.getOwner()); if (targetType == null) { return obfData; } @@ -109,7 +110,7 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * null then an empty dataset is returned * @return obfuscation data for the relocated member */ - private ObfuscationData getObfEntryUsing(MemberInfo targetMember, TypeHandle targetClass) { + private ObfuscationData getObfEntryUsing(ITargetSelectorRemappable targetMember, TypeHandle targetClass) { return targetClass == null ? new ObfuscationData() : this.getObfEntry(targetMember.move(targetClass.getName())); } @@ -120,7 +121,7 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { */ @Override @SuppressWarnings("unchecked") - public ObfuscationData getObfEntry(MemberInfo targetMember) { + public ObfuscationData getObfEntry(ITargetSelectorRemappable targetMember) { if (targetMember.isField()) { return (ObfuscationData)this.getObfField(targetMember); } @@ -147,7 +148,7 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * org.spongepowered.asm.mixin.injection.struct.MemberInfo) */ @Override - public ObfuscationData getObfMethodRecursive(MemberInfo targetMember) { + public ObfuscationData getObfMethodRecursive(ITargetSelectorRemappable targetMember) { return this.getObfEntryRecursive(targetMember); } @@ -157,16 +158,16 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * org.spongepowered.asm.mixin.injection.struct.MemberInfo) */ @Override - public ObfuscationData getObfMethod(MemberInfo method) { + public ObfuscationData getObfMethod(ITargetSelectorRemappable method) { return this.getRemappedMethod(method, method.isConstructor()); } @Override - public ObfuscationData getRemappedMethod(MemberInfo method) { + public ObfuscationData getRemappedMethod(ITargetSelectorRemappable method) { return this.getRemappedMethod(method, true); } - private ObfuscationData getRemappedMethod(MemberInfo method, boolean remapDescriptor) { + private ObfuscationData getRemappedMethod(ITargetSelectorRemappable method, boolean remapDescriptor) { ObfuscationData data = new ObfuscationData(); for (ObfuscationEnvironment env : this.environments) { @@ -222,9 +223,9 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * @param method Method to remap * @return data */ - public ObfuscationData remapDescriptor(ObfuscationData data, MemberInfo method) { + public ObfuscationData remapDescriptor(ObfuscationData data, ITargetSelectorRemappable method) { for (ObfuscationEnvironment env : this.environments) { - MemberInfo obfMethod = env.remapDescriptor(method); + ITargetSelectorRemappable obfMethod = env.remapDescriptor(method); if (obfMethod != null) { data.put(env.getType(), obfMethod.asMethodMapping()); } @@ -239,7 +240,7 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * org.spongepowered.asm.mixin.injection.struct.MemberInfo) */ @Override - public ObfuscationData getObfFieldRecursive(MemberInfo targetMember) { + public ObfuscationData getObfFieldRecursive(ITargetSelectorRemappable targetMember) { return this.getObfEntryRecursive(targetMember); } @@ -248,7 +249,7 @@ public class ObfuscationDataProvider implements IObfuscationDataProvider { * #getObfField(java.lang.String) */ @Override - public ObfuscationData getObfField(MemberInfo field) { + public ObfuscationData getObfField(ITargetSelectorRemappable field) { return this.getObfField(field.asFieldMapping()); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java index 137f8907..8cf91fc3 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java @@ -36,6 +36,7 @@ import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -182,14 +183,14 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment * Get an obfuscation mapping for a method */ @Override - public MappingMethod getObfMethod(MemberInfo method) { + public MappingMethod getObfMethod(ITargetSelectorRemappable method) { MappingMethod obfd = this.getObfMethod(method.asMethodMapping()); if (obfd != null || !method.isFullyQualified()) { return obfd; } // Get a type handle for the declared method owner - TypeHandle type = this.ap.getTypeProvider().getTypeHandle(method.owner); + TypeHandle type = this.ap.getTypeProvider().getTypeHandle(method.getOwner()); if (type == null || type.isImaginary()) { return null; } @@ -202,7 +203,7 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment // Well we found it, let's inflect the class name and recurse the search String superClassName = ((TypeElement)((DeclaredType)superClass).asElement()).getQualifiedName().toString(); - return this.getObfMethod(new MemberInfo(method.name, superClassName.replace('.', '/'), method.desc, method.matchAll)); + return this.getObfMethod(method.move(superClassName.replace('.', '/'))); } /** @@ -220,8 +221,9 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment public MappingMethod getObfMethod(MappingMethod method, boolean lazyRemap) { if (this.initMappings()) { boolean remapped = true; + boolean superRef = false; MappingMethod mapping = null; - for (MappingMethod md = method; md != null && mapping == null; md = md.getSuper()) { + for (MappingMethod md = method; md != null && mapping == null; md = md.getSuper(), superRef = true) { mapping = this.mappingProvider.getMethodMapping(md); } @@ -232,6 +234,11 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment } mapping = method.copy(); remapped = false; + } else if (superRef) { + // If we mapped via super and owner class is non-obf, restore the + // original owner + String obfOwner = this.getObfClass(method.getOwner()); + mapping = mapping.move(obfOwner != null ? obfOwner : method.getOwner()); } String remappedOwner = this.getObfClass(mapping.getOwner()); if (remappedOwner == null || remappedOwner.equals(method.getOwner()) || remappedOwner.equals(mapping.getOwner())) { @@ -253,10 +260,10 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment * @return remapped method or null if no remapping occurred */ @Override - public MemberInfo remapDescriptor(MemberInfo method) { + public ITargetSelectorRemappable remapDescriptor(ITargetSelectorRemappable method) { boolean transformed = false; - String owner = method.owner; + String owner = method.getOwner(); if (owner != null) { String newOwner = this.remapper.map(owner); if (newOwner != null) { @@ -265,16 +272,16 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment } } - String desc = method.desc; + String desc = method.getDesc(); if (desc != null) { - String newDesc = ObfuscationUtil.mapDescriptor(method.desc, this.remapper); - if (!newDesc.equals(method.desc)) { + String newDesc = ObfuscationUtil.mapDescriptor(method.getDesc(), this.remapper); + if (!newDesc.equals(method.getDesc())) { desc = newDesc; transformed = true; } } - return transformed ? new MemberInfo(method.name, owner, desc, method.matchAll) : null; + return transformed ? new MemberInfo(method.getName(), owner, desc, method.getMatchCount() > 1) : null; } /** @@ -293,7 +300,7 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment * Get an obfuscation mapping for a field */ @Override - public MappingField getObfField(MemberInfo field) { + public MappingField getObfField(ITargetSelectorRemappable field) { return this.getObfField(field.asFieldMapping(), true); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java index 1515f1b8..41e407a0 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationType.java @@ -27,6 +27,7 @@ package org.spongepowered.tools.obfuscation; import java.lang.reflect.Constructor; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; @@ -112,7 +113,7 @@ public final class ObfuscationType { public boolean isDefault() { String defaultEnv = this.options.getOption(SupportedOptions.DEFAULT_OBFUSCATION_ENV); return (defaultEnv == null && this.key.equals(ObfuscationServiceMCP.SEARGE)) - || (defaultEnv != null && this.key.equals(defaultEnv.toLowerCase())); + || (defaultEnv != null && this.key.equals(defaultEnv.toLowerCase(Locale.ROOT))); } /** diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ReferenceManager.java b/src/ap/java/org/spongepowered/tools/obfuscation/ReferenceManager.java index e4b0f9c1..f338232a 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ReferenceManager.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ReferenceManager.java @@ -33,6 +33,7 @@ import javax.tools.FileObject; import javax.tools.StandardLocation; import javax.tools.Diagnostic.Kind; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; @@ -190,11 +191,12 @@ public class ReferenceManager implements IReferenceManager { * org.spongepowered.tools.obfuscation.ObfuscationData) */ @Override - public void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData obfMethodData) { + public void addMethodMapping(String className, String reference, ITargetSelectorRemappable context, + ObfuscationData obfMethodData) { for (ObfuscationEnvironment env : this.environments) { MappingMethod obfMethod = obfMethodData.get(env.getType()); if (obfMethod != null) { - MemberInfo remappedReference = context.remapUsing(obfMethod, true); + ITargetSelectorRemappable remappedReference = context.remapUsing(obfMethod, true); this.addMapping(env.getType(), className, reference, remappedReference.toString()); } } @@ -207,11 +209,11 @@ public class ReferenceManager implements IReferenceManager { * org.spongepowered.tools.obfuscation.ObfuscationData) */ @Override - public void addFieldMapping(String className, String reference, MemberInfo context, ObfuscationData obfFieldData) { + public void addFieldMapping(String className, String reference, ITargetSelectorRemappable context, ObfuscationData obfFieldData) { for (ObfuscationEnvironment env : this.environments) { MappingField obfField = obfFieldData.get(env.getType()); if (obfField != null) { - MemberInfo remappedReference = MemberInfo.fromMapping(obfField.transform(env.remapDescriptor(context.desc))); + MemberInfo remappedReference = MemberInfo.fromMapping(obfField.transform(env.remapDescriptor(context.getDesc()))); this.addMapping(env.getType(), className, reference, remappedReference.toString()); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java index ad6f07dc..ac296681 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java @@ -45,6 +45,7 @@ public final class SupportedOptions { public static final String OVERWRITE_ERROR_LEVEL = "overwriteErrorLevel"; public static final String DEFAULT_OBFUSCATION_ENV = "defaultObfuscationEnv"; public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile"; + public static final String MAPPING_TYPES = "mappingTypes"; private SupportedOptions() {} @@ -61,7 +62,8 @@ public final class SupportedOptions { SupportedOptions.DISABLE_OVERWRITE_CHECKER, SupportedOptions.OVERWRITE_ERROR_LEVEL, SupportedOptions.DEFAULT_OBFUSCATION_ENV, - SupportedOptions.DEPENDENCY_TARGETS_FILE + SupportedOptions.DEPENDENCY_TARGETS_FILE, + SupportedOptions.MAPPING_TYPES ); options.addAll( ObfuscationServices.getInstance().getSupportedOptions() diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/fg3/ObfuscationEnvironmentFG3.java b/src/ap/java/org/spongepowered/tools/obfuscation/fg3/ObfuscationEnvironmentFG3.java new file mode 100644 index 00000000..c7f5b660 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/fg3/ObfuscationEnvironmentFG3.java @@ -0,0 +1,59 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.fg3; + +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; + +import org.spongepowered.tools.obfuscation.ObfuscationEnvironment; +import org.spongepowered.tools.obfuscation.ObfuscationType; +import org.spongepowered.tools.obfuscation.mapping.IMappingProvider; +import org.spongepowered.tools.obfuscation.mapping.IMappingWriter; +import org.spongepowered.tools.obfuscation.mapping.fg3.MappingProviderTSrg; +import org.spongepowered.tools.obfuscation.mapping.fg3.MappingWriterTSrg; + +/** + * A ForgeGradle 3.+ obfuscation environment + */ +public class ObfuscationEnvironmentFG3 extends ObfuscationEnvironment { + + private MappingProviderTSrg provider; + + protected ObfuscationEnvironmentFG3(ObfuscationType type) { + super(type); + } + + @Override + protected IMappingProvider getMappingProvider(Messager messager, Filer filer) { + return this.provider = new MappingProviderTSrg(messager, filer); + } + + @Override + protected IMappingWriter getMappingWriter(Messager messager, Filer filer) { + String outputBehaviour = this.ap.getOption(ObfuscationServiceFG3.TSRG_OUTPUT_BEHAVIOUR); + return new MappingWriterTSrg(messager, filer, this.provider, outputBehaviour != null && outputBehaviour.equalsIgnoreCase("merge")); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/fg3/ObfuscationServiceFG3.java b/src/ap/java/org/spongepowered/tools/obfuscation/fg3/ObfuscationServiceFG3.java new file mode 100644 index 00000000..bf83a2fd --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/fg3/ObfuscationServiceFG3.java @@ -0,0 +1,78 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.fg3; + +import java.util.Collection; +import java.util.Set; + +import org.spongepowered.tools.obfuscation.SupportedOptions; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; +import org.spongepowered.tools.obfuscation.service.IObfuscationService; +import org.spongepowered.tools.obfuscation.service.ObfuscationTypeDescriptor; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; +import com.google.common.collect.ImmutableSet; + +/** + * Obfuscation service for ForgeGradle 3.+ + */ +public class ObfuscationServiceFG3 implements IObfuscationService { + + public static final String SEARGE = "searge"; + + public static final String REOBF_TSRG_FILE = "reobfTsrgFile"; + public static final String OUT_TSRG_SRG_FILE = "outTsrgFile"; + public static final String OUT_REFMAP_FILE = "outRefMapFile"; + public static final String TSRG_OUTPUT_BEHAVIOUR = "mergeBehaviour"; + + @Override + public Set getSupportedOptions() { + return ImmutableSet.of( + ObfuscationServiceFG3.REOBF_TSRG_FILE, + ObfuscationServiceFG3.OUT_TSRG_SRG_FILE, + ObfuscationServiceFG3.OUT_REFMAP_FILE, + ObfuscationServiceFG3.TSRG_OUTPUT_BEHAVIOUR + ); + } + + @Override + public Collection getObfuscationTypes(IMixinAnnotationProcessor ap) { + Builder list = ImmutableList.builder(); + if (ap.getOptions(SupportedOptions.MAPPING_TYPES).contains("tsrg")) { + list.add( + new ObfuscationTypeDescriptor( + ObfuscationServiceFG3.SEARGE, + ObfuscationServiceFG3.REOBF_TSRG_FILE, + null, + ObfuscationServiceFG3.OUT_TSRG_SRG_FILE, + ObfuscationEnvironmentFG3.class + ) + ); + } + return list.build(); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java new file mode 100644 index 00000000..4295e676 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java @@ -0,0 +1,80 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.interfaces; + +import javax.annotation.processing.Messager; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.tools.Diagnostic; + +/** + * An extended {@link Messager} which supports messages that can be suppressed + * using the standard Java {@link SuppressWarnings} annotation. + */ +public interface IMessagerSuppressible extends Messager { + + /** + * Prints a message of the specified kind at the location of the + * element. + * + * @param kind the kind of message + * @param msg the message, or an empty string if none + * @param e the element to use as a position hint + * @param suppressedBy the {@link SuppressWarnings} value which will silence + * this message + */ + void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, String suppressedBy); + + /** + * Prints a message of the specified kind at the location of the + * annotation mirror of the annotated element. + * + * @param kind the kind of message + * @param msg the message, or an empty string if none + * @param e the annotated element + * @param a the annotation to use as a position hint + * @param suppressedBy the {@link SuppressWarnings} value which will silence + * this message + */ + void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, String suppressedBy); + + /** + * Prints a message of the specified kind at the location of the + * annotation value inside the annotation mirror of the annotated + * element. + * + * @param kind the kind of message + * @param msg the message, or an empty string if none + * @param e the annotated element + * @param a the annotation containing the annotation value + * @param v the annotation value to use as a position hint + * @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); + + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java index 8bc37660..5827eae8 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMixinAnnotationProcessor.java @@ -24,7 +24,6 @@ */ package org.spongepowered.tools.obfuscation.interfaces; -import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import org.spongepowered.asm.util.ITokenProvider; @@ -32,7 +31,7 @@ import org.spongepowered.asm.util.ITokenProvider; /** * Interface for annotation processor core */ -public interface IMixinAnnotationProcessor extends Messager, IOptionProvider { +public interface IMixinAnnotationProcessor extends IMessagerSuppressible, IOptionProvider { /** * Detected compiler argument, specifies the behaviour of some operations diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationDataProvider.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationDataProvider.java index 2e7eab72..b9aa9f6f 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationDataProvider.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationDataProvider.java @@ -24,7 +24,7 @@ */ package org.spongepowered.tools.obfuscation.interfaces; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -48,7 +48,7 @@ public interface IObfuscationDataProvider { * original owner class * or String for fields) */ - public abstract ObfuscationData getObfEntryRecursive(MemberInfo targetMember); + public abstract ObfuscationData getObfEntryRecursive(ITargetSelectorRemappable targetMember); /** * Resolves a field or method reference to an ObfuscationData set @@ -58,7 +58,7 @@ public interface IObfuscationDataProvider { * @return obfuscation data (by type) for the supplied member * or String for fields) */ - public abstract ObfuscationData getObfEntry(MemberInfo targetMember); + public abstract ObfuscationData getObfEntry(ITargetSelectorRemappable targetMember); /** * Resolves a field or method reference to an ObfuscationData set @@ -80,14 +80,14 @@ public interface IObfuscationDataProvider { * @return ObfuscationData with remapped owner class corresponding to the * original owner class */ - public abstract ObfuscationData getObfMethodRecursive(MemberInfo method); + public abstract ObfuscationData getObfMethodRecursive(ITargetSelectorRemappable method); /** * Get an obfuscation mapping for a method * * @param method method to fetch obfuscation mapping for */ - public abstract ObfuscationData getObfMethod(MemberInfo method); + public abstract ObfuscationData getObfMethod(ITargetSelectorRemappable method); /** * Get an obfuscation mapping for a method if an explicit mapping exists. @@ -95,7 +95,7 @@ public interface IObfuscationDataProvider { * * @param method method to fetch obfuscation mapping for */ - public abstract ObfuscationData getRemappedMethod(MemberInfo method); + public abstract ObfuscationData getRemappedMethod(ITargetSelectorRemappable method); /** * Get an obfuscation mapping for a method @@ -122,14 +122,14 @@ public interface IObfuscationDataProvider { * @return ObfuscationData with remapped owner class corresponding to the * original owner class */ - public abstract ObfuscationData getObfFieldRecursive(MemberInfo field); + public abstract ObfuscationData getObfFieldRecursive(ITargetSelectorRemappable field); /** * Get an obfuscation mapping for a field * * @param field field to fetch obfuscation mapping for */ - public abstract ObfuscationData getObfField(MemberInfo field); + public abstract ObfuscationData getObfField(ITargetSelectorRemappable field); /** * Get an obfuscation mapping for a field diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationEnvironment.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationEnvironment.java index 19953291..9e8c2438 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationEnvironment.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IObfuscationEnvironment.java @@ -26,7 +26,7 @@ package org.spongepowered.tools.obfuscation.interfaces; import java.util.Collection; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer; @@ -45,7 +45,7 @@ public interface IObfuscationEnvironment { * @param method method to locate a mapping for * @return remapped method or null if no mapping exists */ - public abstract MappingMethod getObfMethod(MemberInfo method); + public abstract MappingMethod getObfMethod(ITargetSelectorRemappable method); /** * Get an obfuscation mapping for a method, returns null if no mapping @@ -78,7 +78,7 @@ public interface IObfuscationEnvironment { * @param field field to locate a mapping for * @return remapped field or null if no mapping exists */ - public abstract MappingField getObfField(MemberInfo field); + public abstract MappingField getObfField(ITargetSelectorRemappable field); /** * Get an obfuscation mapping for a field, returns null if no mapping @@ -119,7 +119,7 @@ public interface IObfuscationEnvironment { * @param method method to remap * @return remapped method or null if no remapping occurred */ - public abstract MemberInfo remapDescriptor(MemberInfo method); + public abstract ITargetSelectorRemappable remapDescriptor(ITargetSelectorRemappable method); /** * Remap a single descriptor in the context of this environment diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java index e0bbd48a..10d5eb8e 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IOptionProvider.java @@ -24,6 +24,8 @@ */ package org.spongepowered.tools.obfuscation.interfaces; +import java.util.List; + /** * An object which can provide option values to consumers */ @@ -37,4 +39,22 @@ public interface IOptionProvider { */ public abstract String getOption(String option); + /** + * Fetch the value of the specified option, if available. If the option is + * not available, return the specified default value + * + * @param option Name of the option to fetch + * @param defaultValue Default value to return if the option is not present + * @return Option value or default if absent + */ + public abstract boolean getOption(String option, boolean defaultValue); + + /** + * Fetch the values of the specified comma-separated option, if available + * + * @param option Name of the option to fetch + * @return Option value or null if absent + */ + public abstract List getOptions(String option); + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IReferenceManager.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IReferenceManager.java index 2521a04b..74312a84 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IReferenceManager.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IReferenceManager.java @@ -24,7 +24,7 @@ */ package org.spongepowered.tools.obfuscation.interfaces; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -75,7 +75,7 @@ public interface IReferenceManager { /** * Adds a method mapping to the internal refmap, generates refmap entries - * using the supplied parsed memberinfo as context + * using the supplied parsed target selector as context * * @param className Mixin class name which owns the refmap entry * @param reference Original reference, as it appears in the annotation @@ -83,11 +83,12 @@ public interface IReferenceManager { * supplied obfuscation data * @param obfMethodData Method data to add for this mapping */ - public abstract void addMethodMapping(String className, String reference, MemberInfo context, ObfuscationData obfMethodData); + public abstract void addMethodMapping(String className, String reference, ITargetSelectorRemappable context, + ObfuscationData obfMethodData); /** * Adds a field mapping to the internal refmap, generates refmap entries - * using the supplied parsed memberinfo as context + * using the supplied parsed target selector as context * * @param className Mixin class name which owns the refmap entry * @param reference Original reference, as it appears in the annotation @@ -95,7 +96,8 @@ public interface IReferenceManager { * supplied obfuscation data * @param obfFieldData Field data to add for this mapping */ - public abstract void addFieldMapping(String className, String reference, MemberInfo context, ObfuscationData obfFieldData); + public abstract void addFieldMapping(String className, String reference, ITargetSelectorRemappable context, + ObfuscationData obfFieldData); /** * Adds a class mapping to the internal refmap diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingMethodLazy.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingMethodLazy.java new file mode 100644 index 00000000..e8c08c1d --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingMethodLazy.java @@ -0,0 +1,83 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.mapping.fg3; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.tools.obfuscation.mapping.IMappingProvider; + +/** + * A MappingMethod which computes transformed descriptor on demand using the + * supplied mapping provider. This means we only need to compute transformed + * descriptors for methods which are actually used. + */ +public class MappingMethodLazy extends MappingMethod { + + private static final Pattern PATTERN_CLASSNAME = Pattern.compile("L([^;]+);"); + + private final String originalDesc; + + private final IMappingProvider mappingProvider; + + private String newDesc; + + public MappingMethodLazy(String owner, String simpleName, String originalDesc, IMappingProvider mappingProvider) { + super(owner, simpleName, "{" + originalDesc + "}"); // descriptor provided since it's used for hash generation + this.originalDesc = originalDesc; + this.mappingProvider = mappingProvider; + } + + @Override + public String getDesc() { + if (this.newDesc == null) { + this.newDesc = this.generateDescriptor(); + } + return this.newDesc; + } + + @Override + public String toString() { + String desc = this.getDesc(); + return String.format("%s%s%s", this.getName(), desc != null ? " " : "", desc != null ? desc : ""); + } + + private String generateDescriptor() { + StringBuffer desc = new StringBuffer(); + Matcher matcher = MappingMethodLazy.PATTERN_CLASSNAME.matcher(this.originalDesc); + while (matcher.find()) { + String remapped = this.mappingProvider.getClassMapping(matcher.group(1)); + if (remapped != null) { + matcher.appendReplacement(desc, Matcher.quoteReplacement("L" + remapped + ";")); + } else { + matcher.appendReplacement(desc, Matcher.quoteReplacement("L" + matcher.group(1) + ";")); + } + } + matcher.appendTail(desc); + return desc.toString(); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java new file mode 100644 index 00000000..7a6af8bf --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingProviderTSrg.java @@ -0,0 +1,130 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.mapping.fg3; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Collections; +import java.util.List; + +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; + +import org.spongepowered.asm.obfuscation.mapping.common.MappingField; +import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.asm.obfuscation.mapping.mcp.MappingFieldSrg; +import org.spongepowered.tools.obfuscation.mapping.common.MappingProvider; + +import com.google.common.base.Strings; +import com.google.common.collect.BiMap; +import com.google.common.io.Files; + +/** + * TSRG Mapping provider + */ +public class MappingProviderTSrg extends MappingProvider { + + private List inputMappings = Collections.emptyList(); + + public MappingProviderTSrg(Messager messager, Filer filer) { + super(messager, filer); + } + + @Override + public void read(final File input) throws IOException { + // Locally scoped to avoid synthetic accessor + final BiMap packageMap = this.packageMap; + final BiMap classMap = this.classMap; + final BiMap fieldMap = this.fieldMap; + final BiMap methodMap = this.methodMap; + + String fromClass = null, toClass = null; + this.inputMappings = Files.readLines(input, Charset.defaultCharset()); + + for (String line : this.inputMappings) { + if (Strings.isNullOrEmpty(line) || line.startsWith("#")) { + continue; + } + + String[] parts = line.split(" "); + if (line.startsWith("\t")) { + if (fromClass == null) { + throw new IllegalStateException("Error parsing TSRG file, found member declaration with no class: " + line); + } + parts[0] = parts[0].substring(1); + if (parts.length == 2) { + fieldMap.forcePut(new MappingField(fromClass, parts[0]), new MappingField(toClass, parts[1])); + } else if (parts.length == 3) { + methodMap.forcePut(new MappingMethod(fromClass, parts[0], parts[1]), new MappingMethodLazy(toClass, parts[2], + parts[1], MappingProviderTSrg.this)); + } else { + throw new IllegalStateException("Error parsing TSRG file, too many arguments: " + line); + } + } else if (parts.length > 1) { + String from = parts[0]; + if (parts.length == 2) { + String to = parts[1]; + if (from.endsWith("/")) { + packageMap.forcePut(from.substring(0, from.length() - 1), to.substring(0, to.length() - 1)); + } else { + classMap.forcePut(from, to); + fromClass = from; + toClass = to; + } + } else if (parts.length > 2) { + String to = classMap.get(from); + if (to == null) { + throw new IllegalStateException("Error parsing TSRG file, found inline member before class mapping: " + line); + } + if (parts.length == 3) { + fieldMap.forcePut(new MappingField(from, parts[1]), new MappingField(to, parts[2])); + } else if (parts.length == 4) { + methodMap.forcePut(new MappingMethod(from, parts[1], parts[2]), new MappingMethodLazy(to, parts[3], parts[2], + MappingProviderTSrg.this)); + } else { + throw new IllegalStateException("Error parsing TSRG file, too many arguments: " + line); + } + } + } else { + throw new IllegalStateException("Error parsing TSRG, unrecognised directive: " + line); + } + } + } + + @Override + public MappingField getFieldMapping(MappingField field) { + // SRG fields do not have descriptors so strip the field descriptor before looking up + if (field.getDesc() != null) { + field = new MappingFieldSrg(field); + } + return this.fieldMap.get(field); + } + + List getInputMappings() { + return this.inputMappings; + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java new file mode 100644 index 00000000..ece47054 --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java @@ -0,0 +1,77 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.mapping.fg3; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; + +import org.spongepowered.asm.obfuscation.mapping.common.MappingField; +import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.tools.obfuscation.ObfuscationType; +import org.spongepowered.tools.obfuscation.mapping.IMappingConsumer.MappingSet.Pair; +import org.spongepowered.tools.obfuscation.mapping.mcp.MappingWriterSrg; + +/** + * Writer for SRG mappings + */ +public class MappingWriterTSrg extends MappingWriterSrg { + + private final MappingProviderTSrg provider; + private final boolean mergeExisting; + + public MappingWriterTSrg(Messager messager, Filer filer, MappingProviderTSrg provider, boolean mergeExisting) { + super(messager, filer); + this.provider = provider; + this.mergeExisting = mergeExisting; + } + + @Override + protected PrintWriter openFileWriter(String output, ObfuscationType type) throws IOException { + return this.openFileWriter(output, type + " composite mappings"); + } + + @Override + protected void writeHeader(PrintWriter writer) { + if (this.mergeExisting) { + for (String line : this.provider.getInputMappings()) { + writer.println(line); + } + } + } + + @Override + protected String formatFieldMapping(Pair field) { + return String.format("%s %s %s %s", field.from.getOwner(), field.from.getSimpleName(), field.to.getSimpleName()); + } + + @Override + protected String formatMethodMapping(Pair method) { + return String.format("%s %s %s %s", method.from.getOwner(), method.from.getSimpleName(), method.from.getDesc(), method.to.getSimpleName()); + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/mcp/MappingWriterSrg.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/mcp/MappingWriterSrg.java index b0dde3f3..6843ceb8 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/mcp/MappingWriterSrg.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/mcp/MappingWriterSrg.java @@ -55,7 +55,8 @@ public class MappingWriterSrg extends MappingWriter { PrintWriter writer = null; try { - writer = this.openFileWriter(output, type + " output SRGs"); + writer = this.openFileWriter(output, type); + this.writeHeader(writer); this.writeFieldMappings(writer, fields); this.writeMethodMappings(writer, methods); } catch (IOException ex) { @@ -71,6 +72,14 @@ public class MappingWriterSrg extends MappingWriter { } } + protected PrintWriter openFileWriter(String output, ObfuscationType type) throws IOException { + return this.openFileWriter(output, type + " output SRGs"); + } + + protected void writeHeader(PrintWriter writer) { + // stub + } + protected void writeFieldMappings(PrintWriter writer, MappingSet fields) { for (Pair field : fields) { writer.println(this.formatFieldMapping(field)); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mcp/ObfuscationServiceMCP.java b/src/ap/java/org/spongepowered/tools/obfuscation/mcp/ObfuscationServiceMCP.java index 6c5edbc1..9c8ccb63 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mcp/ObfuscationServiceMCP.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mcp/ObfuscationServiceMCP.java @@ -27,11 +27,14 @@ package org.spongepowered.tools.obfuscation.mcp; import java.util.Collection; import java.util.Set; +import org.spongepowered.tools.obfuscation.SupportedOptions; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.service.IObfuscationService; import org.spongepowered.tools.obfuscation.service.ObfuscationTypeDescriptor; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableList.Builder; /** * Default obfuscation service, provides MCP @@ -63,15 +66,20 @@ public class ObfuscationServiceMCP implements IObfuscationService { } @Override - public Collection getObfuscationTypes() { - return ImmutableList.of( - new ObfuscationTypeDescriptor( - ObfuscationServiceMCP.SEARGE, - ObfuscationServiceMCP.REOBF_SRG_FILE, - ObfuscationServiceMCP.REOBF_EXTRA_SRG_FILES, - ObfuscationServiceMCP.OUT_SRG_SRG_FILE, - ObfuscationEnvironmentMCP.class - ), + public Collection getObfuscationTypes(IMixinAnnotationProcessor ap) { + Builder list = ImmutableList.builder(); + if (!ap.getOptions(SupportedOptions.MAPPING_TYPES).contains("tsrg")) { + list.add( + new ObfuscationTypeDescriptor( + ObfuscationServiceMCP.SEARGE, + ObfuscationServiceMCP.REOBF_SRG_FILE, + ObfuscationServiceMCP.REOBF_EXTRA_SRG_FILES, + ObfuscationServiceMCP.OUT_SRG_SRG_FILE, + ObfuscationEnvironmentMCP.class + ) + ); + } + list.add( new ObfuscationTypeDescriptor( ObfuscationServiceMCP.NOTCH, ObfuscationServiceMCP.REOBF_NOTCH_FILE, @@ -80,6 +88,7 @@ public class ObfuscationServiceMCP implements IObfuscationService { ObfuscationEnvironmentMCP.class ) ); + return list.build(); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/MethodHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/MethodHandle.java index a78be0e2..29f1cfc0 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/MethodHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/MethodHandle.java @@ -27,7 +27,7 @@ package org.spongepowered.tools.obfuscation.mirror; import javax.lang.model.element.ExecutableElement; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; -import org.spongepowered.tools.obfuscation.mirror.mapping.ResolvableMappingMethod; +import org.spongepowered.tools.obfuscation.mirror.mapping.MappingMethodResolvable; import com.google.common.base.Strings; @@ -83,7 +83,7 @@ public class MethodHandle extends MemberHandle { public MappingMethod asMapping(boolean includeOwner) { if (includeOwner) { if (this.ownerHandle != null) { - return new ResolvableMappingMethod(this.ownerHandle, this.getName(), this.getDesc()); + return new MappingMethodResolvable(this.ownerHandle, this.getName(), this.getDesc()); } return new MappingMethod(this.getOwner(), this.getName(), this.getDesc()); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java index f753d6eb..6e5c83ae 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandle.java @@ -39,9 +39,10 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; -import org.spongepowered.tools.obfuscation.mirror.mapping.ResolvableMappingMethod; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.tools.obfuscation.mirror.mapping.MappingMethodResolvable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; @@ -122,6 +123,13 @@ public class TypeHandle { return this.name; } + /** + * Returns the simple class name + */ + public final String getSimpleName() { + return Bytecode.getSimpleName(this.name); + } + /** * Returns the enclosing package element */ @@ -255,20 +263,20 @@ public class TypeHandle { * @return this handle as a mapping method */ public MappingMethod getMappingMethod(String name, String desc) { - return new ResolvableMappingMethod(this, name, desc); + return new MappingMethodResolvable(this, name, desc); } /** - * Find a descriptor for the supplied MemberInfo + * Find a descriptor for the supplied target selector * - * @param memberInfo MemberInfo to use as search term + * @param selector Target selector to use as search term * @return descriptor or null if no matching member could be located */ - public String findDescriptor(MemberInfo memberInfo) { - String desc = memberInfo.desc; + public String findDescriptor(ITargetSelectorByName selector) { + String desc = selector.getDesc(); if (desc == null) { for (ExecutableElement method : this.getEnclosedElements(ElementKind.METHOD)) { - if (method.getSimpleName().toString().equals(memberInfo.name)) { + if (method.getSimpleName().toString().equals(selector.getName())) { desc = TypeUtils.getDescriptor(method); break; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandleSimulated.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandleSimulated.java index 3c7fa92f..a269d8de 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandleSimulated.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandleSimulated.java @@ -32,7 +32,7 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.SignaturePrinter; @@ -117,9 +117,9 @@ public class TypeHandleSimulated extends TypeHandle { * #findDescriptor(org.spongepowered.asm.mixin.injection.struct.MemberInfo) */ @Override - public String findDescriptor(MemberInfo memberInfo) { + public String findDescriptor(ITargetSelectorByName memberInfo) { // Identity, refs need to be FQ - return memberInfo != null ? memberInfo.desc : null; + return memberInfo != null ? memberInfo.getDesc() : null; } /* (non-Javadoc) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java index 05d57f0e..e9c3f3b2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeUtils.java @@ -37,6 +37,8 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.SignaturePrinter; /** @@ -51,7 +53,6 @@ public abstract class TypeUtils { private static final int MAX_GENERIC_RECURSION_DEPTH = 5; private static final String OBJECT_SIG = "java.lang.Object"; - private static final String OBJECT_REF = "java/lang/Object"; // No instances for you private TypeUtils() {} @@ -185,6 +186,16 @@ public abstract class TypeUtils { return new SignaturePrinter("", descriptor).setFullyQualified(true).toDescriptor(); } + /** + * Get the simple type name for the specified type + * + * @param type type mirror + * @return type name + */ + public static String getSimpleName(TypeMirror type) { + return Bytecode.getSimpleName(TypeUtils.getTypeName(type)); + } + /** * Get the type name for the specified type * @@ -285,7 +296,7 @@ public abstract class TypeUtils { case SHORT: return "S"; case VOID: return "V"; // TODO figure out a better way to not crash when we get here - case ERROR: return "L" + TypeUtils.OBJECT_REF + ";"; + case ERROR: return Constants.OBJECT_DESC; default: } @@ -300,7 +311,7 @@ public abstract class TypeUtils { */ public static String getInternalName(DeclaredType type) { if (type == null) { - return TypeUtils.OBJECT_REF; + return Constants.OBJECT; } return TypeUtils.getInternalName((TypeElement)type.asElement()); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/mapping/ResolvableMappingMethod.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/mapping/MappingMethodResolvable.java similarity index 90% rename from src/ap/java/org/spongepowered/tools/obfuscation/mirror/mapping/ResolvableMappingMethod.java rename to src/ap/java/org/spongepowered/tools/obfuscation/mirror/mapping/MappingMethodResolvable.java index 4ce512f5..a93685ab 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/mapping/ResolvableMappingMethod.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/mapping/MappingMethodResolvable.java @@ -33,11 +33,11 @@ import org.spongepowered.tools.obfuscation.mirror.TypeUtils; * mapping allows references in superclasses to be resolved when necessary since * the hierarchy information is available. */ -public final class ResolvableMappingMethod extends MappingMethod { +public final class MappingMethodResolvable extends MappingMethod { private final TypeHandle ownerHandle; - public ResolvableMappingMethod(TypeHandle owner, String name, String desc) { + public MappingMethodResolvable(TypeHandle owner, String name, String desc) { super(owner.getName(), name, desc); this.ownerHandle = owner; } @@ -87,22 +87,22 @@ public final class ResolvableMappingMethod extends MappingMethod { * @return remapped method */ public MappingMethod move(TypeHandle newOwner) { - return new ResolvableMappingMethod(newOwner, this.getSimpleName(), this.getDesc()); + return new MappingMethodResolvable(newOwner, this.getSimpleName(), this.getDesc()); } @Override public MappingMethod remap(String newName) { - return new ResolvableMappingMethod(this.ownerHandle, newName, this.getDesc()); + return new MappingMethodResolvable(this.ownerHandle, newName, this.getDesc()); } @Override public MappingMethod transform(String newDesc) { - return new ResolvableMappingMethod(this.ownerHandle, this.getSimpleName(), newDesc); + return new MappingMethodResolvable(this.ownerHandle, this.getSimpleName(), newDesc); } @Override public MappingMethod copy() { - return new ResolvableMappingMethod(this.ownerHandle, this.getSimpleName(), this.getDesc()); + return new MappingMethodResolvable(this.ownerHandle, this.getSimpleName(), this.getDesc()); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/service/IObfuscationService.java b/src/ap/java/org/spongepowered/tools/obfuscation/service/IObfuscationService.java index 2fc38b3b..f308a911 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/service/IObfuscationService.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/service/IObfuscationService.java @@ -27,6 +27,8 @@ package org.spongepowered.tools.obfuscation.service; import java.util.Collection; import java.util.Set; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; + /** * Service interface for obfuscation services */ @@ -43,8 +45,9 @@ public interface IObfuscationService { * This method should return a collection of available obfuscation types * supported by this service * + * @param ap Annotation Processor instance * @return available obfuscation types or null */ - public abstract Collection getObfuscationTypes(); + public abstract Collection getObfuscationTypes(IMixinAnnotationProcessor ap); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationServices.java b/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationServices.java index c1ac26da..f65e9673 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationServices.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationServices.java @@ -85,7 +85,7 @@ public final class ObfuscationServices { String serviceName = service.getClass().getSimpleName(); // ap.printMessage(Kind.NOTE, "Preparing service " + serviceName); - Collection obfTypes = service.getObfuscationTypes(); + Collection obfTypes = service.getObfuscationTypes(ap); if (obfTypes != null) { for (ObfuscationTypeDescriptor obfType : obfTypes) { try { @@ -109,7 +109,7 @@ public final class ObfuscationServices { */ public Set getSupportedOptions() { Set supportedOptions = new HashSet(); - for (IObfuscationService provider : this.serviceLoader) { + for (IObfuscationService provider : this.services) { Set options = provider.getSupportedOptions(); if (options != null) { supportedOptions.addAll(options); @@ -125,7 +125,7 @@ public final class ObfuscationServices { * @return service instance or null if no matching services were loaded */ public IObfuscationService getService(Class serviceClass) { - for (IObfuscationService service : this.serviceLoader) { + for (IObfuscationService service : this.services) { if (serviceClass.getName().equals(service.getClass().getName())) { return service; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationTypeDescriptor.java b/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationTypeDescriptor.java index 1f8de409..adc7a109 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationTypeDescriptor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/service/ObfuscationTypeDescriptor.java @@ -106,4 +106,5 @@ public class ObfuscationTypeDescriptor { public Class getEnvironmentType() { return this.environmentType; } + } diff --git a/src/ap/resources/META-INF/services/org.spongepowered.tools.obfuscation.service.IObfuscationService b/src/ap/resources/META-INF/services/org.spongepowered.tools.obfuscation.service.IObfuscationService index 96b5eb81..8e5b702b 100644 --- a/src/ap/resources/META-INF/services/org.spongepowered.tools.obfuscation.service.IObfuscationService +++ b/src/ap/resources/META-INF/services/org.spongepowered.tools.obfuscation.service.IObfuscationService @@ -1 +1,2 @@ -org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP \ No newline at end of file +org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP +org.spongepowered.tools.obfuscation.fg3.ObfuscationServiceFG3 \ No newline at end of file diff --git a/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java b/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java index a3a39e87..82d8e8f4 100644 --- a/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java +++ b/src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapter.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.bridge; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.objectweb.asm.commons.Remapper; import org.spongepowered.asm.mixin.extensibility.IRemapper; import org.spongepowered.asm.util.ObfuscationUtil; import org.spongepowered.asm.util.ObfuscationUtil.IClassRemapper; @@ -38,7 +39,7 @@ public abstract class RemapperAdapter implements IRemapper, IClassRemapper { protected final Logger logger = LogManager.getLogger("mixin"); protected final org.objectweb.asm.commons.Remapper remapper; - public RemapperAdapter(org.objectweb.asm.commons.Remapper remapper) { + public RemapperAdapter(Remapper remapper) { this.remapper = remapper; } diff --git a/src/example/java/org/spongepowered/tools/obfuscation/json/ObfuscationServiceJson.java b/src/example/java/org/spongepowered/tools/obfuscation/json/ObfuscationServiceJson.java index 7c12c5e9..07193709 100644 --- a/src/example/java/org/spongepowered/tools/obfuscation/json/ObfuscationServiceJson.java +++ b/src/example/java/org/spongepowered/tools/obfuscation/json/ObfuscationServiceJson.java @@ -27,6 +27,7 @@ package org.spongepowered.tools.obfuscation.json; import java.util.Collection; import java.util.Set; +import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.mcp.ObfuscationServiceMCP; import org.spongepowered.tools.obfuscation.service.IObfuscationService; import org.spongepowered.tools.obfuscation.service.ObfuscationTypeDescriptor; @@ -54,7 +55,7 @@ public class ObfuscationServiceJson implements IObfuscationService { } @Override - public Collection getObfuscationTypes() { + public Collection getObfuscationTypes(IMixinAnnotationProcessor ap) { return ImmutableList.of( new ObfuscationTypeDescriptor( ObfuscationServiceJson.KEY, diff --git a/src/fernflower/java/org/spongepowered/asm/mixin/transformer/debug/RuntimeDecompiler.java b/src/fernflower/java/org/spongepowered/asm/mixin/transformer/debug/RuntimeDecompiler.java index 2cc232fa..9480a533 100644 --- a/src/fernflower/java/org/spongepowered/asm/mixin/transformer/debug/RuntimeDecompiler.java +++ b/src/fernflower/java/org/spongepowered/asm/mixin/transformer/debug/RuntimeDecompiler.java @@ -29,7 +29,6 @@ import java.io.IOException; import java.util.Map; import java.util.jar.Manifest; -import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -43,6 +42,8 @@ import org.spongepowered.asm.mixin.transformer.ext.IDecompiler; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; +import com.google.common.io.MoreFiles; +import com.google.common.io.RecursiveDeleteOption; /** * Wrapper for FernFlower to support runtime-decompilation of post-mixin classes @@ -63,7 +64,7 @@ public class RuntimeDecompiler extends IFernflowerLogger implements IDecompiler, this.outputPath = outputPath; if (this.outputPath.exists()) { try { - FileUtils.deleteDirectory(this.outputPath); + MoreFiles.deleteRecursively(this.outputPath.toPath(), RecursiveDeleteOption.ALLOW_INSECURE); } catch (IOException ex) { this.logger.warn("Error cleaning output directory: {}", ex.getMessage()); } diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java b/src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java index 9de14aeb..06740b42 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/MixinTweaker.java @@ -27,6 +27,8 @@ package org.spongepowered.asm.launch; import java.io.File; import java.util.List; +import org.spongepowered.asm.launch.platform.CommandLineOptions; + import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.LaunchClassLoader; @@ -50,7 +52,7 @@ public class MixinTweaker implements ITweaker { */ @Override public final void acceptOptions(List args, File gameDir, File assetsDir, String profile) { - MixinBootstrap.doInit(args); + MixinBootstrap.doInit(CommandLineOptions.ofArgs(args)); } /* (non-Javadoc) diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java similarity index 61% rename from src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java rename to src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java index e6b4a2fc..10a43d86 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFML.java +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentFMLLegacy.java @@ -28,37 +28,46 @@ import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.net.URI; -//import java.util.Collection; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; import org.spongepowered.asm.launch.GlobalProperties; +import org.spongepowered.asm.launch.platform.container.ContainerHandleURI; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixin.MixinEnvironment; -//import org.spongepowered.asm.mixin.environment.IPhaseProvider; -//import org.spongepowered.asm.mixin.environment.PhaseDefinition; -//import org.spongepowered.asm.mixin.environment.phase.OnLogMessage; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.extensibility.IRemapper; import org.spongepowered.asm.service.mojang.MixinServiceLaunchWrapper; - -//import com.google.common.collect.ImmutableList; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.IConsumer; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; /** - * Platform agent for use under FML. + * Platform agent for use under FML and LaunchWrapper. * *

When FML is present we scan containers for the manifest entries which are * inhibited by the tweaker, in particular the FMLCorePlugin and * FMLCorePluginContainsFMLMod entries. This is required because FML * performs no further processing of containers if they contain a tweaker!

*/ -public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { +public class MixinPlatformAgentFMLLegacy extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent { + + private static final String OLD_LAUNCH_HANDLER_CLASS = "cpw.mods.fml.relauncher.FMLLaunchHandler"; + private static final String NEW_LAUNCH_HANDLER_CLASS = "net.minecraftforge.fml.relauncher.FMLLaunchHandler"; + private static final String CLIENT_TWEAKER_TAIL = ".common.launcher.FMLTweaker"; + private static final String SERVER_TWEAKER_TAIL = ".common.launcher.FMLServerTweaker"; + private static final String GETSIDE_METHOD = "side"; private static final String LOAD_CORE_MOD_METHOD = "loadCoreMod"; private static final String GET_REPARSEABLE_COREMODS_METHOD = "getReparseableCoremods"; @@ -91,14 +100,24 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { * startup so that we know to ignore them */ static { - for (String cmdLineCoreMod : System.getProperty(MixinPlatformAgentFML.FML_CMDLINE_COREMODS, "").split(",")) { + for (String cmdLineCoreMod : System.getProperty(MixinPlatformAgentFMLLegacy.FML_CMDLINE_COREMODS, "").split(",")) { if (!cmdLineCoreMod.isEmpty()) { MixinPlatformAgentAbstract.logger.debug("FML platform agent will ignore coremod {} specified on the command line", cmdLineCoreMod); - MixinPlatformAgentFML.loadedCoreMods.add(cmdLineCoreMod); + MixinPlatformAgentFMLLegacy.loadedCoreMods.add(cmdLineCoreMod); } } } - + + /** + * Container file + */ + private File file; + + /** + * Name of this container + */ + private String fileName; + /** * If running under FML, we will attempt to inject any coremod specified in * the metadata, FML's CoremodManager returns an ITweaker instance which is @@ -107,12 +126,7 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { * under FML or if an FMLCorePlugin key is not specified in the metadata) * then this handle will be null. */ - private final ITweaker coreModWrapper; - - /** - * Name of this container - */ - private final String fileName; + private ITweaker coreModWrapper; /** * Core mod manager class @@ -124,14 +138,17 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { */ private boolean initInjectionState; - /** - * @param manager platform manager - * @param uri URI of the resource for this agent - */ - public MixinPlatformAgentFML(MixinPlatformManager manager, URI uri) { - super(manager, uri); - this.fileName = this.container.getName(); + @Override + public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { + if (!(handle instanceof ContainerHandleURI)) { + return false; + } + + this.file = ((ContainerHandleURI)handle).getFile(); + this.fileName = this.file.getName(); this.coreModWrapper = this.initFMLCoreMod(); + + return super.accept(manager, handle); } /** @@ -140,14 +157,14 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { private ITweaker initFMLCoreMod() { try { try { - this.clCoreModManager = MixinPlatformAgentFML.getCoreModManagerClass(); + this.clCoreModManager = MixinPlatformAgentFMLLegacy.getCoreModManagerClass(); } catch (ClassNotFoundException ex) { MixinPlatformAgentAbstract.logger.info("FML platform manager could not load class {}. Proceeding without FML support.", ex.getMessage()); return null; } - if ("true".equalsIgnoreCase(this.attributes.get(MixinPlatformAgentFML.MFATT_FORCELOADASMOD))) { + if ("true".equalsIgnoreCase(this.handle.getAttribute(MixinPlatformAgentFMLLegacy.MFATT_FORCELOADASMOD))) { MixinPlatformAgentAbstract.logger.debug("ForceLoadAsMod was specified for {}, attempting force-load", this.fileName); this.loadAsMod(); } @@ -172,12 +189,12 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { */ private void loadAsMod() { try { - MixinPlatformAgentFML.getIgnoredMods(this.clCoreModManager).remove(this.fileName); + MixinPlatformAgentFMLLegacy.getIgnoredMods(this.clCoreModManager).remove(this.fileName); } catch (Exception ex) { MixinPlatformAgentAbstract.logger.catching(ex); } - if (this.attributes.get(MixinPlatformAgentFML.MFATT_COREMODCONTAINSMOD) != null) { + if (this.handle.getAttribute(MixinPlatformAgentFMLLegacy.MFATT_COREMODCONTAINSMOD) != null) { if (this.isIgnoredReparseable()) { MixinPlatformAgentAbstract.logger.debug( "Ignoring request to add {} to reparseable coremod collection - it is a deobfuscated dependency", this.fileName); @@ -188,7 +205,7 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { } private boolean isIgnoredReparseable() { - return this.container.toString().contains("deobfedDeps"); + return this.handle.toString().contains("deobfedDeps"); } /** @@ -198,7 +215,7 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { private void addReparseableJar() { try { Method mdGetReparsedCoremods = this.clCoreModManager.getDeclaredMethod(GlobalProperties.getString( - GlobalProperties.Keys.FML_GET_REPARSEABLE_COREMODS, MixinPlatformAgentFML.GET_REPARSEABLE_COREMODS_METHOD)); + GlobalProperties.Keys.FML_GET_REPARSEABLE_COREMODS, MixinPlatformAgentFMLLegacy.GET_REPARSEABLE_COREMODS_METHOD)); @SuppressWarnings("unchecked") List reparsedCoremods = (List)mdGetReparsedCoremods.invoke(null); if (!reparsedCoremods.contains(this.fileName)) { @@ -211,7 +228,7 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { } private ITweaker injectCorePlugin() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { - String coreModName = this.attributes.get(MixinPlatformAgentFML.MFATT_FMLCOREPLUGIN); + String coreModName = this.handle.getAttribute(MixinPlatformAgentFMLLegacy.MFATT_FMLCOREPLUGIN); if (coreModName == null) { return null; } @@ -223,9 +240,9 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { MixinPlatformAgentAbstract.logger.debug("{} has core plugin {}. Injecting it into FML for co-initialisation:", this.fileName, coreModName); Method mdLoadCoreMod = this.clCoreModManager.getDeclaredMethod(GlobalProperties.getString(GlobalProperties.Keys.FML_LOAD_CORE_MOD, - MixinPlatformAgentFML.LOAD_CORE_MOD_METHOD), LaunchClassLoader.class, String.class, File.class); + MixinPlatformAgentFMLLegacy.LOAD_CORE_MOD_METHOD), LaunchClassLoader.class, String.class, File.class); mdLoadCoreMod.setAccessible(true); - ITweaker wrapper = (ITweaker)mdLoadCoreMod.invoke(null, Launch.classLoader, coreModName, this.container); + ITweaker wrapper = (ITweaker)mdLoadCoreMod.invoke(null, Launch.classLoader, coreModName, this.file); if (wrapper == null) { MixinPlatformAgentAbstract.logger.debug("Core plugin {} could not be loaded.", coreModName); return null; @@ -233,15 +250,15 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { // If the injection tweaker is queued, we are most likely in development // and will NOT need to co-init the coremod - this.initInjectionState = MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_INJECTION); + this.initInjectionState = MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_INJECTION); - MixinPlatformAgentFML.loadedCoreMods.add(coreModName); + MixinPlatformAgentFMLLegacy.loadedCoreMods.add(coreModName); return wrapper; } private boolean isAlreadyInjected(String coreModName) { // Did we already inject this ourselves, or was it specified on the command line - if (MixinPlatformAgentFML.loadedCoreMods.contains(coreModName)) { + if (MixinPlatformAgentFMLLegacy.loadedCoreMods.contains(coreModName)) { return true; } @@ -254,8 +271,8 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { for (ITweaker tweaker : tweakers) { Class tweakClass = tweaker.getClass(); - if (MixinPlatformAgentFML.FML_PLUGIN_WRAPPER_CLASS.equals(tweakClass.getSimpleName())) { - Field fdCoreModInstance = tweakClass.getField(MixinPlatformAgentFML.FML_CORE_MOD_INSTANCE_FIELD); + if (MixinPlatformAgentFMLLegacy.FML_PLUGIN_WRAPPER_CLASS.equals(tweakClass.getSimpleName())) { + Field fdCoreModInstance = tweakClass.getField(MixinPlatformAgentFMLLegacy.FML_CORE_MOD_INSTANCE_FIELD); fdCoreModInstance.setAccessible(true); Object coreMod = fdCoreModInstance.get(tweaker); if (coreModName.equals(coreMod.getClass().getName())) { @@ -272,7 +289,7 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { @Override public String getPhaseProvider() { - return MixinPlatformAgentFML.class.getName() + "$PhaseProvider"; + return MixinPlatformAgentFMLLegacy.class.getName() + "$PhaseProvider"; } /* (non-Javadoc) @@ -280,7 +297,7 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { */ @Override public void prepare() { - this.initInjectionState |= MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_INJECTION); + this.initInjectionState |= MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_INJECTION); } /* (non-Javadoc) @@ -290,15 +307,15 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { @Override public void initPrimaryContainer() { if (this.clCoreModManager != null) { -// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFML.class.getName() + "$PhaseProvider"); +// MixinEnvironment.registerPhaseProvider(MixinPlatformAgentFMLLegacy.class.getName() + "$PhaseProvider"); this.injectRemapper(); } } private void injectRemapper() { try { - MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFML.FML_REMAPPER_ADAPTER_CLASS); - Class clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFML.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader); + MixinPlatformAgentAbstract.logger.debug("Creating FML remapper adapter: {}", MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS); + Class clFmlRemapperAdapter = Class.forName(MixinPlatformAgentFMLLegacy.FML_REMAPPER_ADAPTER_CLASS, true, Launch.classLoader); Method mdCreate = clFmlRemapperAdapter.getDeclaredMethod("create"); IRemapper remapper = (IRemapper)mdCreate.invoke(null); MixinEnvironment.getDefaultEnvironment().getRemappers().add(remapper); @@ -313,19 +330,11 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { @Override public void inject() { if (this.coreModWrapper != null && this.checkForCoInitialisation()) { - MixinPlatformAgentAbstract.logger.debug("FML agent is co-initiralising coremod instance {} for {}", this.coreModWrapper, this.uri); + MixinPlatformAgentAbstract.logger.debug("FML agent is co-initiralising coremod instance {} for {}", this.coreModWrapper, this.handle); this.coreModWrapper.injectIntoClassLoader(Launch.classLoader); } } - /* (non-Javadoc) - * @see org.spongepowered.asm.launch.IMixinPlatformAgent#getLaunchTarget() - */ - @Override - public String getLaunchTarget() { - return null; - } - /** * Performs a naive check which attempts to discover whether we are pre or * post FML's main injection. If we are pre, then we must not @@ -339,14 +348,14 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { * @return true if FML was already injected */ protected final boolean checkForCoInitialisation() { - boolean injectionTweaker = MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_INJECTION); - boolean terminalTweaker = MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_TERMINAL); + boolean injectionTweaker = MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_INJECTION); + boolean terminalTweaker = MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_TERMINAL); if ((this.initInjectionState && terminalTweaker) || injectionTweaker) { MixinPlatformAgentAbstract.logger.debug("FML agent is skipping co-init for {} because FML will inject it normally", this.coreModWrapper); return false; } - return !MixinPlatformAgentFML.isTweakerQueued(MixinPlatformAgentFML.FML_TWEAKER_DEOBF); + return !MixinPlatformAgentFMLLegacy.isTweakerQueued(MixinPlatformAgentFMLLegacy.FML_TWEAKER_DEOBF); } /** @@ -372,9 +381,9 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { private static Class getCoreModManagerClass() throws ClassNotFoundException { try { return Class.forName(GlobalProperties.getString( - GlobalProperties.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS)); + GlobalProperties.Keys.FML_CORE_MOD_MANAGER, MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS)); } catch (ClassNotFoundException ex) { - return Class.forName(MixinPlatformAgentFML.CORE_MOD_MANAGER_CLASS_LEGACY); + return Class.forName(MixinPlatformAgentFMLLegacy.CORE_MOD_MANAGER_CLASS_LEGACY); } } @@ -384,11 +393,11 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { try { mdGetIgnoredMods = clCoreModManager.getDeclaredMethod(GlobalProperties.getString( - GlobalProperties.Keys.FML_GET_IGNORED_MODS, MixinPlatformAgentFML.GET_IGNORED_MODS_METHOD)); + GlobalProperties.Keys.FML_GET_IGNORED_MODS, MixinPlatformAgentFMLLegacy.GET_IGNORED_MODS_METHOD)); } catch (NoSuchMethodException ex1) { try { // Legacy name - mdGetIgnoredMods = clCoreModManager.getDeclaredMethod(MixinPlatformAgentFML.GET_IGNORED_MODS_METHOD_LEGACY); + mdGetIgnoredMods = clCoreModManager.getDeclaredMethod(MixinPlatformAgentFMLLegacy.GET_IGNORED_MODS_METHOD_LEGACY); } catch (NoSuchMethodException ex2) { MixinPlatformAgentAbstract.logger.catching(Level.DEBUG, ex2); return Collections.emptyList(); @@ -397,5 +406,144 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract { return (List)mdGetIgnoredMods.invoke(null); } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent + * #init() + */ + @Override + public void init() { + // Nothing to do here + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.MixinPlatformAgentAbstract + * #getSideName() + */ + @Override + public String getSideName() { + // Using this method first prevents us from accidentally loading FML + // classes too early when using the tweaker in dev + for (ITweaker tweaker : GlobalProperties.>get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKS)) { + if (tweaker.getClass().getName().endsWith(MixinPlatformAgentFMLLegacy.SERVER_TWEAKER_TAIL)) { + return Constants.SIDE_SERVER; + } else if (tweaker.getClass().getName().endsWith(MixinPlatformAgentFMLLegacy.CLIENT_TWEAKER_TAIL)) { + return Constants.SIDE_CLIENT; + } + } + + String name = MixinPlatformAgentAbstract.invokeStringMethod(Launch.classLoader, MixinPlatformAgentFMLLegacy.NEW_LAUNCH_HANDLER_CLASS, + MixinPlatformAgentFMLLegacy.GETSIDE_METHOD); + if (name != null) { + return name; + } + + return MixinPlatformAgentAbstract.invokeStringMethod(Launch.classLoader, MixinPlatformAgentFMLLegacy.OLD_LAUNCH_HANDLER_CLASS, + MixinPlatformAgentFMLLegacy.GETSIDE_METHOD); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent + * #getMixinContainers() + */ + @Override + public Collection getMixinContainers() { + return null; + } + + // AMS - Temp. Legacy log watcher stuff moved here: + + @Override + @Deprecated + public void wire(Phase phase, IConsumer phaseConsumer) { + super.wire(phase, phaseConsumer); + if (phase == Phase.PREINIT) { + MixinPlatformAgentFMLLegacy.begin(phaseConsumer); + } + } + + + /** + * Called when the DEFAULT phase is started + * @deprecated temporary + */ + @Override + @Deprecated + public void unwire() { + MixinPlatformAgentFMLLegacy.end(); + } + + static MixinAppender appender; + static org.apache.logging.log4j.core.Logger log; + static Level oldLevel = null; + + static void begin(IConsumer delegate) { + /* + * In order to determine when to switch to the INIT phase, Mixin + * relies on being able to detect a specific message + * ("Validating minecraft") logged to FMLRelaunchLog. + * However, this message is logged at the DEBUG level, which may + * not be enabled depending on the launcher or game version. + * + * To ensure that Mixin is always able to detect this message, + * we temporarily set the log level of FMLRelaunchLog to 'ALL'. + * To minimize the overall impact, the log level is restored + * (unless it was changed in the meantime) once MixinAppender + * detects the message. + */ + Logger fmlLog = LogManager.getLogger("FML"); + if (!(fmlLog instanceof org.apache.logging.log4j.core.Logger)) { + return; + } + + MixinPlatformAgentFMLLegacy.log = (org.apache.logging.log4j.core.Logger)fmlLog; + MixinPlatformAgentFMLLegacy.oldLevel = MixinPlatformAgentFMLLegacy.log.getLevel(); + + MixinPlatformAgentFMLLegacy.appender = new MixinAppender(delegate); + MixinPlatformAgentFMLLegacy.appender.start(); + MixinPlatformAgentFMLLegacy.log.addAppender(MixinPlatformAgentFMLLegacy.appender); + + MixinPlatformAgentFMLLegacy.log.setLevel(Level.ALL); + } + + static void end() { + if (MixinPlatformAgentFMLLegacy.log != null) { + // remove appender, we're done watching for messages + MixinPlatformAgentFMLLegacy.log.removeAppender(MixinPlatformAgentFMLLegacy.appender); + } + } + + /** + * Temporary + */ + static class MixinAppender extends AbstractAppender { + + private final IConsumer delegate; + + MixinAppender(IConsumer delegate) { + super("MixinLogWatcherAppender", null, null); + this.delegate = delegate; + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() != Level.DEBUG || !"Validating minecraft".equals(event.getMessage().getFormattedMessage())) { + return; + } + + // transition to INIT + this.delegate.accept(Phase.INIT); + + // Only reset the log level if it's still ALL. If something + // else changed the log level after we did, we don't want + // overwrite that change. No null check is needed here + // because the appender will not be injected if the log is + // null + if (MixinPlatformAgentFMLLegacy.log.getLevel() == Level.ALL) { + MixinPlatformAgentFMLLegacy.log.setLevel(MixinPlatformAgentFMLLegacy.oldLevel); + } + } + + } } diff --git a/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java new file mode 100644 index 00000000..0aa026c8 --- /dev/null +++ b/src/launchwrapper/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentLiteLoaderLegacy.java @@ -0,0 +1,74 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform; + +import java.util.Collection; + +import org.spongepowered.asm.launch.platform.container.IContainerHandle; + +import net.minecraft.launchwrapper.Launch; + +/** + * Platform agent for LiteLoader in legacy (LaunchWrapper) environment + */ +public class MixinPlatformAgentLiteLoaderLegacy extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent { + + private static final String GETSIDE_METHOD = "getEnvironmentType"; + private static final String LITELOADER_TWEAKER_NAME = "com.mumfrey.liteloader.launch.LiteLoaderTweaker"; + + @Override + public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { + return false; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.MixinPlatformAgentAbstract + * #getSideName() + */ + @Override + public String getSideName() { + return MixinPlatformAgentAbstract.invokeStringMethod(Launch.classLoader, MixinPlatformAgentLiteLoaderLegacy.LITELOADER_TWEAKER_NAME, + MixinPlatformAgentLiteLoaderLegacy.GETSIDE_METHOD); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent + * #init() + */ + @Override + public void init() { + // Nothing to do here + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent + * #getMixinContainers() + */ + @Override + public Collection getMixinContainers() { + return null; + } + +} diff --git a/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java b/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java index e9776207..979a9baf 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java +++ b/src/launchwrapper/java/org/spongepowered/asm/mixin/transformer/Proxy.java @@ -58,8 +58,8 @@ public final class Proxy implements IClassTransformer, ILegacyClassTransformer { private boolean isActive = true; public Proxy() { - for (Proxy hook : Proxy.proxies) { - hook.isActive = false; + for (Proxy proxy : Proxy.proxies) { + proxy.isActive = false; } Proxy.proxies.add(this); diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/Blackboard.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/Blackboard.java index 55c4e611..afe6a6f1 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/Blackboard.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/Blackboard.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.service.mojang; import org.spongepowered.asm.service.IGlobalPropertyService; +import org.spongepowered.asm.service.IPropertyKey; import net.minecraft.launchwrapper.Launch; @@ -32,6 +33,32 @@ import net.minecraft.launchwrapper.Launch; * Global property service backed by LaunchWrapper blackboard */ public class Blackboard implements IGlobalPropertyService { + + /** + * Property key + */ + class Key implements IPropertyKey { + + private final String key; + + Key(String key) { + this.key = key; + } + + @Override + public String toString() { + return this.key; + } + } + + public Blackboard() { + Launch.classLoader.hashCode(); + } + + @Override + public IPropertyKey resolveKey(String name) { + return new Key(name); + } /** * Get a value from the blackboard and duck-type it to the specified type @@ -42,8 +69,8 @@ public class Blackboard implements IGlobalPropertyService { */ @Override @SuppressWarnings("unchecked") - public final T getProperty(String key) { - return (T)Launch.blackboard.get(key); + public final T getProperty(IPropertyKey key) { + return (T)Launch.blackboard.get(key.toString()); } /** @@ -53,8 +80,8 @@ public class Blackboard implements IGlobalPropertyService { * @param value new value */ @Override - public final void setProperty(String key, Object value) { - Launch.blackboard.put(key, value); + public final void setProperty(IPropertyKey key, Object value) { + Launch.blackboard.put(key.toString(), value); } /** @@ -68,8 +95,8 @@ public class Blackboard implements IGlobalPropertyService { */ @Override @SuppressWarnings("unchecked") - public final T getProperty(String key, T defaultValue) { - Object value = Launch.blackboard.get(key); + public final T getProperty(IPropertyKey key, T defaultValue) { + Object value = Launch.blackboard.get(key.toString()); return value != null ? (T)value : defaultValue; } @@ -83,8 +110,8 @@ public class Blackboard implements IGlobalPropertyService { * @return value from blackboard or default */ @Override - public final String getPropertyString(String key, String defaultValue) { - Object value = Launch.blackboard.get(key); + public final String getPropertyString(IPropertyKey key, String defaultValue) { + Object value = Launch.blackboard.get(key.toString()); return value != null ? value.toString() : defaultValue; } diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java index 59652686..45169565 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java @@ -176,7 +176,7 @@ final class LaunchClassLoaderUtil { field.setAccessible(true); return (T)field.get(classLoader); } catch (Exception ex) { - ex.printStackTrace(); +// ex.printStackTrace(); } return null; } diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java index 14a3faeb..e5c41451 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java @@ -24,76 +24,98 @@ */ package org.spongepowered.asm.service.mojang; +import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Locale; +import java.util.Set; -import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.GlobalProperties; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.spongepowered.asm.launch.GlobalProperties.Keys; +import org.spongepowered.asm.launch.platform.MainAttributes; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; +import org.spongepowered.asm.launch.platform.container.ContainerHandleURI; +import org.spongepowered.asm.launch.platform.container.ContainerHandleVirtual; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; 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.ILegacyClassTransformer; -import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.ITransformer; -import org.spongepowered.asm.util.ReEntranceLock; +import org.spongepowered.asm.service.MixinServiceAbstract; +import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Sets; +import com.google.common.io.ByteStreams; +import com.google.common.io.Closeables; +import com.google.common.collect.ImmutableList.Builder; import net.minecraft.launchwrapper.IClassNameTransformer; import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.Launch; /** * Mixin service for launchwrapper */ -public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, IClassBytecodeProvider { +public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements IClassProvider, IClassBytecodeProvider { // Blackboard keys - public static final String BLACKBOARD_KEY_TWEAKCLASSES = "TweakClasses"; - public static final String BLACKBOARD_KEY_TWEAKS = "Tweaks"; + public static final Keys BLACKBOARD_KEY_TWEAKCLASSES = Keys.of("TweakClasses"); + public static final Keys BLACKBOARD_KEY_TWEAKS = Keys.of("Tweaks"); + + private static final String MIXIN_TWEAKER_CLASS = "org.spongepowered.asm.launch.MixinTweaker"; // Consts - private static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; - private static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin."; - private static final String STATE_TWEAKER = MixinServiceLaunchWrapper.MIXIN_PACKAGE + "EnvironmentStateTweaker"; - private static final String TRANSFORMER_PROXY_CLASS = MixinServiceLaunchWrapper.MIXIN_PACKAGE + "transformer.Proxy"; - + private static final String STATE_TWEAKER = MixinServiceAbstract.MIXIN_PACKAGE + "EnvironmentStateTweaker"; + private static final String TRANSFORMER_PROXY_CLASS = MixinServiceAbstract.MIXIN_PACKAGE + "transformer.Proxy"; + /** - * Logger + * Known re-entrant transformers, other re-entrant transformers will + * detected automatically */ - private static final Logger logger = LogManager.getLogger("mixin"); + private static final Set excludeTransformers = Sets.newHashSet( + "net.minecraftforge.fml.common.asm.transformers.EventSubscriptionTransformer", + "cpw.mods.fml.common.asm.transformers.EventSubscriptionTransformer", + "net.minecraftforge.fml.common.asm.transformers.TerminalTransformer", + "cpw.mods.fml.common.asm.transformers.TerminalTransformer" + ); /** * Utility for reflecting into Launch ClassLoader */ - private final LaunchClassLoaderUtil classLoaderUtil = new LaunchClassLoaderUtil(Launch.classLoader); + private final LaunchClassLoaderUtil classLoaderUtil; /** - * Transformer re-entrance lock, shared between the mixin transformer and - * the metadata service + * Local transformer chain, this consists of all transformers present at the + * init phase with the exclusion of the mixin transformer itself and known + * re-entrant transformers. Detected re-entrant transformers will be + * subsequently removed. */ - private final ReEntranceLock lock = new ReEntranceLock(1); - + private List delegatedTransformers; + /** * Class name transformer (if present) */ private IClassNameTransformer nameTransformer; + public MixinServiceLaunchWrapper() { + this.classLoaderUtil = new LaunchClassLoaderUtil(Launch.classLoader); + } + @Override public String getName() { return "LaunchWrapper"; @@ -119,7 +141,7 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, @Override public void prepare() { // Only needed in dev, in production this would be handled by the tweaker - Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapper.LAUNCH_PACKAGE); + Launch.classLoader.addClassLoaderExclusion(MixinServiceAbstract.LAUNCH_PACKAGE); } /* (non-Javadoc) @@ -127,6 +149,11 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, */ @Override public Phase getInitialPhase() { + String command = System.getProperty("sun.java.command"); + if (command != null && command.contains("GradleStart")) { + System.setProperty("mixin.env.remapRefMap", "true"); + } + if (MixinServiceLaunchWrapper.findInStackTrace("net.minecraft.launchwrapper.Launch", "launch") > 132) { return Phase.DEFAULT; } @@ -139,21 +166,15 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, @Override public void init() { if (MixinServiceLaunchWrapper.findInStackTrace("net.minecraft.launchwrapper.Launch", "launch") < 4) { - MixinServiceLaunchWrapper.logger.error("MixinBootstrap.doInit() called during a tweak constructor!"); + MixinServiceAbstract.logger.error("MixinBootstrap.doInit() called during a tweak constructor!"); } List tweakClasses = GlobalProperties.>get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKCLASSES); if (tweakClasses != null) { tweakClasses.add(MixinServiceLaunchWrapper.STATE_TWEAKER); } - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#getReEntranceLock() - */ - @Override - public ReEntranceLock getReEntranceLock() { - return this.lock; + + super.init(); } /* (non-Javadoc) @@ -162,10 +183,56 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, @Override public Collection getPlatformAgents() { return ImmutableList.of( - "org.spongepowered.asm.launch.platform.MixinPlatformAgentFML" + "org.spongepowered.asm.launch.platform.MixinPlatformAgentFMLLegacy", + "org.spongepowered.asm.launch.platform.MixinPlatformAgentLiteLoaderLegacy" ); } + @Override + public IContainerHandle getPrimaryContainer() { + URI uri = null; + try { + uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI(); + if (uri != null) { + return new ContainerHandleURI(uri); + } + } catch (URISyntaxException ex) { + ex.printStackTrace(); + } + return new ContainerHandleVirtual(this.getName()); + } + + @Override + public Collection getMixinContainers() { + Builder list = ImmutableList.builder(); + this.getContainersFromClassPath(list); + this.getContainersFromAgents(list); + return list.build(); + } + + private void getContainersFromClassPath(Builder list) { + // We know this is deprecated, it works for LW though, so access directly + URL[] sources = this.getClassPath(); + if (sources != null) { + for (URL url : sources) { + try { + URI uri = url.toURI(); + MixinServiceAbstract.logger.debug("Scanning {} for mixin tweaker", uri); + if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) { + continue; + } + MainAttributes attributes = MainAttributes.of(uri); + String tweaker = attributes.get(Constants.ManifestAttributes.TWEAKER); + if (MixinServiceLaunchWrapper.MIXIN_TWEAKER_CLASS.equals(tweaker)) { + list.add(new ContainerHandleURI(uri)); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + } + /* (non-Javadoc) * @see org.spongepowered.asm.service.IMixinService#getClassProvider() */ @@ -215,6 +282,7 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, @Override public void beginPhase() { Launch.classLoader.registerTransformer(MixinServiceLaunchWrapper.TRANSFORMER_PROXY_CLASS); + this.delegatedTransformers = null; } /* (non-Javadoc) @@ -275,6 +343,7 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, * @see org.spongepowered.asm.service.IClassProvider#getClassPath() */ @Override + @Deprecated public URL[] getClassPath() { return Launch.classLoader.getSources().toArray(new URL[0]); } @@ -294,7 +363,7 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, } if (transformer instanceof IClassNameTransformer) { - MixinServiceLaunchWrapper.logger.debug("Found name transformer: {}", transformer.getClass().getName()); + MixinServiceAbstract.logger.debug("Found name transformer: {}", transformer.getClass().getName()); this.nameTransformer = (IClassNameTransformer)transformer; } @@ -302,11 +371,83 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, return wrapped; } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#getClassBytes( - * java.lang.String, java.lang.String) + /** + * Returns (and generates if necessary) the transformer delegation list for + * this environment. + * + * @return current transformer delegation list (read-only) */ @Override + public List getDelegatedTransformers() { + return Collections.unmodifiableList(this.getDelegatedLegacyTransformers()); + } + + private List getDelegatedLegacyTransformers() { + if (this.delegatedTransformers == null) { + this.buildTransformerDelegationList(); + } + + return this.delegatedTransformers; + } + + /** + * Builds the transformer list to apply to loaded mixin bytecode. Since + * generating this list requires inspecting each transformer by name (to + * cope with the new wrapper functionality added by FML) we generate the + * list just once per environment and cache the result. + */ + private void buildTransformerDelegationList() { + MixinServiceAbstract.logger.debug("Rebuilding transformer delegation list:"); + this.delegatedTransformers = new ArrayList(); + for (ITransformer transformer : this.getTransformers()) { + if (!(transformer instanceof ILegacyClassTransformer)) { + continue; + } + + ILegacyClassTransformer legacyTransformer = (ILegacyClassTransformer)transformer; + String transformerName = legacyTransformer.getName(); + boolean include = true; + for (String excludeClass : MixinServiceLaunchWrapper.excludeTransformers) { + if (transformerName.contains(excludeClass)) { + include = false; + break; + } + } + if (include && !legacyTransformer.isDelegationExcluded()) { + MixinServiceAbstract.logger.debug(" Adding: {}", transformerName); + this.delegatedTransformers.add(legacyTransformer); + } else { + MixinServiceAbstract.logger.debug(" Excluding: {}", transformerName); + } + } + + MixinServiceAbstract.logger.debug("Transformer delegation list created with {} entries", this.delegatedTransformers.size()); + } + + /** + * Adds a transformer to the transformer exclusions list + * + * @param name Class transformer exclusion to add + */ + @Override + public void addTransformerExclusion(String name) { + MixinServiceLaunchWrapper.excludeTransformers.add(name); + + // Force rebuild of the list + this.delegatedTransformers = null; + } + + /** + * Retrieve class bytes using available classloaders, does not transform the + * class + * + * @param name class name + * @param transformedName transformed class name + * @return class bytes or null if not found + * @throws IOException propagated + * @deprecated Use {@link #getClassNode} instead + */ + @Deprecated public byte[] getClassBytes(String name, String transformedName) throws IOException { byte[] classBytes = Launch.classLoader.getClassBytes(name); if (classBytes != null) { @@ -319,11 +460,11 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, try { final String resourcePath = transformedName.replace('.', '/').concat(".class"); classStream = appClassLoader.getResourceAsStream(resourcePath); - return IOUtils.toByteArray(classStream); + return ByteStreams.toByteArray(classStream); } catch (Exception ex) { return null; } finally { - IOUtils.closeQuietly(classStream); + Closeables.closeQuietly(classStream); } } @@ -337,7 +478,7 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, * @throws ClassNotFoundException if the specified class could not be loaded * @throws IOException if an error occurs whilst reading the specified class */ - @Override + @Deprecated public byte[] getClassBytes(String className, boolean runTransformers) throws ClassNotFoundException, IOException { String transformedName = className.replace('/', '.'); String name = this.unmapClassName(transformedName); @@ -375,25 +516,23 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, return basicClass; } - MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); - - for (ILegacyClassTransformer transformer : environment.getTransformers()) { + for (ILegacyClassTransformer transformer : this.getDelegatedLegacyTransformers()) { // Clear the re-entrance semaphore this.lock.clear(); int pos = transformer.getName().lastIndexOf('.'); String simpleName = transformer.getName().substring(pos + 1); - Section transformTime = profiler.begin(Profiler.FINE, simpleName.toLowerCase()); + Section transformTime = profiler.begin(Profiler.FINE, simpleName.toLowerCase(Locale.ROOT)); transformTime.setInfo(transformer.getName()); basicClass = transformer.transformClassBytes(name, transformedName, basicClass); transformTime.end(); if (this.lock.isSet()) { // Also add it to the exclusion list so we can exclude it if the environment triggers a rebuild - environment.addTransformerExclusion(transformer.getName()); + this.addTransformerExclusion(transformer.getName()); this.lock.clear(); - MixinServiceLaunchWrapper.logger.info("A re-entrant transformer '{}' was detected and will no longer process meta class data", + MixinServiceAbstract.logger.info("A re-entrant transformer '{}' was detected and will no longer process meta class data", transformer.getName()); } } @@ -417,7 +556,7 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, List transformers = Launch.classLoader.getTransformers(); for (IClassTransformer transformer : transformers) { if (transformer instanceof IClassNameTransformer) { - MixinServiceLaunchWrapper.logger.debug("Found name transformer: {}", transformer.getClass().getName()); + MixinServiceAbstract.logger.debug("Found name transformer: {}", transformer.getClass().getName()); this.nameTransformer = (IClassNameTransformer) transformer; } } @@ -429,7 +568,16 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, */ @Override public ClassNode getClassNode(String className) throws ClassNotFoundException, IOException { - return this.getClassNode(this.getClassBytes(className, true), 0); + return this.getClassNode(this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassBytecodeProvider#getClassNode( + * java.lang.String, boolean) + */ + @Override + public ClassNode getClassNode(String className, boolean runTransformers) throws ClassNotFoundException, IOException { + return this.getClassNode(this.getClassBytes(className, true), ClassReader.EXPAND_FRAMES); } /** @@ -446,49 +594,6 @@ public class MixinServiceLaunchWrapper implements IMixinService, IClassProvider, return classNode; } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#getSideName() - */ - @Override - public final String getSideName() { - // Using this method first prevents us from accidentally loading FML - // classes too early when using the tweaker in dev - for (ITweaker tweaker : GlobalProperties.>get(MixinServiceLaunchWrapper.BLACKBOARD_KEY_TWEAKS)) { - if (tweaker.getClass().getName().endsWith(".common.launcher.FMLServerTweaker")) { - return "SERVER"; - } else if (tweaker.getClass().getName().endsWith(".common.launcher.FMLTweaker")) { - return "CLIENT"; - } - } - - String name = this.getSideName("net.minecraftforge.fml.relauncher.FMLLaunchHandler", "side"); - if (name != null) { - return name; - } - - name = this.getSideName("cpw.mods.fml.relauncher.FMLLaunchHandler", "side"); - if (name != null) { - return name; - } - - name = this.getSideName("com.mumfrey.liteloader.launch.LiteLoaderTweaker", "getEnvironmentType"); - if (name != null) { - return name; - } - - return "UNKNOWN"; - } - - private String getSideName(String className, String methodName) { - try { - Class clazz = Class.forName(className, false, Launch.classLoader); - Method method = clazz.getDeclaredMethod(methodName); - return ((Enum)method.invoke(null)).name(); - } catch (Exception ex) { - return null; - } - } - private static int findInStackTrace(String className, String methodName) { Thread currentThread = Thread.currentThread(); diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java index 8717f52b..0b1aaaf4 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapperBootstrap.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.service.mojang; import org.spongepowered.asm.service.IMixinServiceBootstrap; +import org.spongepowered.asm.service.ServiceInitialisationException; import net.minecraft.launchwrapper.Launch; @@ -36,7 +37,8 @@ public class MixinServiceLaunchWrapperBootstrap implements IMixinServiceBootstra private static final String SERVICE_PACKAGE = "org.spongepowered.asm.service."; private static final String MIXIN_UTIL_PACKAGE = "org.spongepowered.asm.util."; - private static final String ASM_PACKAGE = "org.spongepowered.asm.lib."; + private static final String LEGACY_ASM_PACKAGE = "org.spongepowered.asm.lib."; + private static final String ASM_PACKAGE = "org.objectweb.asm."; private static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin."; @Override @@ -51,11 +53,18 @@ public class MixinServiceLaunchWrapperBootstrap implements IMixinServiceBootstra @Override public void bootstrap() { + try { + Launch.classLoader.hashCode(); + } catch (Throwable th) { + throw new ServiceInitialisationException(this.getName() + " is not available"); + } + // Essential ones Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.SERVICE_PACKAGE); // Important ones Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.ASM_PACKAGE); + Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.LEGACY_ASM_PACKAGE); Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.MIXIN_PACKAGE); Launch.classLoader.addClassLoaderExclusion(MixinServiceLaunchWrapperBootstrap.MIXIN_UTIL_PACKAGE); } diff --git a/src/legacy/java/org/spongepowered/asm/mixin/throwables/CompanionPluginError.java b/src/legacy/java/org/spongepowered/asm/mixin/throwables/CompanionPluginError.java new file mode 100644 index 00000000..a9874757 --- /dev/null +++ b/src/legacy/java/org/spongepowered/asm/mixin/throwables/CompanionPluginError.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.throwables; + +/** + * Thrown for unsupported legacy API calls + */ +public class CompanionPluginError extends LinkageError { + + private static final long serialVersionUID = 1L; + + public CompanionPluginError() { + } + + public CompanionPluginError(String message) { + super(message); + } + + public CompanionPluginError(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/GlobalProperties.java b/src/main/java/org/spongepowered/asm/launch/GlobalProperties.java index a5fef67d..85725d52 100644 --- a/src/main/java/org/spongepowered/asm/launch/GlobalProperties.java +++ b/src/main/java/org/spongepowered/asm/launch/GlobalProperties.java @@ -24,9 +24,12 @@ */ package org.spongepowered.asm.launch; -import java.util.ServiceLoader; +import java.util.HashMap; +import java.util.Map; import org.spongepowered.asm.service.IGlobalPropertyService; +import org.spongepowered.asm.service.IPropertyKey; +import org.spongepowered.asm.service.MixinService; /** * Access to underlying global property service provided by the current @@ -39,19 +42,56 @@ public final class GlobalProperties { */ public static final class Keys { - public static final String INIT = "mixin.initialised"; - public static final String AGENTS = "mixin.agents"; - public static final String CONFIGS = "mixin.configs"; - public static final String TRANSFORMER = "mixin.transformer"; - public static final String PLATFORM_MANAGER = "mixin.platform"; + public static final Keys INIT = Keys.of("mixin.initialised"); + public static final Keys AGENTS = Keys.of("mixin.agents"); + public static final Keys CONFIGS = Keys.of("mixin.configs"); + public static final Keys PLATFORM_MANAGER = Keys.of("mixin.platform"); - public static final String FML_LOAD_CORE_MOD = "mixin.launch.fml.loadcoremodmethod"; - public static final String FML_GET_REPARSEABLE_COREMODS = "mixin.launch.fml.reparseablecoremodsmethod"; - public static final String FML_CORE_MOD_MANAGER = "mixin.launch.fml.coremodmanagerclass"; - public static final String FML_GET_IGNORED_MODS = "mixin.launch.fml.ignoredmodsmethod"; + public static final Keys FML_LOAD_CORE_MOD = Keys.of("mixin.launch.fml.loadcoremodmethod"); + public static final Keys FML_GET_REPARSEABLE_COREMODS = Keys.of("mixin.launch.fml.reparseablecoremodsmethod"); + public static final Keys FML_CORE_MOD_MANAGER = Keys.of("mixin.launch.fml.coremodmanagerclass"); + public static final Keys FML_GET_IGNORED_MODS = Keys.of("mixin.launch.fml.ignoredmodsmethod"); + + private static Map keys; + + private final String name; + + private IPropertyKey key; - private Keys() {} + private Keys(String name) { + this.name = name; + } + + IPropertyKey resolve(IGlobalPropertyService service) { + if (this.key != null) { + return this.key; + } + if (service == null) { + return null; + } + + return this.key = service.resolveKey(this.name); + } + /** + * Get or create a new global property key + * + * @param name name of key to get or create + * @return new or existing key + */ + public static Keys of(String name) { + if (Keys.keys == null) { + Keys.keys = new HashMap(); + } + + Keys key = Keys.keys.get(name); + if (key == null) { + key = new Keys(name); + Keys.keys.put(name, key); + } + return key; + } + } private static IGlobalPropertyService service; @@ -60,9 +100,7 @@ public final class GlobalProperties { private static IGlobalPropertyService getService() { if (GlobalProperties.service == null) { - ServiceLoader serviceLoader = - ServiceLoader.load(IGlobalPropertyService.class, GlobalProperties.class.getClassLoader()); - GlobalProperties.service = serviceLoader.iterator().next(); + GlobalProperties.service = MixinService.getGlobalPropertyService(); } return GlobalProperties.service; } @@ -74,8 +112,9 @@ public final class GlobalProperties { * @param duck type * @return value */ - public static T get(String key) { - return GlobalProperties.getService().getProperty(key); + public static T get(Keys key) { + IGlobalPropertyService service = GlobalProperties.getService(); + return service.getProperty(key.resolve(service)); } /** @@ -84,8 +123,9 @@ public final class GlobalProperties { * @param key blackboard key * @param value new value */ - public static void put(String key, Object value) { - GlobalProperties.getService().setProperty(key, value); + public static void put(Keys key, Object value) { + IGlobalPropertyService service = GlobalProperties.getService(); + service.setProperty(key.resolve(service), value); } /** @@ -97,8 +137,9 @@ public final class GlobalProperties { * @param duck type * @return value from blackboard or default value */ - public static T get(String key, T defaultValue) { - return GlobalProperties.getService().getProperty(key, defaultValue); + public static T get(Keys key, T defaultValue) { + IGlobalPropertyService service = GlobalProperties.getService(); + return service.getProperty(key.resolve(service), defaultValue); } /** @@ -110,8 +151,9 @@ public final class GlobalProperties { * set or is null * @return value from blackboard or default */ - public static String getString(String key, String defaultValue) { - return GlobalProperties.getService().getPropertyString(key, defaultValue); + public static String getString(Keys key, String defaultValue) { + IGlobalPropertyService service = GlobalProperties.getService(); + return service.getPropertyString(key.resolve(service), defaultValue); } } diff --git a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java index 8d44117c..dab551b1 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinBootstrap.java @@ -28,6 +28,7 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.platform.CommandLineOptions; import org.spongepowered.asm.launch.platform.MixinPlatformManager; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; @@ -60,7 +61,7 @@ public abstract class MixinBootstrap { /** * Subsystem version */ - public static final String VERSION = "0.7.12"; + public static final String VERSION = "0.8-preview"; /** * Log all the things @@ -81,6 +82,11 @@ public abstract class MixinBootstrap { * Platform manager instance */ private static MixinPlatformManager platform; + + /** + * Connectors + */ + private static MixinConnectorManager connectors = new MixinConnectorManager(); private MixinBootstrap() {} @@ -117,7 +123,7 @@ public abstract class MixinBootstrap { return; } - MixinBootstrap.doInit(null); + MixinBootstrap.doInit(CommandLineOptions.defaultArgs()); } /** @@ -137,16 +143,11 @@ public abstract class MixinBootstrap { if (!MixinBootstrap.initialised) { MixinBootstrap.initialised = true; - String command = System.getProperty("sun.java.command"); - if (command != null && command.contains("GradleStart")) { - System.setProperty("mixin.env.remapRefMap", "true"); - } - Phase initialPhase = MixinService.getService().getInitialPhase(); if (initialPhase == Phase.DEFAULT) { MixinBootstrap.logger.error("Initialising mixin subsystem after game pre-init phase! Some mixins may be skipped."); MixinEnvironment.init(initialPhase); - MixinBootstrap.getPlatform().prepare(null); + MixinBootstrap.getPlatform().prepare(CommandLineOptions.defaultArgs()); MixinBootstrap.initState = false; } else { MixinEnvironment.init(initialPhase); @@ -160,10 +161,15 @@ public abstract class MixinBootstrap { return true; } + @Deprecated + static void doInit(List args) { + MixinBootstrap.doInit(CommandLineOptions.ofArgs(args)); + } + /** * Phase 2 of mixin initialisation, initialise the phases */ - static void doInit(List args) { + static void doInit(CommandLineOptions args) { if (!MixinBootstrap.initialised) { if (MixinBootstrap.isSubsystemRegistered()) { MixinBootstrap.logger.warn("Multiple Mixin containers present, init suppressed for " + MixinBootstrap.VERSION); @@ -187,6 +193,7 @@ public abstract class MixinBootstrap { static void inject() { MixinBootstrap.getPlatform().inject(); + MixinBootstrap.connectors.inject(); } private static boolean isSubsystemRegistered() { diff --git a/src/main/java/org/spongepowered/asm/launch/MixinConnectorManager.java b/src/main/java/org/spongepowered/asm/launch/MixinConnectorManager.java new file mode 100644 index 00000000..552cda96 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/MixinConnectorManager.java @@ -0,0 +1,79 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.mixin.connect.IMixinConnector; + +/** + * Manager for Mixin containers bootstrapping via {@link IMixinConnector} + */ +public class MixinConnectorManager { + + /** + * Logging to the max + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + private List connectors = new ArrayList(); + + MixinConnectorManager() { + } + + void inject() { + this.loadConnectors(); + this.initConnectors(); + } + + void loadConnectors() { + ServiceLoader serviceLoader = ServiceLoader.load(IMixinConnector.class); + for (Iterator iterator = serviceLoader.iterator(); iterator.hasNext(); ) { + try { + IMixinConnector connector = iterator.next(); + this.connectors.add(connector); + } catch (ServiceConfigurationError e) { + MixinConnectorManager.logger.catching(e); + } + } + } + + void initConnectors() { + for (IMixinConnector connector : this.connectors) { + try { + connector.connect(); + } catch (Exception ex) { + MixinConnectorManager.logger.warn("Error initialising Mixin Connector [" + connector.getClass().getName() + "]", ex); + } + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java b/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java index 8d32df36..028ffc9a 100644 --- a/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java +++ b/src/main/java/org/spongepowered/asm/launch/MixinInitialisationError.java @@ -24,10 +24,12 @@ */ package org.spongepowered.asm.launch; +import org.spongepowered.asm.mixin.throwables.MixinError; + /** * Error raised when mixin subsystem initialisation fails */ -public class MixinInitialisationError extends Error { +public class MixinInitialisationError extends MixinError { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/launch/platform/CommandLineOptions.java b/src/main/java/org/spongepowered/asm/launch/platform/CommandLineOptions.java new file mode 100644 index 00000000..af92bb0b --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/CommandLineOptions.java @@ -0,0 +1,103 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Options passed in to Mixin via the command line + */ +public final class CommandLineOptions { + + private List configs = new ArrayList(); + + private CommandLineOptions() { + } + + public List getConfigs() { + return Collections.unmodifiableList(this.configs); + } + + /** + * Read and parse command-line arguments + * + * @param args command-line arguments + */ + private void parseArgs(List args) { + boolean captureNext = false; + for (String arg : args) { + if (captureNext) { + this.configs.add(arg); + } + captureNext = "--mixin".equals(arg) || "--mixin.config".equals(arg); + } + } + + /** + * Create a CommandLineOptions with default args (read from system property) + * + * @return CommandLineOptions instance + */ + public static CommandLineOptions defaultArgs() { + return CommandLineOptions.ofArgs(null); + } + + /** + * Create a CommandLineOptions using the supplied unparsed argument list. + * Uses args from system property if + * + * @param args Argument list to parse, can be null + * @return CommandLineOptions instance + */ + public static CommandLineOptions ofArgs(List args) { + CommandLineOptions options = new CommandLineOptions(); + if (args == null) { + String argv = System.getProperty("sun.java.command"); + if (argv != null) { + args = Arrays.asList(argv.split(" ")); + } + } + if (args != null) { + options.parseArgs(args); + } + return options; + } + + /** + * Create a CommandLineOptions using the supplied list of pre-parsed configs + * + * @param configs List of configs + * @return CommandLineOptions instance + */ + public static CommandLineOptions of(List configs) { + CommandLineOptions options = new CommandLineOptions(); + options.configs.addAll(configs); + return options; + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java index c57062a7..6f9487ae 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformAgent.java @@ -24,17 +24,34 @@ */ package org.spongepowered.asm.launch.platform; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; + /** * Base interface for platform agents. Platform agents are environment-specific * handlers which are used by the Mixin subsystem to perform platform-specific - * tasks required by different environments without having to litter the Mixin - * codebase with a bunch of environment-specific cruft. + * tasks required by different environments without having to litter other parts + * of the Mixin codebase with a bunch of environment-specific cruft. * *

Platform Agents handle mixin environment tasks on a per-container basis, * with each container in the environment being assigned one of each available * type of agent to handle those tasks on behalf of the container.

*/ public interface IMixinPlatformAgent { + + /** + * Accept and bind to a container handle. This method is called for agents + * hosted by {@link MixinContainer} and the agent should react accordingly. + * If the agent is not able to delegate for container handles of + * the supplied type, this method should return false to indicate + * that the agent should not be added for this container. + * + * @param manager platform manager instance + * @param handle handle to container + * @return true if this agent can accept a container of the supplied type, + * false if the agent cannot handle the container (in which case it + * will be discarded) + */ + public abstract boolean accept(MixinPlatformManager manager, IContainerHandle handle); /** * Get the phase provider for this agent @@ -58,11 +75,5 @@ public interface IMixinPlatformAgent { * Called from inject in the parent tweaker */ public abstract void inject(); - - /** - * Get the launch target from this container, should return null if no - * custom target is available. - */ - public abstract String getLaunchTarget(); - + } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java new file mode 100644 index 00000000..495279ac --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/IMixinPlatformServiceAgent.java @@ -0,0 +1,72 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform; + +import java.util.Collection; + +import org.spongepowered.asm.launch.platform.container.IContainerHandle; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.util.IConsumer; + +/** + * Service agents provide additional platform-specific extensions leveraged by + * mixin services. Implementing this interface on an agent class will cause an + * additional instance to be spun up by the service. + */ +public interface IMixinPlatformServiceAgent extends IMixinPlatformAgent { + + /** + * Perform initialisation-stage logic for this agent + */ + public abstract void init(); + + /** + * Attempt to determine the side name from the current environment + */ + public abstract String getSideName(); + + /** + * Get environment-specific mixin containers + */ + public abstract Collection getMixinContainers(); + + /** + * Temp wiring + * + * @param phase Initial phase + * @param phaseConsumer Phase setter callback + * @deprecated temporary + */ + @Deprecated + public abstract void wire(Phase phase, IConsumer phaseConsumer); + + /** + * Temp wiring - Called when the DEFAULT phase is started + * @deprecated temporary + */ + @Deprecated + public abstract void unwire(); + +} diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java b/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java index 6ccef4d7..17980cf7 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.launch.platform; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.util.HashMap; import java.util.Map; @@ -33,11 +34,14 @@ import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; +import com.google.common.io.ByteSource; +import com.google.common.io.Files; + /** * "Main" attribute cache for a URI container, mainly to avoid constantly * opening jar files just to read odd values out of the manifest. */ -final class MainAttributes { +public final class MainAttributes { private static final Map instances = new HashMap(); @@ -54,6 +58,13 @@ final class MainAttributes { this.attributes = MainAttributes.getAttributes(jar); } + /** + * Retrieve the value of attribute with the specified name, or null if not + * present + * + * @param name attribute name + * @return attribute value or null if not present + */ public final String get(String name) { if (this.attributes != null) { return this.attributes.getValue(name); @@ -61,11 +72,29 @@ final class MainAttributes { return null; } - private static Attributes getAttributes(File jar) { - if (jar == null) { + private static Attributes getAttributes(File codeSource) { + if (codeSource == null) { return null; } + if (codeSource.isFile()) { + Attributes attributes = MainAttributes.getJarAttributes(codeSource); + if (attributes != null) { + return attributes; + } + } + + if (codeSource.isDirectory()) { + Attributes attributes = MainAttributes.getDirAttributes(codeSource); + if (attributes != null) { + return attributes; + } + } + + return new Attributes(); + } + + private static Attributes getJarAttributes(File jar) { JarFile jarFile = null; try { jarFile = new JarFile(jar); @@ -84,13 +113,51 @@ final class MainAttributes { // ignore } } - return new Attributes(); + return null; } + private static Attributes getDirAttributes(File dir) { + File manifestFile = new File(dir, JarFile.MANIFEST_NAME); + if (manifestFile.isFile()) { + ByteSource source = Files.asByteSource(manifestFile); + InputStream inputStream = null; + try { + inputStream = source.openBufferedStream(); + Manifest manifest = new Manifest(inputStream); + return manifest.getMainAttributes(); + } catch (IOException ex) { + // be quiet checkstyle + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + // ignore + } + } + } + + return null; + } + + + /** + * Create a MainAttributes instance for the supplied jar file + * + * @param jar jar file + * @return MainAttributes instance + */ public static MainAttributes of(File jar) { return MainAttributes.of(jar.toURI()); } + /** + * Create a MainAttributes instance for the supplied jar file + * + * @param uri jar file location + * @return MainAttributes instance + */ public static MainAttributes of(URI uri) { MainAttributes attributes = MainAttributes.instances.get(uri); if (attributes == null) { diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java index 15c2f70d..4723ca00 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinContainer.java @@ -24,8 +24,6 @@ */ package org.spongepowered.asm.launch.platform; -import java.lang.reflect.Constructor; -import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -33,10 +31,12 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.GlobalProperties; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.service.MixinService; /** - * A collection of {@link IMixinPlatformAgent} platform agents) + * A collection of {@link IMixinPlatformAgent} platform agents) for a particular + * container */ public class MixinContainer { @@ -50,25 +50,39 @@ public class MixinContainer { MixinContainer.agentClasses.add("org.spongepowered.asm.launch.platform.MixinPlatformAgentDefault"); } - private final Logger logger = LogManager.getLogger("mixin"); + private static final Logger logger = LogManager.getLogger("mixin"); - private final URI uri; + private final IContainerHandle handle; private final List agents = new ArrayList(); - public MixinContainer(MixinPlatformManager manager, URI uri) { - this.uri = uri; + public MixinContainer(MixinPlatformManager manager, IContainerHandle handle) { + this.handle = handle; for (String agentClass : MixinContainer.agentClasses) { try { @SuppressWarnings("unchecked") Class clazz = (Class)Class.forName(agentClass); - Constructor ctor = clazz.getDeclaredConstructor(MixinPlatformManager.class, URI.class); - this.logger.debug("Instancing new {} for {}", clazz.getSimpleName(), this.uri); - IMixinPlatformAgent agent = ctor.newInstance(manager, uri); - this.agents.add(agent); - } catch (Exception ex) { - this.logger.catching(ex); + String simpleName = clazz.getSimpleName(); + String acceptAction = "rejected"; + + MixinContainer.logger.debug("Instancing new {} for {}", simpleName, this.handle); + IMixinPlatformAgent agent = clazz.newInstance(); + + if (agent.accept(manager, this.handle)) { + this.agents.add(agent); + acceptAction = "accepted"; + } + + MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction, this.handle); + } catch (InstantiationException ex) { + Throwable cause = ex.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException)cause; + } + throw new RuntimeException(cause); + } catch (ReflectiveOperationException ex) { + MixinContainer.logger.catching(ex); } } } @@ -76,8 +90,8 @@ public class MixinContainer { /** * */ - public URI getURI() { - return this.uri; + public IContainerHandle getDescriptor() { + return this.handle; } /** @@ -99,7 +113,7 @@ public class MixinContainer { */ public void prepare() { for (IMixinPlatformAgent agent : this.agents) { - this.logger.debug("Processing prepare() for {}", agent); + MixinContainer.logger.debug("Processing prepare() for {}", agent); agent.prepare(); } } @@ -110,7 +124,7 @@ public class MixinContainer { */ public void initPrimaryContainer() { for (IMixinPlatformAgent agent : this.agents) { - this.logger.debug("Processing launch tasks for {}", agent); + MixinContainer.logger.debug("Processing launch tasks for {}", agent); agent.initPrimaryContainer(); } } @@ -120,26 +134,9 @@ public class MixinContainer { */ public void inject() { for (IMixinPlatformAgent agent : this.agents) { - this.logger.debug("Processing inject() for {}", agent); + MixinContainer.logger.debug("Processing inject() for {}", agent); agent.inject(); } } - - /** - * Analogue of ITweaker::getLaunchTarget, queries all agents and - * returns first valid launch target. Returns null if no agents have launch - * target. - * - * @return launch target from agent or null - */ - public String getLaunchTarget() { - for (IMixinPlatformAgent agent : this.agents) { - String launchTarget = agent.getLaunchTarget(); - if (launchTarget != null) { - return launchTarget; - } - } - return null; - } } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java index 381d05da..79637f51 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentAbstract.java @@ -24,11 +24,13 @@ */ package org.spongepowered.asm.launch.platform; -import java.io.File; -import java.net.URI; +import java.lang.reflect.Method; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.util.IConsumer; /** * Platform agent base class @@ -40,39 +42,24 @@ public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent */ protected static final Logger logger = LogManager.getLogger("mixin"); - protected final MixinPlatformManager manager; + protected MixinPlatformManager manager; /** * URI to the container */ - protected final URI uri; - - /** - * File containing this tweaker - */ - protected final File container; + protected IContainerHandle handle; /** - * "Main" manifest attributes from the container + * Ctor */ - protected final MainAttributes attributes; - - /** - * Create a new platform agent for the specified URI - * - * @param manager platform manager - * @param uri URI of the resource for this agent - */ - public MixinPlatformAgentAbstract(MixinPlatformManager manager, URI uri) { - this.manager = manager; - this.uri = uri; - this.container = this.uri != null ? new File(this.uri) : null; - this.attributes = MainAttributes.of(uri); + protected MixinPlatformAgentAbstract() { } @Override - public String toString() { - return String.format("PlatformAgent[%s:%s]", this.getClass().getSimpleName(), this.uri); + public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { + this.manager = manager; + this.handle = handle; + return true; } @Override @@ -80,4 +67,53 @@ public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent return null; } + @Override + public void prepare() { + } + + @Override + public void initPrimaryContainer() { + } + + @Override + public void inject() { + } + + @Override + public String toString() { + return String.format("PlatformAgent[%s:%s]", this.getClass().getSimpleName(), this.handle); + } + + protected static String invokeStringMethod(ClassLoader classLoader, String className, String methodName) { + try { + Class clazz = Class.forName(className, false, classLoader); + Method method = clazz.getDeclaredMethod(methodName); + return ((Enum)method.invoke(null)).name(); + } catch (Exception ex) { + return null; + } + } + + // AMS - Temp + + /** + * Temp wiring. Called when the initial phase is spun up in the environment. + * + * @param phase Initial phase + * @param phaseConsumer Delegate for the service (or agents) to trigger + * later phases + * @deprecated temporary + */ + @Deprecated + public void wire(Phase phase, IConsumer phaseConsumer) { + } + + /** + * Called when the DEFAULT phase is started + * @deprecated temporary + */ + @Deprecated + public void unwire() { + } + } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java index e48d3659..348d26a3 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentDefault.java @@ -24,8 +24,6 @@ */ package org.spongepowered.asm.launch.platform; -import java.net.URI; - import org.spongepowered.asm.util.Constants.ManifestAttributes; /** @@ -34,48 +32,27 @@ import org.spongepowered.asm.util.Constants.ManifestAttributes; */ public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract { - /** - * @param manager platform manager - * @param uri URI of the resource for this agent - */ - public MixinPlatformAgentDefault(MixinPlatformManager manager, URI uri) { - super(manager, uri); - } - @Override public void prepare() { @SuppressWarnings("deprecation") - String compatibilityLevel = this.attributes.get(ManifestAttributes.COMPATIBILITY); + String compatibilityLevel = this.handle.getAttribute(ManifestAttributes.COMPATIBILITY); if (compatibilityLevel != null) { this.manager.setCompatibilityLevel(compatibilityLevel); } - String mixinConfigs = this.attributes.get(ManifestAttributes.MIXINCONFIGS); + String mixinConfigs = this.handle.getAttribute(ManifestAttributes.MIXINCONFIGS); if (mixinConfigs != null) { for (String config : mixinConfigs.split(",")) { this.manager.addConfig(config.trim()); } } - String tokenProviders = this.attributes.get(ManifestAttributes.TOKENPROVIDERS); + String tokenProviders = this.handle.getAttribute(ManifestAttributes.TOKENPROVIDERS); if (tokenProviders != null) { for (String provider : tokenProviders.split(",")) { this.manager.addTokenProvider(provider.trim()); } } } - - @Override - public void initPrimaryContainer() { - } - - @Override - public void inject() { - } - - @Override - public String getLaunchTarget() { - return this.attributes.get(ManifestAttributes.MAINCLASS); - } } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java index 6a96bb1d..0d689eff 100644 --- a/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java +++ b/src/main/java/org/spongepowered/asm/launch/platform/MixinPlatformManager.java @@ -24,26 +24,24 @@ */ package org.spongepowered.asm.launch.platform; -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Arrays; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -//import org.spongepowered.asm.launch.MixinBootstrap.Delegate; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.service.MixinService; -import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.service.ServiceVersionError; import org.spongepowered.asm.mixin.Mixins; +import org.spongepowered.asm.mixin.throwables.MixinError; //import com.google.common.collect.ImmutableList; @@ -54,7 +52,6 @@ import org.spongepowered.asm.mixin.Mixins; public class MixinPlatformManager { private static final String DEFAULT_MAIN_CLASS = "net.minecraft.client.main.Main"; - private static final String MIXIN_TWEAKER_CLASS = "org.spongepowered.asm.launch.MixinTweaker"; /** * Make with the logging already @@ -69,7 +66,7 @@ public class MixinPlatformManager { /** * Tweak containers */ - private final Map containers = new LinkedHashMap(); + private final Map containers = new LinkedHashMap(); /** * Container for this tweaker @@ -92,25 +89,16 @@ public class MixinPlatformManager { } /** - * Initialise this platform manager by scanning the classpath + * Initialise the platform manager */ public void init() { MixinPlatformManager.logger.debug("Initialising Mixin Platform Manager"); - - // Add agents for the tweak container - URI uri = null; - try { - uri = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI(); - if (uri != null) { - MixinPlatformManager.logger.debug("Mixin platform: primary container is {}", uri); - this.primaryContainer = this.addContainer(uri); - } - } catch (URISyntaxException ex) { - ex.printStackTrace(); - } - + + IContainerHandle primaryContainerHandle = MixinService.getService().getPrimaryContainer(); + this.primaryContainer = this.addContainer(primaryContainerHandle); + // Do an early scan to ensure preinit mixins are discovered - this.scanClasspath(); + this.scanForContainers(); } /** @@ -126,60 +114,54 @@ public class MixinPlatformManager { } /** - * Add a new URI to this platform and return the new container (or an - * existing container if the URI was previously registered) + * Add a new container to this platform and return the new container (or an + * existing container if the handle was previously registered) * - * @param uri URI to add - * @return container for specified URI + * @param handle Container handle to add + * @return container for specified resource handle */ - public final MixinContainer addContainer(URI uri) { - MixinContainer existingContainer = this.containers.get(uri); + public final MixinContainer addContainer(IContainerHandle handle) { + MixinContainer existingContainer = this.containers.get(handle); if (existingContainer != null) { return existingContainer; } - MixinPlatformManager.logger.debug("Adding mixin platform agents for container {}", uri); - MixinContainer container = new MixinContainer(this, uri); - this.containers.put(uri, container); - + MixinContainer container = this.createContainerFor(handle); + this.containers.put(handle, container); + this.addNestedContainers(handle); + return container; + } + + private MixinContainer createContainerFor(IContainerHandle handle) { + MixinPlatformManager.logger.debug("Adding mixin platform agents for container {}", handle); + MixinContainer container = new MixinContainer(this, handle); if (this.prepared) { container.prepare(); } return container; } + private void addNestedContainers(IContainerHandle handle) { + for (IContainerHandle nested : handle.getNestedContainers()) { + if (!this.containers.containsKey(nested)) { + this.addContainer(nested); + } + } + } + /** * Prepare all containers in this platform * * @param args command-line arguments from tweaker */ - public final void prepare(List args) { + public final void prepare(CommandLineOptions args) { this.prepared = true; for (MixinContainer container : this.containers.values()) { container.prepare(); } - if (args != null) { - this.parseArgs(args); - } else { - String argv = System.getProperty("sun.java.command"); - if (argv != null) { - this.parseArgs(Arrays.asList(argv.split(" "))); - } - } - } - - /** - * Read and parse command-line arguments - * - * @param args command-line arguments - */ - private void parseArgs(List args) { - boolean captureNext = false; - for (String arg : args) { - if (captureNext) { - this.addConfig(arg); - } - captureNext = "--mixin".equals(arg); + + for (String config : args.getConfigs()) { + this.addConfig(config); } } @@ -196,7 +178,7 @@ public class MixinPlatformManager { this.primaryContainer.initPrimaryContainer(); } - this.scanClasspath(); + this.scanForContainers(); MixinPlatformManager.logger.debug("inject() running with {} agents", this.containers.size()); for (MixinContainer container : this.containers.values()) { try { @@ -208,27 +190,26 @@ public class MixinPlatformManager { } /** - * Scan the classpath for mixin containers (containers which declare the - * mixin tweaker in their manifest) and add agents for them + * Scan the current environment for mixin containers and add agents for them */ - private void scanClasspath() { - URL[] sources = MixinService.getService().getClassProvider().getClassPath(); - for (URL url : sources) { + private void scanForContainers() { + Collection mixinContainers = null; + + try { + mixinContainers = MixinService.getService().getMixinContainers(); + } catch (AbstractMethodError ame) { + throw new ServiceVersionError("Mixin service is out of date"); + } + + List existingContainers = new ArrayList(this.containers.keySet()); + for (IContainerHandle existingContainer : existingContainers) { + this.addNestedContainers(existingContainer); + } + + for (IContainerHandle handle : mixinContainers) { try { - URI uri = url.toURI(); - if (this.containers.containsKey(uri)) { - continue; - } - MixinPlatformManager.logger.debug("Scanning {} for mixin tweaker", uri); - if (!"file".equals(uri.getScheme()) || !new File(uri).exists()) { - continue; - } - MainAttributes attributes = MainAttributes.of(uri); - String tweaker = attributes.get(Constants.ManifestAttributes.TWEAKER); - if (MixinPlatformManager.MIXIN_TWEAKER_CLASS.equals(tweaker)) { - MixinPlatformManager.logger.debug("{} contains a mixin tweaker, adding agents", uri); - this.addContainer(uri); - } + MixinPlatformManager.logger.debug("Adding agents for Mixin Container {}", handle); + this.addContainer(handle); } catch (Exception ex) { ex.printStackTrace(); } @@ -240,13 +221,6 @@ public class MixinPlatformManager { * specify a launch target */ public String getLaunchTarget() { - for (MixinContainer container : this.containers.values()) { - String mainClass = container.getLaunchTarget(); - if (mainClass != null) { - return mainClass; - } - } - return MixinPlatformManager.DEFAULT_MAIN_CLASS; } @@ -259,7 +233,7 @@ public class MixinPlatformManager { @SuppressWarnings("deprecation") final void setCompatibilityLevel(String level) { try { - CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase()); + CompatibilityLevel value = CompatibilityLevel.valueOf(level.toUpperCase(Locale.ROOT)); MixinPlatformManager.logger.debug("Setting mixin compatibility level: {}", value); MixinEnvironment.setCompatibilityLevel(value); } catch (IllegalArgumentException ex) { @@ -275,21 +249,12 @@ public class MixinPlatformManager { * * @param config config resource name, does not require a leading / */ - @SuppressWarnings("deprecation") final void addConfig(String config) { if (config.endsWith(".json")) { MixinPlatformManager.logger.debug("Registering mixin config: {}", config); Mixins.addConfiguration(config); } else if (config.contains(".json@")) { - int pos = config.indexOf(".json@"); - String phaseName = config.substring(pos + 6); - config = config.substring(0, pos + 5); - Phase phase = Phase.forName(phaseName); - if (phase != null) { - MixinPlatformManager.logger.warn("Setting config phase via manifest is deprecated: {}. Specify target in config instead", config); - MixinPlatformManager.logger.debug("Registering mixin config: {}", config); - MixinEnvironment.getEnvironment(phase).addConfiguration(config); - } + throw new MixinError("Setting config phase via manifest is no longer supported: " + config + ". Specify target in config instead"); } } diff --git a/src/main/java/org/spongepowered/asm/launch/platform/container/ContainerHandleURI.java b/src/main/java/org/spongepowered/asm/launch/platform/container/ContainerHandleURI.java new file mode 100644 index 00000000..8abb6194 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/container/ContainerHandleURI.java @@ -0,0 +1,120 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform.container; + +import java.io.File; +import java.net.URI; +import java.util.Collection; +import java.util.Collections; + +import org.spongepowered.asm.launch.platform.MainAttributes; + +/** + * Container handle which directly replaces the use of classpath location URIs + * from previous mixin versions + */ +public class ContainerHandleURI implements IContainerHandle { + + /** + * Target URI + */ + private final URI uri; + + /** + * File containing this tweaker + */ + private final File file; + + /** + * "Main" manifest attributes from the container + */ + private final MainAttributes attributes; + + public ContainerHandleURI(URI uri) { + this.uri = uri; + this.file = this.uri != null ? new File(this.uri) : null; + this.attributes = MainAttributes.of(uri); + } + + /** + * Get the URI for this handle + */ + public URI getURI() { + return this.uri; + } + + /** + * Get the container file + */ + public File getFile() { + return this.file; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.container.IContainerHandle + * #getAttribute(java.lang.String) + */ + @Override + public String getAttribute(String name) { + return this.attributes.get(name); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.container.IContainerHandle + * #getNestedContainers() + */ + @Override + public Collection getNestedContainers() { + return Collections.emptyList(); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object other) { + if (!(other instanceof ContainerHandleURI)) { + return false; + } + return this.uri.equals(((ContainerHandleURI)other).uri); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return this.uri.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("ContainerHandleURI(%s)", this.uri); + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/platform/container/ContainerHandleVirtual.java b/src/main/java/org/spongepowered/asm/launch/platform/container/ContainerHandleVirtual.java new file mode 100644 index 00000000..3b624a1a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/container/ContainerHandleVirtual.java @@ -0,0 +1,130 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform.container; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * A virtual container, used to marshal other containers around + */ +public class ContainerHandleVirtual implements IContainerHandle { + + /** + * Name, used mainly for differentiation since containers are used as map + * keys + */ + private final String name; + + /** + * Virtual attributes + */ + private final Map attributes = new HashMap(); + + /** + * Virtual nested containers (might be real containers, depending on the + * purpose of this container + */ + private final Set nestedContainers = new LinkedHashSet(); + + /** + * .ctor + * + * @param name Unique container name + */ + public ContainerHandleVirtual(String name) { + this.name = name; + } + + /** + * Set a virtual attribute on this virtual container + * + * @param key attribute key + * @param value attribute value + * @return fluent interface + */ + public ContainerHandleVirtual setAttribute(String key, String value) { + this.attributes.put(key, value); + return this; + } + + /** + * Add a nested container to this virtual container + * + * @param nested Nested container to add + * @return fluent + */ + public ContainerHandleVirtual add(IContainerHandle nested) { + this.nestedContainers.add(nested); + return this; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.container.IContainerHandle + * #getAttribute(java.lang.String) + */ + @Override + public String getAttribute(String name) { + return this.attributes.get(name); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.container.IContainerHandle + * #getNestedContainers() + */ + @Override + public Collection getNestedContainers() { + return Collections.unmodifiableSet(this.nestedContainers); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + return obj instanceof String && obj.toString().equals(this.name); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return this.name.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("ContainerHandleVirtual(%s:%x)", this.name, this.hashCode()); + } + +} diff --git a/src/main/java/org/spongepowered/asm/launch/platform/container/IContainerHandle.java b/src/main/java/org/spongepowered/asm/launch/platform/container/IContainerHandle.java new file mode 100644 index 00000000..0d05af9d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/launch/platform/container/IContainerHandle.java @@ -0,0 +1,54 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform.container; + +import java.util.Collection; + +/** + * Interface for container handles. Previously resources considered by Mixin + * were indexed by URI but in order to provide more flexibility the container + * handle system now wraps URIs in a more expressive object, and provides + * support for both virtual containers and nested container resolution. + */ +public interface IContainerHandle { + + /** + * Retrieve the value of attribute with the specified name, or null if not + * present + * + * @param name attribute name + * @return attribute value or null if not present + */ + public abstract String getAttribute(String name); + + /** + * Get nested containers from this container, allows a container to detect + * and return containers within itself. For example a folder container + * detecting and returning file containers, or a virtual container returning + * real containers after a scan. + */ + public abstract Collection getNestedContainers(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 7edfa2ac..60718b81 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -29,34 +29,34 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; -import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.LogEvent; -import org.apache.logging.log4j.core.appender.AbstractAppender; import org.spongepowered.asm.launch.GlobalProperties; +import org.spongepowered.asm.launch.GlobalProperties.Keys; import org.spongepowered.asm.launch.MixinBootstrap; -import org.spongepowered.asm.lib.Opcodes; +import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.extensibility.IEnvironmentTokenProvider; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.throwables.MixinException; -import org.spongepowered.asm.mixin.transformer.MixinTransformer; +import org.spongepowered.asm.mixin.transformer.IMixinTransformer; import org.spongepowered.asm.obfuscation.RemapperChain; -import org.spongepowered.asm.service.ILegacyClassTransformer; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.ITransformer; import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.service.MixinServiceAbstract; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.IConsumer; import org.spongepowered.asm.util.ITokenProvider; import org.spongepowered.asm.util.JavaVersion; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.asm.util.perf.Profiler; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Sets; /** * The mixin environment manages global state information for the mixin @@ -175,7 +175,7 @@ public final class MixinEnvironment implements ITokenProvider { @Override protected boolean detect() { String sideName = MixinService.getService().getSideName(); - return "CLIENT".equals(sideName); + return Constants.SIDE_CLIENT.equals(sideName); } }, @@ -186,7 +186,7 @@ public final class MixinEnvironment implements ITokenProvider { @Override protected boolean detect() { String sideName = MixinService.getService().getSideName(); - return "SERVER".equals(sideName) || "DEDICATEDSERVER".equals(sideName); + return Constants.SIDE_SERVER.equals(sideName) || Constants.SIDE_DEDICATEDSERVER.equals(sideName); } }; @@ -574,7 +574,7 @@ public final class MixinEnvironment implements ITokenProvider { > E getEnumValue(E defaultValue) { String value = System.getProperty(this.property, defaultValue.name()); try { - return (E)Enum.valueOf(defaultValue.getClass(), value.toUpperCase()); + return (E)Enum.valueOf(defaultValue.getClass(), value.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException ex) { return defaultValue; } @@ -589,12 +589,12 @@ public final class MixinEnvironment implements ITokenProvider { /** * Java 6 and above */ - JAVA_6(6, Opcodes.V1_6, false), + JAVA_6(6, Opcodes.V1_6, 0), /** * Java 7 and above */ - JAVA_7(7, Opcodes.V1_7, false) { + JAVA_7(7, Opcodes.V1_7, 0) { @Override boolean isSupported() { @@ -606,7 +606,7 @@ public final class MixinEnvironment implements ITokenProvider { /** * Java 8 and above */ - JAVA_8(8, Opcodes.V1_8, true) { + JAVA_8(8, Opcodes.V1_8, LanguageFeature.METHODS_IN_INTERFACES) { @Override boolean isSupported() { @@ -618,30 +618,79 @@ public final class MixinEnvironment implements ITokenProvider { /** * Java 9 and above */ - JAVA_9(9, CompatibilityLevel.CLASS_V1_9, true) { + JAVA_9(9, Opcodes.V9, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) { @Override boolean isSupported() { - return false; + return JavaVersion.current() >= 9.0; + } + + }, + + /** + * Java 10 and above + */ + JAVA_10(10, Opcodes.V10, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES) { + + @Override + boolean isSupported() { + return JavaVersion.current() >= 10.0; + } + + }, + + /** + * Java 10 and above + */ + JAVA_11(11, Opcodes.V11, LanguageFeature.METHODS_IN_INTERFACES | LanguageFeature.PRIVATE_METHODS_IN_INTERFACES + | LanguageFeature.NESTING | LanguageFeature.DYNAMIC_CONSTANTS) { + + @Override + boolean isSupported() { + return JavaVersion.current() >= 11.0; } }; - // Temp, until ASM supports Java 9 - private static final int CLASS_V1_9 = 0 << 16 | 53; + /** + * Bitmask values for language features supported + */ + public static class LanguageFeature { + + /** + * Language version supports methods in interfaces + */ + public static final int METHODS_IN_INTERFACES = 1; + + /** + * Language version supports private methods in interfaces + */ + public static final int PRIVATE_METHODS_IN_INTERFACES = 2; + + /** + * Native nesting + */ + public static final int NESTING = 4; + + /** + * Native nesting + */ + public static final int DYNAMIC_CONSTANTS = 8; + + } private final int ver; private final int classVersion; - private final boolean supportsMethodsInInterfaces; + private final int languageFeatures; private CompatibilityLevel maxCompatibleLevel; - private CompatibilityLevel(int ver, int classVersion, boolean resolveMethodsInInterfaces) { + private CompatibilityLevel(int ver, int classVersion, int languageFeatures) { this.ver = ver; this.classVersion = classVersion; - this.supportsMethodsInInterfaces = resolveMethodsInInterfaces; + this.languageFeatures = languageFeatures; } @SuppressWarnings("unused") @@ -667,9 +716,23 @@ public final class MixinEnvironment implements ITokenProvider { /** * Get whether this environment supports non-abstract methods in * interfaces, true in Java 1.8 and above + * + * @deprecated Use {@link #supports(int)} instead */ + @Deprecated public boolean supportsMethodsInInterfaces() { - return this.supportsMethodsInInterfaces; + return (this.languageFeatures & LanguageFeature.METHODS_IN_INTERFACES) != 0; + } + + /** + * Get whether the specified {@link LanguageFeature} is supported by + * this runtime. + * + * @param languageFeature language feature (or features) to check + * @return true if all specified language features are supported + */ + public boolean supports(int languageFeature) { + return (this.languageFeatures & languageFeature) != 0; } /** @@ -709,6 +772,21 @@ public final class MixinEnvironment implements ITokenProvider { return level.canElevateTo(this); } + + static String getSupportedVersions() { + StringBuilder sb = new StringBuilder(); + boolean comma = false; + for (CompatibilityLevel level : CompatibilityLevel.values()) { + if (level.isSupported()) { + if (comma) { + sb.append(", "); + } + sb.append(level.ver); + comma = true; + } + } + return sb.toString(); + } } @@ -752,93 +830,19 @@ public final class MixinEnvironment implements ITokenProvider { } } - + /** - * Temporary + * Phase setter callback delegate */ - static class MixinLogWatcher { + static class PhaseConsumer implements IConsumer { - static MixinAppender appender = new MixinAppender(); - static org.apache.logging.log4j.core.Logger log; - static Level oldLevel = null; - - static void begin() { - /* - * In order to determine when to switch to the INIT phase, Mixin - * relies on being able to detect a specific message - * ("Validating minecraft") logged to FMLRelaunchLog. - * However, this message is logged at the DEBUG level, which may - * not be enabled depending on the launcher or game version. - * - * To ensure that Mixin is always able to detect this message, - * we temporarily set the log level of FMLRelaunchLog to 'ALL'. - * To minimize the overall impact, the log level is restored - * (unless it was changed in the meantime) once MixinAppender - * detects the message. - */ - Logger fmlLog = LogManager.getLogger("FML"); - if (!(fmlLog instanceof org.apache.logging.log4j.core.Logger)) { - return; - } - - MixinLogWatcher.log = (org.apache.logging.log4j.core.Logger)fmlLog; - MixinLogWatcher.oldLevel = MixinLogWatcher.log.getLevel(); - - MixinLogWatcher.appender.start(); - MixinLogWatcher.log.addAppender(MixinLogWatcher.appender); - - MixinLogWatcher.log.setLevel(Level.ALL); + @Override + public void accept(Phase phase) { + MixinEnvironment.gotoPhase(phase); } - static void end() { - if (MixinLogWatcher.log != null) { - // remove appender, we're done watching for messages - MixinLogWatcher.log.removeAppender(MixinLogWatcher.appender); - } - } - - /** - * Temporary - */ - static class MixinAppender extends AbstractAppender { - - MixinAppender() { - super("MixinLogWatcherAppender", null, null); - } - - @Override - public void append(LogEvent event) { - if (event.getLevel() != Level.DEBUG || !"Validating minecraft".equals(event.getMessage().getFormattedMessage())) { - return; - } - - // transition to INIT - MixinEnvironment.gotoPhase(Phase.INIT); - - // Only reset the log level if it's still ALL. If something - // else changed the log level after we did, we don't want - // overwrite that change. No null check is needed here - // because the appender will not be injected if the log is - // null - if (MixinLogWatcher.log.getLevel() == Level.ALL) { - MixinLogWatcher.log.setLevel(MixinLogWatcher.oldLevel); - } - } - - } } - /** - * Known re-entrant transformers, other re-entrant transformers will - * detected automatically - */ - private static final Set excludeTransformers = Sets.newHashSet( - "net.minecraftforge.fml.common.asm.transformers.EventSubscriptionTransformer", - "cpw.mods.fml.common.asm.transformers.EventSubscriptionTransformer", - "net.minecraftforge.fml.common.asm.transformers.TerminalTransformer", - "cpw.mods.fml.common.asm.transformers.TerminalTransformer" - ); - /** * Currently active environment */ @@ -869,6 +873,11 @@ public final class MixinEnvironment implements ITokenProvider { * Performance profiler */ private static final Profiler profiler = new Profiler(); + + /** + * Active transformer + */ + private static IMixinTransformer transformer; /** * Service @@ -883,7 +892,7 @@ public final class MixinEnvironment implements ITokenProvider { /** * The blackboard key for this environment's configs */ - private final String configsKey; + private final Keys configsKey; /** * This environment's options @@ -915,14 +924,6 @@ public final class MixinEnvironment implements ITokenProvider { */ private Side side; - /** - * Local transformer chain, this consists of all transformers present at the - * init phase with the exclusion of the mixin transformer itself and known - * re-entrant transformers. Detected re-entrant transformers will be - * subsequently removed. - */ - private List transformers; - /** * Obfuscation context (refmap key to use in this environment) */ @@ -931,7 +932,7 @@ public final class MixinEnvironment implements ITokenProvider { MixinEnvironment(Phase phase) { this.service = MixinService.getService(); this.phase = phase; - this.configsKey = GlobalProperties.Keys.CONFIGS + "." + this.phase.name.toLowerCase(); + this.configsKey = Keys.of(GlobalProperties.Keys.CONFIGS + "." + this.phase.name.toLowerCase(Locale.ROOT)); // Sanity check Object version = this.getVersion(); @@ -965,9 +966,10 @@ public final class MixinEnvironment implements ITokenProvider { printer.add("SpongePowered MIXIN%s", verbose ? " (Verbose debugging enabled)" : "").centre().hr(); printer.kv("Code source", codeSource); printer.kv("Internal Version", version); - printer.kv("Java 8 Supported", CompatibilityLevel.JAVA_8.isSupported()).hr(); + printer.kv("Java Versions Supported", CompatibilityLevel.getSupportedVersions()).hr(); printer.kv("Service Name", serviceName); - printer.kv("Service Class", this.service.getClass().getName()).hr(); + printer.kv("Mixin Service Class", this.service.getClass().getName()); + printer.kv("Global Property Service Class", MixinService.getGlobalPropertyService().getClass().getName()).hr(); for (Option option : Option.values()) { StringBuilder indent = new StringBuilder(); for (int i = 0; i < option.depth; i++) { @@ -1013,20 +1015,6 @@ 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 configs = this.getMixinConfigs(); if (!configs.contains(config)) { @@ -1034,19 +1022,6 @@ public final class MixinEnvironment implements ITokenProvider { } } - /** - * Add a new error handler class to this environment - * - * @param handlerName Handler class to add - * @return fluent interface - * @deprecated use Mixins::registerErrorHandlerClass - */ - @Deprecated - public MixinEnvironment registerErrorHandlerClass(String handlerName) { - Mixins.registerErrorHandlerClass(handlerName); - return this; - } - /** * Add a new token provider class to this environment * @@ -1096,7 +1071,7 @@ public final class MixinEnvironment implements ITokenProvider { */ @Override public Integer getToken(String token) { - token = token.toUpperCase(); + token = token.toUpperCase(Locale.ROOT); for (TokenProviderWrapper provider : this.tokenProviders) { Integer value = provider.getToken(token); @@ -1125,7 +1100,7 @@ public final class MixinEnvironment implements ITokenProvider { * @return active mixin transformer instance */ public Object getActiveTransformer() { - return GlobalProperties.get(GlobalProperties.Keys.TRANSFORMER); + return MixinEnvironment.transformer; } /** @@ -1133,9 +1108,9 @@ public final class MixinEnvironment implements ITokenProvider { * * @param transformer Mixin Transformer */ - public void setActiveTransformer(ITransformer transformer) { + public void setActiveTransformer(IMixinTransformer transformer) { if (transformer != null) { - GlobalProperties.put(GlobalProperties.Keys.TRANSFORMER, transformer); + MixinEnvironment.transformer = transformer; } } @@ -1260,9 +1235,8 @@ public final class MixinEnvironment implements ITokenProvider { */ public void audit() { Object activeTransformer = this.getActiveTransformer(); - if (activeTransformer instanceof MixinTransformer) { - MixinTransformer transformer = (MixinTransformer)activeTransformer; - transformer.audit(this); + if (activeTransformer instanceof IMixinTransformer) { + ((IMixinTransformer)activeTransformer).audit(this); } } @@ -1271,59 +1245,24 @@ public final class MixinEnvironment implements ITokenProvider { * this environment. * * @return current transformer delegation list (read-only) + * @deprecated Do not use this method */ - public List getTransformers() { - if (this.transformers == null) { - this.buildTransformerDelegationList(); - } - - return Collections.unmodifiableList(this.transformers); + @Deprecated + public List getTransformers() { + MixinEnvironment.logger.warn("MixinEnvironment::getTransformers is deprecated!"); + return (List)this.service.getTransformers(); } /** * Adds a transformer to the transformer exclusions list * * @param name Class transformer exclusion to add + * @deprecated Do not use this method */ + @Deprecated public void addTransformerExclusion(String name) { - MixinEnvironment.excludeTransformers.add(name); - - // Force rebuild of the list - this.transformers = null; - } - - /** - * Builds the transformer list to apply to loaded mixin bytecode. Since - * generating this list requires inspecting each transformer by name (to - * cope with the new wrapper functionality added by FML) we generate the - * list just once per environment and cache the result. - */ - private void buildTransformerDelegationList() { - MixinEnvironment.logger.debug("Rebuilding transformer delegation list:"); - this.transformers = new ArrayList(); - for (ITransformer transformer : this.service.getTransformers()) { - if (!(transformer instanceof ILegacyClassTransformer)) { - continue; - } - - ILegacyClassTransformer legacyTransformer = (ILegacyClassTransformer)transformer; - String transformerName = legacyTransformer.getName(); - boolean include = true; - for (String excludeClass : MixinEnvironment.excludeTransformers) { - if (transformerName.contains(excludeClass)) { - include = false; - break; - } - } - if (include && !legacyTransformer.isDelegationExcluded()) { - MixinEnvironment.logger.debug(" Adding: {}", transformerName); - this.transformers.add(legacyTransformer); - } else { - MixinEnvironment.logger.debug(" Excluding: {}", transformerName); - } - } - - MixinEnvironment.logger.debug("Transformer delegation list created with {} entries", this.transformers.size()); + MixinEnvironment.logger.warn("MixinEnvironment::addTransformerExclusion is deprecated!"); + this.service.addTransformerExclusion(name); } /* (non-Javadoc) @@ -1350,13 +1289,18 @@ public final class MixinEnvironment implements ITokenProvider { * * @param phase initial phase */ + @SuppressWarnings("deprecation") public static void init(Phase phase) { if (MixinEnvironment.currentPhase == Phase.NOT_INITIALISED) { MixinEnvironment.currentPhase = phase; MixinEnvironment env = MixinEnvironment.getEnvironment(phase); MixinEnvironment.getProfiler().setActive(env.getOption(Option.DEBUG_PROFILER)); - MixinLogWatcher.begin(); + // AMS - Temp wiring to avoid merging multiphase + IMixinService service = MixinService.getService(); + if (service instanceof MixinServiceAbstract) { + ((MixinServiceAbstract)service).wire(phase, new PhaseConsumer()); + } } } @@ -1440,20 +1384,24 @@ public final class MixinEnvironment implements ITokenProvider { * * @param phase phase to go to */ + @SuppressWarnings("deprecation") static void gotoPhase(Phase phase) { if (phase == null || phase.ordinal < 0) { throw new IllegalArgumentException("Cannot go to the specified phase, phase is null or invalid"); } + IMixinService service = MixinService.getService(); if (phase.ordinal > MixinEnvironment.getCurrentPhase().ordinal) { - MixinService.getService().beginPhase(); - } - - if (phase == Phase.DEFAULT) { - MixinLogWatcher.end(); + service.beginPhase(); } MixinEnvironment.currentPhase = phase; MixinEnvironment.currentEnvironment = MixinEnvironment.getEnvironment(MixinEnvironment.getCurrentPhase()); + + // AMS - Temp wiring to avoid merging multiphase + if (service instanceof MixinServiceAbstract && phase == Phase.DEFAULT) { + ((MixinServiceAbstract)service).unwire(); + } + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/Mixins.java b/src/main/java/org/spongepowered/asm/mixin/Mixins.java index c78f3878..399e13fe 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Mixins.java +++ b/src/main/java/org/spongepowered/asm/mixin/Mixins.java @@ -32,6 +32,9 @@ import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.GlobalProperties; +import org.spongepowered.asm.launch.GlobalProperties.Keys; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.Config; /** @@ -49,7 +52,7 @@ public final class Mixins { /** * GlobalProperties key storing mixin configs which are pending */ - private static final String CONFIGS_KEY = GlobalProperties.Keys.CONFIGS + ".queue"; + private static final Keys CONFIGS_KEY = Keys.of(GlobalProperties.Keys.CONFIGS + ".queue"); /** * Error handlers for environment @@ -157,6 +160,21 @@ public final class Mixins { } return mixinConfigs; } + + /** + * Get information about mixins applied to the specified class in the + * current session. + * + * @param className Name of class to retrieve mixins for + * @return Set of applied mixins + */ + public static Set getMixinsForClass(String className) { + ClassInfo classInfo = ClassInfo.fromCache(className); + if (classInfo != null) { + return classInfo.getAppliedMixins(); + } + return Collections.emptySet(); + } /** * Register a gloabl error handler class diff --git a/src/main/java/org/spongepowered/asm/mixin/connect/IMixinConnector.java b/src/main/java/org/spongepowered/asm/mixin/connect/IMixinConnector.java new file mode 100644 index 00000000..1c4d85c6 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/connect/IMixinConnector.java @@ -0,0 +1,41 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.connect; + +import org.spongepowered.asm.mixin.Mixins; + +/** + * A connector class is a bootstrap agent for a mixin consumer. It should call + * back against {@link Mixins} to register its resources much like previous + * "CoreMod" bootstraps. + */ +public interface IMixinConnector { + + /** + * Connect to Mixin + */ + public abstract void connect(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java index 88e3295b..fba779c0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinConfigPlugin.java @@ -27,7 +27,7 @@ package org.spongepowered.asm.mixin.extensibility; import java.util.List; import java.util.Set; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.tree.ClassNode; /** *

A companion plugin for a mixin configuration object. Objects implementing @@ -121,4 +121,5 @@ public interface IMixinConfigPlugin { * @param mixinInfo Information about this mixin */ public abstract void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java index a5612820..4e946ccf 100644 --- a/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/extensibility/IMixinInfo.java @@ -26,7 +26,7 @@ package org.spongepowered.asm.mixin.extensibility; import java.util.List; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java b/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java index 6fa3ee2a..3dfebc08 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/Accessor.java @@ -36,6 +36,10 @@ import org.spongepowered.asm.mixin.Shadow; * return the field type and take no arguments) or a setter (must take an * argument of the field type and return void). The annotated method must be * abstract. + * + *

The target field for an accessor can be specified as part of the decorated + * method name (eg. setFoo or getFoo to provide accessors for + * a target field foo) or specified in the annotation value.

* *

Accessors provide a simple way of gaining access to internal class members * in a target class without needing to resort to access transformers, and diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java index fd78c074..6ee65bbd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java @@ -26,9 +26,12 @@ package org.spongepowered.asm.mixin.gen; import java.util.ArrayList; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.Bytecode; /** * Base class for accessor generators @@ -39,9 +42,23 @@ public abstract class AccessorGenerator { * Accessor info which describes the accessor */ protected final AccessorInfo info; - - public AccessorGenerator(AccessorInfo info) { + + /** + * True for static field, false for instance field + */ + protected final boolean targetIsStatic; + + public AccessorGenerator(AccessorInfo info, boolean isStatic) { this.info = info; + this.targetIsStatic = isStatic; + } + + protected void checkModifiers() { + if (this.info.isStatic() && !this.targetIsStatic) { + IMixinContext context = this.info.getContext(); + throw new InvalidInjectionException(context, String.format("%s is invalid. Accessor method is%s static but the target is not.", + this.info, this.info.isStatic() ? "" : " not")); + } } /** @@ -53,8 +70,8 @@ public abstract class AccessorGenerator { */ protected final MethodNode createMethod(int maxLocals, int maxStack) { MethodNode method = this.info.getMethod(); - MethodNode accessor = new MethodNode(Opcodes.ASM5, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name, method.desc, - null, null); + MethodNode accessor = new MethodNode(Bytecode.ASM_API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name, + method.desc, null, null); accessor.visibleAnnotations = new ArrayList(); accessor.visibleAnnotations.add(this.info.getAnnotation()); accessor.maxLocals = maxLocals; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java index 15c38a2a..41be7d26 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorField.java @@ -24,9 +24,9 @@ */ package org.spongepowered.asm.mixin.gen; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.FieldNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.FieldNode; +import org.spongepowered.asm.util.Bytecode; /** * Accessor generator for field accessors @@ -43,16 +43,11 @@ public abstract class AccessorGeneratorField extends AccessorGenerator { */ protected final Type targetType; - /** - * True for instance field, false for static field - */ - protected final boolean isInstanceField; - public AccessorGeneratorField(AccessorInfo info) { - super(info); + super(info, Bytecode.isStatic(info.getTargetField())); this.targetField = info.getTargetField(); this.targetType = info.getTargetFieldType(); - this.isInstanceField = (this.targetField.access & Opcodes.ACC_STATIC) == 0; + this.checkModifiers(); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java index da48ae67..b34a592e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldGetter.java @@ -24,11 +24,11 @@ */ package org.spongepowered.asm.mixin.gen; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; /** * Generator for instance field getters @@ -45,10 +45,10 @@ public class AccessorGeneratorFieldGetter extends AccessorGeneratorField { @Override public MethodNode generate() { MethodNode method = this.createMethod(this.targetType.getSize(), this.targetType.getSize()); - if (this.isInstanceField) { + if (!this.targetIsStatic) { method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); } - int opcode = this.isInstanceField ? Opcodes.GETFIELD : Opcodes.GETSTATIC; + int opcode = this.targetIsStatic ? Opcodes.GETSTATIC : Opcodes.GETFIELD; method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc)); method.instructions.add(new InsnNode(this.targetType.getOpcode(Opcodes.IRETURN))); return method; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java index 012457f8..9ba3cce5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java @@ -24,11 +24,11 @@ */ package org.spongepowered.asm.mixin.gen; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; /** * Generator for field setters @@ -44,15 +44,15 @@ public class AccessorGeneratorFieldSetter extends AccessorGeneratorField { */ @Override public MethodNode generate() { - int stackSpace = this.isInstanceField ? 1 : 0; + int stackSpace = this.targetIsStatic ? 0 : 1; // Stack space for "this" int maxLocals = stackSpace + this.targetType.getSize(); int maxStack = stackSpace + this.targetType.getSize(); MethodNode method = this.createMethod(maxLocals, maxStack); - if (this.isInstanceField) { + if (!this.targetIsStatic) { method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); } method.instructions.add(new VarInsnNode(this.targetType.getOpcode(Opcodes.ILOAD), stackSpace)); - int opcode = this.isInstanceField ? Opcodes.PUTFIELD : Opcodes.PUTSTATIC; + int opcode = this.targetIsStatic ? Opcodes.PUTSTATIC : Opcodes.PUTFIELD; method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc)); method.instructions.add(new InsnNode(Opcodes.RETURN)); return method; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java index 6a6927e1..9617f29b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorMethodProxy.java @@ -24,12 +24,12 @@ */ package org.spongepowered.asm.mixin.gen; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.util.Bytecode; /** @@ -40,41 +40,43 @@ public class AccessorGeneratorMethodProxy extends AccessorGenerator { /** * The target field, identified by the accessor info */ - private final MethodNode targetMethod; + protected final MethodNode targetMethod; /** * Accessor method argument types (raw, from method) */ - private final Type[] argTypes; + protected final Type[] argTypes; /** * Accessor method return type (raw, from method) */ - private final Type returnType; - - /** - * True for instance method, false for static method - */ - private final boolean isInstanceMethod; + protected final Type returnType; public AccessorGeneratorMethodProxy(AccessorInfo info) { - super(info); + super(info, Bytecode.isStatic(info.getTargetMethod())); + this.targetMethod = info.getTargetMethod(); + this.argTypes = info.getArgTypes(); + this.returnType = info.getReturnType(); + this.checkModifiers(); + } + + protected AccessorGeneratorMethodProxy(AccessorInfo info, boolean isStatic) { + super(info, isStatic); this.targetMethod = info.getTargetMethod(); this.argTypes = info.getArgTypes(); this.returnType = info.getReturnType(); - this.isInstanceMethod = !Bytecode.hasFlag(this.targetMethod, Opcodes.ACC_STATIC); } @Override public MethodNode generate() { - int size = Bytecode.getArgsSize(this.argTypes) + this.returnType.getSize() + (this.isInstanceMethod ? 1 : 0); + int size = Bytecode.getArgsSize(this.argTypes) + this.returnType.getSize() + (this.targetIsStatic ? 0 : 1); MethodNode method = this.createMethod(size, size); - if (this.isInstanceMethod) { + if (!this.targetIsStatic) { method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); } - Bytecode.loadArgs(this.argTypes, method.instructions, this.isInstanceMethod ? 1 : 0); + Bytecode.loadArgs(this.argTypes, method.instructions, this.targetIsStatic ? 0 : 1); boolean isPrivate = Bytecode.hasFlag(this.targetMethod, Opcodes.ACC_PRIVATE); - int opcode = this.isInstanceMethod ? (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL) : Opcodes.INVOKESTATIC; + int opcode = this.targetIsStatic ? (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL) : Opcodes.INVOKESTATIC; method.instructions.add(new MethodInsnNode(opcode, this.info.getClassNode().name, this.targetMethod.name, this.targetMethod.desc, false)); method.instructions.add(new InsnNode(this.returnType.getOpcode(Opcodes.IRETURN))); return method; diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java new file mode 100644 index 00000000..1c928134 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java @@ -0,0 +1,67 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.gen; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Constants; + +/** + * Generator for factory methods (constructor invokers) + */ +public class AccessorGeneratorObjectFactory extends AccessorGeneratorMethodProxy { + + public AccessorGeneratorObjectFactory(AccessorInfo info) { + super(info, true); + if (!info.isStatic()) { + throw new InvalidInjectionException(info.getContext(), String.format("%s is invalid. Factory method must be static.", this.info)); + } + } + + @Override + public MethodNode generate() { + int returnSize = this.returnType.getSize(); + // size includes return size x2 since we immediately DUP the value to invoke the ctor on it + int size = Bytecode.getArgsSize(this.argTypes) + (returnSize * 2); + MethodNode method = this.createMethod(size, size); + + String className = this.info.getClassNode().name; + method.instructions.add(new TypeInsnNode(Opcodes.NEW, className)); + method.instructions.add(new InsnNode(returnSize == 1 ? Opcodes.DUP : Opcodes.DUP2)); + Bytecode.loadArgs(this.argTypes, method.instructions, 0); + method.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, className, Constants.CTOR, this.targetMethod.desc, false)); + method.instructions.add(new InsnNode(Opcodes.ARETURN)); + + assert 1 == 3; + + return method; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index 5261c32b..f15aa07d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -26,24 +26,31 @@ package org.spongepowered.asm.mixin.gen; import java.lang.annotation.Annotation; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.asm.ElementNode; +import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; @@ -86,6 +93,16 @@ public class AccessorInfo extends SpecialMethodInfo { AccessorGenerator getGenerator(AccessorInfo info) { return new AccessorGeneratorMethodProxy(info); } + }, + + /** + * An invoker (proxy) method + */ + OBJECT_FACTORY(ImmutableSet.of("new", "create")) { + @Override + AccessorGenerator getGenerator(AccessorInfo info) { + return new AccessorGeneratorObjectFactory(info); + } }; private final Set expectedPrefixes; @@ -112,17 +129,111 @@ public class AccessorInfo extends SpecialMethodInfo { * @return string representation of expected prefixes for this accessor * type */ - public String getExpectedPrefixes() { - return this.expectedPrefixes.toString(); + public Set getExpectedPrefixes() { + return Collections.unmodifiableSet(this.expectedPrefixes); } abstract AccessorGenerator getGenerator(AccessorInfo info); + } /** - * Pattern for matching accessor names (for inflector) + * Accessor Name struct */ - protected static final Pattern PATTERN_ACCESSOR = Pattern.compile("^(get|set|is|invoke|call)(([A-Z])(.*?))(_\\$md.*)?$"); + public static final class AccessorName { + + /** + * Pattern for matching accessor names (for inflector) + */ + private static final Pattern PATTERN = Pattern.compile("^(" + AccessorName.getPrefixList() + ")(([A-Z])(.*?))(_\\$md.*)?$"); + + /** + * Name of the accessor method + */ + public final String methodName; + + /** + * Accessor prefix + */ + public final String prefix; + + /** + * Accessor name part + */ + public final String name; + + private AccessorName(String methodName, String prefix, String name) { + this.methodName = methodName; + this.prefix = prefix; + this.name = name; + } + + @Override + public String toString() { + return super.toString(); + } + + /** + * Get an accessor name from the supplied string. If the string matches + * the accessor name regex, split the string into the relevant parts + * + * @param methodName Name of the accessor method + * @return Parsed AccessorName struct or null if the name is not a valid + * accessor name + */ + public static AccessorName of(String methodName) { + return AccessorName.of(methodName, true); + } + + /** + * Get an accessor name from the supplied string. If the string matches + * the accessor name regex, split the string into the relevant parts + * + * @param methodName Name of the accessor method + * @param toMemberCase True if the first character of the name should be + * conditionally converted to lowercase. If the name is all + * uppercase (eg. if the NAME_IS_A_CONSTANT) the first character + * will not be lowercased, regardless of the state of this argument + * @return Parsed AccessorName struct or null if the name is not a valid + * accessor name + */ + public static AccessorName of(String methodName, boolean toMemberCase) { + Matcher nameMatcher = AccessorName.PATTERN.matcher(methodName); + if (nameMatcher.matches()) { + String prefix = nameMatcher.group(1); + String namePart = nameMatcher.group(2); + String firstChar = nameMatcher.group(3); + String remainder = nameMatcher.group(4); + boolean nameIsUpperCase = AccessorName.isUpperCase(Locale.ROOT, namePart); + // If the entire name is upper case, do not lowercase the first char + String name = String.format("%s%s", AccessorName.toLowerCaseIf(Locale.ROOT, firstChar, toMemberCase && !nameIsUpperCase), remainder); + return new AccessorName(methodName, prefix, name); + } + return null; + } + + private static boolean isUpperCase(Locale locale, String string) { + return string.toUpperCase(locale).equals(string); + } + + private static String toLowerCaseIf(Locale locale, String string, boolean condition) { + return condition ? string.toLowerCase(locale) : string; + } + + private static String getPrefixList() { + List prefixes = new ArrayList(); + for (AccessorType type : AccessorType.values()) { + prefixes.addAll(type.getExpectedPrefixes()); + } + return Joiner.on('|').join(prefixes); + } + + } + + /** + * Annotation class + */ + protected final Class annotationClass; /** * Accessor method argument types (raw, from method) @@ -134,6 +245,16 @@ public class AccessorInfo extends SpecialMethodInfo { */ protected final Type returnType; + /** + * Accessor method staticness + */ + protected final boolean isStatic; + + /** + * Name specified in the attached annotation, can be null + */ + protected final String specifiedName; + /** * Type of accessor to generate, computed based on the signature of the * target method. @@ -149,7 +270,7 @@ public class AccessorInfo extends SpecialMethodInfo { * Computed information about the target field or method, name and * descriptor */ - protected final MemberInfo target; + protected final ITargetSelector target; /** * For accessors, stores the discovered target field @@ -167,8 +288,11 @@ public class AccessorInfo extends SpecialMethodInfo { protected AccessorInfo(MixinTargetContext mixin, MethodNode method, Class annotationClass) { super(mixin, method, Annotations.getVisible(method, annotationClass)); + this.annotationClass = annotationClass; this.argTypes = Type.getArgumentTypes(method.desc); this.returnType = Type.getReturnType(method.desc); + this.isStatic = Bytecode.isStatic(method); + this.specifiedName = Annotations.getValue(this.annotation); this.type = this.initType(); this.targetFieldType = this.initTargetFieldType(); this.target = this.initTarget(); @@ -200,22 +324,22 @@ public class AccessorInfo extends SpecialMethodInfo { } } - protected MemberInfo initTarget() { - MemberInfo target = new MemberInfo(this.getTargetName(), null, this.targetFieldType.getDescriptor()); + protected ITargetSelector initTarget() { + MemberInfo target = new MemberInfo(this.getTargetName(this.specifiedName), null, this.targetFieldType.getDescriptor()); this.annotation.visit("target", target.toString()); return target; } - protected String getTargetName() { - String name = Annotations.getValue(this.annotation); + protected String getTargetName(String name) { if (Strings.isNullOrEmpty(name)) { String inflectedTarget = this.inflectTarget(); if (inflectedTarget == null) { - throw new InvalidAccessorException(this.mixin, "Failed to inflect target name for " + this + ", supported prefixes: [get, set, is]"); + throw new InvalidAccessorException(this.mixin, String.format("Failed to inflect target name for %s, supported prefixes: %s", + this, this.type.getExpectedPrefixes())); } return inflectedTarget; } - return MemberInfo.parse(name, this.mixin).name; + return TargetSelector.parseName(name, this.mixin); } /** @@ -235,31 +359,45 @@ public class AccessorInfo extends SpecialMethodInfo { * named getFoo to be inflected to a target named foo for * example. * - * @param accessorName Name of the accessor method - * @param accessorType Type of accessor being processed, this is calculated + * @param name Name of the accessor method + * @param type Type of accessor being processed, this is calculated * from the method signature (void methods being setters, * methods with return types being getters) - * @param accessorDescription description of the accessor to include in + * @param description description of the accessor to include in * error messages * @param context Mixin context * @param verbose Emit warnings when accessor prefix doesn't match type * @return inflected target member name or null if name cannot be * inflected */ - public static String inflectTarget(String accessorName, AccessorType accessorType, String accessorDescription, - IMixinContext context, boolean verbose) { - Matcher nameMatcher = AccessorInfo.PATTERN_ACCESSOR.matcher(accessorName); - if (nameMatcher.matches()) { - String prefix = nameMatcher.group(1); - String firstChar = nameMatcher.group(3); - String remainder = nameMatcher.group(4); - // If the entire name is upper case, do not lowercase the first char - String name = String.format("%s%s", AccessorInfo.toLowerCase(firstChar, !AccessorInfo.isUpperCase(remainder)), remainder); - if (!accessorType.isExpectedPrefix(prefix) && verbose) { - LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", accessorDescription, prefix, - accessorType.getExpectedPrefixes()); + public static String inflectTarget(String name, AccessorType type, String description, IMixinContext context, boolean verbose) { + return AccessorInfo.inflectTarget(AccessorName.of(name), type, description, context, verbose); + } + + /** + * Uses the name of an accessor method and the accessor type to try and + * inflect the name of the target field or method. This allows a method + * named getFoo to be inflected to a target named foo for + * example. + * + * @param name Name of the accessor method + * @param type Type of accessor being processed, this is calculated + * from the method signature (void methods being setters, + * methods with return types being getters) + * @param description description of the accessor to include in + * error messages + * @param context Mixin context + * @param verbose Emit warnings when accessor prefix doesn't match type + * @return inflected target member name or null if name cannot be + * inflected + */ + public static String inflectTarget(AccessorName name, AccessorType type, String description, IMixinContext context, boolean verbose) { + if (name != null) { + if (!type.isExpectedPrefix(name.prefix) && verbose) { + LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", description, name.prefix, + type.getExpectedPrefixes()); } - return MemberInfo.parse(name, context).name; + return TargetSelector.parseName(name.name, context); } return null; } @@ -267,7 +405,7 @@ public class AccessorInfo extends SpecialMethodInfo { /** * Get the inflected/specified target member for this accessor */ - public final MemberInfo getTarget() { + public final ITargetSelector getTarget() { return this.target; } @@ -305,10 +443,18 @@ public class AccessorInfo extends SpecialMethodInfo { public final Type[] getArgTypes() { return this.argTypes; } + + /** + * Get whether the accessor itself is static + */ + public boolean isStatic() { + return this.isStatic; + } @Override public String toString() { - return String.format("%s->@%s[%s]::%s%s", this.mixin.toString(), Bytecode.getSimpleName(this.annotation), this.type.toString(), + String typeString = this.type != null ? this.type.toString() : "UNPARSED_ACCESSOR"; + return String.format("%s->@%s[%s]::%s%s", this.mixin, Bytecode.getSimpleName(this.annotation), typeString, this.method.name, this.method.desc); } @@ -330,12 +476,12 @@ public class AccessorInfo extends SpecialMethodInfo { */ public MethodNode generate() { MethodNode generatedAccessor = this.type.getGenerator(this).generate(); - Bytecode.mergeAnnotations(this.method, generatedAccessor); + Annotations.merge(this.method, generatedAccessor); return generatedAccessor; } private FieldNode findTargetField() { - return this.findTarget(this.classNode.fields); + return this.findTarget(ElementNode.fieldList(this.classNode)); } /** @@ -346,49 +492,14 @@ public class AccessorInfo extends SpecialMethodInfo { * @param node type * @return best match */ - protected TNode findTarget(List nodes) { - TNode exactMatch = null; - List candidates = new ArrayList(); - - for (TNode node : nodes) { - String desc = AccessorInfo.getNodeDesc(node); - if (desc == null || !desc.equals(this.target.desc)) { - continue; - } - - String name = AccessorInfo.getNodeName(node); - if (name != null) { - if (name.equals(this.target.name)) { - exactMatch = node; - } - if (name.equalsIgnoreCase(this.target.name)) { - candidates.add(node); - } - } - } - - if (exactMatch != null) { - if (candidates.size() > 1) { - LogManager.getLogger("mixin").debug("{} found an exact match for {} but other candidates were found!", this, this.target); - } - return exactMatch; - } - - if (candidates.size() == 1) { - return candidates.get(0); - } - - String number = candidates.size() == 0 ? "No" : "Multiple"; - throw new InvalidAccessorException(this, number + " candidates were found matching " + this.target + " in " + this.classNode.name - + " for " + this); - } - - private static String getNodeDesc(TNode node) { - return (node instanceof MethodNode) ? ((MethodNode)node).desc : ((node instanceof FieldNode) ? ((FieldNode)node).desc : null); - } + protected TNode findTarget(List> nodes) { + Result result = TargetSelector.run(this.target.configure("orphan"), nodes); - private static String getNodeName(TNode node) { - return (node instanceof MethodNode) ? ((MethodNode)node).name : ((node instanceof FieldNode) ? ((FieldNode)node).name : null); + try { + return result.getSingleResult(true); + } catch (IllegalStateException ex) { + throw new InvalidAccessorException(this, ex.getMessage() + " matching " + this.target + " in " + this.classNode.name + " for " + this); + } } /** @@ -409,12 +520,4 @@ public class AccessorInfo extends SpecialMethodInfo { throw new InvalidAccessorException(mixin, "Could not parse accessor for unknown type " + type.getName()); } - private static String toLowerCase(String string, boolean condition) { - return condition ? string.toLowerCase() : string; - } - - private static boolean isUpperCase(String string) { - return string.toUpperCase().equals(string); - } - } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java b/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java index 489815f0..6fad5f5c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/Invoker.java @@ -36,6 +36,12 @@ import org.spongepowered.asm.mixin.Shadow; * a mixin, the method. The annotated method must be abstract and the * signature of the method must match the target method precisely. * + *

The target method for an accessor can be specified as part of the + * decorated method name (eg. callFoo to invoke a target method named + * foo()) or specified in the annotation value. Invokers for + * constructors can be created by specifying <init> in the + * annotation or the fully-qualified class name.

+ * *

Invokers provide a simple way of gaining access to internal class members * in a target class without needing to resort to access transformers, and * without the usual need to {@link Shadow} a target method. This can both @@ -66,7 +72,8 @@ public @interface Invoker { * *

However sometimes it maye be desirable to name an accessor method * differently to the target method. In this case you may specify the method - * using its name.

+ * using its name. Use <init> or the fully qualified name of + * the target class to invoke a constructor.

* * @return name for the target method, or empty string to inflect using the * annotated method name diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java index bc418bf9..0671112d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -24,42 +24,98 @@ */ package org.spongepowered.asm.mixin.gen; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.asm.ElementNode; /** * Information about an invoker */ -public class InvokerInfo extends AccessorInfo { - +class InvokerInfo extends AccessorInfo { + public InvokerInfo(MixinTargetContext mixin, MethodNode method) { super(mixin, method, Invoker.class); } @Override protected AccessorType initType() { + if (this.specifiedName != null) { + String mappedReference = this.mixin.getReferenceMapper().remap(this.mixin.getClassRef(), this.specifiedName); + return this.initType(mappedReference.replace('.', '/'), this.mixin.getTargetClassRef()); + } + + AccessorName accessorName = AccessorName.of(this.method.name, false); + if (accessorName != null) { + for (String prefix : AccessorType.OBJECT_FACTORY.getExpectedPrefixes()) { + if (prefix.equals(accessorName.prefix)) { + return this.initType(accessorName.name, this.mixin.getTargetClassInfo().getSimpleName()); + } + } + } + return AccessorType.METHOD_PROXY; } + private AccessorType initType(String targetName, String targetClassName) { + if (Constants.CTOR.equals(targetName) || targetClassName.equals(targetName)) { + if (!this.returnType.equals(this.mixin.getTargetClassInfo().getType())) { + throw new InvalidAccessorException(this.mixin, + String.format("%s appears to have an invalid return type. %s requires matching return type. Found %s expected %s", + this, AccessorType.OBJECT_FACTORY, Bytecode.getSimpleName(this.returnType), this.mixin.getTargetClassInfo().getSimpleName())); + } + if (!this.isStatic) { + throw new InvalidAccessorException(this.mixin, String.format("%s for %s must be static", this, AccessorType.OBJECT_FACTORY, + Bytecode.getSimpleName(this.returnType))); + } + + return AccessorType.OBJECT_FACTORY; + } + return AccessorType.METHOD_PROXY; + } + @Override protected Type initTargetFieldType() { return null; } @Override - protected MemberInfo initTarget() { - return new MemberInfo(this.getTargetName(), null, this.method.desc); + protected ITargetSelector initTarget() { + if (this.type == AccessorType.OBJECT_FACTORY) { + return new MemberInfo(Constants.CTOR, null, Bytecode.changeDescriptorReturnType(this.method.desc, "V")); + } + + return new MemberInfo(this.getTargetName(this.specifiedName), null, this.method.desc); } - + @Override public void locate() { this.targetMethod = this.findTargetMethod(); } private MethodNode findTargetMethod() { - return this.findTarget(this.classNode.methods); + Result result = TargetSelector.run(this.target.configure("orphan"), ElementNode.methodList(this.classNode)); + + try { + return result.getSingleResult(true); + } catch (IllegalStateException ex) { + String message = ex.getMessage() + " matching " + this.target + " in " + this.classNode.name + " for " + this; + if (this.type == AccessorType.METHOD_PROXY && this.specifiedName != null && this.target instanceof ITargetSelectorByName) { + String name = ((ITargetSelectorByName)this.target).getName(); + if (name != null && (name.contains(".") || name.contains("/"))) { + throw new InvalidAccessorException(this, "Invalid factory invoker failed to match the target class. " + message); + } + } + throw new InvalidAccessorException(this, message); + } } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java index 47806e11..1e502fb9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java @@ -200,4 +200,5 @@ public @interface At { * obfuscation mappings for this annotation */ public boolean remap() default true; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java index 7c2daec8..c8764dab 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java @@ -27,7 +27,7 @@ package org.spongepowered.asm.mixin.injection; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.spongepowered.asm.lib.Opcodes; +import org.objectweb.asm.Opcodes; /** * Annotation for specifying the injection point for an {@link ModifyConstant} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java index 7aca7718..e1dd1b7a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java @@ -24,8 +24,8 @@ */ package org.spongepowered.asm.mixin.injection; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.refmap.IMixinContext; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java index 16c8f056..3e11f64b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java @@ -32,6 +32,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.LocalCapture; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -56,8 +57,8 @@ public @interface Inject { /** * String representation of one or more - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo - * MemberInfo} which identify the target methods. + * {@link ITargetSelector target selectors} which identify the target + * methods. * * @return target method(s) for this injector */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index a0a91b43..08fa108b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -39,12 +39,13 @@ import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; import org.spongepowered.asm.mixin.injection.points.*; @@ -754,4 +755,5 @@ public abstract class InjectionPoint { InjectionPoint.types.put(code.value(), type); } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java index 4e47d099..645a60bf 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArg.java @@ -30,6 +30,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -74,8 +75,8 @@ public @interface ModifyArg { /** * String representation of one or more - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo - * MemberInfo} which identify the target methods. + * {@link ITargetSelector target selectors} which identify the target + * methods. * * @return target method(s) for this injector */ @@ -92,7 +93,7 @@ public @interface ModifyArg { /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only - * return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances + * return {@link org.objectweb.asm.tree.MethodInsnNode} instances * and an exception will be thrown if this is not the case. * * @return {@link At} which identifies the target method invocation diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java index 316e3a05..69018c32 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyArgs.java @@ -31,6 +31,7 @@ import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -79,8 +80,8 @@ public @interface ModifyArgs { /** * String representation of one or more - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo - * MemberInfo} which identify the target methods. + * {@link ITargetSelector target selectors} which identify the target + * methods. * * @return target method(s) for this injector */ @@ -97,7 +98,7 @@ public @interface ModifyArgs { /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only - * return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances + * return {@link org.objectweb.asm.tree.MethodInsnNode} instances * and an exception will be thrown if this is not the case. * * @return {@link At} which identifies the target method invocation diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java index 06b87f8d..6e7ba332 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyConstant.java @@ -30,6 +30,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -61,8 +62,8 @@ public @interface ModifyConstant { /** * String representation of one or more - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo - * MemberInfo} which identify the target methods. + * {@link ITargetSelector target selectors} which identify the target + * methods. * * @return target method(s) for this injector */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index 65388982..0e055a30 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -30,6 +30,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -69,8 +70,8 @@ public @interface ModifyVariable { /** * String representation of one or more - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo - * MemberInfo} which identify the target methods. + * {@link ITargetSelector target selectors} which identify the target + * methods. * * @return target method(s) for this injector */ @@ -87,7 +88,7 @@ public @interface ModifyVariable { /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only - * return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} instances + * return {@link org.objectweb.asm.tree.MethodInsnNode} instances * and an exception will be thrown if this is not the case. * * @return {@link At} which identifies the target method invocation diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 5cb286eb..0821599d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -31,6 +31,7 @@ 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.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.ConstraintParser.Constraint; @@ -228,8 +229,8 @@ public @interface Redirect { /** * String representation of one or more - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo - * MemberInfo} which identify the target methods. + * {@link ITargetSelector target selectors} which identify the target + * methods. * * @return target method(s) for this injector */ @@ -246,7 +247,7 @@ public @interface Redirect { /** * An {@link At} annotation which describes the {@link InjectionPoint} in * the target method. The specified {@link InjectionPoint} must only - * return {@link org.spongepowered.asm.lib.tree.MethodInsnNode} and an + * return {@link org.objectweb.asm.tree.MethodInsnNode} and an * exception will be thrown if this is not the case. * * @return {@link At} which identifies the target method invocation diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java index 72981492..9bae4579 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfo.java @@ -24,7 +24,7 @@ */ package org.spongepowered.asm.mixin.injection.callback; -import org.spongepowered.asm.lib.Type; +import org.objectweb.asm.Type; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.util.Constants; @@ -128,14 +128,14 @@ public class CallbackInfo implements Cancellable { } if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { - return String.format("(%sZ%s)V", Constants.STRING, Constants.OBJECT); + return String.format("(%sZ%s)V", Constants.STRING_DESC, Constants.OBJECT_DESC); } - return String.format("(%sZ%s)V", Constants.STRING, returnType.getDescriptor()); + return String.format("(%sZ%s)V", Constants.STRING_DESC, returnType.getDescriptor()); } static String getConstructorDescriptor() { - return String.format("(%sZ)V", Constants.STRING); + return String.format("(%sZ)V", Constants.STRING_DESC); } static String getIsCancelledMethodName() { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java index 588baf42..7325c611 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInfoReturnable.java @@ -24,7 +24,7 @@ */ package org.spongepowered.asm.mixin.injection.callback; -import org.spongepowered.asm.lib.Type; +import org.objectweb.asm.Type; import org.spongepowered.asm.util.Constants; /** @@ -134,7 +134,7 @@ public class CallbackInfoReturnable extends CallbackInfo { static String getReturnDescriptor(Type returnType) { if (returnType.getSort() == Type.OBJECT || returnType.getSort() == Type.ARRAY) { - return String.format("()%s", Constants.OBJECT); + return String.format("()%s", Constants.OBJECT_DESC); } return String.format("()%s", returnType.getDescriptor()); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index f8bb37b8..8db18ef5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -30,9 +30,9 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.*; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.*; import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.Surrogate; @@ -370,7 +370,7 @@ public class CallbackInjector extends Injector { /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.code.Injector#addTargetNode( * org.spongepowered.asm.mixin.injection.struct.Target, java.util.List, - * org.spongepowered.asm.lib.tree.AbstractInsnNode, java.util.Set) + * org.objectweb.asm.tree.AbstractInsnNode, java.util.Set) */ @Override protected void addTargetNode(Target target, List myNodes, AbstractInsnNode node, Set nominators) { @@ -624,7 +624,8 @@ public class CallbackInjector extends Injector { return; } - callback.add(new InsnNode(Opcodes.DUP)); + int dupCode = callback.target.returnType.getSize() == 1 ? Opcodes.DUP : Opcodes.DUP2; + callback.add(new InsnNode(dupCode)); callback.add(new VarInsnNode(callback.target.returnType.getOpcode(Opcodes.ISTORE), callback.marshalVar())); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 95537fb7..f8f69cf1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -35,16 +35,16 @@ import java.util.TreeMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.LdcInsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.TypeInsnNode; +import org.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.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; @@ -55,6 +55,7 @@ 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.TypeLookup; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; @@ -154,7 +155,7 @@ public abstract class Injector { this.methodArgs = Type.getArgumentTypes(this.methodNode.desc); this.returnType = Type.getReturnType(this.methodNode.desc); - this.isStatic = Bytecode.methodIsStatic(this.methodNode); + this.isStatic = Bytecode.isStatic(this.methodNode); } @Override @@ -376,7 +377,7 @@ public abstract class Injector { */ public static boolean canCoerce(Type from, Type to) { if (from.getSort() == Type.OBJECT && to.getSort() == Type.OBJECT) { - return Injector.canCoerce(ClassInfo.forType(from), ClassInfo.forType(to)); + return Injector.canCoerce(ClassInfo.forType(from, TypeLookup.ELEMENT_TYPE), ClassInfo.forType(to, TypeLookup.ELEMENT_TYPE)); } return Injector.canCoerce(from.getDescriptor(), to.getDescriptor()); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java index 3d45dbf1..23c053c7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/InjectorTarget.java @@ -27,9 +27,9 @@ package org.spongepowered.asm.mixin.injection.code; import java.util.HashMap; import java.util.Map; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfig; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.struct.Target; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java index 04fd617a..85ac3af6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java @@ -31,10 +31,10 @@ import java.util.NoSuchElementException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.InjectionPoint; @@ -54,7 +54,7 @@ public final class MethodSlice { /** * A read-only wrapper for an {@link InsnList} which only allows the segment - * identified by {@link #start} and {@link #end} to be accessed. In essence + * identified by start and end to be accessed. In essence * this class provides a view of the underlying InsnList. */ static final class InsnListSlice extends ReadOnlyInsnList { @@ -255,7 +255,7 @@ public final class MethodSlice { /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.code.ReadOnlyInsnList - * #contains(org.spongepowered.asm.lib.tree.AbstractInsnNode) + * #contains(org.objectweb.asm.tree.AbstractInsnNode) */ @Override public boolean contains(AbstractInsnNode insn) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java index a8f3792a..3681ed5a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlices.java @@ -27,7 +27,7 @@ package org.spongepowered.asm.mixin.injection.code; import java.util.HashMap; import java.util.Map; -import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.objectweb.asm.tree.AnnotationNode; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException; import org.spongepowered.asm.util.Annotations; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java index 8f595b9c..528ebac6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/ReadOnlyInsnList.java @@ -26,8 +26,8 @@ package org.spongepowered.asm.mixin.injection.code; import java.util.ListIterator; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; /** * Read-only wrapper for InsnList, defensively passed to InjectionPoint diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java index 8e300726..be64c0f2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java @@ -26,12 +26,12 @@ package org.spongepowered.asm.mixin.injection.invoke; import java.util.List; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java index c404ba84..6ea389f0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgInjector.java @@ -27,9 +27,9 @@ package org.spongepowered.asm.mixin.injection.invoke; import java.util.Arrays; import java.util.List; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java index 95e196d6..bd20fe66 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java @@ -24,12 +24,12 @@ */ package org.spongepowered.asm.mixin.injection.invoke; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; @@ -83,7 +83,7 @@ public class ModifyArgsInjector extends InvokeInjector { + targetMethod.name + targetMethod.desc + " with no arguments!"); } - String clArgs = this.argsClassGenerator.getClassRef(targetMethod.desc); + String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getContext().getMixin()).getName(); boolean withArgs = this.verifyTarget(target); InsnList insns = new InsnList(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java index 61ed3796..270b2090 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -25,15 +25,15 @@ package org.spongepowered.asm.mixin.injection.invoke; import org.apache.logging.log4j.Level; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.JumpInsnNode; -import org.spongepowered.asm.lib.tree.LocalVariableNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +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.VarInsnNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.util.InsnFinder; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index 66c7a4d4..01934366 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -29,9 +29,9 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.*; +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; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java index 1af10490..f75ca478 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/arg/ArgsClassGenerator.java @@ -27,25 +27,28 @@ package org.spongepowered.asm.mixin.injection.invoke.arg; import java.util.HashMap; import java.util.Map; -import org.spongepowered.asm.lib.ClassVisitor; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.Label; -import org.spongepowered.asm.lib.MethodVisitor; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.util.CheckClassAdapter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.util.CheckClassAdapter; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.injection.ModifyArgs; +import org.spongepowered.asm.mixin.transformer.SyntheticClassInfo; import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator; +import org.spongepowered.asm.service.ISyntheticClassInfo; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.IConsumer; import org.spongepowered.asm.util.SignaturePrinter; import org.spongepowered.asm.util.asm.MethodVisitorEx; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; - /** * Class generator which creates subclasses of {@link Args} to be used by the * {@link ModifyArgs} injector. The subclasses contain getter and setter logic @@ -82,6 +85,43 @@ public final class ArgsClassGenerator implements IClassGenerator { private static final String ACE = "org/spongepowered/asm/mixin/injection/invoke/arg/ArgumentCountException"; private static final String ACE_CTOR_DESC = "(IILjava/lang/String;)V"; + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Synthetic class info for args class + */ + class ArgsClassInfo extends SyntheticClassInfo { + + final String desc; + + final Type[] args; + + int loaded = 0; + + ArgsClassInfo(IMixinInfo mixin, String name, String desc) { + super(mixin, name); + this.desc = desc; + this.args = Type.getArgumentTypes(desc); + } + + @Override + public boolean isLoaded() { + return this.loaded > 0; + } + + String getSignature() { + return new SignaturePrinter("", null, this.args).setFullyQualified(true).getFormattedArgs(); + } + } + + /** + * Synthetic class registry + */ + private final IConsumer registry; /** * The next subclass number, classes generated in sequence eg. @@ -90,18 +130,24 @@ public final class ArgsClassGenerator implements IClassGenerator { private int nextIndex = 1; /** - * Map of descriptors to generated class names + * Map of descriptors to generated class infos */ - private final BiMap classNames = HashBiMap.create(); + private final Map descToClass = new HashMap(); /** - * Generated bytes. Technically a generator shouldn't have to return class - * bytes for a class more than once, but this saves the class being - * regenerated if anything causes a second invocation of {@link #generate} - * for the same class + * Map of class names to generated class infos */ - private final Map classBytes = new HashMap(); + private final Map nameToClass = new HashMap(); + /** + * Ctor + * + * @param registry sythetic class registry + */ + public ArgsClassGenerator(IConsumer registry) { + this.registry = registry; + } + /** * Get (or generate) the class name for the specified descriptor. The class * will not be generated until it is used. Calling this method simply @@ -109,89 +155,59 @@ public final class ArgsClassGenerator implements IClassGenerator { * * @param desc Descriptor of the target method, the return type is * ignored for the purposes of generating Args subclasses + * @param mixin Mixin which requires the class. Only the first mixin to + * request a class will be registered against it but this is for + * debugging only anyway * @return name of the Args subclass to use */ - public String getClassName(String desc) { + public ISyntheticClassInfo getArgsClass(String desc, IMixinInfo mixin) { String voidDesc = Bytecode.changeDescriptorReturnType(desc, "V"); - String name = this.classNames.get(voidDesc); - if (name == null) { - name = String.format("%s%d", ArgsClassGenerator.CLASS_NAME_BASE, this.nextIndex++); - this.classNames.put(voidDesc, name); + ArgsClassInfo info = this.descToClass.get(voidDesc); + if (info == null) { + String name = String.format("%s%d", ArgsClassGenerator.CLASS_NAME_BASE, this.nextIndex++); + ArgsClassGenerator.logger.debug("ArgsClassGenerator assigning {} for descriptor {}", name, voidDesc); + info = new ArgsClassInfo(mixin, name, voidDesc); + this.descToClass.put(voidDesc, info); + this.nameToClass.put(name, info); + this.registry.accept(info); } - return name; - } - - /** - * Get (or generate) the class name for the specified descriptor in internal - * format (reference). The class will not be generated until it is used. - * Calling this method simply allocates a name for the specified descriptor. - * - * @param desc Descriptor of the target method, with the return - * type changed to void (V) - * @return reference of the Args subclass to use - */ - public String getClassRef(String desc) { - return this.getClassName(desc).replace('.', '/'); + return info; } /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.transformer.IClassGenerator#generate - * (java.lang.String) + * @see org.spongepowered.asm.mixin.transformer.ext.IClassGenerator + * #generate(java.lang.String, org.objectweb.asm.tree.ClassNode) */ @Override - public byte[] generate(String name) { - return this.getBytes(name); - } - - /** - * Fetch or generate class bytes for the specified class name. Returns null - * if this generator does not have bytes for the specified class. - * - * @param name Class name - * @return class bytes or null - */ - public byte[] getBytes(String name) { - byte[] bytes = this.classBytes.get(name); - if (bytes == null) { - String desc = this.classNames.inverse().get(name); - if (desc == null) { - return null; - } - bytes = this.generateClass(name, desc); - this.classBytes.put(name, bytes); + public boolean generate(String name, ClassNode classNode) { + ArgsClassInfo info = this.nameToClass.get(name); + if (info == null) { + return false; } - return bytes; - } - - /** - * Generate an {@link Args} subclass - * - * @param name Class name to generate - * @param desc Argument descriptor (return type ignored) - * @return generated class - */ - private byte[] generateClass(String name, String desc) { - String ref = name.replace('.', '/'); - Type[] args = Type.getArgumentTypes(desc); - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - ClassVisitor visitor = writer; + if (info.loaded > 0) { + ArgsClassGenerator.logger.debug("ArgsClassGenerator is re-generating {}, already did this {} times!", name, info.loaded); + } + + ClassVisitor visitor = classNode; if (MixinEnvironment.getCurrentEnvironment().getOption(Option.DEBUG_VERIFY)) { - visitor = new CheckClassAdapter(writer); + visitor = new CheckClassAdapter(classNode); } - visitor.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_SYNTHETIC, ref, null, ArgsClassGenerator.ARGS_REF, null); + visitor.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_SYNTHETIC, info.getName(), null, + ArgsClassGenerator.ARGS_REF, null); visitor.visitSource(name.substring(name.lastIndexOf('.') + 1) + ".java", null); - this.generateCtor(ref, desc, args, visitor); - this.generateToString(ref, desc, args, visitor); - this.generateFactory(ref, desc, args, visitor); - this.generateSetters(ref, desc, args, visitor); - this.generateGetters(ref, desc, args, visitor); + this.generateCtor(info, visitor); + this.generateToString(info, visitor); + this.generateFactory(info, visitor); + this.generateSetters(info, visitor); + this.generateGetters(info, visitor); visitor.visitEnd(); + info.loaded++; - return writer.toByteArray(); + return true; } /** @@ -203,7 +219,7 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateCtor(String ref, String desc, Type[] args, ClassVisitor writer) { + private void generateCtor(ArgsClassInfo info, ClassVisitor writer) { MethodVisitor ctor = writer.visitMethod(Opcodes.ACC_PRIVATE, Constants.CTOR, ArgsClassGenerator.CTOR_DESC, null, null); ctor.visitCode(); ctor.visitVarInsn(Opcodes.ALOAD, 0); @@ -222,10 +238,10 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateToString(String ref, String desc, Type[] args, ClassVisitor writer) { + private void generateToString(ArgsClassInfo info, ClassVisitor writer) { MethodVisitor toString = writer.visitMethod(Opcodes.ACC_PUBLIC, "toString", "()Ljava/lang/String;", null, null); toString.visitCode(); - toString.visitLdcInsn("Args" + ArgsClassGenerator.getSignature(args)); + toString.visitLdcInsn("Args" + info.getSignature()); toString.visitInsn(Opcodes.ARETURN); toString.visitMaxs(1, 1); toString.visitEnd(); @@ -242,8 +258,9 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateFactory(String ref, String desc, Type[] args, ClassVisitor writer) { - String factoryDesc = Bytecode.changeDescriptorReturnType(desc, "L" + ref + ";"); + private void generateFactory(ArgsClassInfo info, ClassVisitor writer) { + String ref = info.getName(); + String factoryDesc = Bytecode.changeDescriptorReturnType(info.desc, "L" + ref + ";"); MethodVisitorEx of = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "of", factoryDesc, null, null)); of.visitCode(); @@ -252,14 +269,14 @@ public final class ArgsClassGenerator implements IClassGenerator { of.visitInsn(Opcodes.DUP); // Create Object[] array to contain args - of.visitConstant((byte)args.length); + of.visitConstant((byte)info.args.length); of.visitTypeInsn(Opcodes.ANEWARRAY, ArgsClassGenerator.OBJECT); // Iterate over args and stuff them into the array - byte argIndex = 0; - for (Type arg : args) { + for (byte index = 0, argIndex = 0; index < info.args.length; index++) { + Type arg = info.args[index]; of.visitInsn(Opcodes.DUP); - of.visitConstant(argIndex); + of.visitConstant(index); of.visitVarInsn(arg.getOpcode(Opcodes.ILOAD), argIndex); ArgsClassGenerator.box(of, arg); of.visitInsn(Opcodes.AASTORE); @@ -272,7 +289,7 @@ public final class ArgsClassGenerator implements IClassGenerator { // Return the new object of.visitInsn(Opcodes.ARETURN); - of.visitMaxs(6, Bytecode.getArgsSize(args)); + of.visitMaxs(6, Bytecode.getArgsSize(info.args)); of.visitEnd(); } @@ -287,9 +304,9 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateGetters(String ref, String desc, Type[] args, ClassVisitor writer) { + private void generateGetters(ArgsClassInfo info, ClassVisitor writer) { byte argIndex = 0; - for (Type arg : args) { + for (Type arg : info.args) { String name = ArgsClassGenerator.GETTER_PREFIX + argIndex; String sig = "()" + arg.getDescriptor(); MethodVisitorEx get = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC, name, sig, null, null)); @@ -297,7 +314,7 @@ public final class ArgsClassGenerator implements IClassGenerator { // Read the value from the values field get.visitVarInsn(Opcodes.ALOAD, 0); - get.visitFieldInsn(Opcodes.GETFIELD, ref, ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); + get.visitFieldInsn(Opcodes.GETFIELD, info.getName(), ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); get.visitConstant(argIndex); get.visitInsn(Opcodes.AALOAD); @@ -322,9 +339,9 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateSetters(String ref, String desc, Type[] args, ClassVisitor writer) { - this.generateIndexedSetter(ref, desc, args, writer); - this.generateMultiSetter(ref, desc, args, writer); + private void generateSetters(ArgsClassInfo info, ClassVisitor writer) { + this.generateIndexedSetter(info, writer); + this.generateMultiSetter(info, writer); } /** @@ -338,23 +355,23 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateIndexedSetter(String ref, String desc, Type[] args, ClassVisitor writer) { + private void generateIndexedSetter(ArgsClassInfo info, ClassVisitor writer) { MethodVisitorEx set = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC, ArgsClassGenerator.SET, ArgsClassGenerator.SET_DESC, null, null)); set.visitCode(); Label store = new Label(), checkNull = new Label(); - Label[] labels = new Label[args.length]; + Label[] labels = new Label[info.args.length]; for (int label = 0; label < labels.length; label++) { labels[label] = new Label(); } // Put the values array on the stack to begin with set.visitVarInsn(Opcodes.ALOAD, 0); - set.visitFieldInsn(Opcodes.GETFIELD, ref, ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); + set.visitFieldInsn(Opcodes.GETFIELD, info.getName(), ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); // Each argument index will jump to its own label - for (byte index = 0; index < args.length; index++) { + for (byte index = 0; index < info.args.length; index++) { set.visitVarInsn(Opcodes.ILOAD, 1); set.visitConstant(index); set.visitJumpInsn(Opcodes.IF_ICMPEQ, labels[index]); @@ -366,12 +383,12 @@ public final class ArgsClassGenerator implements IClassGenerator { // For each arg we do a CHECKCAST to ensure the supplied type is // assignable to the arg type, we leave the index and value on the stack // and jump to the next stage - for (int index = 0; index < args.length; index++) { - String boxingType = Bytecode.getBoxingType(args[index]); + for (int index = 0; index < info.args.length; index++) { + String boxingType = Bytecode.getBoxingType(info.args[index]); set.visitLabel(labels[index]); set.visitVarInsn(Opcodes.ILOAD, 1); set.visitVarInsn(Opcodes.ALOAD, 2); - set.visitTypeInsn(Opcodes.CHECKCAST, boxingType != null ? boxingType : args[index].getInternalName()); + set.visitTypeInsn(Opcodes.CHECKCAST, boxingType != null ? boxingType : info.args[index].getInternalName()); set.visitJumpInsn(Opcodes.GOTO, boxingType != null ? checkNull : store); } @@ -401,7 +418,7 @@ public final class ArgsClassGenerator implements IClassGenerator { * @param args Parsed argument list from descriptor * @param writer Class writer */ - private void generateMultiSetter(String ref, String desc, Type[] args, ClassVisitor writer) { + private void generateMultiSetter(ArgsClassInfo info, ClassVisitor writer) { MethodVisitorEx set = new MethodVisitorEx(writer.visitMethod(Opcodes.ACC_PUBLIC, ArgsClassGenerator.SETALL, ArgsClassGenerator.SETALL_DESC, null, null)); set.visitCode(); @@ -413,17 +430,18 @@ public final class ArgsClassGenerator implements IClassGenerator { set.visitVarInsn(Opcodes.ALOAD, 1); set.visitInsn(Opcodes.ARRAYLENGTH); set.visitInsn(Opcodes.DUP); - set.visitConstant((byte)args.length); + set.visitConstant((byte)info.args.length); // If the lengths are the same, proceed with assignment set.visitJumpInsn(Opcodes.IF_ICMPEQ, lengthOk); + // Otherwise prepare and throw an ArgumentCountException set.visitTypeInsn(Opcodes.NEW, ArgsClassGenerator.ACE); set.visitInsn(Opcodes.DUP); set.visitInsn(Opcodes.DUP2_X1); set.visitInsn(Opcodes.POP2); - set.visitConstant((byte)args.length); - set.visitLdcInsn(ArgsClassGenerator.getSignature(args)); + set.visitConstant((byte)info.args.length); + set.visitLdcInsn(info.getSignature()); set.visitMethodInsn(Opcodes.INVOKESPECIAL, ArgsClassGenerator.ACE, Constants.CTOR, ArgsClassGenerator.ACE_CTOR_DESC, false); set.visitInsn(Opcodes.ATHROW); @@ -433,9 +451,9 @@ public final class ArgsClassGenerator implements IClassGenerator { // Put the values array on the stack to begin with set.visitVarInsn(Opcodes.ALOAD, 0); - set.visitFieldInsn(Opcodes.GETFIELD, ref, ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); + set.visitFieldInsn(Opcodes.GETFIELD, info.getName(), ArgsClassGenerator.VALUES_FIELD, ArgsClassGenerator.OBJECT_ARRAY); - for (byte index = 0; index < args.length; index++) { + for (byte index = 0; index < info.args.length; index++) { // Dup the member array reference and target index set.visitInsn(Opcodes.DUP); set.visitConstant(index); @@ -446,8 +464,8 @@ public final class ArgsClassGenerator implements IClassGenerator { set.visitInsn(Opcodes.AALOAD); // Check the argument type - String boxingType = Bytecode.getBoxingType(args[index]); - set.visitTypeInsn(Opcodes.CHECKCAST, boxingType != null ? boxingType : args[index].getInternalName()); + String boxingType = Bytecode.getBoxingType(info.args[index]); + set.visitTypeInsn(Opcodes.CHECKCAST, boxingType != null ? boxingType : info.args[index].getInternalName()); // For primitives, check the value is not null if (boxingType != null) { @@ -525,9 +543,5 @@ public final class ArgsClassGenerator implements IClassGenerator { method.visitTypeInsn(Opcodes.CHECKCAST, var.getInternalName()); } } - - private static String getSignature(Type[] args) { - return new SignaturePrinter("", null, args).setFullyQualified(true).getFormattedArgs(); - } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java index af82ca74..364ceba3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/util/InsnFinder.java @@ -26,13 +26,13 @@ package org.spongepowered.asm.mixin.injection.invoke.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.analysis.Analyzer; -import org.spongepowered.asm.lib.tree.analysis.AnalyzerException; -import org.spongepowered.asm.lib.tree.analysis.BasicInterpreter; -import org.spongepowered.asm.lib.tree.analysis.BasicValue; -import org.spongepowered.asm.lib.tree.analysis.Frame; -import org.spongepowered.asm.lib.tree.analysis.Interpreter; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.analysis.Analyzer; +import org.objectweb.asm.tree.analysis.AnalyzerException; +import org.objectweb.asm.tree.analysis.BasicInterpreter; +import org.objectweb.asm.tree.analysis.BasicValue; +import org.objectweb.asm.tree.analysis.Frame; +import org.objectweb.asm.tree.analysis.Interpreter; import org.spongepowered.asm.mixin.injection.struct.Target; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java index bf9d60dd..e1eef5f4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/AfterStoreLocal.java @@ -24,7 +24,7 @@ */ package org.spongepowered.asm.mixin.injection.modify; -import org.spongepowered.asm.lib.Opcodes; +import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java index ad9eb0c3..5b31a5c2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/BeforeLoadLocal.java @@ -27,10 +27,10 @@ package org.spongepowered.asm.mixin.injection.modify; import java.util.Collection; import java.util.ListIterator; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector.ContextualInjectionPoint; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java index 86825a2d..499589a1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java @@ -31,10 +31,10 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.LocalVariableNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.LocalVariableNode; import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator.Context.Local; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.util.Bytecode; @@ -122,7 +122,7 @@ public class LocalVariableDiscriminator { private final boolean isStatic; public Context(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) { - this.isStatic = Bytecode.methodIsStatic(target.method); + this.isStatic = Bytecode.isStatic(target.method); this.returnType = returnType; this.target = target; this.node = node; @@ -147,7 +147,7 @@ public class LocalVariableDiscriminator { Local[] lvt = new Local[this.baseArgIndex + target.arguments.length]; if (!this.isStatic) { - lvt[0] = new Local("this", Type.getType(target.classNode.name)); + lvt[0] = new Local("this", Type.getObjectType(target.classNode.name)); } for (int local = this.baseArgIndex; local < lvt.length; local++) { Type arg = target.arguments[local - this.baseArgIndex]; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 0f3e2529..affc51bb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -27,12 +27,12 @@ package org.spongepowered.asm.mixin.injection.modify; import java.util.Collection; import java.util.List; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +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.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.code.Injector; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java index d0be8d46..2bf05485 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/AfterInvoke.java @@ -26,14 +26,15 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +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.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; /** @@ -47,7 +48,7 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; *
*
target
*
A - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} + * {@link ITargetSelector Target Selector} * which identifies the target method
*
ordinal
*
The ordinal position of the method invocation to match. For example if @@ -88,4 +89,5 @@ public class AfterInvoke extends BeforeInvoke { nodes.add(insn); return true; } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index b12b4ae0..8354bb58 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -29,17 +29,18 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.ListIterator; +import java.util.Locale; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.FrameNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.LabelNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.LabelNode; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.Constant.Condition; @@ -187,9 +188,9 @@ public class BeforeConstant extends InjectionPoint { } List conditions = new ArrayList(); - String strConditions = data.get("expandZeroConditions", "").toLowerCase(); + String strConditions = data.get("expandZeroConditions", "").toLowerCase(Locale.ROOT); for (Condition condition : Condition.values()) { - if (strConditions.contains(condition.name().toLowerCase())) { + if (strConditions.contains(condition.name().toLowerCase(Locale.ROOT))) { conditions.add(condition); } } @@ -281,7 +282,7 @@ public class BeforeConstant extends InjectionPoint { Object value = Bytecode.getConstant(insn); if (value == null) { this.log(" BeforeConstant found NULL constant: nullValue = {}", this.nullValue); - return this.nullValue || Constants.OBJECT.equals(this.matchByType); + return this.nullValue || Constants.OBJECT_DESC.equals(this.matchByType); } else if (value instanceof Integer) { this.log(" BeforeConstant found INTEGER constant: value = {}, intValue = {}", value, this.intValue); return value.equals(this.intValue) || "I".equals(this.matchByType); @@ -296,10 +297,10 @@ public class BeforeConstant extends InjectionPoint { return value.equals(this.doubleValue) || "D".equals(this.matchByType); } else if (value instanceof String) { this.log(" BeforeConstant found STRING constant: value = {}, stringValue = {}", value, this.stringValue); - return value.equals(this.stringValue) || Constants.STRING.equals(this.matchByType); + return value.equals(this.stringValue) || Constants.STRING_DESC.equals(this.matchByType); } else if (value instanceof Type) { this.log(" BeforeConstant found CLASS constant: value = {}, typeValue = {}", value, this.typeValue); - return value.equals(this.typeValue) || Constants.CLASS.equals(this.matchByType); + return value.equals(this.typeValue) || Constants.CLASS_DESC.equals(this.matchByType); } return false; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java index 5f1834c6..0cc4b05d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFieldAccess.java @@ -27,16 +27,16 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; import java.util.Iterator; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.InsnList; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.util.Bytecode; /** @@ -48,7 +48,8 @@ import org.spongepowered.asm.util.Bytecode; * *
*
target
- *
A {@link MemberInfo MemberInfo} which identifies the target field.
+ *
A {@link ITargetSelector Target Selector} which identifies the target + * field.
*
opcode
*
The {@link Opcodes opcode} of the field access, must be one of * GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java index 1f2f57cf..053fb872 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java @@ -27,11 +27,11 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; import java.util.ListIterator; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.InsnNode; +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.InsnNode; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index a46988c4..343c84c6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -26,16 +26,19 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; import java.util.ListIterator; +import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -48,7 +51,8 @@ import org.spongepowered.asm.mixin.refmap.IMixinContext; * *
*
target
- *
A {@link MemberInfo MemberInfo} which identifies the target method
+ *
A {@link ITargetSelector Target Selector} which identifies the target + * method
*
ordinal
*
The ordinal position of the method invocation to match. For example if * the method is invoked 3 times and you want to match the 3rd then you can @@ -80,7 +84,7 @@ public class BeforeInvoke extends InjectionPoint { } - protected final MemberInfo target; + protected final ITargetSelector target; /** * This option enables a fallback "permissive" search to occur if initial @@ -130,7 +134,7 @@ public class BeforeInvoke extends InjectionPoint { private String getClassName() { AtCode atCode = this.getClass().getAnnotation(AtCode.class); - return String.format("@At(%s)", atCode != null ? atCode.value() : this.getClass().getSimpleName().toUpperCase()); + return String.format("@At(%s)", atCode != null ? atCode.value() : this.getClass().getSimpleName().toUpperCase(Locale.ROOT)); } /** @@ -146,14 +150,16 @@ public class BeforeInvoke extends InjectionPoint { /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.InjectionPoint - * #find(java.lang.String, org.spongepowered.asm.lib.tree.InsnList, + * #find(java.lang.String, org.objectweb.asm.tree.InsnList, * java.util.Collection) */ @Override public boolean find(String desc, InsnList insns, Collection nodes) { this.log("{} is searching for an injection point in method with descriptor {}", this.className, desc); - if (!this.find(desc, insns, nodes, this.target, SearchType.STRICT) && this.target.desc != null && this.allowPermissive) { + boolean hasDescriptor = this.target instanceof ITargetSelectorByName && ((ITargetSelectorByName)this.target).getDesc() == null; + + if (!this.find(desc, insns, nodes, this.target, SearchType.STRICT) && hasDescriptor && this.allowPermissive) { this.logger.warn("STRICT match for {} using \"{}\" in {} returned 0 results, attempting permissive search. " + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.context); return this.find(desc, insns, nodes, this.target, SearchType.PERMISSIVE); @@ -161,12 +167,12 @@ public class BeforeInvoke extends InjectionPoint { return true; } - protected boolean find(String desc, InsnList insns, Collection nodes, MemberInfo member, SearchType searchType) { - if (member == null) { + protected boolean find(String desc, InsnList insns, Collection nodes, ITargetSelector selector, SearchType searchType) { + if (selector == null) { return false; } - MemberInfo target = searchType == SearchType.PERMISSIVE ? member.transform(null) : member; + ITargetSelector target = searchType == SearchType.PERMISSIVE ? selector.configure("permissive") : selector; int ordinal = 0; int found = 0; @@ -179,10 +185,10 @@ public class BeforeInvoke extends InjectionPoint { MemberInfo nodeInfo = new MemberInfo(insn); this.log("{} is considering insn {}", this.className, nodeInfo); - if (target.matches(nodeInfo.owner, nodeInfo.name, nodeInfo.desc)) { + if (target.match(insn).isExactMatch()) { this.log("{} > found a matching insn, checking preconditions...", this.className); - if (this.matchesInsn(nodeInfo, ordinal)) { + if (this.matchesOrdinal(ordinal)) { this.log("{} > > > found a matching insn at ordinal {}", this.className, ordinal); if (this.addInsn(insns, nodes, insn)) { @@ -203,7 +209,7 @@ public class BeforeInvoke extends InjectionPoint { if (searchType == SearchType.PERMISSIVE && found > 1) { this.logger.warn("A permissive match for {} using \"{}\" in {} matched {} instructions, this may cause unexpected behaviour. " - + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, member, this.context, found); + + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.context, found); } return found > 0; @@ -222,7 +228,7 @@ public class BeforeInvoke extends InjectionPoint { // stub for subclasses } - protected boolean matchesInsn(MemberInfo nodeInfo, int ordinal) { + protected boolean matchesOrdinal(int ordinal) { this.log("{} > > comparing target ordinal {} with current ordinal {}", this.className, this.ordinal, ordinal); return this.ordinal == -1 || this.ordinal == ordinal; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java index db0a8cc8..7b0df8ce 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java @@ -29,15 +29,18 @@ import java.util.Collection; import java.util.Iterator; import java.util.ListIterator; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.TypeInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.TypeInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.util.Constants; import com.google.common.base.Strings; @@ -108,9 +111,14 @@ public class BeforeNew extends InjectionPoint { this.ordinal = data.getOrdinal(); String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/')); - MemberInfo member = MemberInfo.parseAndValidate(target, data.getContext()); - this.target = member.toCtorType(); - this.desc = member.toCtorDesc(); + ITargetSelector member = TargetSelector.parseAndValidate(target, data.getContext()); + if (!(member instanceof ITargetSelectorConstructor)) { + throw new InvalidInjectionPointException(data.getContext(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s", + target, data.getDescription()); + } + ITargetSelectorConstructor targetSelector = (ITargetSelectorConstructor)member; + this.target = targetSelector.toCtorType(); + this.desc = targetSelector.toCtorDesc(); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java index 4ecd1bf8..4aeefbfd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeReturn.java @@ -27,11 +27,11 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; import java.util.ListIterator; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.InsnNode; +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.InsnNode; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java index 5d4227a7..fe02f649 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeStringInvoke.java @@ -26,12 +26,13 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.LdcInsnNode; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.LdcInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; /** *

Like {@link BeforeInvoke}, this injection point searches for @@ -54,7 +55,7 @@ import org.spongepowered.asm.mixin.injection.struct.MemberInfo; *

*
target
*
A - * {@link org.spongepowered.asm.mixin.injection.struct.MemberInfo MemberInfo} + * {@link ITargetSelector Target Selector} * which identifies the target method, the method must be specified * with a signature which accepts a single string and returns void, * eg. (Ljava/lang/String;)V
@@ -104,7 +105,7 @@ public class BeforeStringInvoke extends BeforeInvoke { throw new IllegalArgumentException(this.getClass().getSimpleName() + " requires named argument \"ldc\" to specify the desired target"); } - if (!STRING_VOID_SIG.equals(this.target.desc)) { + if (!(this.target instanceof ITargetSelectorByName) || !STRING_VOID_SIG.equals(((ITargetSelectorByName)this.target).getDesc())) { throw new IllegalArgumentException(this.getClass().getSimpleName() + " requires target method with with signature " + STRING_VOID_SIG); } } @@ -131,8 +132,8 @@ public class BeforeStringInvoke extends BeforeInvoke { } @Override - protected boolean matchesInsn(MemberInfo nodeInfo, int ordinal) { + protected boolean matchesOrdinal(int ordinal) { this.log("{} > > found LDC \"{}\" = {}", this.className, this.ldcValue, this.foundLdc); - return this.foundLdc && super.matchesInsn(nodeInfo, ordinal); + return this.foundLdc && super.matchesOrdinal(ordinal); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java index 233b475e..ed198ee0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/JumpInsnPoint.java @@ -27,10 +27,10 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; import java.util.ListIterator; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.JumpInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.JumpInsnNode; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java index 172a6948..93b3642d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/MethodHead.java @@ -26,8 +26,8 @@ package org.spongepowered.asm.mixin.injection.points; import java.util.Collection; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.InsnList; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.InsnList; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java new file mode 100644 index 00000000..4760ff22 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -0,0 +1,106 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.util.asm.ElementNode; + +/** + * Target Selectors are used to identify target members in a class, with the + * criteria for selection being specified in a single string, effectively + * defining the query parameters. They are used by injectors and other + * components which need to identify a target element using a string. + * + *

Explicit Target Selectors

+ * + *

Explicit Target Selectors are handled internally using + * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the + * supported variants and examples.

+ */ +public interface ITargetSelector { + + /** + * Configure and return a modified version of this selector by consuming the + * supplied arguments. Results from this method should be idempotent in + * terms of the configuration of the returned object, but do not have to + * necessarily return the same object if the callee already matches the + * supplied configuration, though this is generally the case. + * + *

In other words, calling configure("foo") when this object is + * already configured according to "foo" may simply return this + * object, or might return an identically-configured copy.

+ * + * @param args Configuration arguments + * @return Configured selector, may return this selector if the specified + * condition is already satisfied + */ + public abstract ITargetSelector configure(String... args); + + /** + * Perform basic sanity-check validation of the selector, checks that the + * parsed out parameters are basically sane + * + * @return fluent (this selector) + * + * @throws InvalidSelectorException if any sanity check fails + */ + public abstract ITargetSelector validate() throws InvalidSelectorException; + + /** + * Attach this selector to the specified context. Should return this + * selector unmodified if all is well, or a new selector to be used for + * further processing of the supplied context. If the supplied context is + * invalid, an {@link InvalidSelectorException} is thrown. + * + * @param context Context to attach to + * @return Attached selector + */ + public abstract ITargetSelector attach(IMixinContext context) throws InvalidSelectorException; + + /** + * Number of candidates which this selector should match + */ + public abstract int getMatchCount(); + + /** + * Test whether this selector matches the supplied element node + * + * @param node node node to test + * @param node type + * @return true if this selector can match the supplied field + */ + public abstract MatchResult match(ElementNode node); + + /** + * Test whether this selector matches the supplied instruction node + * + * @param insn instruction node to test + * @return true if this selector can match the supplied instruction + */ + public abstract MatchResult match(AbstractInsnNode insn); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java new file mode 100644 index 00000000..c1c9d803 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java @@ -0,0 +1,101 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +/** + * A target selector which selects elements directly by name. + */ +public interface ITargetSelectorByName extends ITargetSelector { + + /** + * Get the member owner, can be null + */ + public abstract String getOwner(); + + /** + * Get the member name, can be null + */ + public abstract String getName(); + + /** + * Get the member descriptor, can be null + */ + public abstract String getDesc(); + + /** + * Get whether this reference is fully qualified + * + * @return true if all components of this reference are non-null + */ + public abstract boolean isFullyQualified(); + + /** + * Get whether this target selector is definitely a field, the output of + * this method is undefined if {@link #isFullyQualified} returns false. + * + * @return true if this is definitely a field + */ + public abstract boolean isField(); + + /** + * Get whether this member represents a constructor + * + * @return true if member name is <init> + */ + public abstract boolean isConstructor(); + + /** + * Get whether this selector represents a class initialiser + * + * @return true if member name is <clinit> + */ + public abstract boolean isClassInitialiser(); + + /** + * Get whether this selector represents a constructor or class initialiser + * + * @return true if member name is <init> or + * <clinit> + */ + public abstract boolean isInitialiser(); + + /** + * Get a representation of this selector as a complete descriptor + */ + public abstract String toDescriptor(); + + /** + * Test whether this selector matches the supplied values. Null values are + * ignored. + + * @param owner Owner to compare with, null to skip + * @param name Name to compare with, null to skip + * @param desc Signature to compare with, null to skip + * @return true if all non-null values in this reference match non-null + * arguments supplied to this method + */ + public abstract MatchResult matches(String owner, String name, String desc); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorConstructor.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorConstructor.java new file mode 100644 index 00000000..5655f1bf --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorConstructor.java @@ -0,0 +1,43 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +/** + * A target selector which can identify constructor types + */ +public interface ITargetSelectorConstructor extends ITargetSelectorByName { + + /** + * Returns the constructor type represented by this selector + */ + public abstract String toCtorType(); + + /** + * Returns the constructor descriptor represented by this + * selector, returns null if no descriptor is present. + */ + public abstract String toCtorDesc(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java new file mode 100644 index 00000000..55780b59 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java @@ -0,0 +1,76 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +import org.spongepowered.asm.obfuscation.mapping.IMapping; +import org.spongepowered.asm.obfuscation.mapping.common.MappingField; +import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; + +/** + * A target selector which can be remapped at compile time via an obfuscation + * service + */ +public interface ITargetSelectorRemappable extends ITargetSelectorByName { + + /** + * Returns this selector as a {@link MappingField} or + * {@link MappingMethod} + */ + public abstract IMapping asMapping(); + + /** + * Returns this selector as a mapping method + */ + public abstract MappingMethod asMethodMapping(); + + /** + * Returns this selector as a mapping field + */ + public abstract MappingField asFieldMapping(); + + /** + * Create a new version of this member with a different owner + * + * @param newOwner New owner for this member + */ + public abstract ITargetSelectorRemappable move(String newOwner); + + /** + * Create a new version of this member with a different descriptor + * + * @param newDesc New descriptor for this member + */ + public abstract ITargetSelectorRemappable transform(String newDesc); + + /** + * Create a remapped version of this member using the supplied method data + * + * @param srgMethod SRG method data to use + * @param setOwner True to set the owner as well as the name + * @return New MethodInfo with remapped values + */ + public abstract ITargetSelectorRemappable remapUsing(MappingMethod srgMethod, boolean setOwner); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelectorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelectorException.java new file mode 100644 index 00000000..024cc3bd --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelectorException.java @@ -0,0 +1,49 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Exception to be thrown from {@link ITargetSelector#validate} when a target + * selector fails verification + */ +public class InvalidSelectorException extends MixinException { + + private static final long serialVersionUID = 1L; + + public InvalidSelectorException(String message) { + super(message); + } + + public InvalidSelectorException(Throwable cause) { + super(cause); + } + + public InvalidSelectorException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MatchResult.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MatchResult.java new file mode 100644 index 00000000..0555d0be --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MatchResult.java @@ -0,0 +1,85 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +/** + * Result of a {@link ITargetSelector target selector} match operation + * which describes the type of match. + */ +public enum MatchResult { + + /** + * No result, the selector does not match the candidate + */ + NONE, + + /** + * Matches only in the weakest sense, use this result only if all else fails + * and nothing else matches at all + */ + WEAK, + + /** + * A confident match, but not an exact match. It may be that other optional + * parts of the selector did not match the candidate. For example this could + * mean that the selector matched case-insensitively. This is the best + * result if an {@link #EXACT_MATCH} match is not found. + */ + MATCH, + + /** + * All parts, including optional parts of the selector matched the candidate + * and this result is the best. If more than one EXACT_MATCH is + * returned from a query, the first one should be used. + */ + EXACT_MATCH; + + + /** + * Get whether this match level represents a level which is the + * same or greater than the supplied level + * + * @param other level to compare to + * @return true if greater or equal + */ + public boolean isAtLeast(MatchResult other) { + return other == null || other.ordinal() <= this.ordinal(); + } + + /** + * Get whether this match succeeded + */ + public boolean isMatch() { + return this.ordinal() >= MatchResult.MATCH.ordinal(); + } + + /** + * Get whether this is an exact match + */ + public boolean isExactMatch() { + return this == MatchResult.EXACT_MATCH; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java new file mode 100644 index 00000000..f3ed43cb --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -0,0 +1,210 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.selectors; + +import java.util.ArrayList; +import java.util.List; + +import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.refmap.IReferenceMapper; +import org.spongepowered.asm.util.asm.ElementNode; + +/** + * Utility class for parsing selectors + */ +public final class TargetSelector { + + /** + * Query result struct + * + * @param Node type + */ + public static class Result { + + /** + * Any exact match returned by the query + */ + public final TNode exactMatch; + + /** + * All candidates returned by the query + */ + public final List candidates; + + Result(TNode exactMatch, List candidates) { + this.exactMatch = exactMatch; + this.candidates = candidates; + } + + /** + * Get only a single result from this handle. Preferentially returns an + * exact match if one was found, or returns the first result if only one + * result was found or if strict is false. If + * strict is true and more than one candidate was found, a + * {@link IllegalStateException} is thrown. If no results are found then + * the exception is also thrown. + * + * @param strict True to only return the first (non-exact) result + * if exactly one result was found. If more than one + * candidate was found, throws {@link IllegalStateException} + */ + public TNode getSingleResult(boolean strict) { + int resultCount = this.candidates.size(); + if (this.exactMatch != null) { + return this.exactMatch; + } + if (resultCount == 1 || !strict) { + return this.candidates.get(0); + } + throw new IllegalStateException((resultCount == 0 ? "No" : "Multiple") + " candidates were found"); + } + + } + + private TargetSelector() { + } + + /** + * Parse a target selector from a string and perform validation + * + * @param string String to parse target selector from + * @return parsed target selector + */ + public static ITargetSelector parseAndValidate(String string) throws InvalidMemberDescriptorException { + return TargetSelector.parse(string, null, null).validate(); + } + + /** + * Parse a target selector from a string and perform validation + * + * @param string String to parse target selector from + * @param context Context to use for reference mapping + * @return parsed target selector + */ + public static ITargetSelector parseAndValidate(String string, IMixinContext context) throws InvalidMemberDescriptorException { + return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()).validate(); + } + + /** + * Parse a target selector from a string + * + * @param string String to parse target selector from + * @return parsed target selector + */ + public static ITargetSelector parse(String string) { + return TargetSelector.parse(string, null, null); + } + + /** + * Parse a target selector from a string + * + * @param string String to parse target selector from + * @param context Context to use for reference mapping + * @return parsed target selector + */ + public static ITargetSelector parse(String string, IMixinContext context) { + return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()); + } + + /** + * Parse a target selector from the supplied name, and then return the name + * of the match. This is used mainly to remap input names in the same + * context as a selector without needing the selector itself. If the + * supplied name does not successfully parse to a name-based selector, then + * the name is returned unchanged. + * + * @param name Name to parse + * @param context Mixin context + * @return remapped name or original name + */ + public static String parseName(String name, IMixinContext context) { + ITargetSelector selector = TargetSelector.parse(name, context); + if (!(selector instanceof ITargetSelectorByName)) { + return name; + } + String mappedName = ((ITargetSelectorByName)selector).getName(); + return mappedName != null ? mappedName : name; + } + + private static ITargetSelector parse(String input, IReferenceMapper refMapper, String mixinClass) { + return MemberInfo.parse(input, refMapper, mixinClass); + } + + /** + * Run query on supplied target nodes + * + * @param target Target selector + * @param nodes Node collection to enumerate + * @param Node type + * @return query result + */ + public static Result run(ITargetSelector target, List> nodes) { + List candidates = new ArrayList(); + TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates); + return new Result(exactMatch, candidates); + } + + /** + * Run query on supplied target nodes + * + * @param targets Target selector + * @param nodes Node collection to enumerate + * @param Node type + * @return query result + */ + public static Result run(Iterable targets, List> nodes) { + TNode exactMatch = null; + List candidates = new ArrayList(); + + for (ITargetSelector target : targets) { + TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); + if (exactMatch == null) { + exactMatch = selectorExactMatch; + } + } + + return new Result(exactMatch, candidates); + } + + private static TNode runSelector(ITargetSelector target, List> nodes, List candidates) { + TNode exactMatch = null; + for (ElementNode element : nodes) { + MatchResult match = target.match(element); + if (match.isMatch()) { + TNode node = element.get(); + if (!candidates.contains(node)) { + candidates.add(node); + } + if (exactMatch == null && match.isExactMatch()) { + exactMatch = node; + } + } + } + return exactMatch; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java index 85168466..c1875ba4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/CallbackInjectionInfo.java @@ -24,12 +24,13 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.asm.mixin.injection.code.Injector; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.AnnotationType; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; @@ -38,6 +39,7 @@ import com.google.common.base.Strings; /** * Information about a callback to inject, usually specified by {@link Inject} */ +@AnnotationType(Inject.class) public class CallbackInjectionInfo extends InjectionInfo { protected CallbackInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 4f02efd8..c8ce1e98 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -24,47 +24,46 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Deque; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; +import java.lang.annotation.Annotation; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.reflect.Constructor; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +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.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Dynamic; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.ModifyArgs; -import org.spongepowered.asm.mixin.injection.ModifyConstant; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.ISliceContext; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.code.MethodSlice; import org.spongepowered.asm.mixin.injection.code.MethodSlices; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; 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.struct.SpecialMethodInfo; +import org.spongepowered.asm.mixin.throwables.MixinError; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; 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.asm.ElementNode; import com.google.common.base.Strings; @@ -74,6 +73,97 @@ import com.google.common.base.Strings; */ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceContext { + /** + * Decoration for subclasses which indicates the injector annotation that + * the subclass handles + */ + @Retention(RetentionPolicy.RUNTIME) + @java.lang.annotation.Target(ElementType.TYPE) + public @interface AnnotationType { + + /** + * The injector annotation this InjectionInfo can handle + */ + public Class value(); + + } + + /** + * Decoration for subclasses which specifies the prefix to use when + * conforming annotated handler methods + */ + @Retention(RetentionPolicy.RUNTIME) + @java.lang.annotation.Target(ElementType.TYPE) + public @interface HandlerPrefix { + + /** + * String prefix for conforming handler methods + */ + public String value(); + + } + + /** + * An injector registration entry + */ + static class InjectorEntry { + + final Class annotationType; + + final Class type; + + final Constructor ctor; + + final String simpleName; + + final String prefix; + + InjectorEntry(Class annotationType, Class type) throws NoSuchMethodException { + this.annotationType = annotationType; + this.type = type; + this.ctor = type.getDeclaredConstructor(MixinTargetContext.class, MethodNode.class, AnnotationNode.class); + this.simpleName = annotationType.getSimpleName() + ";"; + + HandlerPrefix handlerPrefix = type.getAnnotation(HandlerPrefix.class); + this.prefix = handlerPrefix != null ? handlerPrefix.value() : InjectionInfo.DEFAULT_PREFIX; + } + + InjectionInfo create(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { + try { + return this.ctor.newInstance(mixin, method, annotation); + } catch (ReflectiveOperationException ex) { + throw new MixinError("Failed to instantiate injector metaclass [" + this.type + "] for annotation " + annotation.desc, ex); + } + } + } + + /** + * Default conform prefix for handler methods + */ + public static final String DEFAULT_PREFIX = "handler"; + + /** + * Registry of subclasses + */ + private static Map registry = new LinkedHashMap(); + + /** + * Registered annotations, baked and used to call + * Annotations::getSingleVisible efficiently + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Class[] registeredAnnotations = new Class[0]; + + static { + // Standard injectors + InjectionInfo.register(CallbackInjectionInfo.class); // @Inject + InjectionInfo.register(ModifyArgInjectionInfo.class); // @ModifyArg + InjectionInfo.register(ModifyArgsInjectionInfo.class); // @ModifyArgs + InjectionInfo.register(RedirectInjectionInfo.class); // @Redirect + InjectionInfo.register(ModifyVariableInjectionInfo.class); // @ModifyVariable + InjectionInfo.register(ModifyConstantInjectionInfo.class); // @ModifyConstant + } + /** * Annotated method is static */ @@ -153,7 +243,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation, String atKey) { super(mixin, method, annotation); - this.isStatic = Bytecode.methodIsStatic(method); + this.isStatic = Bytecode.isStatic(method); this.slices = MethodSlices.parse(this); this.atKey = atKey; this.readAnnotation(); @@ -175,28 +265,30 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC this.injector = this.parseInjector(this.annotation); } - protected Set parseTargets(String type) { + protected Set parseTargets(String type) { List methods = Annotations.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)); } - Set members = new LinkedHashSet(); + Set selectors = new LinkedHashSet(); for (String method : methods) { try { - MemberInfo targetMember = MemberInfo.parseAndValidate(method, this.mixin); - if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) { - throw new InvalidInjectionException(this, - String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.method.name, - targetMember.owner)); - } - members.add(targetMember); + 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())); + } 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())); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionException(this, + String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.method.name, + ex.getMessage())); } } - return members; + return selectors; } protected List readInjectionPoints(String type) { @@ -365,7 +457,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * @return new method */ public MethodNode addMethod(int access, String name, String desc) { - MethodNode method = new MethodNode(Opcodes.ASM5, access | Opcodes.ACC_SYNTHETIC, name, desc, null, null); + MethodNode method = new MethodNode(Bytecode.ASM_API_VERSION, access | Opcodes.ACC_SYNTHETIC, name, desc, null, null); this.injectedMethods.add(method); return method; } @@ -382,10 +474,10 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC /** * Finds methods in the target class which match searchFor * - * @param searchFor members to search for + * @param selectors members to search for * @param type annotation type */ - private void findMethods(Set searchFor, String type) { + private void findMethods(Set selectors, String type) { this.targets.clear(); // When remapping refmap is enabled this implies we are in a development @@ -394,32 +486,35 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC // descriptor if this happens. int passes = this.mixin.getEnvironment().getOption(Option.REFMAP_REMAP) ? 2 : 1; - for (MemberInfo member : searchFor) { + for (ITargetSelector selector : selectors) { + int matchCount = selector.getMatchCount(); for (int count = 0, pass = 0; pass < passes && count < 1; pass++) { - int ordinal = 0; for (MethodNode target : this.classNode.methods) { - if (member.matches(target.name, target.desc, ordinal)) { + if (selector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { boolean isMixinMethod = Annotations.getVisible(target, MixinMerged.class) != null; - if (member.matchAll && (Bytecode.methodIsStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { + if (matchCount > 1 && (Bytecode.isStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { continue; } this.checkTarget(target); this.targets.add(target); - ordinal++; count++; + + if (count >= matchCount) { + break; + } } } // Second pass ignores descriptor - member = member.transform(null); + selector = selector.configure("permissive"); } } if (this.targets.size() == 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(searchFor), this.mixin.getTarget(), + type, this.method.name, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } } @@ -468,18 +563,10 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC return null; } - if (annotation.desc.endsWith(Inject.class.getSimpleName() + ";")) { - return new CallbackInjectionInfo(mixin, method, annotation); - } else if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) { - return new ModifyArgInjectionInfo(mixin, method, annotation); - } else if (annotation.desc.endsWith(ModifyArgs.class.getSimpleName() + ";")) { - return new ModifyArgsInjectionInfo(mixin, method, annotation); - } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { - return new RedirectInjectionInfo(mixin, method, annotation); - } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { - return new ModifyVariableInjectionInfo(mixin, method, annotation); - } else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) { - return new ModifyConstantInjectionInfo(mixin, method, annotation); + for (InjectorEntry injector : InjectionInfo.registry.values()) { + if (annotation.desc.endsWith(injector.simpleName)) { + return injector.create(mixin, method, annotation); + } } return null; @@ -494,18 +581,10 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * @param method mixin method * @return annotation or null */ - @SuppressWarnings("unchecked") public static AnnotationNode getInjectorAnnotation(IMixinInfo mixin, MethodNode method) { AnnotationNode annotation = null; try { - annotation = Annotations.getSingleVisible(method, - Inject.class, - ModifyArg.class, - ModifyArgs.class, - Redirect.class, - ModifyVariable.class, - ModifyConstant.class - ); + annotation = Annotations.getSingleVisible(method, InjectionInfo.registeredAnnotations); } catch (IllegalArgumentException ex) { throw new InvalidMixinException(mixin, String.format("Error parsing annotations on %s in %s: %s", method.name, mixin.getClassName(), ex.getMessage())); @@ -520,20 +599,17 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * @return conform prefix */ public static String getInjectorPrefix(AnnotationNode annotation) { - if (annotation != null) { - if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) { - return "modify"; - } else if (annotation.desc.endsWith(ModifyArgs.class.getSimpleName() + ";")) { - return "args"; - } else if (annotation.desc.endsWith(Redirect.class.getSimpleName() + ";")) { - return "redirect"; - } else if (annotation.desc.endsWith(ModifyVariable.class.getSimpleName() + ";")) { - return "localvar"; - } else if (annotation.desc.endsWith(ModifyConstant.class.getSimpleName() + ";")) { - return "constant"; + if (annotation == null) { + return InjectionInfo.DEFAULT_PREFIX; + } + + for (InjectorEntry injector : InjectionInfo.registry.values()) { + if (annotation.desc.endsWith(injector.simpleName)) { + return injector.prefix; } } - return "handler"; + + return InjectionInfo.DEFAULT_PREFIX; } static String describeInjector(IMixinContext mixin, AnnotationNode annotation, MethodNode method) { @@ -543,13 +619,13 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC /** * Print the names of the specified members as a human-readable list * - * @param members members to print + * @param selectors members to print * @return human-readable list of member names */ - private static String namesOf(Collection members) { - int index = 0, count = members.size(); + private static String namesOf(Collection selectors) { + int index = 0, count = selectors.size(); StringBuilder sb = new StringBuilder(); - for (MemberInfo member : members) { + for (ITargetSelector selector : selectors) { if (index > 0) { if (index == (count - 1)) { sb.append(" or "); @@ -557,10 +633,47 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC sb.append(", "); } } - sb.append('\'').append(member.name).append('\''); + sb.append('\'').append(selector.toString()).append('\''); index++; } return sb.toString(); } + /** + * Register an injector info class. The supplied class must be decorated + * with an {@link AnnotationType} annotation for registration purposes. + * + * @param type injection info subclass to register + */ + public static void register(Class type) { + AnnotationType annotationType = type.getAnnotation(AnnotationType.class); + if (annotationType == null) { + throw new IllegalArgumentException("Injection info class " + type + " is not annotated with @AnnotationType"); + } + + Logger logger = LogManager.getLogger("mixin"); + + InjectorEntry entry; + try { + entry = new InjectorEntry(annotationType.value(), type); + } catch (NoSuchMethodException ex) { + throw new MixinError("InjectionInfo class " + type.getName() + " is missing a valid constructor"); + } + InjectorEntry existing = InjectionInfo.registry.get(entry.simpleName); + if (existing != null && !existing.type.equals(type)) { + logger.debug("WARNING: Overriding InjectionInfo for {} with {} (previously {})", annotationType.value().getSimpleName(), type.getName(), + existing.type.getName()); + } else { + logger.debug("Registering new injector for {} with {}", annotationType.value().getSimpleName(), type.getName()); + } + + InjectionInfo.registry.put(entry.simpleName, entry); + + ArrayList> annotations = new ArrayList>(); + for (InjectorEntry injector : InjectionInfo.registry.values()) { + annotations.add(injector.annotationType); + } + InjectionInfo.registeredAnnotations = annotations.toArray(InjectionInfo.registeredAnnotations); + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java index 07d12d33..235d7f17 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionNodes.java @@ -28,7 +28,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.util.Bytecode; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index 2a3f2989..3cb6bba1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -30,13 +30,15 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -251,33 +253,40 @@ public class InjectionPointData { } /** - * Get the supplied value from the named args as a {@link MemberInfo}, - * throws an exception if the argument cannot be parsed as a MemberInfo. + * Get the supplied value from the named args as a target selector, + * throws an exception if the argument cannot be parsed as a target selector * * @param key argument name - * @return argument value as a MemberInfo + * @return argument value as a target selector */ - public MemberInfo get(String key) { + public ITargetSelector get(String key) { try { - return MemberInfo.parseAndValidate(this.get(key, ""), this.context); + return TargetSelector.parseAndValidate(this.get(key, ""), this.context); } catch (InvalidMemberDescriptorException ex) { throw new InvalidInjectionPointException(this.context, "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s", - this.at, key, this.target, InjectionInfo.describeInjector(this.context, this.parent, this.method)); + this.at, key, this.target, this.getDescription()); } } /** * Get the target value specified on the injector */ - public MemberInfo getTarget() { + public ITargetSelector getTarget() { try { - return MemberInfo.parseAndValidate(this.target, this.context); + return TargetSelector.parseAndValidate(this.target, this.context); } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.context, "Failed parsing @At(\"%s\") descriptor \"%s\" on %s", - this.at, this.target, InjectionInfo.describeInjector(this.context, this.parent, this.method)); + throw new InvalidInjectionPointException(this.context, "Failed parsing @At(\"%s\").target descriptor \"%s\" on %s", + this.at, this.target, this.getDescription()); } } - + + /** + * Get a description of this injector for use in error messages + */ + public String getDescription() { + return InjectionInfo.describeInjector(this.context, this.parent, this.method); + } + /** * Get the ordinal specified on the injection point */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java index 81ed63e8..0871898d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java @@ -31,8 +31,8 @@ import java.util.HashMap; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.Group; import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException; import org.spongepowered.asm.util.Annotations; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java index 15be6346..82ffd7ee 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java @@ -24,12 +24,12 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; /** * Thrown when a {@link MemberInfo} fails basic syntax validation */ -public class InvalidMemberDescriptorException extends MixinException { +public class InvalidMemberDescriptorException extends InvalidSelectorException { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index d2715d65..d1eb26bf 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -24,27 +24,36 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.MatchResult; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; +import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.SignaturePrinter; +import org.spongepowered.asm.util.asm.ElementNode; import com.google.common.base.Objects; import com.google.common.base.Strings; /** - *

Information bundle about a member (method or field) parsed from a String - * token in another annotation, this is used where target members need to be - * specified as Strings in order to parse the String representation to something - * useful.

+ *

Target selector, also used as a general-purpose information bundle about a + * member (method or field) parsed from a String token in another annotation, + * this is used where target members need to be specified as Strings in order to + * parse the String representation to something useful. See + * {@link ITargetSelector} for other supported selector types.

* *

Some examples:

*
@@ -80,27 +89,27 @@ import com.google.common.base.Strings;
  *   foo.bar.Baz.func_1234_a(DDD)V
*
*/ -public final class MemberInfo { +public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelectorConstructor { /** * Member owner in internal form but without L;, can be null */ - public final String owner; + private final String owner; /** * Member name, can be null to match any member */ - public final String name; + private final String name; /** * Member descriptor, can be null */ - public final String desc; + private final String desc; /** * True to match all matching members, not just the first */ - public final boolean matchAll; + private final boolean matchAll; /** * Force this member to report as a field @@ -252,6 +261,26 @@ public final class MemberInfo { this.unparsed = null; } + @Override + public String getOwner() { + return this.owner; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public String getDesc() { + return this.desc; + } + + @Override + public int getMatchCount() { + return this.matchAll ? Integer.MAX_VALUE : 1; + } + /* (non-Javadoc) * @see java.lang.Object#toString() */ @@ -287,6 +316,7 @@ public final class MemberInfo { /** * Returns this MemberInfo as a java-style descriptor */ + @Override public String toDescriptor() { if (this.desc == null) { return ""; @@ -298,6 +328,7 @@ public final class MemberInfo { /** * Returns the constructor type represented by this MemberInfo */ + @Override public String toCtorType() { if (this.unparsed == null) { return null; @@ -318,17 +349,14 @@ public final class MemberInfo { return this.desc != null ? this.desc : this.unparsed; } - + /** * Returns the constructor descriptor represented by this * MemberInfo, returns null if no descriptor is present. */ + @Override public String toCtorDesc() { - if (this.desc != null && this.desc.startsWith("(") && this.desc.indexOf(')') > -1) { - return this.desc.substring(0, this.desc.indexOf(')') + 1) + "V"; - } - - return null; + return Bytecode.changeDescriptorReturnType(this.desc, "V"); } /** @@ -336,7 +364,7 @@ public final class MemberInfo { * returns null if the descriptor is absent or if this MemberInfo represents * a field */ - public String getReturnType() { + private String getReturnType() { if (this.desc == null || this.desc.indexOf(')') == -1 || this.desc.indexOf('(') != 0 ) { return null; } @@ -352,6 +380,7 @@ public final class MemberInfo { * Returns this MemberInfo as a {@link MappingField} or * {@link MappingMethod} */ + @Override public IMapping asMapping() { return this.isField() ? this.asFieldMapping() : this.asMethodMapping(); } @@ -359,6 +388,7 @@ public final class MemberInfo { /** * Returns this MemberInfo as a mapping method */ + @Override public MappingMethod asMethodMapping() { if (!this.isFullyQualified()) { throw new MixinException("Cannot convert unqualified reference " + this + " to MethodMapping"); @@ -374,6 +404,7 @@ public final class MemberInfo { /** * Returns this MemberInfo as a mapping field */ + @Override public MappingField asFieldMapping() { if (!this.isField()) { throw new MixinException("Cannot convert non-field reference " + this + " to FieldMapping"); @@ -382,11 +413,7 @@ public final class MemberInfo { return new MappingField(this.owner, this.name, this.desc); } - /** - * Get whether this reference is fully qualified - * - * @return true if all components of this reference are non-null - */ + @Override public boolean isFullyQualified() { return this.owner != null && this.name != null && this.desc != null; } @@ -397,6 +424,7 @@ public final class MemberInfo { * * @return true if this is definitely a field */ + @Override public boolean isField() { return this.forceField || (this.desc != null && !this.desc.startsWith("(")); } @@ -406,6 +434,7 @@ public final class MemberInfo { * * @return true if member name is <init> */ + @Override public boolean isConstructor() { return Constants.CTOR.equals(this.name); } @@ -415,6 +444,7 @@ public final class MemberInfo { * * @return true if member name is <clinit> */ + @Override public boolean isClassInitialiser() { return Constants.CLINIT.equals(this.name); } @@ -425,6 +455,7 @@ public final class MemberInfo { * @return true if member name is <init> or * <clinit> */ + @Override public boolean isInitialiser() { return this.isConstructor() || this.isClassInitialiser(); } @@ -437,6 +468,7 @@ public final class MemberInfo { * * @throws InvalidMemberDescriptorException if any validation check fails */ + @Override public MemberInfo validate() throws InvalidMemberDescriptorException { // Extremely naive class name validation, just to spot really egregious errors if (this.owner != null) { @@ -486,90 +518,73 @@ public final class MemberInfo { return this; } - - /** - * Test whether this MemberInfo matches the supplied values. Null values are - * ignored. - - * @param owner Owner to compare with, null to skip - * @param name Name to compare with, null to skip - * @param desc Signature to compare with, null to skip - * @return true if all non-null values in this reference match non-null - * arguments supplied to this method + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #match(org.spongepowered.asm.util.asm.ElementNode) */ - public boolean matches(String owner, String name, String desc) { - return this.matches(owner, name, desc, 0); + @Override + public MatchResult match(ElementNode node) { + return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc()); } - /** - * Test whether this MemberInfo matches the supplied values at the specified - * ordinal. Null values are ignored. - * - * @param owner Owner to compare with, null to skip - * @param name Name to compare with, null to skip - * @param desc Signature to compare with, null to skip - * @param ordinal ordinal position within the class, used to honour the - * matchAll semantics - * @return true if all non-null values in this reference match non-null - * arguments supplied to this method + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #matches(org.objectweb.asm.tree.AbstractInsnNode) */ - public boolean matches(String owner, String name, String desc, int ordinal) { - if (this.desc != null && desc != null && !this.desc.equals(desc)) { - return false; + @Override + public MatchResult match(AbstractInsnNode insn) { + if (insn instanceof MethodInsnNode) { + MethodInsnNode method = (MethodInsnNode)insn; + return this.matches(method.owner, method.name, method.desc); + } else if (insn instanceof FieldInsnNode) { + FieldInsnNode field = (FieldInsnNode)insn; + return this.matches(field.owner, field.name, field.desc); } - if (this.name != null && name != null && !this.name.equals(name)) { - return false; + return MatchResult.NONE; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #matches(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public MatchResult matches(String owner, String name, String desc) { + if (this.desc != null && desc != null && !this.desc.equals(desc)) { + return MatchResult.NONE; } if (this.owner != null && owner != null && !this.owner.equals(owner)) { - return false; + return MatchResult.NONE; } - return ordinal == 0 || this.matchAll; + if (this.name != null && name != null) { + if (this.name.equals(name)) { + return MatchResult.EXACT_MATCH; + } + if (this.name.equalsIgnoreCase(name)) { + return MatchResult.MATCH; + } + return MatchResult.NONE; + } + return MatchResult.EXACT_MATCH; } - /** - * Test whether this MemberInfo matches the supplied values. Null values are - * ignored. - - * @param name Name to compare with, null to skip - * @param desc Signature to compare with, null to skip - * @return true if all non-null values in this reference match non-null - * arguments supplied to this method - */ - public boolean matches(String name, String desc) { - return this.matches(name, desc, 0); - } - - /** - * Test whether this MemberInfo matches the supplied values at the specified - * ordinal. Null values are ignored. - * - * @param name Name to compare with, null to skip - * @param desc Signature to compare with, null to skip - * @param ordinal ordinal position within the class, used to honour the - * matchAll semantics - * @return true if all non-null values in this reference match non-null - * arguments supplied to this method - */ - public boolean matches(String name, String desc, int ordinal) { - return (this.name == null || this.name.equals(name)) - && (this.desc == null || (desc != null && desc.equals(this.desc))) - && (ordinal == 0 || this.matchAll); - } - /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { - if (obj == null || obj.getClass() != MemberInfo.class) { + if (obj == null || !(obj instanceof ITargetSelectorByName)) { return false; } - MemberInfo other = (MemberInfo)obj; - return this.matchAll == other.matchAll && this.forceField == other.forceField - && Objects.equal(this.owner, other.owner) - && Objects.equal(this.name, other.name) - && Objects.equal(this.desc, other.desc); + ITargetSelectorByName other = (ITargetSelectorByName)obj; + boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField : other.isField(); + boolean otherMatchAll = other.getMatchCount() == Integer.MAX_VALUE; + + return this.matchAll == otherMatchAll && this.forceField == otherForceField + && Objects.equal(this.owner, other.getOwner()) + && Objects.equal(this.name, other.getName()) + && Objects.equal(this.desc, other.getDesc()); } /* (non-Javadoc) @@ -580,12 +595,50 @@ public final class MemberInfo { return Objects.hashCode(this.matchAll, this.owner, this.name, this.desc); } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #configure(java.lang.String[]) + */ + @Override + public ITargetSelector configure(String... args) { + ITargetSelectorRemappable configured = this; + for (String arg : args) { + if (arg == null) { + continue; + } + + if (arg.startsWith("move:")) { + configured = configured.move(Strings.emptyToNull(arg.substring(5))); + } else if (arg.startsWith("transform:")) { + configured = configured.transform(Strings.emptyToNull(arg.substring(10))); + } else if ("permissive".equals(arg)) { + configured = configured.transform(null); + } else if ("orphan".equals(arg)) { + configured = configured.move(null); + } + } + return configured; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #attach(org.spongepowered.asm.mixin.refmap.IMixinContext) + */ + @Override + public ITargetSelector attach(IMixinContext context) throws InvalidSelectorException { + if (this.owner != null && !this.owner.equals(context.getTargetClassRef())) { + throw new TargetNotSupportedException(this.owner); + } + return this; + } + /** * Create a new version of this member with a different owner * * @param newOwner New owner for this member */ - public MemberInfo move(String newOwner) { + @Override + public ITargetSelectorRemappable move(String newOwner) { if ((newOwner == null && this.owner == null) || (newOwner != null && newOwner.equals(this.owner))) { return this; } @@ -597,7 +650,8 @@ public final class MemberInfo { * * @param newDesc New descriptor for this member */ - public MemberInfo transform(String newDesc) { + @Override + public ITargetSelectorRemappable transform(String newDesc) { if ((newDesc == null && this.desc == null) || (newDesc != null && newDesc.equals(this.desc))) { return this; } @@ -611,67 +665,26 @@ public final class MemberInfo { * @param setOwner True to set the owner as well as the name * @return New MethodInfo with remapped values */ - public MemberInfo remapUsing(MappingMethod srgMethod, boolean setOwner) { + @Override + public ITargetSelectorRemappable remapUsing(MappingMethod srgMethod, boolean setOwner) { return new MemberInfo(this, srgMethod, setOwner); } - /** - * Parse a MemberInfo from a string and perform validation - * - * @param string String to parse MemberInfo from - * @return parsed MemberInfo - */ - public static MemberInfo parseAndValidate(String string) throws InvalidMemberDescriptorException { - return MemberInfo.parse(string, null, null).validate(); - } - - /** - * Parse a MemberInfo from a string and perform validation - * - * @param string String to parse MemberInfo from - * @param context Context to use for reference mapping - * @return parsed MemberInfo - */ - public static MemberInfo parseAndValidate(String string, IMixinContext context) throws InvalidMemberDescriptorException { - return MemberInfo.parse(string, context.getReferenceMapper(), context.getClassRef()).validate(); - } - - /** - * Parse a MemberInfo from a string - * - * @param string String to parse MemberInfo from - * @return parsed MemberInfo - */ - public static MemberInfo parse(String string) { - return MemberInfo.parse(string, null, null); - } - - /** - * Parse a MemberInfo from a string - * - * @param string String to parse MemberInfo from - * @param context Context to use for reference mapping - * @return parsed MemberInfo - */ - public static MemberInfo parse(String string, IMixinContext context) { - return MemberInfo.parse(string, context.getReferenceMapper(), context.getClassRef()); - } - /** * Parse a MemberInfo from a string * * @param input String to parse MemberInfo from * @param refMapper Reference mapper to use - * @param mixinClass Mixin class to use for remapping + * @param className Class context to use for remapping * @return parsed MemberInfo */ - private static MemberInfo parse(String input, IReferenceMapper refMapper, String mixinClass) { + public static MemberInfo parse(String input, IReferenceMapper refMapper, String className) { String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); if (refMapper != null) { - name = refMapper.remap(mixinClass, name); + name = refMapper.remap(className, name); } int lastDotPos = name.lastIndexOf('.'); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java index a7fc753e..9446e980 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgInjectionInfo.java @@ -24,17 +24,21 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.ModifyArgInjector; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.AnnotationType; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.HandlerPrefix; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; /** * Information about a {@link ModifyArg} injector */ +@AnnotationType(ModifyArg.class) +@HandlerPrefix("modify") public class ModifyArgInjectionInfo extends InjectionInfo { public ModifyArgInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java index ca1104be..52ff5573 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyArgsInjectionInfo.java @@ -24,16 +24,20 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.ModifyArgsInjector; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.AnnotationType; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.HandlerPrefix; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; /** * Information about a {@link ModifyArgs} injector */ +@AnnotationType(ModifyArgs.class) +@HandlerPrefix("args") public class ModifyArgsInjectionInfo extends InjectionInfo { public ModifyArgsInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java index 36eb297c..859851c9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -26,13 +26,16 @@ package org.spongepowered.asm.mixin.injection.struct; import java.util.List; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.Constant; +import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.ModifyConstantInjector; import org.spongepowered.asm.mixin.injection.points.BeforeConstant; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.AnnotationType; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.HandlerPrefix; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import com.google.common.base.Strings; @@ -41,6 +44,8 @@ import com.google.common.collect.ImmutableList; /** * Information about a constant modifier injector */ +@AnnotationType(ModifyConstant.class) +@HandlerPrefix("constant") public class ModifyConstantInjectionInfo extends InjectionInfo { private static final String CONSTANT_ANNOTATION_CLASS = Constant.class.getName().replace('.', '/'); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java index 5b3f53ad..cefb00ae 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyVariableInjectionInfo.java @@ -24,17 +24,21 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator; import org.spongepowered.asm.mixin.injection.modify.ModifyVariableInjector; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.AnnotationType; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.HandlerPrefix; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; /** * Information about a {@link ModifyVariable} injector */ +@AnnotationType(ModifyVariable.class) +@HandlerPrefix("localvar") public class ModifyVariableInjectionInfo extends InjectionInfo { public ModifyVariableInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java index f46332f3..91ee7cd8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/RedirectInjectionInfo.java @@ -24,15 +24,20 @@ */ package org.spongepowered.asm.mixin.injection.struct; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.AnnotationType; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo.HandlerPrefix; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; /** * Information about a redirector injector */ +@AnnotationType(Redirect.class) +@HandlerPrefix("redirect") public class RedirectInjectionInfo extends InjectionInfo { public RedirectInjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java index aa0d72cb..58eb9d6a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/Target.java @@ -28,17 +28,17 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.spongepowered.asm.lib.Label; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.LabelNode; -import org.spongepowered.asm.lib.tree.LocalVariableNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.TypeInsnNode; +import org.objectweb.asm.Label; +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.LabelNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.transformer.ClassInfo; @@ -141,7 +141,7 @@ public class Target implements Comparable, Iterable { this.classNode = classNode; this.method = method; this.insns = method.instructions; - this.isStatic = Bytecode.methodIsStatic(method); + this.isStatic = Bytecode.isStatic(method); this.isCtor = method.name.equals(Constants.CTOR); this.arguments = Type.getArgumentTypes(method.desc); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/TargetNotSupportedException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/TargetNotSupportedException.java new file mode 100644 index 00000000..29f98ff1 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/TargetNotSupportedException.java @@ -0,0 +1,50 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.injection.struct; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; + +/** + * Exception thrown when target selector is not valid for the supplied target + * context during {@link ITargetSelector#attach} + */ +public class TargetNotSupportedException extends InvalidSelectorException { + + private static final long serialVersionUID = 1L; + + public TargetNotSupportedException(String message) { + super(message); + } + + public TargetNotSupportedException(Throwable cause) { + super(cause); + } + + public TargetNotSupportedException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java index 518cf649..8c41e546 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InjectionError.java @@ -24,10 +24,12 @@ */ package org.spongepowered.asm.mixin.injection.throwables; +import org.spongepowered.asm.mixin.throwables.MixinError; + /** * Error to throw for critical injection problems */ -public class InjectionError extends Error { +public class InjectionError extends MixinError { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java index e0935d94..fd12eddb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/IMixinContext.java @@ -24,7 +24,7 @@ */ package org.spongepowered.asm.mixin.refmap; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.injection.struct.Target; diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java index 3139edd2..242069c6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java @@ -31,13 +31,13 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; import com.google.common.collect.Maps; +import com.google.common.io.Closeables; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; @@ -216,7 +216,11 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { * @return replaced value, per the contract of {@link Map#put} */ public String addMapping(String context, String className, String reference, String newReference) { - if (this.readOnly || reference == null || newReference == null || reference.equals(newReference)) { + if (this.readOnly || reference == null || newReference == null) { + return null; + } + String conformedReference = reference.replaceAll("\\s", ""); + if (conformedReference.equals(newReference)) { return null; } Map> mappings = this.mappings; @@ -232,7 +236,7 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { classMappings = new HashMap(); mappings.put(className, classMappings); } - return classMappings.put(reference, newReference); + return classMappings.put(conformedReference, newReference); } /** @@ -267,7 +271,7 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { } catch (Exception ex) { logger.error("Failed reading REFMAP JSON from " + resourcePath + ": " + ex.getClass().getName() + " " + ex.getMessage()); } finally { - IOUtils.closeQuietly(reader); + Closeables.closeQuietly(reader); } return ReferenceMapper.DEFAULT_MAPPER; diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java b/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java index 4e82cdf6..b8baec32 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/MemberRef.java @@ -24,9 +24,9 @@ */ package org.spongepowered.asm.mixin.struct; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Bytecode; @@ -185,7 +185,7 @@ public abstract class MemberRef { */ public static final class Handle extends MemberRef { - private org.spongepowered.asm.lib.Handle handle; + private org.objectweb.asm.Handle handle; /** * Creates a member reference initially referring to the member referred @@ -194,7 +194,7 @@ public abstract class MemberRef { * * @param handle Initial method handle. */ - public Handle(org.spongepowered.asm.lib.Handle handle) { + public Handle(org.objectweb.asm.Handle handle) { this.handle = handle; } @@ -203,7 +203,7 @@ public abstract class MemberRef { * * @return Method handle representing this object */ - public org.spongepowered.asm.lib.Handle getMethodHandle() { + public org.objectweb.asm.Handle getMethodHandle() { return this.handle; } @@ -242,7 +242,7 @@ public abstract class MemberRef { throw new MixinTransformerError("Invalid opcode " + Bytecode.getOpcodeName(opcode) + " for method handle " + this.handle + "."); } boolean itf = tag == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.spongepowered.asm.lib.Handle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), itf); + this.handle = new org.objectweb.asm.Handle(tag, this.handle.getOwner(), this.handle.getName(), this.handle.getDesc(), itf); } @Override @@ -253,7 +253,7 @@ public abstract class MemberRef { @Override public void setOwner(String owner) { boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), itf); + this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), owner, this.handle.getName(), this.handle.getDesc(), itf); } @Override @@ -264,7 +264,7 @@ public abstract class MemberRef { @Override public void setName(String name) { boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), itf); + this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), name, this.handle.getDesc(), itf); } @Override @@ -275,7 +275,7 @@ public abstract class MemberRef { @Override public void setDesc(String desc) { boolean itf = this.handle.getTag() == Opcodes.H_INVOKEINTERFACE; - this.handle = new org.spongepowered.asm.lib.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, itf); + this.handle = new org.objectweb.asm.Handle(this.handle.getTag(), this.handle.getOwner(), this.handle.getName(), desc, itf); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SourceMap.java b/src/main/java/org/spongepowered/asm/mixin/struct/SourceMap.java index 67539752..a761d0aa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SourceMap.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SourceMap.java @@ -28,10 +28,10 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.LineNumberNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.util.Bytecode; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java index d682472e..e6f2a013 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -24,9 +24,9 @@ */ package org.spongepowered.asm.mixin.struct; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +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; diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java index a3fa7bfc..b43cb6ae 100644 --- a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinApplyError.java @@ -27,7 +27,7 @@ package org.spongepowered.asm.mixin.throwables; /** * Error to throw for required mixins when mixing of the mixin fails */ -public class MixinApplyError extends Error { +public class MixinApplyError extends MixinError { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinError.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinError.java new file mode 100644 index 00000000..0f2a1467 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinError.java @@ -0,0 +1,50 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.throwables; + +/** + * An internal error in mixin, not an invalid mixin or user state, but + * something wrong in Mixin's state which isn't the user's fault + */ +public class MixinError extends Error { + + private static final long serialVersionUID = 1L; + + public MixinError() { + } + + public MixinError(String message) { + super(message); + } + + public MixinError(Throwable cause) { + super(cause); + } + + public MixinError(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java index 145f5452..085bb4f3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinException.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.mixin.throwables; +import org.spongepowered.asm.mixin.transformer.ActivityStack; + /** * Base class for all mixin processor exceptions */ @@ -31,19 +33,50 @@ public class MixinException extends RuntimeException { private static final long serialVersionUID = 1L; - public MixinException() { - } + private String activityDescriptor; public MixinException(String message) { super(message); } + public MixinException(String message, ActivityStack context) { + super(message); + this.activityDescriptor = context != null ? context.toString() : null; + } + public MixinException(Throwable cause) { super(cause); } + public MixinException(Throwable cause, ActivityStack context) { + super(cause); + this.activityDescriptor = context != null ? context.toString() : null; + } + public MixinException(String message, Throwable cause) { super(message, cause); } + public MixinException(String message, Throwable cause, ActivityStack context) { + super(message, cause); + this.activityDescriptor = context != null ? context.toString() : null; + } + + /** + * Decorate this exception with additional upstream activity context + * + * @param upstreamContext Upstream activity stack to decorate + */ + public void prepend(ActivityStack upstreamContext) { + String strContext = upstreamContext.toString(); + this.activityDescriptor = this.activityDescriptor != null ? strContext + ActivityStack.GLUE_STRING + this.activityDescriptor + : ActivityStack.GLUE_STRING + strContext; + } + + @Override + public String getMessage() { + String message = super.getMessage(); + return this.activityDescriptor != null ? message + " [" + this.activityDescriptor + "]" : message; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java index f5e64c05..f399f05d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/MixinPrepareError.java @@ -27,7 +27,7 @@ package org.spongepowered.asm.mixin.throwables; /** * Error to throw for required configs when initialising of the config fails */ -public class MixinPrepareError extends Error { +public class MixinPrepareError extends MixinError { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ActivityStack.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ActivityStack.java new file mode 100644 index 00000000..4239b66a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ActivityStack.java @@ -0,0 +1,202 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +/** + * Tracker for processors which want to express their activity stack on crash in + * a user-readable way. + */ +public class ActivityStack { + + /** + * An activity node in the activity stack (yes it's actually a doubly-linked + * list). + */ + public class Activity { + + /** + * Description of this activity + */ + public String description; + + Activity last, next; + + Activity(Activity last, String description) { + if (last != null) { + last.next = this; + } + this.last = last; + this.description = description; + } + + /** + * Append text to the activity description + * + * @param text Text to append + */ + public void append(String text) { + this.description = this.description != null ? this.description + text : text; + } + + /** + * Append text to the activity description + * + * @param textFormat Format for text to append + * @param args Format args + */ + public void append(String textFormat, Object...args) { + this.append(String.format(textFormat, args)); + } + + /** + * End this activity and remove it (and any descendants) + */ + public void end() { + // Cannot end head or ended activity + if (this.last != null) { + ActivityStack.this.end(this); + this.last = null; + } + } + + /** + * End this activity (and any descendants) and begin the next activity + * using the same activity handle + * + * @param description New activity description + */ + public void next(String description) { + if (this.next != null) { + this.next.end(); + } + this.description = description; + } + + /** + * End this activity (and any descendants) and begin the next activity + * using the same activity handle + * + * @param descriptionFormat New activity description format + * @param args New activity description args + */ + public void next(String descriptionFormat, Object... args) { + if (descriptionFormat == null) { + descriptionFormat = "null"; + } + this.next(String.format(descriptionFormat, args)); + } + + } + + public static final String GLUE_STRING = " -> "; + + private final Activity head; + private Activity tail; + + private String glue; + + public ActivityStack() { + this(null, ActivityStack.GLUE_STRING); + } + + public ActivityStack(String root) { + this(root, ActivityStack.GLUE_STRING); + } + + public ActivityStack(String root, String glue) { + this.head = this.tail = new Activity(null, root); + this.glue = glue; + } + + /** + * Clear the activity stack + */ + public void clear() { + this.tail = this.head; + this.head.next = null; + } + + /** + * Begin a new activity (push it onto this activity stack) + * + * @param description Activity description + * @return new activity handle + */ + public Activity begin(String description) { + return this.tail = new Activity(this.tail, description != null ? description : "null"); + } + + /** + * Begin a new activity (push it onto this activity stack) + * + * @param descriptionFormat Activity description format + * @param args format args + * @return new activity handle + */ + public Activity begin(String descriptionFormat, Object... args) { + if (descriptionFormat == null) { + descriptionFormat = "null"; + } + return this.tail = new Activity(this.tail, String.format(descriptionFormat, args)); + } + + void end(Activity activity) { + this.tail = activity.last; + this.tail.next = null; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return this.toString(this.glue); + } + + /** + * Convert this activity stack to a string representation using the + * specified glue string + * + * @param glue glue string + * @return string representation of this activity stack + */ + public String toString(String glue) { + if (this.head.description == null && this.head.next == null) { + return "Unknown"; + } + + StringBuilder sb = new StringBuilder(); + for (Activity activity = this.head; activity != null; activity = activity.next) { + if (activity.description != null) { + sb.append(activity.description); + if (activity.next != null) { + sb.append(glue); + } + } + } + return sb.toString(); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassContext.java index 3845ef9e..1ccb6089 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassContext.java @@ -28,11 +28,11 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.struct.MemberRef; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java index 342360b5..bebbe307 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java @@ -36,19 +36,21 @@ import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.FrameNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type; @@ -90,6 +92,27 @@ public final class ClassInfo { SUPER_CLASSES_ONLY } + + /** + * When using {@link ClassInfo#forType}, determines whether an array type + * should be returned as declared (eg. as Object) or whether the + * element type should be returned instead. + */ + public static enum TypeLookup { + + /** + * Return the type as declared in the descriptor. This means that array + * types will be treated Object for the purposes of type + * hierarchy lookups returning the correct member methods. + */ + DECLARED_TYPE, + + /** + * Legacy behaviour. A lookup by type will return the element type. + */ + ELEMENT_TYPE + + } /** *

To all intents and purposes, the "real" class hierarchy and the mixin @@ -431,6 +454,8 @@ public final class ClassInfo { private boolean isAccessor; + private boolean conformed; + public Method(Member member) { super(member); this.frames = member instanceof Method ? ((Method)member).frames : null; @@ -489,6 +514,33 @@ public final class ClassInfo { public boolean isAccessor() { return this.isAccessor; } + + public boolean isConformed() { + return this.conformed; + } + + @Override + public String renameTo(String name) { + this.conformed = false; + return super.renameTo(name); + } + + /** + * @param name new name + * @return the passed-in argument, for fluency + */ + public String conform(String name) { + boolean nameChanged = !name.equals(this.getName()); + if (this.conformed && nameChanged) { + throw new IllegalStateException("Method " + this + " was already conformed. Original= " + this.getOriginalName() + + " Current=" + this.getName() + " New=" + name); + } + if (nameChanged) { + this.renameTo(name); + this.conformed = true; + } + return name; + } @Override public boolean equals(Object obj) { @@ -636,7 +688,7 @@ public final class ClassInfo { /** * Mixins which target this class */ - private final Set mixins = new HashSet(); + private final Set mixins; /** * Map of mixin types to corresponding supertypes, to avoid repeated @@ -681,6 +733,11 @@ public final class ClassInfo { */ private ClassSignature signature; + /** + * Mixins which have been applied this class + */ + private Set appliedMixins; + /** * Private constructor used to initialise the ClassInfo for {@link Object} */ @@ -708,6 +765,7 @@ public final class ClassInfo { this.access = Opcodes.ACC_PUBLIC; this.isMixin = false; this.mixin = null; + this.mixins = Collections.emptySet(); this.methodMapper = null; } @@ -728,6 +786,7 @@ public final class ClassInfo { this.access = classNode.access; this.isMixin = classNode instanceof MixinClassNode; this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null; + this.mixins = this.isMixin ? Collections.emptySet() : new HashSet(); this.interfaces.addAll(classNode.interfaces); @@ -786,20 +845,44 @@ public final class ClassInfo { } this.mixins.add(mixin); } + + /** + * Add a mixin which has been applied to this class + */ + void addAppliedMixin(MixinInfo mixin) { + if (this.appliedMixins == null) { + this.appliedMixins = new HashSet(); + } + this.appliedMixins.add(mixin); + } /** * Get all mixins which target this class */ - public Set getMixins() { - return Collections.unmodifiableSet(this.mixins); + Set getMixins() { + return this.isMixin ? Collections.emptySet() : Collections.unmodifiableSet(this.mixins); } + /** + * Get all mixins which have been successfully applied to this class + */ + public Set getAppliedMixins() { + return this.appliedMixins != null ? Collections.unmodifiableSet(this.appliedMixins) : Collections.emptySet(); + } + /** * Get whether this class is a mixin */ public boolean isMixin() { return this.isMixin; } + + /** + * Get whether this class is loadable mixin + */ + public boolean isLoadable() { + return this.mixin != null && this.mixin.isLoadable(); + } /** * Get whether this class has ACC_PUBLIC @@ -877,6 +960,21 @@ public final class ClassInfo { return this.name.replace('/', '.'); } + /** + * Get the class name (simple name, java format) + */ + public String getSimpleName() { + int pos = this.name.lastIndexOf('/'); + return pos < 0 ? this.name : this.name.substring(pos + 1); + } + + /** + * Get the object type (ASM type) + */ + public org.objectweb.asm.Type getType() { + return org.objectweb.asm.Type.getObjectType(this.name); + } + /** * Get the superclass name (binary name) */ @@ -1276,6 +1374,18 @@ public final class ClassInfo { return this.findMethodInHierarchy(method.name, method.desc, searchType, Traversal.NONE); } + /** + * Finds the specified private or protected method in this class's hierarchy + * + * @param method Method to search for + * @param searchType Search strategy to use + * @param traversal Traversal type to allow during this lookup + * @return the method object or null if the method could not be resolved + */ + public Method findMethodInHierarchy(MethodNode method, SearchType searchType, Traversal traversal) { + return this.findMethodInHierarchy(method.name, method.desc, searchType, traversal, 0); + } + /** * Finds the specified private or protected method in this class's hierarchy * @@ -1288,6 +1398,19 @@ public final class ClassInfo { return this.findMethodInHierarchy(method.name, method.desc, searchType, Traversal.NONE, flags); } + /** + * Finds the specified private or protected method in this class's hierarchy + * + * @param method Method to search for + * @param searchType Search strategy to use + * @param traversal Traversal type to allow during this lookup + * @param flags search flags + * @return the method object or null if the method could not be resolved + */ + public Method findMethodInHierarchy(MethodNode method, SearchType searchType, Traversal traversal, int flags) { + return this.findMethodInHierarchy(method.name, method.desc, searchType, traversal, flags); + } + /** * Finds the specified public or protected method in this class's hierarchy * @@ -1476,7 +1599,7 @@ public final class ClassInfo { } } - if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces())) { + if (type == Type.METHOD && (this.isInterface || MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES))) { for (String implemented : this.interfaces) { ClassInfo iface = ClassInfo.forName(implemented); if (iface == null) { @@ -1661,7 +1784,7 @@ public final class ClassInfo { /** * Return a ClassInfo for the specified class name, fetches the ClassInfo - * from the cache where possible + * from the cache where possible. * * @param className Binary name of the class to look up * @return ClassInfo for the specified class name or null if the specified @@ -1688,24 +1811,87 @@ public final class ClassInfo { return info; } - + + /** + * Return a ClassInfo for the specified type descriptor, fetches the + * ClassInfo from the cache where possible. + * + * @param descriptor Internal descriptor of the type to inspect + * @param lookup Lookup type to use (literal/element) + * @return ClassInfo for the specified class name or null if the specified + * name cannot be resolved for some reason + */ + public static ClassInfo forDescriptor(String descriptor, TypeLookup lookup) { + org.objectweb.asm.Type type; + try { + type = org.objectweb.asm.Type.getObjectType(descriptor); + } catch (IllegalArgumentException ex) { + ClassInfo.logger.warn("Error resolving type from descriptor: {}", descriptor); + return null; + } + return ClassInfo.forType(type, lookup); + } + /** * Return a ClassInfo for the specified class type, fetches the ClassInfo * from the cache where possible and generates the class meta if not. * * @param type Type to look up + * @param lookup Lookup type to use (literal/element) * @return ClassInfo for the supplied type or null if the supplied type * cannot be found or is a primitive type */ - public static ClassInfo forType(org.spongepowered.asm.lib.Type type) { - if (type.getSort() == org.spongepowered.asm.lib.Type.ARRAY) { - return ClassInfo.forType(type.getElementType()); - } else if (type.getSort() < org.spongepowered.asm.lib.Type.ARRAY) { + public static ClassInfo forType(org.objectweb.asm.Type type, TypeLookup lookup) { + if (type.getSort() == org.objectweb.asm.Type.ARRAY) { + if (lookup == TypeLookup.ELEMENT_TYPE) { + return ClassInfo.forType(type.getElementType(), TypeLookup.ELEMENT_TYPE); + } + return ClassInfo.OBJECT; + } else if (type.getSort() < org.objectweb.asm.Type.ARRAY) { return null; } return ClassInfo.forName(type.getClassName().replace('.', '/')); } + /** + * Return a ClassInfo for the specified class name, but only if the class + * information already exists in the cache. This prevents class loads in the + * instance that a ClassInfo is only being retrieved for a class which + * should definitely have already been processed but will be missing in case + * of an error condition. + * + * @param className Binary name of the class to look up + * @return ClassInfo for the specified class name or null if the specified + * class does not have an entry in the cache + */ + public static ClassInfo fromCache(String className) { + return ClassInfo.cache.get(className.replace('.', '/')); + } + + /** + * Return a ClassInfo for the specified class type, but only if the class + * information already exists in the cache. This prevents class loads in the + * instance that a ClassInfo is only being retrieved for a class which + * should definitely have already been processed but will be missing in case + * of an error condition. + * + * @param type Type to look up + * @param lookup Lookup type to use (literal/element) + * @return ClassInfo for the supplied type or null if the supplied type + * does not have an entry in the cache + */ + public static ClassInfo fromCache(org.objectweb.asm.Type type, TypeLookup lookup) { + if (type.getSort() == org.objectweb.asm.Type.ARRAY) { + if (lookup == TypeLookup.ELEMENT_TYPE) { + return ClassInfo.fromCache(type.getElementType(), TypeLookup.ELEMENT_TYPE); + } + return ClassInfo.OBJECT; + } else if (type.getSort() < org.objectweb.asm.Type.ARRAY) { + return null; + } + return ClassInfo.fromCache(type.getClassName()); + } + /** * ASM logic applied via ClassInfo, returns first common superclass of * classes specified by type1 and type2. @@ -1729,12 +1915,12 @@ public final class ClassInfo { * @param type2 Second type * @return common superclass info */ - public static ClassInfo getCommonSuperClass(org.spongepowered.asm.lib.Type type1, org.spongepowered.asm.lib.Type type2) { + public static ClassInfo getCommonSuperClass(org.objectweb.asm.Type type1, org.objectweb.asm.Type type2) { if (type1 == null || type2 == null - || type1.getSort() != org.spongepowered.asm.lib.Type.OBJECT || type2.getSort() != org.spongepowered.asm.lib.Type.OBJECT) { + || type1.getSort() != org.objectweb.asm.Type.OBJECT || type2.getSort() != org.objectweb.asm.Type.OBJECT) { return ClassInfo.OBJECT; } - return ClassInfo.getCommonSuperClass(ClassInfo.forType(type1), ClassInfo.forType(type2)); + return ClassInfo.getCommonSuperClass(ClassInfo.forType(type1, TypeLookup.DECLARED_TYPE), ClassInfo.forType(type2, TypeLookup.DECLARED_TYPE)); } /** @@ -1772,12 +1958,13 @@ public final class ClassInfo { * @param type2 Second type * @return common superclass info */ - public static ClassInfo getCommonSuperClassOrInterface(org.spongepowered.asm.lib.Type type1, org.spongepowered.asm.lib.Type type2) { + public static ClassInfo getCommonSuperClassOrInterface(org.objectweb.asm.Type type1, org.objectweb.asm.Type type2) { if (type1 == null || type2 == null - || type1.getSort() != org.spongepowered.asm.lib.Type.OBJECT || type2.getSort() != org.spongepowered.asm.lib.Type.OBJECT) { + || type1.getSort() != org.objectweb.asm.Type.OBJECT || type2.getSort() != org.objectweb.asm.Type.OBJECT) { return ClassInfo.OBJECT; } - return ClassInfo.getCommonSuperClassOrInterface(ClassInfo.forType(type1), ClassInfo.forType(type2)); + return ClassInfo.getCommonSuperClassOrInterface(ClassInfo.forType(type1, TypeLookup.DECLARED_TYPE), + ClassInfo.forType(type2, TypeLookup.DECLARED_TYPE)); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/DefaultExtensions.java b/src/main/java/org/spongepowered/asm/mixin/transformer/DefaultExtensions.java new file mode 100644 index 00000000..1589715c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/DefaultExtensions.java @@ -0,0 +1,60 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator; +import org.spongepowered.asm.mixin.transformer.ext.Extensions; +import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckClass; +import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckInterfaces; +import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExporter; +import org.spongepowered.asm.service.ISyntheticClassInfo; +import org.spongepowered.asm.util.IConsumer; + +/** + * Default extensions for mixin processor + */ +final class DefaultExtensions { + + private DefaultExtensions() { + } + + static void create(final MixinEnvironment environment, final Extensions extensions, final SyntheticClassRegistry registry) { + IConsumer registryDelegate = new IConsumer() { + @Override + public void accept(ISyntheticClassInfo item) { + registry.registerSyntheticClass(item); + } + }; + + extensions.add(new ArgsClassGenerator(registryDelegate)); + extensions.add(new InnerClassGenerator(registryDelegate)); + + extensions.add(new ExtensionClassExporter(environment)); + extensions.add(new ExtensionCheckClass()); + extensions.add(new ExtensionCheckInterfaces()); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java new file mode 100644 index 00000000..183190c7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/IMixinTransformer.java @@ -0,0 +1,76 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.List; + +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry; +import org.spongepowered.asm.service.ILegacyClassTransformer; + +/** + * Transformation engine + */ +public interface IMixinTransformer { + + /** + * Force-load all classes targetted by mixins but not yet applied + * + * @param environment current environment + */ + public abstract void audit(MixinEnvironment environment); + + /** + * Update a mixin class with new bytecode. + * + * @param mixinClass Name of the mixin + * @param classNode New bytecode + * @return List of classes that need to be updated + */ + public abstract List reload(String mixinClass, ClassNode classNode); + + /** + * Callback from the hotswap agent and LaunchWrapper Proxy, transform class + * bytecode. This method delegates to class generation or class + * transformation based on whether the supplied byte array is null + * and is therefore suitable for hosts which follow the LaunchWrapper + * contract. + * + * @param name Class name + * @param transformedName Transformed class name + * @param basicClass class bytecode + * @return transformed class bytecode + * + * @see ILegacyClassTransformer#transformClassBytes(String, String, byte[]) + */ + public abstract byte[] transformClassBytes(String name, String transformedName, byte[] basicClass); + + /** + * Get the transformer extensions + */ + public abstract IExtensionRegistry getExtensions(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java index 8f0e1d74..84a2d787 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InnerClassGenerator.java @@ -31,18 +31,19 @@ import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.AnnotationVisitor; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.ClassVisitor; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.commons.Remapper; -import org.spongepowered.asm.lib.commons.ClassRemapper; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.commons.Remapper; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.commons.ClassRemapper; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.service.ISyntheticClassInfo; import org.spongepowered.asm.service.MixinService; -import org.spongepowered.asm.transformers.MixinClassWriter; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.IConsumer; /** * Class generator which creates unique copies of inner classes within mixins @@ -54,10 +55,15 @@ final class InnerClassGenerator implements IClassGenerator { * Information about an inner class instance. Implements {@link Remapper} so * that it can participate in the remapping process. */ - static class InnerClassInfo extends Remapper { + static class InnerClassInfo extends Remapper implements ISyntheticClassInfo { /** - * Generated class name + * Mixin which provides this class + */ + private final IMixinInfo mixin; + + /** + * Class name (internal name) */ private final String name; @@ -85,8 +91,14 @@ final class InnerClassGenerator implements IClassGenerator { * Name of the target class (class ref) */ private final String targetName; + + /** + * Number of times this inner class has been generated + */ + private int loadCounter; - InnerClassInfo(String name, String originalName, MixinInfo owner, MixinTargetContext target) { + InnerClassInfo(IMixinInfo mixin, String name, String originalName, MixinInfo owner, MixinTargetContext target) { + this.mixin = mixin; this.name = name; this.originalName = originalName; this.owner = owner; @@ -95,10 +107,26 @@ final class InnerClassGenerator implements IClassGenerator { this.targetName = target.getTargetClassRef(); } - String getName() { + @Override + public IMixinInfo getMixin() { + return this.mixin; + } + + @Override + public boolean isLoaded() { + return this.loadCounter > 0; + } + + @Override + public String getName() { return this.name; } + @Override + public String getClassName() { + return this.name.replace('/', '.'); + } + String getOriginalName() { return this.originalName; } @@ -119,8 +147,10 @@ final class InnerClassGenerator implements IClassGenerator { return this.targetName; } - byte[] getClassBytes() throws ClassNotFoundException, IOException { - return MixinService.getService().getBytecodeProvider().getClassBytes(this.originalName, true); + void accept(final ClassVisitor classVisitor) throws ClassNotFoundException, IOException { + ClassNode classNode = MixinService.getService().getBytecodeProvider().getClassNode(this.originalName); + classNode.accept(classVisitor); + this.loadCounter++; } /** @@ -139,7 +169,7 @@ final class InnerClassGenerator implements IClassGenerator { } /* (non-Javadoc) - * @see org.spongepowered.asm.lib.commons.Remapper#map(java.lang.String) + * @see org.objectweb.asm.commons.Remapper#map(java.lang.String) */ @Override public String map(String key) { @@ -170,12 +200,12 @@ final class InnerClassGenerator implements IClassGenerator { private final InnerClassInfo info; public InnerClassAdapter(ClassVisitor cv, InnerClassInfo info) { - super(Opcodes.ASM5, cv, info); + super(Bytecode.ASM_API_VERSION, cv, info); this.info = info; } /* (non-Javadoc) - * @see org.spongepowered.asm.lib.ClassVisitor + * @see org.objectweb.asm.ClassVisitor * #visitSource(java.lang.String, java.lang.String) */ @Override @@ -188,7 +218,7 @@ final class InnerClassGenerator implements IClassGenerator { } /* (non-Javadoc) - * @see org.spongepowered.asm.lib.commons.RemappingClassAdapter + * @see org.objectweb.asm.commons.RemappingClassAdapter * #visitInnerClass(java.lang.String, java.lang.String, * java.lang.String, int) */ @@ -209,6 +239,11 @@ final class InnerClassGenerator implements IClassGenerator { */ private static final Logger logger = LogManager.getLogger("mixin"); + /** + * Synthetic class registry + */ + private final IConsumer registry; + /** * Mapping of target class context ids to generated inner class names, used * so we don't accidentally conform the same class twice. @@ -219,6 +254,15 @@ final class InnerClassGenerator implements IClassGenerator { * Mapping of generated class names to the respective inner class info */ private final Map innerClasses = new HashMap(); + + /** + * Ctor + * + * @param registry sythetic class registry + */ + public InnerClassGenerator(IConsumer registry) { + this.registry = registry; + } /** * @param owner Mixin which owns the original inner class @@ -231,8 +275,10 @@ final class InnerClassGenerator implements IClassGenerator { String ref = this.innerClassNames.get(id); if (ref == null) { ref = InnerClassGenerator.getUniqueReference(originalName, context); + InnerClassInfo info = new InnerClassInfo(owner, ref, originalName, owner, context); this.innerClassNames.put(id, ref); - this.innerClasses.put(ref, new InnerClassInfo(ref, originalName, owner, context)); + this.innerClasses.put(ref, info); + this.registry.accept(info); InnerClassGenerator.logger.debug("Inner class {} in {} on {} gets unique name {}", originalName, owner.getClassRef(), context.getTargetClassRef(), ref); } @@ -240,17 +286,17 @@ final class InnerClassGenerator implements IClassGenerator { } /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.transformer.IClassGenerator - * #generate(java.lang.String) + * @see org.spongepowered.asm.mixin.transformer.ext.IClassGenerator + * #generate(java.lang.String, org.objectweb.asm.tree.ClassNode) */ @Override - public byte[] generate(String name) { + public boolean generate(String name, ClassNode classNode) { String ref = name.replace('.', '/'); InnerClassInfo info = this.innerClasses.get(ref); - if (info != null) { - return this.generate(info); + if (info == null) { + return false; } - return null; + return this.generate(info, classNode); } /** @@ -258,22 +304,20 @@ final class InnerClassGenerator implements IClassGenerator { * and remapping it against the target class. * * @param info inner class info to process - * @return generated class or null if generation failed + * @return true if class was generated successfully */ - private byte[] generate(InnerClassInfo info) { + private boolean generate(InnerClassInfo info, ClassNode classNode) { try { InnerClassGenerator.logger.debug("Generating mapped inner class {} (originally {})", info.getName(), info.getOriginalName()); - ClassReader cr = new ClassReader(info.getClassBytes()); - ClassWriter cw = new MixinClassWriter(cr, 0); - cr.accept(new InnerClassAdapter(cw, info), ClassReader.EXPAND_FRAMES); - return cw.toByteArray(); + info.accept(new InnerClassAdapter(classNode, info)); + return true; } catch (InvalidMixinException ex) { throw ex; } catch (Exception ex) { InnerClassGenerator.logger.catching(ex); } - return null; + return false; } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java index 70f5c0fc..5e567f3f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/InterfaceInfo.java @@ -27,10 +27,10 @@ package org.spongepowered.asm.mixin.transformer; import java.util.HashSet; import java.util.Set; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Interface; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java index 0983e6b3..55baab6d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MethodMapper.java @@ -31,7 +31,8 @@ import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; @@ -60,6 +61,11 @@ public class MethodMapper { private final ClassInfo info; + /** + * Unique method and field indices for *this* class + */ + private int nextUniqueMethodIndex, nextUniqueFieldIndex; + public MethodMapper(MixinEnvironment env, ClassInfo info) { this.info = info; } @@ -90,7 +96,7 @@ public class MethodMapper { } String handlerName = this.getHandlerName((MixinMethodNode)handler); - handler.name = method.renameTo(handlerName); + handler.name = method.conform(handlerName); } /** @@ -103,7 +109,34 @@ public class MethodMapper { String prefix = InjectionInfo.getInjectorPrefix(method.getInjectorAnnotation()); String classUID = MethodMapper.getClassUID(method.getOwner().getClassRef()); String methodUID = MethodMapper.getMethodUID(method.name, method.desc, !method.isSurrogate()); - return String.format("%s$%s$%s%s", prefix, method.name, classUID, methodUID); + return String.format("%s$%s%s$%s", prefix, classUID, methodUID, method.name); + } + + /** + * Get a unique name for a method + * + * @param method Method to obtain a unique name for + * @param sessionId Session ID, for uniqueness + * @param preservePrefix If true, appends the unique part, preserving any + * method name prefix + * @return Unique method name + */ + public String getUniqueName(MethodNode method, String sessionId, boolean preservePrefix) { + String uniqueIndex = Integer.toHexString(this.nextUniqueMethodIndex++); + String pattern = preservePrefix ? "%2$s_$md$%1$s$%3$s" : "md%s$%s$%s"; + return String.format(pattern, sessionId.substring(30), method.name, uniqueIndex); + } + + /** + * Get a unique name for a field + * + * @param field Field to obtain a unique name for + * @param sessionId Session ID, for uniqueness + * @return Unique field name + */ + public String getUniqueName(FieldNode field, String sessionId) { + String uniqueIndex = Integer.toHexString(this.nextUniqueFieldIndex++); + return String.format("fd%s$%s$%s", sessionId.substring(30), field.name, uniqueIndex); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java index 1f11f64c..0d7987a6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorInterface.java @@ -26,8 +26,8 @@ package org.spongepowered.asm.mixin.transformer; import java.util.Map.Entry; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index 4d949b95..c1f8f540 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -25,41 +25,38 @@ package org.spongepowered.asm.mixin.transformer; import java.lang.annotation.Annotation; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; -import java.util.SortedSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Label; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.signature.SignatureReader; -import org.spongepowered.asm.lib.signature.SignatureVisitor; -import org.spongepowered.asm.lib.tree.*; +import org.objectweb.asm.Label; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.signature.SignatureReader; +import org.objectweb.asm.signature.SignatureVisitor; +import org.objectweb.asm.tree.*; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.gen.Accessor; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.throwables.MixinError; +import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExporter; import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinApplicatorException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; @@ -234,11 +231,21 @@ class MixinApplicatorStandard { */ protected final ClassNode targetClass; + /** + * Target class info + */ + protected final ClassInfo targetClassInfo; + /** * Profiler */ protected final Profiler profiler = MixinEnvironment.getProfiler(); + /** + * Activity tracker + */ + protected final ActivityStack activities = new ActivityStack(); + /** * Flag to track whether signatures from applied mixins should be merged * into target classes. This is only true when the runtime decompiler is @@ -251,6 +258,7 @@ class MixinApplicatorStandard { this.context = context; this.targetName = context.getClassName(); this.targetClass = context.getClassNode(); + this.targetClassInfo = context.getClassInfo(); ExtensionClassExporter exporter = context.getExtensions().getExtension(ExtensionClassExporter.class); this.mergeSignatures = exporter.isDecompilerActive() @@ -260,7 +268,7 @@ class MixinApplicatorStandard { /** * Apply supplied mixins to the target class */ - void apply(SortedSet mixins) { + final void apply(SortedSet mixins) { List mixinContexts = new ArrayList(); for (MixinInfo mixin : mixins) { @@ -270,27 +278,41 @@ class MixinApplicatorStandard { MixinTargetContext current = null; + this.activities.clear(); try { + Activity activity = this.activities.begin("PreApply Phase"); + Activity preApplyActivity = this.activities.begin("Mixin"); for (MixinTargetContext context : mixinContexts) { + preApplyActivity.next(context.toString()); (current = context).preApply(this.targetName, this.targetClass); } + preApplyActivity.end(); for (ApplicatorPass pass : ApplicatorPass.values()) { - Section timer = this.profiler.begin("pass", pass.name().toLowerCase()); + 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); } + applyActivity.end(); timer.end(); } + 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); } + activity.end(); } catch (InvalidMixinException ex) { + ex.prepend(this.activities); throw ex; } catch (Exception ex) { - throw new InvalidMixinException(current, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst applying the mixin class: " - + ex.getMessage(), ex); + throw new MixinApplicatorException(current, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst applying the mixin class:", ex, + this.activities); } this.applySourceMap(this.context); @@ -298,28 +320,39 @@ class MixinApplicatorStandard { } /** - * Apply the mixin described by mixin to the supplied classNode + * Apply the mixin described by mixin to the supplied ClassNode * * @param mixin Mixin to apply */ protected final void applyMixin(MixinTargetContext mixin, ApplicatorPass pass) { + Activity activity = this.activities.begin("Apply"); switch (pass) { case MAIN: + activity.next("Apply Signature"); this.applySignature(mixin); + activity.next("Apply Interfaces"); this.applyInterfaces(mixin); + activity.next("Apply Attributess"); this.applyAttributes(mixin); + activity.next("Apply Annotations"); this.applyAnnotations(mixin); + activity.next("Apply Fields"); this.applyFields(mixin); + activity.next("Apply Methods"); this.applyMethods(mixin); + activity.next("Apply Initialisers"); this.applyInitialisers(mixin); break; case PREINJECT: + activity.next("Prepare Injections"); this.prepareInjections(mixin); break; case INJECT: + activity.next("Apply Accessors"); this.applyAccessors(mixin); + activity.next("Apply Injections"); this.applyInjections(mixin); break; @@ -327,6 +360,7 @@ class MixinApplicatorStandard { // wat? throw new IllegalStateException("Invalid pass specified " + pass); } + activity.end(); } protected void applySignature(MixinTargetContext mixin) { @@ -344,7 +378,7 @@ class MixinApplicatorStandard { for (String interfaceName : mixin.getInterfaces()) { if (!this.targetClass.interfaces.contains(interfaceName)) { this.targetClass.interfaces.add(interfaceName); - mixin.getTargetClassInfo().addInterface(interfaceName); + this.targetClassInfo.addInterface(interfaceName); } } } @@ -368,7 +402,7 @@ class MixinApplicatorStandard { */ protected void applyAnnotations(MixinTargetContext mixin) { ClassNode sourceClass = mixin.getClassNode(); - Bytecode.mergeAnnotations(sourceClass, this.targetClass); + Annotations.merge(sourceClass, this.targetClass); } /** @@ -389,7 +423,7 @@ class MixinApplicatorStandard { FieldNode shadow = entry.getKey(); FieldNode target = this.findTargetField(shadow); if (target != null) { - Bytecode.mergeAnnotations(shadow, target); + Annotations.merge(shadow, target); // Strip the FINAL flag from @Mutable non-private fields if (entry.getValue().isDecoratedMutable() && !Bytecode.hasFlag(target, Opcodes.ACC_PRIVATE)) { @@ -425,19 +459,23 @@ class MixinApplicatorStandard { * @param mixin mixin target context */ protected void applyMethods(MixinTargetContext mixin) { + Activity activity = this.activities.begin("?"); for (MethodNode shadow : mixin.getShadowMethods()) { + activity.next("@Shadow %s:%s", shadow.desc, shadow.name); this.applyShadowMethod(mixin, shadow); } for (MethodNode mixinMethod : mixin.getMethods()) { + activity.next("%s:%s", mixinMethod.desc, mixinMethod.name); this.applyNormalMethod(mixin, mixinMethod); } + activity.end(); } protected void applyShadowMethod(MixinTargetContext mixin, MethodNode shadow) { MethodNode target = this.findTargetMethod(shadow); if (target != null) { - Bytecode.mergeAnnotations(shadow, target); + Annotations.merge(shadow, target); } } @@ -451,7 +489,9 @@ class MixinApplicatorStandard { this.mergeMethod(mixin, mixinMethod); } else if (Constants.CLINIT.equals(mixinMethod.name)) { // Class initialiser insns get appended + Activity activity = this.activities.begin("Merge CLINIT insns"); this.appendInsns(mixin, mixinMethod); + activity.end(); } } @@ -515,6 +555,7 @@ class MixinApplicatorStandard { * @param target target method being checked * @return true if the target was already merged and should be skipped */ + @SuppressWarnings("unchecked") protected boolean isAlreadyMerged(MixinTargetContext mixin, MethodNode method, boolean isOverwrite, MethodNode target) { AnnotationNode merged = Annotations.getVisible(target, MixinMerged.class); if (merged == null) { @@ -542,6 +583,24 @@ class MixinApplicatorStandard { String owner = Annotations.getValue(merged, "mixin"); int priority = Annotations.getValue(merged, "priority"); + AnnotationNode accMethod = Annotations.getSingleVisible(method, Accessor.class, Invoker.class); + if (accMethod != null) { + AnnotationNode accTarget = Annotations.getSingleVisible(target, Accessor.class, Invoker.class); + if (accTarget != null) { + String myTarget = Annotations.getValue(accMethod, "target"); + String trTarget = Annotations.getValue(accTarget, "target"); + if (myTarget == null) { + throw new MixinError("Encountered undecorated Accessor method in " + mixin + " applying to " + this.targetName); + } + if (myTarget.equals(trTarget)) { + // This is fine, the accessors overlap + return true; + } + throw new InvalidMixinException(mixin, String.format("Incompatible @%s %s (for %s) in %s previously written by %s (for %s)", + Bytecode.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget)); + } + } + if (priority >= mixin.getPriority() && !owner.equals(mixin.getClassName())) { this.logger.warn("Method overwrite conflict for {} in {}, previously written by {}. Skipping method.", method.name, mixin, owner); return true; @@ -658,7 +717,7 @@ class MixinApplicatorStandard { this.targetClass.methods.add(method); } - + /** * (Attempts to) find and patch field initialisers from the mixin into the * target class @@ -816,7 +875,7 @@ class MixinApplicatorStandard { // At the moment I don't handle any transient locals because I haven't seen any in the wild, but let's avoid writing // code which will likely break things and fix it if a real test case ever appears throw new InvalidMixinException(mixin, "Cannot handle " + Bytecode.getOpcodeName(opcode) + " opcode (0x" - + Integer.toHexString(opcode).toUpperCase() + ") in class initialiser"); + + Integer.toHexString(opcode).toUpperCase(Locale.ROOT) + ") in class initialiser"); } } @@ -884,8 +943,8 @@ class MixinApplicatorStandard { } InitialiserInjectionMode mode = this.getInitialiserInjectionMode(mixin.getEnvironment()); - String targetName = mixin.getTargetClassInfo().getName(); - String targetSuperName = mixin.getTargetClassInfo().getSuperName(); + String targetName = this.targetClassInfo.getName(); + String targetSuperName = this.targetClassInfo.getSuperName(); AbstractInsnNode targetInsn = null; for (Iterator iter = ctor.instructions.iterator(); iter.hasNext();) { @@ -915,7 +974,7 @@ class MixinApplicatorStandard { return InitialiserInjectionMode.DEFAULT; } try { - return InitialiserInjectionMode.valueOf(strMode.toUpperCase()); + return InitialiserInjectionMode.valueOf(strMode.toUpperCase(Locale.ROOT)); } catch (Exception ex) { this.logger.warn("Could not parse unexpected value \"{}\" for mixin.initialiserInjectionMode, reverting to DEFAULT", strMode); return InitialiserInjectionMode.DEFAULT; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java new file mode 100644 index 00000000..30f3c28a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java @@ -0,0 +1,78 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.Locale; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.transformer.ext.Extensions; +import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; + +/** + * Handles delegation of class generation tasks to the extensions + */ +public class MixinClassGenerator { + + /** + * Log things for stuff + */ + static final Logger logger = LogManager.getLogger("mixin"); + + private final Extensions extensions; + private final Profiler profiler; + + /** + * ctor + */ + MixinClassGenerator(MixinEnvironment environment, Extensions extensions) { + this.extensions = extensions; + this.profiler = MixinEnvironment.getProfiler(); + } + + synchronized boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode) { + if (name == null) { + MixinClassGenerator.logger.warn("MixinClassGenerator tried to generate a class with no name!"); + return false; + } + + for (IClassGenerator generator : this.extensions.getGenerators()) { + Section genTimer = this.profiler.begin("generator", generator.getClass().getSimpleName().toLowerCase(Locale.ROOT)); + boolean success = generator.generate(name, classNode); + genTimer.end(); + if (success) { + this.extensions.export(environment, name.replace('.', '/'), false, classNode); + return true; + } + } + + return false; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index ad7a9e4c..095e20dd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -26,15 +26,7 @@ package org.spongepowered.asm.mixin.transformer; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -42,7 +34,7 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.launch.MixinInitialisationError; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Option; @@ -139,7 +131,7 @@ final class MixinConfig implements Comparable, IMixinConfig { public abstract void onInit(MixinInfo mixin); } - + /** * Global order of mixin configs, used to determine ordering between configs * with equivalent priority @@ -328,7 +320,7 @@ final class MixinConfig implements Comparable, IMixinConfig { /** * Config plugin, if supplied */ - private transient IMixinConfigPlugin plugin; + private transient PluginHandle plugin; /** * Reference mapper for injectors @@ -448,7 +440,7 @@ final class MixinConfig implements Comparable, IMixinConfig { } if (this.mixinPriority < 0) { - this.priority = defaultMixinPriority; + this.mixinPriority = defaultMixinPriority; } } @@ -469,7 +461,7 @@ final class MixinConfig implements Comparable, IMixinConfig { return; } - CompatibilityLevel level = CompatibilityLevel.valueOf(this.compatibility.trim().toUpperCase()); + CompatibilityLevel level = CompatibilityLevel.valueOf(this.compatibility.trim().toUpperCase(Locale.ROOT)); CompatibilityLevel current = MixinEnvironment.getCompatibilityLevel(); if (level == current) { @@ -573,19 +565,8 @@ final class MixinConfig implements Comparable, IMixinConfig { * Initialise the config once it's selected */ void onSelect() { - if (this.pluginClassName != null) { - try { - Class pluginClass = this.service.getClassProvider().findClass(this.pluginClassName, true); - this.plugin = (IMixinConfigPlugin)pluginClass.newInstance(); - - if (this.plugin != null) { - this.plugin.onLoad(this.mixinPackage); - } - } catch (Throwable th) { - th.printStackTrace(); - this.plugin = null; - } - } + this.plugin = new PluginHandle(this, this.service, this.pluginClassName); + this.plugin.onLoad(this.mixinPackage); if (!this.mixinPackage.endsWith(".")) { this.mixinPackage += "."; @@ -594,9 +575,7 @@ final class MixinConfig implements Comparable, IMixinConfig { boolean suppressRefMapWarning = false; if (this.refMapperConfig == null) { - if (this.plugin != null) { - this.refMapperConfig = this.plugin.getRefMapperConfig(); - } + this.refMapperConfig = this.plugin.getRefMapperConfig(); if (this.refMapperConfig == null) { suppressRefMapWarning = true; @@ -703,7 +682,7 @@ final class MixinConfig implements Comparable, IMixinConfig { MixinInfo mixin = null; try { - mixin = new MixinInfo(this.service, this, mixinClass, true, this.plugin, suppressPlugin); + mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, suppressPlugin); if (mixin.getTargetClasses().size() > 0) { MixinConfig.globalMixinList.add(fqMixinClass); for (String targetClass : mixin.getTargetClasses()) { @@ -917,7 +896,7 @@ final class MixinConfig implements Comparable, IMixinConfig { */ @Override public IMixinConfigPlugin getPlugin() { - return this.plugin; + return this.plugin.get(); } /* (non-Javadoc) @@ -987,14 +966,14 @@ final class MixinConfig implements Comparable, IMixinConfig { * Updates a mixin with new bytecode * * @param mixinClass Name of the mixin class - * @param bytes New bytecode + * @param classNode New class * @return List of classes that need to be updated */ - public List reloadMixin(String mixinClass, byte[] bytes) { + public List reloadMixin(String mixinClass, ClassNode classNode) { for (Iterator iter = this.mixins.iterator(); iter.hasNext();) { MixinInfo mixin = iter.next(); if (mixin.getClassName().equals(mixinClass)) { - mixin.reloadMixin(bytes); + mixin.reloadMixin(classNode); return mixin.getTargetClasses(); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index 49d0f146..942e107d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -36,18 +36,19 @@ import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.MethodVisitor; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.InnerClassNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.InnerClassNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.Overwrite; @@ -55,7 +56,6 @@ import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.extensibility.IMixinConfig; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.injection.Surrogate; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; @@ -87,7 +87,7 @@ class MixinInfo implements Comparable, IMixinInfo { private final String originalName; public MixinMethodNode(int access, String name, String desc, String signature, String[] exceptions) { - super(Opcodes.ASM5, access, name, desc, signature, exceptions); + super(Bytecode.ASM_API_VERSION, access, name, desc, signature, exceptions); this.originalName = name; } @@ -133,20 +133,24 @@ class MixinInfo implements Comparable, IMixinInfo { public final List mixinMethods; - public MixinClassNode(MixinInfo mixin) { - this(Opcodes.ASM5); + MixinClassNode(MixinInfo mixin) { + this(Bytecode.ASM_API_VERSION); } - + @SuppressWarnings("unchecked") - public MixinClassNode(int api) { + protected MixinClassNode(int api) { super(api); this.mixinMethods = (List)(Object)this.methods; } - + public MixinInfo getMixin() { return MixinInfo.this; } + public List getFields() { + return new ArrayList(this.fields); + } + @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { MethodNode method = new MixinMethodNode(access, name, desc, signature, exceptions); @@ -162,10 +166,10 @@ class MixinInfo implements Comparable, IMixinInfo { class State { /** - * Mixin bytes (read once, generate tree on demand) + * Initial ClassNode passed in to the creation of this state object */ - private byte[] mixinBytes; - + private final ClassNode classNode; + /** * Mixin ClassInfo */ @@ -202,43 +206,46 @@ class MixinInfo implements Comparable, IMixinInfo { * Non-synthetic inner classes */ protected final Set innerClasses = new HashSet(); - + /** * Initial ClassNode created for mixin validation, not used for actual * application */ - protected MixinClassNode classNode; + protected MixinClassNode validationClassNode; - State(byte[] mixinBytes) { - this(mixinBytes, null); + State(ClassNode classNode) { + this(classNode, null); } - State(byte[] mixinBytes, ClassInfo classInfo) { - this.mixinBytes = mixinBytes; + State(ClassNode classNode, ClassInfo classInfo) { + this.classNode = classNode; this.connect(); - this.classInfo = classInfo != null ? classInfo : ClassInfo.fromClassNode(this.getClassNode()); + this.classInfo = classInfo != null ? classInfo : ClassInfo.fromClassNode(this.getValidationClassNode()); } - private void connect() { - this.classNode = this.createClassNode(0); + protected void connect() { + this.validationClassNode = this.createClassNode(0); } - private void complete() { - this.classNode = null; + protected void complete() { + this.validationClassNode = null; } ClassInfo getClassInfo() { return this.classInfo; } - - byte[] getClassBytes() { - return this.mixinBytes; - } - MixinClassNode getClassNode() { + ClassNode getClassNode() { return this.classNode; } + MixinClassNode getValidationClassNode() { + if (this.validationClassNode == null) { + throw new IllegalStateException("Attempted a validation task after validation is complete on " + this + " in " + MixinInfo.this); + } + return this.validationClassNode; + } + boolean isDetachedSuper() { return this.detachedSuper; } @@ -270,10 +277,9 @@ class MixinInfo implements Comparable, IMixinInfo { * @return Tree representing the bytecode */ MixinClassNode createClassNode(int flags) { - MixinClassNode classNode = new MixinClassNode(MixinInfo.this); - ClassReader classReader = new ClassReader(this.mixinBytes); - classReader.accept(classNode, flags); - return classNode; + MixinClassNode mixinClassNode = new MixinClassNode(MixinInfo.this); + this.classNode.accept(mixinClassNode); + return mixinClassNode; } /** @@ -283,7 +289,8 @@ class MixinInfo implements Comparable, IMixinInfo { * @param targetClasses Mixin's target classes */ void validate(SubType type, List targetClasses) { - MixinPreProcessorStandard preProcessor = type.createPreProcessor(this.getClassNode()).prepare(); + MixinClassNode classNode = this.getValidationClassNode(); + MixinPreProcessorStandard preProcessor = type.createPreProcessor(classNode).prepare(); for (ClassInfo target : targetClasses) { preProcessor.conform(target); } @@ -291,7 +298,7 @@ class MixinInfo implements Comparable, IMixinInfo { type.validate(this, targetClasses); this.detachedSuper = type.isDetachedSuper(); - this.unique = Annotations.getVisible(this.getClassNode(), Unique.class) != null; + this.unique = Annotations.getVisible(classNode, Unique.class) != null; // Pre-flight checks this.validateInner(); @@ -317,26 +324,26 @@ class MixinInfo implements Comparable, IMixinInfo { } private void validateClassVersion() { - if (this.classNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) { + if (this.validationClassNode.version > MixinEnvironment.getCompatibilityLevel().classVersion()) { String helpText = "."; for (CompatibilityLevel level : CompatibilityLevel.values()) { - if (level.classVersion() >= this.classNode.version) { + if (level.classVersion() >= this.validationClassNode.version) { helpText = String.format(". Mixin requires compatibility level %s or above.", level.name()); } } - throw new InvalidMixinException(MixinInfo.this, "Unsupported mixin class version " + this.classNode.version + helpText); + throw new InvalidMixinException(MixinInfo.this, "Unsupported mixin class version " + this.validationClassNode.version + helpText); } } private void validateRemappables(List targetClasses) { // Can't have remappable fields or methods on a multi-target mixin, because after obfuscation the fields will remap to conflicting names if (targetClasses.size() > 1) { - for (FieldNode field : this.classNode.fields) { + for (FieldNode field : this.validationClassNode.fields) { this.validateRemappable(Shadow.class, field.name, Annotations.getVisible(field, Shadow.class)); } - for (MethodNode method : this.classNode.methods) { + for (MethodNode method : this.validationClassNode.methods) { this.validateRemappable(Shadow.class, method.name, Annotations.getVisible(method, Shadow.class)); AnnotationNode overwrite = Annotations.getVisible(method, Overwrite.class); if (overwrite != null && ((method.access & Opcodes.ACC_STATIC) == 0 || (method.access & Opcodes.ACC_PUBLIC) == 0)) { @@ -357,10 +364,10 @@ class MixinInfo implements Comparable, IMixinInfo { * Read and process any {@link Implements} annotations on the mixin */ void readImplementations(SubType type) { - this.interfaces.addAll(this.classNode.interfaces); + this.interfaces.addAll(this.validationClassNode.interfaces); this.interfaces.addAll(type.getInterfaces()); - AnnotationNode implementsAnnotation = Annotations.getInvisible(this.classNode, Implements.class); + AnnotationNode implementsAnnotation = Annotations.getInvisible(this.validationClassNode, Implements.class); if (implementsAnnotation == null) { return; } @@ -387,10 +394,10 @@ class MixinInfo implements Comparable, IMixinInfo { * parent config. */ void readInnerClasses() { - for (InnerClassNode inner : this.classNode.innerClasses) { + for (InnerClassNode inner : this.validationClassNode.innerClasses) { ClassInfo innerClass = ClassInfo.forName(inner.name); if ((inner.outerName != null && inner.outerName.equals(this.classInfo.getName())) - || inner.name.startsWith(this.classNode.name + "$")) { + || inner.name.startsWith(this.validationClassNode.name + "$")) { if (innerClass.isProbablyStatic() && innerClass.isSynthetic()) { this.syntheticInnerClasses.add(inner.name); } else { @@ -401,7 +408,7 @@ class MixinInfo implements Comparable, IMixinInfo { } protected void validateChanges(SubType type, List targetClasses) { - type.createPreProcessor(this.classNode).prepare(); + type.createPreProcessor(this.validationClassNode).prepare(); } } @@ -415,8 +422,8 @@ class MixinInfo implements Comparable, IMixinInfo { */ private final State previous; - Reloaded(State previous, byte[] mixinBytes) { - super(mixinBytes, previous.getClassInfo()); + Reloaded(State previous, ClassNode classNode) { + super(classNode, previous.getClassInfo()); this.previous = previous; } @@ -435,11 +442,11 @@ class MixinInfo implements Comparable, IMixinInfo { if (!new HashSet(this.softImplements).equals(new HashSet(this.previous.softImplements))) { throw new MixinReloadException(MixinInfo.this, "Cannot change soft interfaces"); } - List targets = MixinInfo.this.readTargetClasses(this.classNode, true); + List targets = MixinInfo.this.readTargetClasses(this.validationClassNode, true); if (!new HashSet(targets).equals(new HashSet(targetClasses))) { throw new MixinReloadException(MixinInfo.this, "Cannot change target classes"); } - int priority = MixinInfo.this.readPriority(this.classNode); + int priority = MixinInfo.this.readPriority(this.validationClassNode); if (priority != MixinInfo.this.getPriority()) { throw new MixinReloadException(MixinInfo.this, "Cannot change mixin priority"); } @@ -531,7 +538,7 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validate(State state, List targetClasses) { - ClassNode classNode = state.getClassNode(); + ClassNode classNode = state.getValidationClassNode(); for (ClassInfo targetClass : targetClasses) { if (classNode.superName.equals(targetClass.getSuperName())) { @@ -576,11 +583,11 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validate(State state, List targetClasses) { - if (!MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces()) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { throw new InvalidMixinException(this.mixin, "Interface mixin not supported in current enviromnment"); } - ClassNode classNode = state.getClassNode(); + ClassNode classNode = state.getValidationClassNode(); if (!"java/lang/Object".equals(classNode.superName)) { throw new InvalidMixinException(this.mixin, "Super class of " + this + " is invalid, found " @@ -620,14 +627,14 @@ class MixinInfo implements Comparable, IMixinInfo { @Override void validateTarget(String targetName, ClassInfo targetInfo) { boolean targetIsInterface = targetInfo.isInterface(); - if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces()) { + if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { throw new InvalidMixinException(this.mixin, "Accessor mixin targetting an interface is not supported in current enviromnment"); } } @Override void validate(State state, List targetClasses) { - ClassNode classNode = state.getClassNode(); + ClassNode classNode = state.getValidationClassNode(); if (!"java/lang/Object".equals(classNode.superName)) { throw new InvalidMixinException(this.mixin, "Super class of " + this + " is invalid, found " @@ -731,7 +738,7 @@ class MixinInfo implements Comparable, IMixinInfo { /** * Configuration plugin */ - private final transient IMixinConfigPlugin plugin; + private final transient PluginHandle plugin; /** * The environment phase in which this mixin was initialised @@ -762,19 +769,17 @@ class MixinInfo implements Comparable, IMixinInfo { * Holds the current validated state */ private transient State state; - + /** * Internal ctor, called by {@link MixinConfig} * * @param parent configuration which owns this mixin, the parent * @param name name of this mixin (class name stub) - * @param runTransformers true if this mixin should run transformers on its - * bytecode when loading - * @param plugin mixin config companion plugin, may be null + * @param plugin mixin config companion plugin handle * @param suppressPlugin true to suppress the plugin from filtering targets * of this mixin */ - MixinInfo(IMixinService service, MixinConfig parent, String name, boolean runTransformers, IMixinConfigPlugin plugin, boolean suppressPlugin) { + MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean suppressPlugin) { this.service = service; this.parent = parent; this.name = name; @@ -785,8 +790,8 @@ class MixinInfo implements Comparable, IMixinInfo { // Read the class bytes and transform try { - byte[] mixinBytes = this.loadMixinClass(this.className, runTransformers); - this.pendingState = new State(mixinBytes); + ClassNode mixinClassNode = this.loadMixinClass(this.className); + this.pendingState = new State(mixinClassNode); this.info = this.pendingState.getClassInfo(); this.type = SubType.getTypeFor(this); } catch (InvalidMixinException ex) { @@ -805,8 +810,8 @@ class MixinInfo implements Comparable, IMixinInfo { // Read the class bytes and transform try { this.priority = this.readPriority(this.pendingState.getClassNode()); - this.virtual = this.readPseudo(this.pendingState.getClassNode()); - this.targetClasses = this.readTargetClasses(this.pendingState.getClassNode(), suppressPlugin); + this.virtual = this.readPseudo(this.pendingState.getValidationClassNode()); + this.targetClasses = this.readTargetClasses(this.pendingState.getValidationClassNode(), suppressPlugin); this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction())); } catch (InvalidMixinException ex) { throw ex; @@ -849,13 +854,13 @@ class MixinInfo implements Comparable, IMixinInfo { } List targets = new ArrayList(); - List publicTargets = Annotations.getValue(mixin, "value"); + List publicTargets = Annotations.getValue(mixin, "value"); List privateTargets = Annotations.getValue(mixin, "targets"); if (publicTargets != null) { - this.readTargets(targets, Lists.transform(publicTargets, new Function() { + this.readTargets(targets, Lists.transform(publicTargets, new Function() { @Override - public String apply(org.spongepowered.asm.lib.Type input) { + public String apply(org.objectweb.asm.Type input) { return input.getClassName(); } }), suppressPlugin, false); @@ -899,7 +904,7 @@ class MixinInfo implements Comparable, IMixinInfo { private boolean shouldApplyMixin(boolean suppressPlugin, String targetName) { Section pluginTimer = this.profiler.begin("plugin"); - boolean result = this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className); + boolean result = suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className); pluginTimer.end(); return result; } @@ -1024,7 +1029,8 @@ class MixinInfo implements Comparable, IMixinInfo { */ @Override public byte[] getClassBytes() { - return this.getState().getClassBytes(); +// return this.getState().getClassBytes(); + throw new RuntimeException("NO"); } /** @@ -1141,31 +1147,27 @@ class MixinInfo implements Comparable, IMixinInfo { MixinTargetContext createContextFor(TargetClassContext target) { MixinClassNode classNode = this.getClassNode(ClassReader.EXPAND_FRAMES); Section preTimer = this.profiler.begin("pre"); - MixinTargetContext preProcessor = this.type.createPreProcessor(classNode).prepare().createContextFor(target); + MixinTargetContext context = this.type.createPreProcessor(classNode).prepare().createContextFor(target); preTimer.end(); - return preProcessor; + return context; } /** * Load the mixin class bytes * * @param mixinClassName mixin class name - * @param runTransformers true to run transformers on the loaded bytecode * @return mixin bytecode * @throws ClassNotFoundException if the mixin bytes could not be found */ - private byte[] loadMixinClass(String mixinClassName, boolean runTransformers) throws ClassNotFoundException { - byte[] mixinBytes = null; + private ClassNode loadMixinClass(String mixinClassName) throws ClassNotFoundException { + ClassNode classNode = null; try { - if (runTransformers) { - String restrictions = this.service.getClassRestrictions(mixinClassName); - if (restrictions.length() > 0) { - this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName); - } + String restrictions = this.service.getClassRestrictions(mixinClassName); + if (restrictions.length() > 0) { + this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName); } - mixinBytes = this.service.getBytecodeProvider().getClassBytes(mixinClassName, runTransformers); - + classNode = this.service.getBytecodeProvider().getClassNode(mixinClassName, true); } catch (ClassNotFoundException ex) { throw new ClassNotFoundException(String.format("The specified mixin '%s' was not found", mixinClassName)); } catch (IOException ex) { @@ -1173,19 +1175,19 @@ class MixinInfo implements Comparable, IMixinInfo { throw new InvalidMixinException(this, "An error was encountered whilst loading the mixin class", ex); } - return mixinBytes; + return classNode; } /** * Updates this mixin with new bytecode * - * @param mixinBytes New bytecode + * @param classNode New bytecode */ - void reloadMixin(byte[] mixinBytes) { + void reloadMixin(ClassNode classNode) { if (this.pendingState != null) { throw new IllegalStateException("Cannot reload mixin while it is initialising"); } - this.pendingState = new Reloaded(this.state, mixinBytes); + this.pendingState = new Reloaded(this.state, classNode); this.validate(); } @@ -1207,10 +1209,13 @@ class MixinInfo implements Comparable, IMixinInfo { * Called immediately before the mixin is applied to targetClass */ public void preApply(String transformedName, ClassNode targetClass) { - if (this.plugin != null) { + if (this.plugin.isAvailable()) { Section pluginTimer = this.profiler.begin("plugin"); - this.plugin.preApply(transformedName, targetClass, this.className, this); - pluginTimer.end(); + try { + this.plugin.preApply(transformedName, targetClass, this.className, this); + } finally { + pluginTimer.end(); + } } } @@ -1218,15 +1223,19 @@ class MixinInfo implements Comparable, IMixinInfo { * Called immediately after the mixin is applied to targetClass */ public void postApply(String transformedName, ClassNode targetClass) { - if (this.plugin != null) { + if (this.plugin.isAvailable()) { Section pluginTimer = this.profiler.begin("plugin"); - this.plugin.postApply(transformedName, targetClass, this.className, this); - pluginTimer.end(); + try { + this.plugin.postApply(transformedName, targetClass, this.className, this); + } finally { + pluginTimer.end(); + } } this.parent.postApply(transformedName, targetClass); + this.info.addAppliedMixin(this); } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java index ddf99b35..8f3632d0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java @@ -26,31 +26,29 @@ package org.spongepowered.asm.mixin.transformer; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; import java.util.Set; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.ClassVisitor; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.FieldVisitor; -import org.spongepowered.asm.lib.MethodVisitor; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.InsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.FieldVisitor; +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.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; +import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel.LanguageFeature; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; +import org.spongepowered.asm.mixin.transformer.meta.MixinProxy; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; -import org.spongepowered.asm.transformers.MixinClassWriter; -import org.spongepowered.asm.transformers.TreeTransformer; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; /** @@ -58,7 +56,12 @@ import org.spongepowered.asm.util.Bytecode; * through the mixin transformer, such as transforming synthetic inner classes * and populating accessor methods in accessor mixins. */ -class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListener { +class MixinPostProcessor implements MixinConfig.IListener { + + /** + * Transformer session ID + */ + private final String sessionId; /** * Synthetic inner classes in mixins @@ -75,6 +78,10 @@ class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListene */ private final Set loadable = new HashSet(); + MixinPostProcessor(String sessionId) { + this.sessionId = sessionId; + } + @Override public void onInit(MixinInfo mixin) { for (String innerClass : mixin.getSyntheticInnerClasses()) { @@ -116,43 +123,23 @@ class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListene * @return True if the specified class name has been registered for post- * processing */ - boolean canTransform(String className) { + boolean canProcess(String className) { return this.syntheticInnerClasses.contains(className) || this.loadable.contains(className); } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.ILegacyClassTransformer#getName() - */ - @Override - public String getName() { - return this.getClass().getName(); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.ILegacyClassTransformer - * #isDelegationExcluded() - */ - @Override - public boolean isDelegationExcluded() { - return true; - } + public boolean processClass(String name, ClassNode classNode) { - /* (non-Javadoc) - * @see org.spongepowered.asm.service.ILegacyClassTransformer - * #transformClassBytes(java.lang.String, java.lang.String, byte[]) - */ - @Override - public byte[] transformClassBytes(String name, String transformedName, byte[] bytes) { - if (this.syntheticInnerClasses.contains(transformedName)) { - return this.processSyntheticInner(bytes); + if (this.syntheticInnerClasses.contains(name)) { + this.processSyntheticInner(classNode); + return true; } - if (this.accessorMixins.containsKey(transformedName)) { - MixinInfo mixin = this.accessorMixins.get(transformedName); - return this.processAccessor(bytes, mixin); + if (this.accessorMixins.containsKey(name)) { + MixinInfo mixin = this.accessorMixins.get(name); + return this.processAccessor(classNode, mixin); } - return bytes; + return false; } /** @@ -160,11 +147,8 @@ class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListene * members in the class into public so that they are accessible from their * new home in the target class */ - private byte[] processSyntheticInner(byte[] bytes) { - ClassReader cr = new ClassReader(bytes); - ClassWriter cw = new MixinClassWriter(cr, 0); - - ClassVisitor visibilityVisitor = new ClassVisitor(Opcodes.ASM5, cw) { + private void processSyntheticInner(ClassNode classNode) { + ClassVisitor visibilityVisitor = new ClassVisitor(Bytecode.ASM_API_VERSION, classNode) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { @@ -190,21 +174,19 @@ class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListene }; - cr.accept(visibilityVisitor, ClassReader.EXPAND_FRAMES); - return cw.toByteArray(); + classNode.accept(visibilityVisitor); } - private byte[] processAccessor(byte[] bytes, MixinInfo mixin) { - if (!MixinEnvironment.getCompatibilityLevel().isAtLeast(CompatibilityLevel.JAVA_8)) { - return bytes; + private boolean processAccessor(ClassNode classNode, MixinInfo mixin) { + if (!MixinEnvironment.getCompatibilityLevel().supports(LanguageFeature.METHODS_IN_INTERFACES)) { + return false; } boolean transformed = false; - MixinClassNode classNode = mixin.getClassNode(0); + MixinClassNode mixinClassNode = mixin.getClassNode(0); ClassInfo targetClass = mixin.getTargets().get(0); - for (Iterator iter = classNode.mixinMethods.iterator(); iter.hasNext();) { - MixinMethodNode methodNode = iter.next(); + for (MixinMethodNode methodNode : mixinClassNode.mixinMethods) { if (!Bytecode.hasFlag(methodNode, Opcodes.ACC_STATIC)) { continue; } @@ -212,32 +194,37 @@ class MixinPostProcessor extends TreeTransformer implements MixinConfig.IListene AnnotationNode accessor = methodNode.getVisibleAnnotation(Accessor.class); AnnotationNode invoker = methodNode.getVisibleAnnotation(Invoker.class); if (accessor != null || invoker != null) { - Method method = MixinPostProcessor.getAccessorMethod(mixin, methodNode, targetClass); + Method method = this.getAccessorMethod(mixin, methodNode, targetClass); MixinPostProcessor.createProxy(methodNode, targetClass, method); + Annotations.setVisible(methodNode, MixinProxy.class, "sessionId", this.sessionId); + classNode.methods.add(methodNode); transformed = true; } } - if (transformed) { - return this.writeClass(classNode); + if (!transformed) { + return false; } - return bytes; + Bytecode.replace(mixinClassNode, classNode); + return true; } - private static Method getAccessorMethod(MixinInfo mixin, MethodNode methodNode, ClassInfo targetClass) throws MixinTransformerError { + private Method getAccessorMethod(MixinInfo mixin, MethodNode methodNode, ClassInfo targetClass) throws MixinTransformerError { Method method = mixin.getClassInfo().findMethod(methodNode, ClassInfo.INCLUDE_ALL); // Normally the target will be renamed when the mixin is conformed to the target, if we get here // without this happening then we will end up invoking an undecorated method, which is bad! - if (!method.isRenamed()) { - throw new MixinTransformerError("Unexpected state: " + mixin + " loaded before " + targetClass + " was conformed"); + if (!method.isConformed()) { + String uniqueName = targetClass.getMethodMapper().getUniqueName(methodNode, this.sessionId, true); + method.conform(uniqueName); } return method; } private static void createProxy(MethodNode methodNode, ClassInfo targetClass, Method method) { + methodNode.access |= Opcodes.ACC_SYNTHETIC; methodNode.instructions.clear(); Type[] args = Type.getArgumentTypes(methodNode.desc); Type returnType = Type.getReturnType(methodNode.desc); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java index 25cd917c..2f54a5d8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorInterface.java @@ -24,9 +24,9 @@ */ package org.spongepowered.asm.mixin.transformer; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.FieldNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.FieldNode; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; @@ -51,7 +51,7 @@ class MixinPreProcessorInterface extends MixinPreProcessorStandard { /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.MixinPreProcessor - * #prepareMethod(org.spongepowered.asm.lib.tree.MethodNode, + * #prepareMethod(org.objectweb.asm.tree.MethodNode, * org.spongepowered.asm.mixin.transformer.ClassInfo.Method) */ @Override @@ -69,12 +69,12 @@ class MixinPreProcessorInterface extends MixinPreProcessorStandard { * @see org.spongepowered.asm.mixin.transformer.MixinPreProcessor * #validateField( * org.spongepowered.asm.mixin.transformer.MixinTargetContext, - * org.spongepowered.asm.lib.tree.FieldNode, - * org.spongepowered.asm.lib.tree.AnnotationNode) + * org.objectweb.asm.tree.FieldNode, + * org.objectweb.asm.tree.AnnotationNode) */ @Override protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { - if (!Bytecode.hasFlag(field, Opcodes.ACC_STATIC)) { + if (!Bytecode.isStatic(field)) { throw new InvalidInterfaceMixinException(this.mixin, "Interface mixin contains an instance field! Found " + field.name + " in " + this.mixin); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index 3e47d35a..00bbe66b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -29,14 +29,14 @@ import java.util.Iterator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.FieldInsnNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Dynamic; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; @@ -47,13 +47,17 @@ import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.ClassInfo.SearchType; +import org.spongepowered.asm.mixin.transformer.ClassInfo.TypeLookup; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode; import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinMethodNode; import org.spongepowered.asm.mixin.transformer.meta.MixinRenamed; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinPreProcessorException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.Visibility; @@ -142,10 +146,12 @@ class MixinPreProcessorStandard { protected final Profiler profiler = MixinEnvironment.getProfiler(); + protected final ActivityStack activities = new ActivityStack(); + private final boolean verboseLogging, strictUnique; private boolean prepared, attached; - + MixinPreProcessorStandard(MixinInfo mixin, MixinClassNode classNode) { this.mixin = mixin; this.classNode = classNode; @@ -166,17 +172,29 @@ class MixinPreProcessorStandard { this.prepared = true; + this.activities.clear(); Section prepareTimer = this.profiler.begin("prepare"); - - for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { - Method method = this.mixin.getClassInfo().findMethod(mixinMethod); - this.prepareMethod(mixinMethod, method); + try { + + Activity activity = this.activities.begin("Prepare method"); + for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { + Method method = this.mixin.getClassInfo().findMethod(mixinMethod); + Activity methodActivity = this.activities.begin(mixinMethod.toString()); + this.prepareMethod(mixinMethod, method); + methodActivity.end(); + } + activity.next("Prepare field"); + for (FieldNode mixinField : this.classNode.fields) { + Activity fieldActivity = this.activities.begin(String.format("%s:%s", mixinField.name, mixinField.desc)); + this.prepareField(mixinField); + fieldActivity.end(); + } + activity.end(); + } catch (MixinException ex) { + throw ex; + } catch (Exception ex) { + throw new MixinPreProcessorException(String.format("Prepare error for %s during activity:", this.mixin), ex, this.activities); } - - for (FieldNode mixinField : this.classNode.fields) { - this.prepareField(mixinField); - } - prepareTimer.end(); return this; } @@ -217,15 +235,22 @@ class MixinPreProcessorStandard { } final MixinPreProcessorStandard conform(ClassInfo target) { + this.activities.clear(); Section conformTimer = this.profiler.begin("conform"); - - for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { - if (mixinMethod.isInjector()) { - Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); - this.conformInjector(target, mixinMethod, method); + try { + for (MixinMethodNode mixinMethod : this.classNode.mixinMethods) { + if (mixinMethod.isInjector()) { + Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL); + Activity methodActivity = this.activities.begin("Conform injector %s", mixinMethod); + this.conformInjector(target, mixinMethod, method); + methodActivity.end(); + } } + } catch (MixinException ex) { + throw ex; + } catch (Exception ex) { + throw new MixinPreProcessorException(String.format("Conform error for %s during activity:", this.mixin), ex, this.activities); } - conformTimer.end(); return this; } @@ -254,26 +279,37 @@ class MixinPreProcessorStandard { this.attached = true; + this.activities.clear(); Section attachTimer = this.profiler.begin("attach"); - - // Perform context-sensitive attachment phase - Section timer = this.profiler.begin("methods"); - this.attachMethods(context); - timer = timer.next("fields"); - this.attachFields(context); - - // Apply transformations to the mixin bytecode - timer = timer.next("transform"); - this.transform(context); - timer.end(); - + try { + // Perform context-sensitive attachment phase + Section timer = this.profiler.begin("methods"); + Activity activity = this.activities.begin("Attach method"); + this.attachMethods(context); + timer = timer.next("fields"); + activity.next("Attach field"); + this.attachFields(context); + + // Apply transformations to the mixin bytecode + timer = timer.next("transform"); + activity.next("Transform"); + this.transform(context); + activity.end(); + timer.end(); + } catch (MixinException ex) { + throw ex; + } catch (Exception ex) { + throw new MixinPreProcessorException(String.format("Attach error for %s during activity:", this.mixin), ex, this.activities); + } attachTimer.end(); return this; } protected void attachMethods(MixinTargetContext context) { + Activity methodActivity = this.activities.begin("?"); for (Iterator iter = this.classNode.mixinMethods.iterator(); iter.hasNext();) { MixinMethodNode mixinMethod = iter.next(); + methodActivity.next(mixinMethod.toString()); if (!this.validateMethod(context, mixinMethod)) { iter.remove(); @@ -309,6 +345,7 @@ class MixinPreProcessorStandard { this.attachMethod(context, mixinMethod); context.addMixinMethod(mixinMethod); } + methodActivity.end(); } protected boolean validateMethod(MixinTargetContext context, MixinMethodNode mixinMethod) { @@ -337,10 +374,14 @@ class MixinPreProcessorStandard { throw new InvalidAccessorException(context, description + " in multi-target mixin is invalid. Mixin must have exactly 1 target."); } - String uniqueName = context.getUniqueName(mixinMethod, true); - MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @Unique method {}{} to {} in {}", - mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); - mixinMethod.name = method.renameTo(uniqueName); + if (method.isConformed()) { + mixinMethod.name = method.getName(); + } else { + String uniqueName = context.getUniqueName(mixinMethod, true); + MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @{} method {}{} to {} in {}", + Bytecode.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); + mixinMethod.name = method.conform(uniqueName); + } } else { if (!method.isAbstract()) { @@ -480,7 +521,7 @@ class MixinPreProcessorStandard { 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.renameTo(uniqueName); + mixinMethod.name = method.conform(uniqueName); return false; } @@ -534,8 +575,10 @@ class MixinPreProcessorStandard { } protected void attachFields(MixinTargetContext context) { - for (Iterator iter = this.classNode.fields.iterator(); iter.hasNext();) { + Activity fieldActivity = this.activities.begin("?"); + for (Iterator iter = this.classNode.getFields().iterator(); iter.hasNext();) { FieldNode mixinField = iter.next(); + fieldActivity.next(String.format("%s:%s", mixinField.name, mixinField.desc)); AnnotationNode shadow = Annotations.getVisible(mixinField, Shadow.class); boolean isShadow = shadow != null; @@ -626,7 +669,7 @@ class MixinPreProcessorStandard { protected boolean validateField(MixinTargetContext context, FieldNode field, AnnotationNode shadow) { // Public static fields will fall foul of early static binding in java, including them in a mixin is an error condition - if (Bytecode.hasFlag(field, Opcodes.ACC_STATIC) + if (Bytecode.isStatic(field) && !Bytecode.hasFlag(field, Opcodes.ACC_PRIVATE) && !Bytecode.hasFlag(field, Opcodes.ACC_SYNTHETIC) && shadow == null) { @@ -663,21 +706,27 @@ class MixinPreProcessorStandard { * accesses in the mixin */ protected void transform(MixinTargetContext context) { + Activity methodActivity = this.activities.begin("method"); for (MethodNode mixinMethod : this.classNode.methods) { + methodActivity.next("Method %s", mixinMethod); for (Iterator iter = mixinMethod.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); + Activity activity = this.activities.begin(Bytecode.getOpcodeName(insn)); if (insn instanceof MethodInsnNode) { this.transformMethod((MethodInsnNode)insn); } else if (insn instanceof FieldInsnNode) { this.transformField((FieldInsnNode)insn); } + activity.end(); } } + methodActivity.end(); } protected void transformMethod(MethodInsnNode methodNode) { + Activity activity = this.activities.begin("%s::%s%s", methodNode.owner, methodNode.name, methodNode.desc); Section metaTimer = this.profiler.begin("meta"); - ClassInfo owner = ClassInfo.forName(methodNode.owner); + ClassInfo owner = ClassInfo.forDescriptor(methodNode.owner, TypeLookup.DECLARED_TYPE); if (owner == null) { throw new RuntimeException(new ClassNotFoundException(methodNode.owner.replace('/', '.'))); } @@ -688,11 +737,13 @@ class MixinPreProcessorStandard { if (method != null && method.isRenamed()) { methodNode.name = method.getName(); } + activity.end(); } protected void transformField(FieldInsnNode fieldNode) { + Activity activity = this.activities.begin("%s::%s:%s", fieldNode.owner, fieldNode.name, fieldNode.desc); Section metaTimer = this.profiler.begin("meta"); - ClassInfo owner = ClassInfo.forName(fieldNode.owner); + ClassInfo owner = ClassInfo.forDescriptor(fieldNode.owner, TypeLookup.DECLARED_TYPE); if (owner == null) { throw new RuntimeException(new ClassNotFoundException(fieldNode.owner.replace('/', '.'))); } @@ -703,6 +754,7 @@ class MixinPreProcessorStandard { if (field != null && field.isRenamed()) { fieldNode.name = field.getName(); } + activity.end(); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java new file mode 100644 index 00000000..9367d287 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -0,0 +1,650 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.lang.reflect.Constructor; +import java.text.DecimalFormat; +import java.util.*; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.mixin.Mixins; +import org.spongepowered.asm.mixin.extensibility.IMixinConfig; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; +import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; +import org.spongepowered.asm.mixin.throwables.MixinApplyError; +import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.throwables.MixinPrepareError; +import org.spongepowered.asm.mixin.transformer.MixinConfig.IListener; +import org.spongepowered.asm.mixin.transformer.ext.Extensions; +import org.spongepowered.asm.mixin.transformer.ext.IHotSwap; +import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckClass.ValidationFailedException; +import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExporter; +import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; +import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; +import org.spongepowered.asm.service.IMixinService; +import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.ReEntranceLock; +import org.spongepowered.asm.util.perf.Profiler; +import org.spongepowered.asm.util.perf.Profiler.Section; + +/** + * Heart of the Mixin pipeline + */ +public class MixinProcessor { + + /** + * Phase during which an error occurred, delegates to functionality in + * available handler + */ + static enum ErrorPhase { + /** + * Error during initialisation of a MixinConfig + */ + PREPARE { + @Override + ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) { + try { + return handler.onPrepareError(mixin.getConfig(), ex, mixin, action); + } catch (AbstractMethodError ame) { + // Catch if error handler is pre-0.5.4 + return action; + } + } + + @Override + protected String getContext(IMixinInfo mixin, String context) { + return String.format("preparing %s in %s", mixin.getName(), context); + } + }, + /** + * Error during application of a mixin to a target class + */ + APPLY { + @Override + ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) { + try { + return handler.onApplyError(context, ex, mixin, action); + } catch (AbstractMethodError ame) { + // Catch if error handler is pre-0.5.4 + return action; + } + } + + @Override + protected String getContext(IMixinInfo mixin, String context) { + return String.format("%s -> %s", mixin, context); + } + }; + + /** + * Human-readable name + */ + private final String text; + + private ErrorPhase() { + this.text = this.name().toLowerCase(Locale.ROOT); + } + + abstract ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action); + + protected abstract String getContext(IMixinInfo mixin, String context); + + public String getLogMessage(String context, InvalidMixinException ex, IMixinInfo mixin) { + return String.format("Mixin %s failed %s: %s %s", this.text, this.getContext(mixin, context), ex.getClass().getName(), ex.getMessage()); + } + + public String getErrorMessage(IMixinInfo mixin, IMixinConfig config, Phase phase) { + return String.format("Mixin [%s] from phase [%s] in config [%s] FAILED during %s", mixin, phase, config, this.name()); + } + + } + + private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent"; + + /** + * Log all the things + */ + static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Service + */ + private final IMixinService service = MixinService.getService(); + + /** + * All mixin configuration bundles + */ + private final List configs = new ArrayList(); + + /** + * Uninitialised mixin configuration bundles + */ + private final List pendingConfigs = new ArrayList(); + + /** + * Re-entrance detector + */ + private final ReEntranceLock lock; + + /** + * Session ID, used as a check when parsing {@link MixinMerged} annotations + * to prevent them being applied at compile time by people trying to + * circumvent mixin application + */ + private final String sessionId = UUID.randomUUID().toString(); + + /** + * Processor extensions + */ + private final Extensions extensions; + + /** + * Hot-Swap agent + */ + private final IHotSwap hotSwapper; + + /** + * Postprocessor for passthrough + */ + private final MixinPostProcessor postProcessor; + + /** + * Profiler + */ + private final Profiler profiler; + + /** + * Current environment + */ + private MixinEnvironment currentEnvironment; + + /** + * Logging level for verbose messages + */ + private Level verboseLoggingLevel = Level.DEBUG; + + /** + * Handling an error state, do not process further mixins + */ + private boolean errorState = false; + + /** + * Number of classes transformed in the current phase + */ + private int transformedCount = 0; + + /** + * ctor + */ + MixinProcessor(MixinEnvironment environment, Extensions extensions) { + this.lock = this.service.getReEntranceLock(); + + this.extensions = extensions; + this.hotSwapper = this.initHotSwapper(environment); + 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 clazz = + (Class)Class.forName(MixinProcessor.MIXIN_AGENT_CLASS); + Constructor 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 + * + * @param environment current environment + */ + public void audit(MixinEnvironment environment) { + Set unhandled = new HashSet(); + + for (MixinConfig config : this.configs) { + unhandled.addAll(config.getUnhandledTargets()); + } + + Logger auditLogger = LogManager.getLogger("mixin/audit"); + + for (String target : unhandled) { + try { + auditLogger.info("Force-loading class {}", target); + this.service.getClassProvider().findClass(target, true); + } catch (ClassNotFoundException ex) { + auditLogger.error("Could not force-load " + target, ex); + } + } + + for (MixinConfig config : this.configs) { + for (String target : config.getUnhandledTargets()) { + ClassAlreadyLoadedException ex = new ClassAlreadyLoadedException(target + " was already classloaded"); + auditLogger.error("Could not force-load " + target, ex); + } + } + + if (environment.getOption(Option.DEBUG_PROFILER)) { + this.profiler.printSummary(); + } + } + + synchronized boolean applyMixins(MixinEnvironment environment, String name, ClassNode targetClassNode) { + if (name == null || this.errorState) { + return false; + } + + boolean locked = this.lock.push().check(); + Section mixinTimer = this.profiler.begin("mixin"); + + if (!locked) { + try { + this.checkSelect(environment); + } catch (Exception ex) { + this.lock.pop(); + mixinTimer.end(); + throw new MixinException(ex); + } + } + + boolean success = false; + + try { + if (this.postProcessor.canProcess(name)) { + Section postTimer = this.profiler.begin("postprocessor"); + success = this.postProcessor.processClass(name, targetClassNode); + postTimer.end(); + this.extensions.export(environment, name, false, targetClassNode); + return success; + } + + SortedSet mixins = null; + boolean invalidRef = false; + + for (MixinConfig config : this.configs) { + if (config.packageMatch(name)) { + invalidRef = true; + continue; + } + + if (config.hasMixinsFor(name)) { + if (mixins == null) { + mixins = new TreeSet(); + } + + // Get and sort mixins for the class + 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."); + 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); + } + + try { + // Tree for target class + Section timer = this.profiler.begin("read"); + TargetClassContext context = new TargetClassContext(environment, this.extensions, this.sessionId, + name, targetClassNode, mixins); + timer.end(); + this.applyMixins(environment, context); + this.transformedCount++; + success = true; + } catch (InvalidMixinException th) { + this.dumpClassOnFailure(name, targetClassNode, environment); + this.handleMixinApplyError(name, th, environment); + } + } + + } catch (Throwable th) { + th.printStackTrace(); + this.dumpClassOnFailure(name, targetClassNode, environment); + throw new MixinTransformerError("An unexpected critical error was encountered", th); + } finally { + this.lock.pop(); + mixinTimer.end(); + } + return success; + } + + /** + * Update a mixin class with new bytecode. + * + * @param mixinClass Name of the mixin + * @param classNode New class + * @return List of classes that need to be updated + */ + public List reload(String mixinClass, ClassNode classNode) { + if (this.lock.getDepth() > 0) { + throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered"); + } + List targets = new ArrayList(); + for (MixinConfig config : this.configs) { + targets.addAll(config.reloadMixin(mixinClass, classNode)); + } + return targets; + } + + private void checkSelect(MixinEnvironment environment) { + if (this.currentEnvironment != environment) { + this.select(environment); + return; + } + + int unvisitedCount = Mixins.getUnvisitedCount(); + if (unvisitedCount > 0 && this.transformedCount == 0) { + this.select(environment); + } + } + + private void select(MixinEnvironment environment) { + this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG; + if (this.transformedCount > 0) { + MixinProcessor.logger.log(this.verboseLoggingLevel, "Ending {}, applied {} mixins", this.currentEnvironment, this.transformedCount); + } + String action = this.currentEnvironment == environment ? "Checking for additional" : "Preparing"; + MixinProcessor.logger.log(this.verboseLoggingLevel, "{} mixins for {}", action, environment); + + this.profiler.setActive(true); + this.profiler.mark(environment.getPhase().toString() + ":prepare"); + Section prepareTimer = this.profiler.begin("prepare"); + + this.selectConfigs(environment); + this.extensions.select(environment); + int totalMixins = this.prepareConfigs(environment); + this.currentEnvironment = environment; + this.transformedCount = 0; + + prepareTimer.end(); + + long elapsedMs = prepareTimer.getTime(); + double elapsedTime = prepareTimer.getSeconds(); + if (elapsedTime > 0.25D) { + long loadTime = this.profiler.get("class.load").getTime(); + long transformTime = this.profiler.get("class.transform").getTime(); + long pluginTime = this.profiler.get("mixin.plugin").getTime(); + String elapsed = new DecimalFormat("###0.000").format(elapsedTime); + String perMixinTime = new DecimalFormat("###0.0").format(((double)elapsedMs) / totalMixins); + + MixinProcessor.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({}ms avg) ({}ms load, {}ms transform, {}ms plugin)", + totalMixins, elapsed, perMixinTime, loadTime, transformTime, pluginTime); + } + + this.profiler.mark(environment.getPhase().toString() + ":apply"); + this.profiler.setActive(environment.getOption(Option.DEBUG_PROFILER)); + } + + /** + * Add configurations from the supplied mixin environment to the configs set + * + * @param environment Environment to query + */ + private void selectConfigs(MixinEnvironment environment) { + for (Iterator iter = Mixins.getConfigs().iterator(); iter.hasNext();) { + Config handle = iter.next(); + try { + MixinConfig config = handle.get(); + if (config.select(environment)) { + iter.remove(); + MixinProcessor.logger.log(this.verboseLoggingLevel, "Selecting config {}", config); + config.onSelect(); + this.pendingConfigs.add(config); + } + } catch (Exception ex) { + MixinProcessor.logger.warn(String.format("Failed to select mixin config: %s", handle), ex); + } + } + + Collections.sort(this.pendingConfigs); + } + + /** + * Prepare mixin configs + * + * @param environment Environment + * @return total number of mixins initialised + */ + private int prepareConfigs(MixinEnvironment environment) { + int totalMixins = 0; + + final IHotSwap hotSwapper = this.hotSwapper; + for (MixinConfig config : this.pendingConfigs) { + config.addListener(this.postProcessor); + if (hotSwapper != null) { + config.addListener(new IListener() { + @Override + public void onPrepare(MixinInfo mixin) { + hotSwapper.registerMixinClass(mixin.getClassName()); + } + @Override + public void onInit(MixinInfo mixin) { + } + }); + } + } + + for (MixinConfig config : this.pendingConfigs) { + try { + MixinProcessor.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount()); + config.prepare(); + totalMixins += config.getMixinCount(); + } catch (InvalidMixinException ex) { + this.handleMixinPrepareError(config, ex, environment); + } catch (Exception ex) { + String message = ex.getMessage(); + MixinProcessor.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + message, ex); + } + } + + for (MixinConfig config : this.pendingConfigs) { + IMixinConfigPlugin plugin = config.getPlugin(); + if (plugin == null) { + continue; + } + + Set otherTargets = new HashSet(); + for (MixinConfig otherConfig : this.pendingConfigs) { + if (!otherConfig.equals(config)) { + otherTargets.addAll(otherConfig.getTargets()); + } + } + + plugin.acceptTargets(config.getTargets(), Collections.unmodifiableSet(otherTargets)); + } + + for (MixinConfig config : this.pendingConfigs) { + try { + config.postInitialise(); + } catch (InvalidMixinException ex) { + this.handleMixinPrepareError(config, ex, environment); + } catch (Exception ex) { + String message = ex.getMessage(); + MixinProcessor.logger.error("Error encountered during mixin config postInit step'" + config.getName() + "': " + message, ex); + } + } + + this.configs.addAll(this.pendingConfigs); + Collections.sort(this.configs); + this.pendingConfigs.clear(); + + return totalMixins; + } + + /** + * Apply mixins for specified target class to the class described by the + * supplied byte array. + * + * @param environment current environment + * @param context target class context + */ + private void applyMixins(MixinEnvironment environment, TargetClassContext context) { + Section timer = this.profiler.begin("preapply"); + this.extensions.preApply(context); + timer = timer.next("apply"); + this.apply(context); + timer = timer.next("postapply"); + boolean export = false; + try { + this.extensions.postApply(context); + export = true; + } catch (ValidationFailedException ex) { + MixinProcessor.logger.info(ex.getMessage()); + // If verify is enabled and failed, write out the bytecode to allow us to inspect it + export |= context.isExportForced() || environment.getOption(Option.DEBUG_EXPORT); + } + timer.end(); + if (export) { + this.extensions.export(this.currentEnvironment, context.getClassName(), context.isExportForced(), context.getClassNode()); + } + } + + /** + * Apply the mixins to the target class + * + * @param context Target class context + */ + private void apply(TargetClassContext context) { + context.applyMixins(); + } + + private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError { + this.handleMixinError(config.getName(), ex, environment, ErrorPhase.PREPARE); + } + + private void handleMixinApplyError(String targetClass, InvalidMixinException ex, MixinEnvironment environment) throws MixinApplyError { + this.handleMixinError(targetClass, ex, environment, ErrorPhase.APPLY); + } + + private void handleMixinError(String context, InvalidMixinException ex, MixinEnvironment environment, ErrorPhase errorPhase) throws Error { + this.errorState = true; + + IMixinInfo mixin = ex.getMixin(); + + if (mixin == null) { + MixinProcessor.logger.error("InvalidMixinException has no mixin!", ex); + throw ex; + } + + IMixinConfig config = mixin.getConfig(); + Phase phase = mixin.getPhase(); + ErrorAction action = config.isRequired() ? ErrorAction.ERROR : ErrorAction.WARN; + + if (environment.getOption(Option.DEBUG_VERBOSE)) { + new PrettyPrinter() + .add("Invalid Mixin").centre() + .hr('-') + .kvWidth(10) + .kv("Action", errorPhase.name()) + .kv("Mixin", mixin.getClassName()) + .kv("Config", config.getName()) + .kv("Phase", phase) + .hr('-') + .add(" %s", ex.getClass().getName()) + .hr('-') + .addWrapped(" %s", ex.getMessage()) + .hr('-') + .add(ex, 8) + .trace(action.logLevel); + } + + for (IMixinErrorHandler handler : this.getErrorHandlers(mixin.getPhase())) { + ErrorAction newAction = errorPhase.onError(handler, context, ex, mixin, action); + if (newAction != null) { + action = newAction; + } + } + + MixinProcessor.logger.log(action.logLevel, errorPhase.getLogMessage(context, ex, mixin), ex); + + this.errorState = false; + + if (action == ErrorAction.ERROR) { + throw new MixinApplyError(errorPhase.getErrorMessage(mixin, config, phase), ex); + } + } + + private List getErrorHandlers(Phase phase) { + List handlers = new ArrayList(); + + for (String handlerClassName : Mixins.getErrorHandlerClasses()) { + try { + MixinProcessor.logger.info("Instancing error handler class {}", handlerClassName); + Class handlerClass = this.service.getClassProvider().findClass(handlerClassName, true); + IMixinErrorHandler handler = (IMixinErrorHandler)handlerClass.newInstance(); + if (handler != null) { + handlers.add(handler); + } + } catch (Throwable th) { + // skip bad handlers + } + } + + return handlers; + } + + private void dumpClassOnFailure(String className, ClassNode classNode, MixinEnvironment env) { + if (env.getOption(Option.DUMP_TARGET_ON_FAILURE)) { + ExtensionClassExporter exporter = this.extensions.getExtension(ExtensionClassExporter.class); + exporter.dumpClass(className.replace('.', '/') + ".target", classNode); + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index 6812c952..48377cd8 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -39,10 +39,10 @@ import java.util.Set; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.Handle; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.*; +import org.objectweb.asm.Handle; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.*; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel; import org.spongepowered.asm.mixin.MixinEnvironment.Option; @@ -60,6 +60,7 @@ import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.struct.MemberRef; import org.spongepowered.asm.mixin.struct.SourceMap.File; +import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.ClassInfo.SearchType; @@ -71,6 +72,7 @@ import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.obfuscation.RemapperChain; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Bytecode.Visibility; import org.spongepowered.asm.util.ClassSignature; import org.spongepowered.asm.util.Constants; @@ -91,6 +93,11 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * Logger */ private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Activity tracker + */ + protected final ActivityStack activities = new ActivityStack(null); /** * Mixin info @@ -184,7 +191,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { this.mixin = mixin; this.classNode = classNode; this.targetClass = context; - this.targetClassInfo = ClassInfo.forName(this.getTarget().getClassRef()); + this.targetClassInfo = context.getClassInfo(); this.stratum = context.getSourceMap().addFile(this.classNode); this.inheritsFromMixin = mixin.getClassInfo().hasMixinInHierarchy() || this.targetClassInfo.hasMixinTargetInHierarchy(); this.detachedSuper = !this.classNode.superName.equals(this.getTarget().getClassNode().superName); @@ -346,7 +353,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @return the local class info */ @Override - protected ClassInfo getClassInfo() { + ClassInfo getClassInfo() { return this.mixin.getClassInfo(); } @@ -420,27 +427,6 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { public boolean requireOverwriteAnnotations() { return this.mixin.getParent().requireOverwriteAnnotations(); } - - /** - * Find the corresponding class type for the supplied mixin class in this - * mixin target's hierarchy - * - * @param mixin Mixin class to discover - * @return Transformed - */ - public ClassInfo findRealType(ClassInfo mixin) { - if (mixin == this.getClassInfo()) { - return this.targetClassInfo; - } - - ClassInfo type = this.targetClassInfo.findCorrespondingType(mixin); - if (type == null) { - throw new InvalidMixinException(this, "Resolution error: unable to find corresponding type for " - + mixin + " in hierarchy of " + this.targetClassInfo); - } - - return type; - } /** * Handles "re-parenting" the method supplied, changes all references to the @@ -450,32 +436,58 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @param method Method to transform */ - public void transformMethod(MethodNode method) { - this.validateMethod(method); - this.transformDescriptor(method); - this.transformLVT(method); - - // Offset line numbers per the stratum - this.stratum.applyOffset(method); + void transformMethod(MethodNode method) { + this.activities.clear(); - AbstractInsnNode lastInsn = null; - for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { - AbstractInsnNode insn = iter.next(); - - if (insn instanceof MethodInsnNode) { - this.transformMethodRef(method, iter, new MemberRef.Method((MethodInsnNode)insn)); - } else if (insn instanceof FieldInsnNode) { - this.transformFieldRef(method, iter, new MemberRef.Field((FieldInsnNode)insn)); - this.checkFinal(method, iter, (FieldInsnNode)insn); - } else if (insn instanceof TypeInsnNode) { - this.transformTypeNode(method, iter, (TypeInsnNode)insn, lastInsn); - } else if (insn instanceof LdcInsnNode) { - this.transformConstantNode(method, iter, (LdcInsnNode)insn); - } else if (insn instanceof InvokeDynamicInsnNode) { - this.transformInvokeDynamicNode(method, iter, (InvokeDynamicInsnNode)insn); - } + try { + Activity activity = this.activities.begin("Validate"); + this.validateMethod(method); + activity.next("Transform Descriptor"); + this.transformDescriptor(method); + activity.next("Transform LVTs"); + this.transformLVT(method); + + // Offset line numbers per the stratum + activity.next("Transform Line Numbers"); + this.stratum.applyOffset(method); - lastInsn = insn; + activity.next("Transform Instructions"); + AbstractInsnNode lastInsn = null; + for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { + AbstractInsnNode insn = iter.next(); + Activity insnActivity = this.activities.begin(Bytecode.getOpcodeName(insn) + " "); + + if (insn instanceof MethodInsnNode) { + MethodInsnNode methodNode = (MethodInsnNode)insn; + insnActivity.append("%s::%s%s", methodNode.owner, methodNode.name, methodNode.desc); + this.transformMethodRef(method, iter, new MemberRef.Method(methodNode)); + } else if (insn instanceof FieldInsnNode) { + FieldInsnNode fieldNode = (FieldInsnNode)insn; + insnActivity.append("%s::%s:%s", fieldNode.owner, fieldNode.name, fieldNode.desc); + this.transformFieldRef(method, iter, new MemberRef.Field(fieldNode)); + this.checkFinal(method, iter, fieldNode); + } else if (insn instanceof TypeInsnNode) { + TypeInsnNode typeNode = (TypeInsnNode)insn; + insnActivity.append(typeNode.desc); + this.transformTypeNode(method, iter, typeNode, lastInsn); + } else if (insn instanceof LdcInsnNode) { + this.transformConstantNode(method, iter, (LdcInsnNode)insn); + } else if (insn instanceof InvokeDynamicInsnNode) { + InvokeDynamicInsnNode invokeNode = (InvokeDynamicInsnNode)insn; + insnActivity.append("%s %s", invokeNode.name, invokeNode.desc); + this.transformInvokeDynamicNode(method, iter, invokeNode); + } + + lastInsn = insn; + insnActivity.end(); + } + activity.end(); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst transforming the mixin class:", ex, + this.activities); } } @@ -488,6 +500,11 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { private void validateMethod(MethodNode method) { // Any method tagged with @SoftOverride must have an implementation visible from if (Annotations.getInvisible(method, SoftOverride.class) != null) { + if (Bytecode.getVisibility(method) == Visibility.PRIVATE) { + throw new InvalidMixinException(this, "Mixin method " + method.name + method.desc + + " is tagged with @SoftOverride but the method is PRIVATE"); + } + ClassInfo.Method superMethod = this.targetClassInfo.findMethodInHierarchy(method.name, method.desc, SearchType.SUPER_CLASSES_ONLY, Traversal.SUPER); if (superMethod == null || !superMethod.isInjected()) { @@ -495,6 +512,14 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { + "valid method was found in superclasses of " + this.getTarget().getClassName()); } } + + if (Bytecode.isVirtual(method)) { + Method superMethod = this.targetClassInfo.findMethodInHierarchy(method, SearchType.SUPER_CLASSES_ONLY, Traversal.ALL, 0); + if (superMethod != null && superMethod.isFinal()) { + throw new InvalidMixinException(this.mixin, String.format("%s%s in %s overrides a final method from %s", + method.name, method.desc, this.mixin, superMethod.getOwner().getClassName())); + } + } } /** @@ -817,7 +842,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @param field Field node to transform */ - public void transformDescriptor(FieldNode field) { + void transformDescriptor(FieldNode field) { if (!this.inheritsFromMixin && this.innerClasses.size() == 0) { return; } @@ -829,7 +854,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @param method Method node to transform */ - public void transformDescriptor(MethodNode method) { + void transformDescriptor(MethodNode method) { if (!this.inheritsFromMixin && this.innerClasses.size() == 0) { return; } @@ -842,7 +867,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @param member Reference to the method or field */ - public void transformDescriptor(MemberRef member) { + void transformDescriptor(MemberRef member) { if (!this.inheritsFromMixin && this.innerClasses.size() == 0) { return; } @@ -858,7 +883,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @param typeInsn Type instruction node to transform */ - public void transformDescriptor(TypeInsnNode typeInsn) { + void transformDescriptor(TypeInsnNode typeInsn) { if (!this.inheritsFromMixin && this.innerClasses.size() == 0) { return; } @@ -906,7 +931,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { ClassInfo typeInfo = ClassInfo.forName(type); - if (!typeInfo.isMixin()) { + if (!typeInfo.isMixin() || typeInfo.isLoadable()) { return desc; } @@ -1039,7 +1064,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return mixin interfaces */ - public Set getInterfaces() { + Set getInterfaces() { return this.mixin.getInterfaces(); } @@ -1048,7 +1073,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return shadow methods in the mixin */ - public Collection getShadowMethods() { + Collection getShadowMethods() { return this.shadowMethods; } @@ -1057,7 +1082,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return non-shadow methods in the mixin */ - public List getMethods() { + List getMethods() { return this.classNode.methods; } @@ -1066,7 +1091,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return shadow fields in the mixin */ - public Set> getShadowFields() { + Set> getShadowFields() { return this.shadowFields.entrySet(); } @@ -1075,7 +1100,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return non-shadow fields in the mixin */ - public List getFields() { + List getFields() { return this.classNode.fields; } @@ -1084,7 +1109,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return the logging level */ - public Level getLoggingLevel() { + Level getLoggingLevel() { return this.mixin.getLoggingLevel(); } @@ -1094,7 +1119,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return true if the sourcefile property should be set on the target class */ - public boolean shouldSetSourceFile() { + boolean shouldSetSourceFile() { return this.mixin.getParent().shouldSetSourceFile(); } @@ -1103,7 +1128,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * * @return mixin source file */ - public String getSourceFile() { + String getSourceFile() { return this.classNode.sourceFile; } @@ -1122,7 +1147,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param transformedName Target class's transformed name * @param targetClass Target class */ - public void preApply(String transformedName, ClassNode targetClass) { + void preApply(String transformedName, ClassNode targetClass) { this.mixin.preApply(transformedName, targetClass); } @@ -1132,7 +1157,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param transformedName Target class's transformed name * @param targetClass Target class */ - public void postApply(String transformedName, ClassNode targetClass) { + void postApply(String transformedName, ClassNode targetClass) { try { this.injectorGroups.validateAll(); } catch (InjectionValidationException ex) { @@ -1154,8 +1179,8 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * postfix) otherwise decorates as infix * @return unique method name */ - public String getUniqueName(MethodNode method, boolean preservePrefix) { - return this.getTarget().getUniqueName(method, preservePrefix); + String getUniqueName(MethodNode method, boolean preservePrefix) { + return this.targetClassInfo.getMethodMapper().getUniqueName(method, this.sessionId, preservePrefix); } /** @@ -1165,15 +1190,15 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param field field to obtain a name for * @return unique field name */ - public String getUniqueName(FieldNode field) { - return this.getTarget().getUniqueName(field); + String getUniqueName(FieldNode field) { + return this.targetClassInfo.getMethodMapper().getUniqueName(field, this.sessionId); } /** * Scans the target class for injector methods and prepares discovered * injectors */ - public void prepareInjections() { + void prepareInjections() { this.injectors.clear(); for (MethodNode method : this.mergedMethods) { @@ -1194,7 +1219,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { /** * Apply injectors discovered in the {@link #prepareInjections()} pass */ - public void applyInjections() { + void applyInjections() { for (InjectionInfo injectInfo : this.injectors) { injectInfo.inject(); } @@ -1210,7 +1235,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * Expand accessor methods mixed into the target class by populating the * method bodies */ - public List generateAccessors() { + List generateAccessors() { for (AccessorInfo accessor : this.accessors) { accessor.locate(); } @@ -1225,4 +1250,27 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { return methods; } + + + /** + * Find the corresponding class type for the supplied mixin class in this + * mixin target's hierarchy + * + * @param mixin Mixin class to discover + * @return Transformed + */ + private ClassInfo findRealType(ClassInfo mixin) { + if (mixin == this.getClassInfo()) { + return this.targetClassInfo; + } + + ClassInfo type = this.targetClassInfo.findCorrespondingType(mixin); + if (type == null) { + throw new InvalidMixinException(this, "Resolution error: unable to find corresponding type for " + + mixin + " in hierarchy of " + this.targetClassInfo); + } + + return type; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index 1a408442..71010d8a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -24,384 +24,73 @@ */ package org.spongepowered.asm.mixin.transformer; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.text.DecimalFormat; -import java.util.*; -import java.util.Map.Entry; +import java.util.List; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.MixinEnvironment.Option; -import org.spongepowered.asm.mixin.MixinEnvironment.Phase; -import org.spongepowered.asm.mixin.Mixins; -import org.spongepowered.asm.mixin.extensibility.IMixinConfig; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; -import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler; -import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; -import org.spongepowered.asm.mixin.injection.invoke.arg.ArgsClassGenerator; -import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException; -import org.spongepowered.asm.mixin.throwables.MixinApplyError; import org.spongepowered.asm.mixin.throwables.MixinException; -import org.spongepowered.asm.mixin.throwables.MixinPrepareError; -import org.spongepowered.asm.mixin.transformer.MixinConfig.IListener; import org.spongepowered.asm.mixin.transformer.ext.Extensions; -import org.spongepowered.asm.mixin.transformer.ext.IClassGenerator; -import org.spongepowered.asm.mixin.transformer.ext.IHotSwap; -import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckClass; -import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckClass.ValidationFailedException; -import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionCheckInterfaces; -import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExporter; -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.service.IMixinService; -import org.spongepowered.asm.service.ITransformer; -import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry; import org.spongepowered.asm.transformers.TreeTransformer; -import org.spongepowered.asm.util.PrettyPrinter; -import org.spongepowered.asm.util.ReEntranceLock; -import org.spongepowered.asm.util.perf.Profiler; -import org.spongepowered.asm.util.perf.Profiler.Section; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Constants; /** * Transformer which manages the mixin configuration and application process */ -public class MixinTransformer extends TreeTransformer { - - /** - * Phase during which an error occurred, delegates to functionality in - * available handler - */ - static enum ErrorPhase { - /** - * Error during initialisation of a MixinConfig - */ - PREPARE { - @Override - ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) { - try { - return handler.onPrepareError(mixin.getConfig(), ex, mixin, action); - } catch (AbstractMethodError ame) { - // Catch if error handler is pre-0.5.4 - return action; - } - } - - @Override - protected String getContext(IMixinInfo mixin, String context) { - return String.format("preparing %s in %s", mixin.getName(), context); - } - }, - /** - * Error during application of a mixin to a target class - */ - APPLY { - @Override - ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action) { - try { - return handler.onApplyError(context, ex, mixin, action); - } catch (AbstractMethodError ame) { - // Catch if error handler is pre-0.5.4 - return action; - } - } - - @Override - protected String getContext(IMixinInfo mixin, String context) { - return String.format("%s -> %s", mixin, context); - } - }; - - /** - * Human-readable name - */ - private final String text; - - private ErrorPhase() { - this.text = this.name().toLowerCase(); - } - - abstract ErrorAction onError(IMixinErrorHandler handler, String context, InvalidMixinException ex, IMixinInfo mixin, ErrorAction action); - - protected abstract String getContext(IMixinInfo mixin, String context); - - public String getLogMessage(String context, InvalidMixinException ex, IMixinInfo mixin) { - return String.format("Mixin %s failed %s: %s %s", this.text, this.getContext(mixin, context), ex.getClass().getName(), ex.getMessage()); - } - - public String getErrorMessage(IMixinInfo mixin, IMixinConfig config, Phase phase) { - return String.format("Mixin [%s] from phase [%s] in config [%s] FAILED during %s", mixin, phase, config, this.name()); - } - - } - - private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent"; - private static final String METRONOME_AGENT_CLASS = "org.spongepowered.metronome.Agent"; - - /** - * Log all the things - */ - static final Logger logger = LogManager.getLogger("mixin"); - - /** - * Service - */ - private final IMixinService service = MixinService.getService(); - - /** - * All mixin configuration bundles - */ - private final List configs = new ArrayList(); - - /** - * Uninitialised mixin configuration bundles - */ - private final List pendingConfigs = new ArrayList(); - - /** - * Re-entrance detector - */ - private final ReEntranceLock lock; - - /** - * Session ID, used as a check when parsing {@link MixinMerged} annotations - * to prevent them being applied at compile time by people trying to - * circumvent mixin application - */ - private final String sessionId = UUID.randomUUID().toString(); +class MixinTransformer extends TreeTransformer implements IMixinTransformer { /** * Transformer extensions */ private final Extensions extensions; - - /** - * Hot-Swap agent - */ - private final IHotSwap hotSwapper; - - /** - * Postprocessor for passthrough - */ - private final MixinPostProcessor postProcessor; - - /** - * Profiler - */ - private final Profiler profiler; /** - * Current environment + * Mixin processor which actually manages application of mixins */ - private MixinEnvironment currentEnvironment; - - /** - * Logging level for verbose messages - */ - private Level verboseLoggingLevel = Level.DEBUG; - - /** - * Handling an error state, do not process further mixins - */ - private boolean errorState = false; + private final MixinProcessor processor; /** - * Number of classes transformed in the current phase + * Class generator */ - private int transformedCount = 0; + private final MixinClassGenerator generator; /** - * ctor + * Synthetic class registry */ - MixinTransformer() { + private final SyntheticClassRegistry syntheticClassRegistry; + + public MixinTransformer() { MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); Object globalMixinTransformer = environment.getActiveTransformer(); - if (globalMixinTransformer instanceof ITransformer) { + if (globalMixinTransformer instanceof IMixinTransformer) { throw new MixinException("Terminating MixinTransformer instance " + this); } // I am a leaf on the wind environment.setActiveTransformer(this); - this.lock = this.service.getReEntranceLock(); - - this.extensions = new Extensions(this); - this.hotSwapper = this.initHotSwapper(environment); - this.postProcessor = new MixinPostProcessor(); - - this.extensions.add(new ArgsClassGenerator()); - this.extensions.add(new InnerClassGenerator()); + this.syntheticClassRegistry = new SyntheticClassRegistry(); + this.extensions = new Extensions(this.syntheticClassRegistry); - this.extensions.add(new ExtensionClassExporter(environment)); - this.extensions.add(new ExtensionCheckClass()); - this.extensions.add(new ExtensionCheckInterfaces()); + this.processor = new MixinProcessor(environment, this.extensions); + this.generator = new MixinClassGenerator(environment, this.extensions); - this.profiler = MixinEnvironment.getProfiler(); - } - - private IHotSwap initHotSwapper(MixinEnvironment environment) { - if (!environment.getOption(Option.HOT_SWAP)) { - return null; - } - - try { - MixinTransformer.logger.info("Attempting to load Hot-Swap agent"); - @SuppressWarnings("unchecked") - Class clazz = - (Class)Class.forName(MixinTransformer.MIXIN_AGENT_CLASS); - Constructor ctor = clazz.getDeclaredConstructor(MixinTransformer.class); - return ctor.newInstance(this); - } catch (Throwable th) { - MixinTransformer.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 - * - * @param environment current environment - */ - public void audit(MixinEnvironment environment) { - Set unhandled = new HashSet(); - - for (MixinConfig config : this.configs) { - unhandled.addAll(config.getUnhandledTargets()); - } - - Logger auditLogger = LogManager.getLogger("mixin/audit"); - - for (String target : unhandled) { - try { - auditLogger.info("Force-loading class {}", target); - this.service.getClassProvider().findClass(target, true); - } catch (ClassNotFoundException ex) { - auditLogger.error("Could not force-load " + target, ex); - } - } - - for (MixinConfig config : this.configs) { - for (String target : config.getUnhandledTargets()) { - ClassAlreadyLoadedException ex = new ClassAlreadyLoadedException(target + " was already classloaded"); - auditLogger.error("Could not force-load " + target, ex); - } - } - - if (environment.getOption(Option.DEBUG_PROFILER)) { - this.printProfilerSummary(); - } - } - - private void printProfilerSummary() { - DecimalFormat threedp = new DecimalFormat("(###0.000"); - DecimalFormat onedp = new DecimalFormat("(###0.0"); - PrettyPrinter printer = this.profiler.printer(false, false); - - long prepareTime = this.profiler.get("mixin.prepare").getTotalTime(); - long readTime = this.profiler.get("mixin.read").getTotalTime(); - long applyTime = this.profiler.get("mixin.apply").getTotalTime(); - long writeTime = this.profiler.get("mixin.write").getTotalTime(); - long totalMixinTime = this.profiler.get("mixin").getTotalTime(); - - long loadTime = this.profiler.get("class.load").getTotalTime(); - long transformTime = this.profiler.get("class.transform").getTotalTime(); - long exportTime = this.profiler.get("mixin.debug.export").getTotalTime(); - long actualTime = totalMixinTime - loadTime - transformTime - exportTime; - double timeSliceMixin = ((double)actualTime / (double)totalMixinTime) * 100.0D; - double timeSliceLoad = ((double)loadTime / (double)totalMixinTime) * 100.0D; - double timeSliceTransform = ((double)transformTime / (double)totalMixinTime) * 100.0D; - double timeSliceExport = ((double)exportTime / (double)totalMixinTime) * 100.0D; - - long worstTransformerTime = 0L; - Section worstTransformer = null; - - for (Section section : this.profiler.getSections()) { - long transformerTime = section.getName().startsWith("class.transform.") ? section.getTotalTime() : 0L; - if (transformerTime > worstTransformerTime) { - worstTransformerTime = transformerTime; - worstTransformer = section; - } - } - - printer.hr().add("Summary").hr().add(); - - String format = "%9d ms %12s seconds)"; - printer.kv("Total mixin time", format, totalMixinTime, threedp.format(totalMixinTime * 0.001)).add(); - printer.kv("Preparing mixins", format, prepareTime, threedp.format(prepareTime * 0.001)); - printer.kv("Reading input", format, readTime, threedp.format(readTime * 0.001)); - printer.kv("Applying mixins", format, applyTime, threedp.format(applyTime * 0.001)); - printer.kv("Writing output", format, writeTime, threedp.format(writeTime * 0.001)).add(); - - printer.kv("of which",""); - printer.kv("Time spent loading from disk", format, loadTime, threedp.format(loadTime * 0.001)); - printer.kv("Time spent transforming classes", format, transformTime, threedp.format(transformTime * 0.001)).add(); - - if (worstTransformer != null) { - printer.kv("Worst transformer", worstTransformer.getName()); - printer.kv("Class", worstTransformer.getInfo()); - printer.kv("Time spent", "%s seconds", worstTransformer.getTotalSeconds()); - printer.kv("called", "%d times", worstTransformer.getTotalCount()).add(); - } - - printer.kv(" Time allocation: Processing mixins", "%9d ms %10s%% of total)", actualTime, onedp.format(timeSliceMixin)); - printer.kv("Loading classes", "%9d ms %10s%% of total)", loadTime, onedp.format(timeSliceLoad)); - printer.kv("Running transformers", "%9d ms %10s%% of total)", transformTime, onedp.format(timeSliceTransform)); - if (exportTime > 0L) { - printer.kv("Exporting classes (debug)", "%9d ms %10s%% of total)", exportTime, onedp.format(timeSliceExport)); - } - printer.add(); - - try { - Class agent = this.service.getClassProvider().findAgentClass(MixinTransformer.METRONOME_AGENT_CLASS, false); - Method mdGetTimes = agent.getDeclaredMethod("getTimes"); - - @SuppressWarnings("unchecked") - Map times = (Map)mdGetTimes.invoke(null); - - printer.hr().add("Transformer Times").hr().add(); - - int longest = 10; - for (Entry entry : times.entrySet()) { - longest = Math.max(longest, entry.getKey().length()); - } - - for (Entry entry : times.entrySet()) { - String name = entry.getKey(); - long mixinTime = 0L; - for (Section section : this.profiler.getSections()) { - if (name.equals(section.getInfo())) { - mixinTime = section.getTotalTime(); - break; - } - } - - if (mixinTime > 0L) { - printer.add("%-" + longest + "s %8s ms %8s ms in mixin)", name, entry.getValue() + mixinTime, "(" + mixinTime); - } else { - printer.add("%-" + longest + "s %8s ms", name, entry.getValue()); - } - } - - printer.add(); - - } catch (Throwable th) { - // Metronome agent not loaded - } - - - printer.print(); + DefaultExtensions.create(environment, this.extensions, this.syntheticClassRegistry); } /* (non-Javadoc) - * @see org.spongepowered.asm.service.ILegacyClassTransformer#getName() + * @see org.spongepowered.asm.mixin.transformer.IMixinTransformer + * #getExtensions() + */ + @Override + public IExtensionRegistry getExtensions() { + return this.extensions; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.ITransformer#getName() */ @Override public String getName() { @@ -409,414 +98,116 @@ public class MixinTransformer extends TreeTransformer { } /* (non-Javadoc) - * @see org.spongepowered.asm.service.ILegacyClassTransformer - * #isDelegationExcluded() + * @see org.spongepowered.asm.service.ITransformer#isDelegationExcluded() */ @Override public boolean isDelegationExcluded() { return true; } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.ILegacyClassTransformer#transform( - * java.lang.String, java.lang.String, byte[]) + /** + * Run audit process on current mixin processor + * + * @param environment Environment for audit */ @Override - public synchronized byte[] transformClassBytes(String name, String transformedName, byte[] basicClass) { - if (transformedName == null || this.errorState) { + public void audit(MixinEnvironment environment) { + this.processor.audit(environment); + } + + /** + * Callback from hotswap agent + * + * @param mixinClass Name of the mixin + * @param classNode New class + * @return List of classes that need to be updated + */ + @Override + public List reload(String mixinClass, ClassNode classNode) { + return this.processor.reload(mixinClass, classNode); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.IMixinTransformer + * #transformClassBytes(java.lang.String, java.lang.String, byte[]) + */ + @Override + public byte[] transformClassBytes(String name, String transformedName, byte[] basicClass) { + if (transformedName == null) { return basicClass; } MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); if (basicClass == null) { - for (IClassGenerator generator : this.extensions.getGenerators()) { - Section genTimer = this.profiler.begin("generator", generator.getClass().getSimpleName().toLowerCase()); - basicClass = generator.generate(transformedName); - genTimer.end(); - if (basicClass != null) { - this.extensions.export(environment, transformedName.replace('.', '/'), false, basicClass); - return basicClass; - } - } - return basicClass; + return this.generateClass(environment, transformedName); } - boolean locked = this.lock.push().check(); - - Section mixinTimer = this.profiler.begin("mixin"); - - if (!locked) { - try { - this.checkSelect(environment); - } catch (Exception ex) { - this.lock.pop(); - mixinTimer.end(); - throw new MixinException(ex); - } - } - - try { - if (this.postProcessor.canTransform(transformedName)) { - Section postTimer = this.profiler.begin("postprocessor"); - byte[] bytes = this.postProcessor.transformClassBytes(name, transformedName, basicClass); - postTimer.end(); - this.extensions.export(environment, transformedName, false, bytes); - return bytes; - } - - SortedSet mixins = null; - boolean invalidRef = false; - - for (MixinConfig config : this.configs) { - if (config.packageMatch(transformedName)) { - invalidRef = true; - continue; - } - - if (config.hasMixinsFor(transformedName)) { - if (mixins == null) { - mixins = new TreeSet(); - } - - // Get and sort mixins for the class - mixins.addAll(config.getMixinsFor(transformedName)); - } - } - - if (invalidRef) { - throw new NoClassDefFoundError(String.format("%s is a mixin class and cannot be referenced directly", transformedName)); - } - - 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) { - MixinTransformer.logger.warn("Re-entrance detected, this will cause serious problems.", new MixinException()); - throw new MixinApplyError("Re-entrance error."); - } - - if (this.hotSwapper != null) { - this.hotSwapper.registerTargetClass(transformedName, basicClass); - } - - try { - // Tree for target class - Section timer = this.profiler.begin("read"); - ClassNode targetClassNode = this.readClass(basicClass, true); - TargetClassContext context = new TargetClassContext(environment, this.extensions, this.sessionId, - transformedName, targetClassNode, mixins); - timer.end(); - basicClass = this.applyMixins(environment, context); - this.transformedCount++; - } catch (InvalidMixinException th) { - this.dumpClassOnFailure(transformedName, basicClass, environment); - this.handleMixinApplyError(transformedName, th, environment); - } - } - - return basicClass; - } catch (Throwable th) { - th.printStackTrace(); - this.dumpClassOnFailure(transformedName, basicClass, environment); - throw new MixinTransformerError("An unexpected critical error was encountered", th); - } finally { - this.lock.pop(); - mixinTimer.end(); - } + return this.transformClass(environment, transformedName, basicClass); } /** - * Update a mixin class with new bytecode. - * - * @param mixinClass Name of the mixin - * @param bytes New bytecode - * @return List of classes that need to be updated - */ - public List reload(String mixinClass, byte[] bytes) { - if (this.lock.getDepth() > 0) { - throw new MixinApplyError("Cannot reload mixin if re-entrant lock entered"); - } - List targets = new ArrayList(); - for (MixinConfig config : this.configs) { - targets.addAll(config.reloadMixin(mixinClass, bytes)); - } - return targets; - } - - private void checkSelect(MixinEnvironment environment) { - if (this.currentEnvironment != environment) { - this.select(environment); - return; - } - - int unvisitedCount = Mixins.getUnvisitedCount(); - if (unvisitedCount > 0 && this.transformedCount == 0) { - this.select(environment); - } - } - - private void select(MixinEnvironment environment) { - this.verboseLoggingLevel = (environment.getOption(Option.DEBUG_VERBOSE)) ? Level.INFO : Level.DEBUG; - if (this.transformedCount > 0) { - MixinTransformer.logger.log(this.verboseLoggingLevel, "Ending {}, applied {} mixins", this.currentEnvironment, this.transformedCount); - } - String action = this.currentEnvironment == environment ? "Checking for additional" : "Preparing"; - MixinTransformer.logger.log(this.verboseLoggingLevel, "{} mixins for {}", action, environment); - - this.profiler.setActive(true); - this.profiler.mark(environment.getPhase().toString() + ":prepare"); - Section prepareTimer = this.profiler.begin("prepare"); - - this.selectConfigs(environment); - this.extensions.select(environment); - int totalMixins = this.prepareConfigs(environment); - this.currentEnvironment = environment; - this.transformedCount = 0; - - prepareTimer.end(); - - long elapsedMs = prepareTimer.getTime(); - double elapsedTime = prepareTimer.getSeconds(); - if (elapsedTime > 0.25D) { - long loadTime = this.profiler.get("class.load").getTime(); - long transformTime = this.profiler.get("class.transform").getTime(); - long pluginTime = this.profiler.get("mixin.plugin").getTime(); - String elapsed = new DecimalFormat("###0.000").format(elapsedTime); - String perMixinTime = new DecimalFormat("###0.0").format(((double)elapsedMs) / totalMixins); - - MixinTransformer.logger.log(this.verboseLoggingLevel, "Prepared {} mixins in {} sec ({}ms avg) ({}ms load, {}ms transform, {}ms plugin)", - totalMixins, elapsed, perMixinTime, loadTime, transformTime, pluginTime); - } - - this.profiler.mark(environment.getPhase().toString() + ":apply"); - this.profiler.setActive(environment.getOption(Option.DEBUG_PROFILER)); - } - - /** - * Add configurations from the supplied mixin environment to the configs set + * Apply mixins and postprocessors to the supplied class * - * @param environment Environment to query + * @param environment Current environment + * @param name Class transformed name + * @param classBytes Class bytecode + * @return Transformed bytecode */ - private void selectConfigs(MixinEnvironment environment) { - for (Iterator iter = Mixins.getConfigs().iterator(); iter.hasNext();) { - Config handle = iter.next(); - try { - MixinConfig config = handle.get(); - if (config.select(environment)) { - iter.remove(); - MixinTransformer.logger.log(this.verboseLoggingLevel, "Selecting config {}", config); - config.onSelect(); - this.pendingConfigs.add(config); - } - } catch (Exception ex) { - MixinTransformer.logger.warn(String.format("Failed to select mixin config: %s", handle), ex); - } + public byte[] transformClass(MixinEnvironment environment, String name, byte[] classBytes) { + ClassNode classNode = this.readClass(classBytes); + if (this.processor.applyMixins(environment, name, classNode)) { + return this.writeClass(classNode); } - - Collections.sort(this.pendingConfigs); + return classBytes; } /** - * Prepare mixin configs + * Apply mixins and postprocessors to the supplied class * - * @param environment Environment - * @return total number of mixins initialised + * @param environment Current environment + * @param name Class transformed name + * @param classNode Class tree + * @return true if the class was transformed */ - private int prepareConfigs(MixinEnvironment environment) { - int totalMixins = 0; - - final IHotSwap hotSwapper = this.hotSwapper; - for (MixinConfig config : this.pendingConfigs) { - config.addListener(this.postProcessor); - if (hotSwapper != null) { - config.addListener(new IListener() { - @Override - public void onPrepare(MixinInfo mixin) { - hotSwapper.registerMixinClass(mixin.getClassName()); - } - @Override - public void onInit(MixinInfo mixin) { - } - }); - } - } - - for (MixinConfig config : this.pendingConfigs) { - try { - MixinTransformer.logger.log(this.verboseLoggingLevel, "Preparing {} ({})", config, config.getDeclaredMixinCount()); - config.prepare(); - totalMixins += config.getMixinCount(); - } catch (InvalidMixinException ex) { - this.handleMixinPrepareError(config, ex, environment); - } catch (Exception ex) { - String message = ex.getMessage(); - MixinTransformer.logger.error("Error encountered whilst initialising mixin config '" + config.getName() + "': " + message, ex); - } - } - - for (MixinConfig config : this.pendingConfigs) { - IMixinConfigPlugin plugin = config.getPlugin(); - if (plugin == null) { - continue; - } - - Set otherTargets = new HashSet(); - for (MixinConfig otherConfig : this.pendingConfigs) { - if (!otherConfig.equals(config)) { - otherTargets.addAll(otherConfig.getTargets()); - } - } - - plugin.acceptTargets(config.getTargets(), Collections.unmodifiableSet(otherTargets)); - } - - for (MixinConfig config : this.pendingConfigs) { - try { - config.postInitialise(); - } catch (InvalidMixinException ex) { - this.handleMixinPrepareError(config, ex, environment); - } catch (Exception ex) { - String message = ex.getMessage(); - MixinTransformer.logger.error("Error encountered during mixin config postInit step'" + config.getName() + "': " + message, ex); - } - } - - this.configs.addAll(this.pendingConfigs); - Collections.sort(this.configs); - this.pendingConfigs.clear(); - - return totalMixins; - } - - /** - * Apply mixins for specified target class to the class described by the - * supplied byte array. - * - * @param environment current environment - * @param context target class context - * @return class bytecode after application of mixins - */ - private byte[] applyMixins(MixinEnvironment environment, TargetClassContext context) { - Section timer = this.profiler.begin("preapply"); - this.extensions.preApply(context); - timer = timer.next("apply"); - this.apply(context); - timer = timer.next("postapply"); - try { - this.extensions.postApply(context); - } catch (ValidationFailedException ex) { - MixinTransformer.logger.info(ex.getMessage()); - // If verify is enabled and failed, write out the bytecode to allow us to inspect it - if (context.isExportForced() || environment.getOption(Option.DEBUG_EXPORT)) { - this.writeClass(context); - } - } - timer.end(); - return this.writeClass(context); - } - - /** - * Apply the mixins to the target class - * - * @param context Target class context - */ - private void apply(TargetClassContext context) { - context.applyMixins(); - } - - private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError { - this.handleMixinError(config.getName(), ex, environment, ErrorPhase.PREPARE); + public boolean transformClass(MixinEnvironment environment, String name, ClassNode classNode) { + return this.processor.applyMixins(environment, name, classNode); } - private void handleMixinApplyError(String targetClass, InvalidMixinException ex, MixinEnvironment environment) throws MixinApplyError { - this.handleMixinError(targetClass, ex, environment, ErrorPhase.APPLY); - } - - private void handleMixinError(String context, InvalidMixinException ex, MixinEnvironment environment, ErrorPhase errorPhase) throws Error { - this.errorState = true; - - IMixinInfo mixin = ex.getMixin(); - - if (mixin == null) { - MixinTransformer.logger.error("InvalidMixinException has no mixin!", ex); - throw ex; + /** + * Generate the specified mixin-synthetic class + * + * @param environment Current environment + * @param name Class name to generate + * @return Generated bytecode or null if no class was generated + */ + public byte[] generateClass(MixinEnvironment environment, String name) { + ClassNode classNode = MixinTransformer.createEmptyClass(name); + if (this.generator.generateClass(environment, name, classNode)) { + return this.writeClass(classNode); } - - IMixinConfig config = mixin.getConfig(); - Phase phase = mixin.getPhase(); - ErrorAction action = config.isRequired() ? ErrorAction.ERROR : ErrorAction.WARN; - - if (environment.getOption(Option.DEBUG_VERBOSE)) { - new PrettyPrinter() - .add("Invalid Mixin").centre() - .hr('-') - .kvWidth(10) - .kv("Action", errorPhase.name()) - .kv("Mixin", mixin.getClassName()) - .kv("Config", config.getName()) - .kv("Phase", phase) - .hr('-') - .add(" %s", ex.getClass().getName()) - .hr('-') - .addWrapped(" %s", ex.getMessage()) - .hr('-') - .add(ex, 8) - .trace(action.logLevel); - } - - for (IMixinErrorHandler handler : this.getErrorHandlers(mixin.getPhase())) { - ErrorAction newAction = errorPhase.onError(handler, context, ex, mixin, action); - if (newAction != null) { - action = newAction; - } - } - - MixinTransformer.logger.log(action.logLevel, errorPhase.getLogMessage(context, ex, mixin), ex); - - this.errorState = false; - - if (action == ErrorAction.ERROR) { - throw new MixinApplyError(errorPhase.getErrorMessage(mixin, config, phase), ex); - } - } - - private List getErrorHandlers(Phase phase) { - List handlers = new ArrayList(); - - for (String handlerClassName : Mixins.getErrorHandlerClasses()) { - try { - MixinTransformer.logger.info("Instancing error handler class {}", handlerClassName); - Class handlerClass = this.service.getClassProvider().findClass(handlerClassName, true); - IMixinErrorHandler handler = (IMixinErrorHandler)handlerClass.newInstance(); - if (handler != null) { - handlers.add(handler); - } - } catch (Throwable th) { - // skip bad handlers - } - } - - return handlers; - } - - private byte[] writeClass(TargetClassContext context) { - return this.writeClass(context.getClassName(), context.getClassNode(), context.isExportForced()); + return null; } - private byte[] writeClass(String transformedName, ClassNode targetClass, boolean forceExport) { - // Collapse tree to bytes - Section writeTimer = this.profiler.begin("write"); - byte[] bytes = this.writeClass(targetClass); - writeTimer.end(); - this.extensions.export(this.currentEnvironment, transformedName, forceExport, bytes); - return bytes; + /** + * @param environment Current environment + * @param name Class transformed name + * @param classNode Empty classnode to populate + * @return True if the class was generated successfully + */ + public boolean generateClass(MixinEnvironment environment, String name, ClassNode classNode) { + return this.generator.generateClass(environment, name, classNode); } - - private void dumpClassOnFailure(String className, byte[] bytes, MixinEnvironment env) { - if (env.getOption(Option.DUMP_TARGET_ON_FAILURE)) { - ExtensionClassExporter exporter = this.extensions.getExtension(ExtensionClassExporter.class); - exporter.dumpClass(className.replace('.', '/') + ".target", bytes); - } + + /** + * You need to ask yourself why you're reading this comment + */ + private static ClassNode createEmptyClass(String name) { + ClassNode classNode = new ClassNode(Bytecode.ASM_API_VERSION); + classNode.name = name.replace('.', '/'); + classNode.version = MixinEnvironment.getCompatibilityLevel().classVersion(); + classNode.superName = Constants.OBJECT; + return classNode; } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java b/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java new file mode 100644 index 00000000..ae301f09 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/PluginHandle.java @@ -0,0 +1,230 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.throwables.CompanionPluginError; +import org.spongepowered.asm.service.IMixinService; + +/** + * Convenience wrapper for mixin config plugins + */ +class PluginHandle { + + /** + * Compatibility mode for companion plugins + */ + enum CompatibilityMode { + + /** + * Companion plugin is compatible or unknown + */ + NORMAL, + + /** + * Companion plugin is outdated but running anyway, preApply and + * postApply will be called via reflection + */ + COMPATIBLE, + + /** + * Companion plugin is disabled due to incompatibility + */ + FAILED + + } + + private static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Parent config which owns this plugin handle + */ + private final MixinConfig parent; + + /** + * Plugin instance, can be null + */ + private final IMixinConfigPlugin plugin; + + /** + * Compatibility mode for companion plugin + */ + private CompatibilityMode mode = CompatibilityMode.NORMAL; + + /** + * Reflection objects for calling legacy (pre 0.8) preApply and postApply + */ + private Method mdPreApply, mdPostApply; + + PluginHandle(MixinConfig parent, IMixinService service, String pluginClassName) { + IMixinConfigPlugin plugin = null; + + if (pluginClassName != null) { + try { + Class pluginClass = service.getClassProvider().findClass(pluginClassName, true); + plugin = (IMixinConfigPlugin)pluginClass.newInstance(); + } catch (Throwable th) { + th.printStackTrace(); + plugin = null; + } + } + + this.parent = parent; + this.plugin = plugin; + } + + IMixinConfigPlugin get() { + return this.plugin; + } + + boolean isAvailable() { + return this.plugin != null; + } + + void onLoad(String mixinPackage) { + if (this.plugin != null) { + this.plugin.onLoad(mixinPackage); + } + } + + String getRefMapperConfig() { + return this.plugin != null ? this.plugin.getRefMapperConfig() : null; + } + + List getMixins() { + return this.plugin != null ? this.plugin.getMixins() : null; + } + + boolean shouldApplyMixin(String targetName, String className) { + return this.plugin == null || this.plugin.shouldApplyMixin(targetName, className); + } + + /** + * Called immediately before the mixin is applied to targetClass + */ + public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, MixinInfo mixinInfo) { + if (this.plugin == null) { + return; + } + + if (this.mode == CompatibilityMode.FAILED) { + throw new IllegalStateException("Companion plugin failure for [" + this.parent + "] plugin [" + this.plugin.getClass() + "]"); + } + + if (this.mode == CompatibilityMode.COMPATIBLE) { + try { + this.applyLegacy(this.mdPreApply, targetClassName, targetClass, mixinClassName, mixinInfo); + } catch (Exception ex) { + this.mode = CompatibilityMode.FAILED; + throw ex; + } + return; + } + + try { + this.plugin.preApply(targetClassName, targetClass, mixinClassName, mixinInfo); + } catch (AbstractMethodError ex) { + this.mode = CompatibilityMode.COMPATIBLE; + this.initReflection(); + this.preApply(targetClassName, targetClass, mixinClassName, mixinInfo); + } + } + + /** + * Called immediately after the mixin is applied to targetClass + */ + public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, MixinInfo mixinInfo) { + if (this.plugin == null) { + return; + } + + if (this.mode == CompatibilityMode.FAILED) { + throw new IllegalStateException("Companion plugin failure for [" + this.parent + "] plugin [" + this.plugin.getClass() + "]"); + } + + if (this.mode == CompatibilityMode.COMPATIBLE) { + try { + this.applyLegacy(this.mdPostApply, targetClassName, targetClass, mixinClassName, mixinInfo); + } catch (Exception ex) { + this.mode = CompatibilityMode.FAILED; + throw ex; + } + return; + } + + try { + this.plugin.postApply(targetClassName, targetClass, mixinClassName, mixinInfo); + } catch (AbstractMethodError ex) { + this.mode = CompatibilityMode.COMPATIBLE; + this.initReflection(); + this.postApply(targetClassName, targetClass, mixinClassName, mixinInfo); + } + } + + private void initReflection() { + if (this.mdPreApply != null) { + return; + } + + try { + Class pluginClass = this.plugin.getClass(); + this.mdPreApply = pluginClass.getMethod("preApply", String.class, org.spongepowered.asm.lib.tree.ClassNode.class, String.class, + IMixinInfo.class); + this.mdPostApply = pluginClass.getMethod("postApply", String.class, org.spongepowered.asm.lib.tree.ClassNode.class, String.class, + IMixinInfo.class); + } catch (Throwable th) { + PluginHandle.logger.catching(th); + } + } + + private void applyLegacy(Method method, String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { + try { + method.invoke(this.plugin, targetClassName, new org.spongepowered.asm.lib.tree.ClassNode(targetClass), mixinClassName, mixinInfo); + } catch (LinkageError err) { + throw new CompanionPluginError(this.apiError("Accessing [" + err.getMessage() + "]"), err); + } catch (IllegalAccessException ex) { + throw new CompanionPluginError(this.apiError("Fallback failed [" + ex.getMessage() + "]"), ex); + } catch (IllegalArgumentException ex) { + throw new CompanionPluginError(this.apiError("Fallback failed [" + ex.getMessage() + "]"), ex); + } catch (InvocationTargetException ex) { + Throwable th = ex.getCause() != null ? ex.getCause() : ex; + throw new CompanionPluginError(this.apiError("Fallback failed [" + th.getMessage() + "]"), th); + } + } + + private String apiError(String message) { + return String.format("Companion plugin attempted to use a deprected API in [%s] plugin [%s]: %s", + this.parent, this.plugin.getClass().getName(), message); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/SyntheticClassInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/SyntheticClassInfo.java new file mode 100644 index 00000000..d53e7e98 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/SyntheticClassInfo.java @@ -0,0 +1,70 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.service.ISyntheticClassInfo; + +import com.google.common.base.Preconditions; + +/** + * Information bundle about a synthetic class provided by Mixin + */ +public abstract class SyntheticClassInfo implements ISyntheticClassInfo { + + /** + * Mixin which provides this class + */ + protected final IMixinInfo mixin; + + /** + * Class name (internal name) + */ + protected final String name; + + protected SyntheticClassInfo(IMixinInfo mixin, String name) { + Preconditions.checkNotNull(mixin, "parent"); + Preconditions.checkNotNull(name, "name"); + + this.mixin = mixin; + this.name = name.replace('.', '/');; + } + + @Override + public final IMixinInfo getMixin() { + return this.mixin; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public String getClassName() { + return this.name.replace('/', '.'); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/SyntheticClassRegistry.java b/src/main/java/org/spongepowered/asm/mixin/transformer/SyntheticClassRegistry.java new file mode 100644 index 00000000..7ca6c502 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/SyntheticClassRegistry.java @@ -0,0 +1,81 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.HashMap; +import java.util.Map; + +import org.spongepowered.asm.mixin.throwables.MixinError; +import org.spongepowered.asm.service.ISyntheticClassInfo; +import org.spongepowered.asm.service.ISyntheticClassRegistry; + +/** + * Implementation of synthetic class registry. This exists to maintain a list of + * classes that the {@link MixinTransformer mixin pipeline} needs to accept in + * order to generate. This used to be done on an on-demand basis under + * LaunchWrapper but under ModLauncher we need to handle this more delicately + * so this registry simply acts as a bridge between pipeline elements which need + * to generate synthetic classes, and the entry point to the processing + * pipeline. + */ +class SyntheticClassRegistry implements ISyntheticClassRegistry { + + /** + * Map of class name to {@link ISyntheticClassInfo} structs + */ + private final Map classes = new HashMap(); + + SyntheticClassRegistry() { + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.ISyntheticClassRegistry + * #findSyntheticClass(java.lang.String) + */ + @Override + public ISyntheticClassInfo findSyntheticClass(String name) { + if (name == null) { + return null; + } + return this.classes.get(name.replace('.', '/')); + } + + /** + * Package-private + */ + void registerSyntheticClass(ISyntheticClassInfo sci) { + String name = sci.getName(); + ISyntheticClassInfo info = this.classes.get(name); + if (info != null) { + if (info == sci) { + return; + } + throw new MixinError("Synthetic class with name " + name + " was already registered by " + info.getMixin() + + ". Duplicate being registered by " + sci.getMixin()); + } + this.classes.put(name, sci); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java index 4cd052b7..bee05de9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java @@ -34,10 +34,10 @@ import java.util.SortedSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Debug; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; @@ -52,7 +52,7 @@ import org.spongepowered.asm.util.ClassSignature; /** * Struct for containing target class information during mixin application */ -class TargetClassContext extends ClassContext implements ITargetClassContext { +final class TargetClassContext extends ClassContext implements ITargetClassContext { /** * Logger @@ -88,7 +88,7 @@ class TargetClassContext extends ClassContext implements ITargetClassContext { * Target class metadata */ private final ClassInfo classInfo; - + /** * Source map that is generated for target class */ @@ -117,11 +117,6 @@ class TargetClassContext extends ClassContext implements ITargetClassContext { */ private final Set mixinMethods = new HashSet(); - /** - * Unique method and field indices - */ - private int nextUniqueMethodIndex, nextUniqueFieldIndex; - /** * True once mixins have been applied to this class */ @@ -328,18 +323,7 @@ class TargetClassContext extends ClassContext implements ITargetClassContext { } return target; } - - String getUniqueName(MethodNode method, boolean preservePrefix) { - String uniqueIndex = Integer.toHexString(this.nextUniqueMethodIndex++); - String pattern = preservePrefix ? "%2$s_$md$%1$s$%3$s" : "md%s$%s$%s"; - return String.format(pattern, this.sessionId.substring(30), method.name, uniqueIndex); - } - String getUniqueName(FieldNode field) { - String uniqueIndex = Integer.toHexString(this.nextUniqueFieldIndex++); - return String.format("fd%s$%s$%s", this.sessionId.substring(30), field.name, uniqueIndex); - } - /** * Apply mixins to this class */ @@ -364,7 +348,7 @@ class TargetClassContext extends ClassContext implements ITargetClassContext { } private void applySignature() { - this.getClassNode().signature = this.signature.toString(); + this.classNode.signature = this.signature.toString(); } private void checkMerges() { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/Extensions.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/Extensions.java index dcf092ac..8512cfba 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/Extensions.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/Extensions.java @@ -30,8 +30,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; -import org.spongepowered.asm.mixin.transformer.MixinTransformer; +import org.spongepowered.asm.service.ISyntheticClassRegistry; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; @@ -39,12 +40,7 @@ import com.google.common.collect.ImmutableList.Builder; /** * Mixin transformer extensions and common modules such as class generators */ -public final class Extensions { - - /** - * Mixin transformer - */ - private final MixinTransformer transformer; +public final class Extensions implements IExtensionRegistry { /** * All transformer extensions @@ -75,19 +71,17 @@ public final class Extensions { private final Map, IClassGenerator> generatorMap = new HashMap, IClassGenerator>(); + private final ISyntheticClassRegistry syntheticClassRegistry; + /** * Active transformer extensions */ private List activeExtensions = Collections.emptyList(); + + public Extensions(ISyntheticClassRegistry syntheticClassRegistry) { + this.syntheticClassRegistry = syntheticClassRegistry; + } - public Extensions(MixinTransformer transformer) { - this.transformer = transformer; - } - - public MixinTransformer getTransformer() { - return this.transformer; - } - /** * Add a new transformer extension * @@ -98,31 +92,42 @@ public final class Extensions { this.extensionMap.put(extension.getClass(), extension); } - /** - * Get all extensions + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry + * #getExtensions() */ + @Override public List getExtensions() { return Collections.unmodifiableList(this.extensions); } - /** - * Get all active extensions + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry + * #getActiveExtensions() */ + @Override public List getActiveExtensions() { return this.activeExtensions; } - /** - * Get a specific extension - * - * @param extensionClass extension class to look up - * @param extension type - * @return extension instance or null + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry + * #getExtension(java.lang.Class) */ @SuppressWarnings("unchecked") + @Override public T getExtension(Class extensionClass) { return (T)Extensions.lookup(extensionClass, this.extensionMap, this.extensions); - } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry + * #getSyntheticClassRegistry() + */ + @Override + public ISyntheticClassRegistry getSyntheticClassRegistry() { + return this.syntheticClassRegistry; + } /** * Selectively activate extensions based on the current environment @@ -170,11 +175,11 @@ public final class Extensions { * @param name Class name * @param force True to export even if the current environment settings * would normally disable it - * @param bytes Bytes to export + * @param classNode Class to export */ - public void export(MixinEnvironment env, String name, boolean force, byte[] bytes) { + public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { for (IExtension extension : this.activeExtensions) { - extension.export(env, name, force, bytes); + extension.export(env, name, force, classNode); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IClassGenerator.java index dd6bebf5..fa6b8781 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IClassGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IClassGenerator.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.mixin.transformer.ext; +import org.objectweb.asm.tree.ClassNode; + /** * Base interface for class generators */ @@ -36,8 +38,9 @@ public interface IClassGenerator { * generator to return a value will halt further processing of the request. * * @param name Class name to generate - * @return Class bytecode or null + * @param classNode Empty ClassNode to populate + * @return True if the class was generated */ - public abstract byte[] generate(String name); + public abstract boolean generate(String name, ClassNode classNode); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtension.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtension.java index 19f7937d..2be7374a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtension.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtension.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.mixin.transformer.ext; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; /** @@ -60,8 +61,8 @@ public interface IExtension { * @param name Class name * @param force True to export even if the current environment settings * would normally disable it - * @param bytes Bytes to export + * @param classNode Class to export */ - public abstract void export(MixinEnvironment env, String name, boolean force, byte[] bytes); + public abstract void export(MixinEnvironment env, String name, boolean force, ClassNode classNode); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtensionRegistry.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtensionRegistry.java new file mode 100644 index 00000000..c6573afc --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IExtensionRegistry.java @@ -0,0 +1,60 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.ext; + +import java.util.List; + +import org.spongepowered.asm.service.ISyntheticClassRegistry; + +/** + * Interface for the mixin Extensions registry + */ +public interface IExtensionRegistry { + + /** + * Get all extensions + */ + public abstract List getExtensions(); + + /** + * Get all active extensions + */ + public abstract List getActiveExtensions(); + + /** + * Get a specific extension + * + * @param extensionClass extension class to look up + * @param extension type + * @return extension instance or null + */ + public abstract T getExtension(Class extensionClass); + + /** + * Get the synthetic class registry + */ + public abstract ISyntheticClassRegistry getSyntheticClassRegistry(); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java index b2b90e73..7f72f773 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java @@ -48,4 +48,5 @@ public interface IHotSwap { * @param bytecode Bytecode of the class before mixin's have been applied */ public abstract void registerTargetClass(String name, byte[] bytecode); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/ITargetClassContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/ITargetClassContext.java index bec3b5b7..001249fb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/ITargetClassContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/ITargetClassContext.java @@ -24,7 +24,7 @@ */ package org.spongepowered.asm.mixin.transformer.ext; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.transformer.ClassInfo; /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckClass.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckClass.java index 33d815a7..570205d7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckClass.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckClass.java @@ -24,8 +24,9 @@ */ package org.spongepowered.asm.mixin.transformer.ext.extensions; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.util.CheckClassAdapter; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.util.CheckClassAdapter; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.throwables.MixinException; @@ -91,12 +92,12 @@ public class ExtensionCheckClass implements IExtension { } /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.transformer.ext.IExtension#export( - * org.spongepowered.asm.mixin.MixinEnvironment, java.lang.String, - * boolean, byte[]) + * @see org.spongepowered.asm.mixin.transformer.ext.IExtension + * #export(org.spongepowered.asm.mixin.MixinEnvironment, + * java.lang.String, boolean, org.objectweb.asm.tree.ClassNode) */ @Override - public void export(MixinEnvironment env, String name, boolean force, byte[] bytes) { + public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java index e6c4d2bc..c72601de 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java @@ -33,9 +33,9 @@ import java.util.Date; import java.util.HashSet; import java.util.Set; -import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.transformer.ClassInfo; @@ -92,6 +92,8 @@ public class ExtensionCheckInterfaces implements IExtension { debugOutputFolder.mkdirs(); this.csv = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_CSV_FILENAME); this.report = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_TXT_FILENAME); + + this.csv.getParentFile().mkdirs(); try { Files.write("Class,Method,Signature,Interface\n", this.csv, Charsets.ISO_8859_1); @@ -188,12 +190,12 @@ public class ExtensionCheckInterfaces implements IExtension { } /* (non-Javadoc) - * @see org.spongepowered.asm.mixin.transformer.ext.IExtension#export( - * org.spongepowered.asm.mixin.MixinEnvironment, java.lang.String, - * boolean, byte[]) + * @see org.spongepowered.asm.mixin.transformer.ext.IExtension + * #export(org.spongepowered.asm.mixin.MixinEnvironment, + * java.lang.String, boolean, org.objectweb.asm.tree.ClassNode) */ @Override - public void export(MixinEnvironment env, String name, boolean force, byte[] bytes) { + public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { } private void appendToCSVReport(String className, Method method, String iface) { @@ -215,7 +217,13 @@ public class ExtensionCheckInterfaces implements IExtension { } catch (Exception ex) { // never mind } finally { - IOUtils.closeQuietly(fos); + if (fos != null) { + try { + fos.close(); + } catch (IOException ex) { + ExtensionCheckInterfaces.logger.catching(ex); + } + } } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java index 02b3664a..427556f7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java @@ -29,17 +29,23 @@ import java.io.IOException; import java.lang.reflect.Constructor; import java.util.regex.Pattern; -import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.transformer.ext.IDecompiler; import org.spongepowered.asm.mixin.transformer.ext.IExtension; import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext; +import org.spongepowered.asm.transformers.MixinClassWriter; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.perf.Profiler.Section; +import com.google.common.io.Files; +import com.google.common.io.MoreFiles; +import com.google.common.io.RecursiveDeleteOption; + /** * Debug exporter */ @@ -69,7 +75,7 @@ public class ExtensionClassExporter implements IExtension { this.decompiler = this.initDecompiler(env, new File(Constants.DEBUG_OUTPUT_DIR, ExtensionClassExporter.EXPORT_JAVA_DIR)); try { - FileUtils.deleteDirectory(this.classExportDir); + MoreFiles.deleteRecursively(this.classExportDir.toPath(), RecursiveDeleteOption.ALLOW_INSECURE); } catch (IOException ex) { ExtensionClassExporter.logger.warn("Error cleaning class output directory: {}", ex.getMessage()); } @@ -125,13 +131,14 @@ public class ExtensionClassExporter implements IExtension { } @Override - public void export(MixinEnvironment env, String name, boolean force, byte[] bytes) { + public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { // Export transformed class for debugging purposes if (force || env.getOption(Option.DEBUG_EXPORT)) { String filter = env.getOptionValue(Option.DEBUG_EXPORT_FILTER); if (force || filter == null || this.applyFilter(filter, name)) { Section exportTimer = MixinEnvironment.getProfiler().begin("debug.export"); - File outputFile = this.dumpClass(name.replace('.', '/'), bytes); + + File outputFile = this.dumpClass(name.replace('.', '/'), classNode); if (this.decompiler != null) { this.decompiler.decompile(outputFile); } @@ -144,17 +151,34 @@ public class ExtensionClassExporter implements IExtension { * Write class bytecode to disk for debug purposes * * @param fileName filename to write (.class will be automatically appended) - * @param bytes class bytes + * @param classNode class to dump * @return written file */ - public File dumpClass(String fileName, byte[] bytes) { + public File dumpClass(String fileName, ClassNode classNode) { File outputFile = new File(this.classExportDir, fileName + ".class"); + outputFile.getParentFile().mkdirs(); try { - FileUtils.writeByteArrayToFile(outputFile, bytes); + byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode); + if (bytecode != null) { + Files.write(bytecode, outputFile); + } } catch (IOException ex) { // don't care } return outputFile; } + private static byte[] getClassBytes(ClassNode classNode) { + byte[] bytes = null; + try { + MixinClassWriter cw = new MixinClassWriter(ClassWriter.COMPUTE_FRAMES); + classNode.accept(cw); + bytes = cw.toByteArray(); + } catch (Exception ex) { + // well, damn + ex.printStackTrace(); + } + return bytes; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java new file mode 100644 index 00000000..1fa78680 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java @@ -0,0 +1,40 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.meta; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +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 }) +@Retention(RetentionPolicy.RUNTIME) +public @interface MixinProxy { + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java index fc99452b..ab996e9c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/InvalidMixinException.java @@ -27,6 +27,7 @@ package org.spongepowered.asm.mixin.transformer.throwables; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.transformer.ActivityStack; /** * Thrown by the mixin validator when a mixin fails a pre-flight check @@ -42,29 +43,57 @@ public class InvalidMixinException extends MixinException { this.mixin = mixin; } + public InvalidMixinException(IMixinInfo mixin, String message, ActivityStack activityContext) { + super(message, activityContext); + this.mixin = mixin; + } + public InvalidMixinException(IMixinContext context, String message) { this(context.getMixin(), message); } + public InvalidMixinException(IMixinContext context, String message, ActivityStack activityContext) { + this(context.getMixin(), message, activityContext); + } + public InvalidMixinException(IMixinInfo mixin, Throwable cause) { super(cause); this.mixin = mixin; } + public InvalidMixinException(IMixinInfo mixin, Throwable cause, ActivityStack activityContext) { + super(cause, activityContext); + this.mixin = mixin; + } + public InvalidMixinException(IMixinContext context, Throwable cause) { this(context.getMixin(), cause); } + public InvalidMixinException(IMixinContext context, Throwable cause, ActivityStack activityContext) { + this(context.getMixin(), cause, activityContext); + } + public InvalidMixinException(IMixinInfo mixin, String message, Throwable cause) { super(message, cause); this.mixin = mixin; } + public InvalidMixinException(IMixinInfo mixin, String message, Throwable cause, ActivityStack activityContext) { + super(message, cause, activityContext); + this.mixin = mixin; + } + public InvalidMixinException(IMixinContext context, String message, Throwable cause) { super(message, cause); this.mixin = context.getMixin(); } + public InvalidMixinException(IMixinContext context, String message, Throwable cause, ActivityStack activityContext) { + super(message, cause, activityContext); + this.mixin = context.getMixin(); + } + public IMixinInfo getMixin() { return this.mixin; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinApplicatorException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinApplicatorException.java new file mode 100644 index 00000000..98e5f0ae --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinApplicatorException.java @@ -0,0 +1,86 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.throwables; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.transformer.ActivityStack; + +/** + * Exception thrown for errors during mixin application + */ +public class MixinApplicatorException extends InvalidMixinException { + + private static final long serialVersionUID = 1L; + + public MixinApplicatorException(IMixinInfo context, String message) { + super(context, message, (ActivityStack)null); + } + + public MixinApplicatorException(IMixinInfo context, String message, ActivityStack activityContext) { + super(context, message, activityContext); + } + + public MixinApplicatorException(IMixinContext context, String message) { + super(context, message, (ActivityStack)null); + } + + public MixinApplicatorException(IMixinContext context, String message, ActivityStack activityContext) { + super(context, message, activityContext); + } + + public MixinApplicatorException(IMixinInfo mixin, String message, Throwable cause) { + super(mixin, message, cause, (ActivityStack)null); + } + + public MixinApplicatorException(IMixinInfo mixin, String message, Throwable cause, ActivityStack activityContext) { + super(mixin, message, cause, activityContext); + } + + public MixinApplicatorException(IMixinContext mixin, String message, Throwable cause) { + super(mixin, message, cause, (ActivityStack)null); + } + + public MixinApplicatorException(IMixinContext mixin, String message, Throwable cause, ActivityStack activityContext) { + super(mixin, message, cause, activityContext); + } + + public MixinApplicatorException(IMixinInfo mixin, Throwable cause) { + super(mixin, cause, (ActivityStack)null); + } + + public MixinApplicatorException(IMixinInfo mixin, Throwable cause, ActivityStack activityContext) { + super(mixin, cause, activityContext); + } + + public MixinApplicatorException(IMixinContext mixin, Throwable cause) { + super(mixin, cause, (ActivityStack)null); + } + + public MixinApplicatorException(IMixinContext mixin, Throwable cause, ActivityStack activityContext) { + super(mixin, cause, activityContext); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinPreProcessorException.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinPreProcessorException.java new file mode 100644 index 00000000..04aa972d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinPreProcessorException.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.throwables; + +import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.transformer.ActivityStack; + +/** + * Exception indicating a problem during pre-processing + */ +public class MixinPreProcessorException extends MixinException { + + private static final long serialVersionUID = 1L; + + public MixinPreProcessorException(String message, ActivityStack context) { + super(message, context); + } + + public MixinPreProcessorException(String message, Throwable cause, ActivityStack context) { + super(message, cause, context); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java index 103e6660..23341acc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/MixinTransformerError.java @@ -24,10 +24,12 @@ */ package org.spongepowered.asm.mixin.transformer.throwables; +import org.spongepowered.asm.mixin.throwables.MixinError; + /** * Error to throw for things which really shouldn't happen */ -public class MixinTransformerError extends Error { +public class MixinTransformerError extends MixinError { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/MappingMethod.java b/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/MappingMethod.java index 89cc5047..6c45f274 100644 --- a/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/MappingMethod.java +++ b/src/main/java/org/spongepowered/asm/obfuscation/mapping/common/MappingMethod.java @@ -122,7 +122,7 @@ public class MappingMethod implements IMapping { @Override public int hashCode() { - return Objects.hashCode(this.getName(), this.getDesc()); + return Objects.hashCode(this.getName(), this.desc); } @Override @@ -143,7 +143,7 @@ public class MappingMethod implements IMapping { @Override public String toString() { - String desc = this.getDesc(); + String desc = this.desc; return String.format("%s%s%s", this.getName(), desc != null ? " " : "", desc != null ? desc : ""); } diff --git a/src/main/java/org/spongepowered/asm/service/IClassBytecodeProvider.java b/src/main/java/org/spongepowered/asm/service/IClassBytecodeProvider.java index b8144338..bc8ac4cf 100644 --- a/src/main/java/org/spongepowered/asm/service/IClassBytecodeProvider.java +++ b/src/main/java/org/spongepowered/asm/service/IClassBytecodeProvider.java @@ -26,37 +26,13 @@ package org.spongepowered.asm.service; import java.io.IOException; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.tree.ClassNode; /** * Interface for object which can provide class bytecode */ public interface IClassBytecodeProvider { - /** - * Retrieve class bytes using available classloaders, does not transform the - * class - * - * @param name class name - * @param transformedName transformed class name - * @return class bytes or null if not found - * @throws IOException propagated - */ - public abstract byte[] getClassBytes(String name, String transformedName) throws IOException; - - /** - * Retrieve transformed class bytes by using available classloaders and - * running transformer delegation chain on the result if the runTransformers - * option is enabled - * - * @param name full class name - * @param runTransformers true to run transformers on the loaded bytecode - * @return transformed bytes - * @throws ClassNotFoundException if class not found - * @throws IOException propagated - */ - public abstract byte[] getClassBytes(String name, boolean runTransformers) throws ClassNotFoundException, IOException; - /** * Retrieve transformed class as an ASM tree * @@ -67,4 +43,15 @@ public interface IClassBytecodeProvider { */ public abstract ClassNode getClassNode(String name) throws ClassNotFoundException, IOException; + /** + * Retrieve transformed class as an ASM tree + * + * @param name full class name + * @param runTransformers true to run transformers when loading the class + * @return tree + * @throws ClassNotFoundException if class not found + * @throws IOException propagated + */ + public abstract ClassNode getClassNode(String name, boolean runTransformers) throws ClassNotFoundException, IOException; + } diff --git a/src/main/java/org/spongepowered/asm/service/IClassProvider.java b/src/main/java/org/spongepowered/asm/service/IClassProvider.java index 7cd1b8d3..6cc7ee31 100644 --- a/src/main/java/org/spongepowered/asm/service/IClassProvider.java +++ b/src/main/java/org/spongepowered/asm/service/IClassProvider.java @@ -33,7 +33,11 @@ public interface IClassProvider { /** * Get the current classpath from the service classloader + * + * @deprecated As of 0.8, use of this method is not a sensible way to access + * available containers. */ + @Deprecated public abstract URL[] getClassPath(); /** diff --git a/src/main/java/org/spongepowered/asm/service/IGlobalPropertyService.java b/src/main/java/org/spongepowered/asm/service/IGlobalPropertyService.java index 890cd42c..326d519b 100644 --- a/src/main/java/org/spongepowered/asm/service/IGlobalPropertyService.java +++ b/src/main/java/org/spongepowered/asm/service/IGlobalPropertyService.java @@ -28,6 +28,14 @@ package org.spongepowered.asm.service; * Global property service */ public interface IGlobalPropertyService { + + /** + * Resolve a property key from the service by name + * + * @param name name of key to resolve + * @return resolved key + */ + public abstract IPropertyKey resolveKey(String name); /** * Get a value from the global property store (blackboard) and duck-type it @@ -37,7 +45,7 @@ public interface IGlobalPropertyService { * @param duck type * @return value */ - public abstract T getProperty(String key); + public abstract T getProperty(IPropertyKey key); /** * Set the specified value in the global property store (blackboard) @@ -45,7 +53,7 @@ public interface IGlobalPropertyService { * @param key blackboard key * @param value new value */ - public abstract void setProperty(String key, Object value); + public abstract void setProperty(IPropertyKey key, Object value); /** * Get the value from the global property store (blackboard) but return @@ -56,7 +64,7 @@ public interface IGlobalPropertyService { * @param duck type * @return value from blackboard or default value */ - public abstract T getProperty(String key, T defaultValue); + public abstract T getProperty(IPropertyKey key, T defaultValue); /** * Get a string from the global property store (blackboard), returns default @@ -67,6 +75,6 @@ public interface IGlobalPropertyService { * set or is null * @return value from blackboard or default */ - public abstract String getPropertyString(String key, String defaultValue); + public abstract String getPropertyString(IPropertyKey key, String defaultValue); } diff --git a/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java b/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java index d2816c34..7559908e 100644 --- a/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java +++ b/src/main/java/org/spongepowered/asm/service/ILegacyClassTransformer.java @@ -29,25 +29,6 @@ package org.spongepowered.asm.service; * operate on raw byte arrays. */ public interface ILegacyClassTransformer extends ITransformer { - - /** - * Get the identifier for this transformer, usually the class name but for - * wrapped transformers this is the class name of the wrapped transformer - * - * @return transformer's identifying name - */ - public abstract String getName(); - - /** - * Get whether this transformer is excluded from delegation. Some - * transformers (such as the mixin transformer itself) should not be - * included in the delegation list because they are re-entrant or do not - * need to run on incoming bytecode. - * - * @return true if this transformer should be excluded from the - * transformer delegation list - */ - public abstract boolean isDelegationExcluded(); /** * Transform a class in byte array form. diff --git a/src/main/java/org/spongepowered/asm/service/IMixinService.java b/src/main/java/org/spongepowered/asm/service/IMixinService.java index 6b7e1a21..eff87a39 100644 --- a/src/main/java/org/spongepowered/asm/service/IMixinService.java +++ b/src/main/java/org/spongepowered/asm/service/IMixinService.java @@ -27,6 +27,7 @@ package org.spongepowered.asm.service; import java.io.InputStream; import java.util.Collection; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.util.ReEntranceLock; @@ -95,11 +96,29 @@ public interface IMixinService { */ public abstract IClassBytecodeProvider getBytecodeProvider(); +// /** +// * Return the synthetic class registry for this service +// */ +// public abstract ISyntheticClassRegistry getSyntheticClassRegistry(); + /** * Get additional platform agents for this service */ public abstract Collection getPlatformAgents(); + /** + * Get the primary container for the current environment, this is usually + * the container which contains the Mixin classes but can be another type + * of container as required by the environment + */ + public abstract IContainerHandle getPrimaryContainer(); + + /** + * Get a collection of containers in the current environment which contain + * mixins we should process + */ + public abstract Collection getMixinContainers(); + /** * Get a resource as a stream from the appropriate classloader, this is * delegated via the service so that the service can choose the correct @@ -141,6 +160,18 @@ public interface IMixinService { */ public abstract Collection getTransformers(); + /** + * Get currently available transformers in the environment + */ + public abstract Collection 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 */ diff --git a/src/main/java/org/spongepowered/asm/service/IPropertyKey.java b/src/main/java/org/spongepowered/asm/service/IPropertyKey.java new file mode 100644 index 00000000..495e32bf --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/IPropertyKey.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +/** + * Marker interface for property keys + */ +public interface IPropertyKey { + +} diff --git a/src/main/java/org/spongepowered/asm/service/ISyntheticClassInfo.java b/src/main/java/org/spongepowered/asm/service/ISyntheticClassInfo.java new file mode 100644 index 00000000..c8f8aa6c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ISyntheticClassInfo.java @@ -0,0 +1,57 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +/** + * Interface for information bundle about a synthetic class provided by Mixin. + * Specified as an interface so that existing generator structs can be decorated + * easily. + */ +public interface ISyntheticClassInfo { + + /** + * Get the mixin which incepted this synthetic class (if more than one mixin + * is resposible, returns the first) + */ + public abstract IMixinInfo getMixin(); + + /** + * Get the class name (binary name) + */ + public abstract String getName(); + + /** + * Get the class name (java format) + */ + public abstract String getClassName(); + + /** + * Get whether the synthetic class has been loaded (and therefore generated) + */ + public abstract boolean isLoaded(); + +} diff --git a/src/main/java/org/spongepowered/asm/service/ISyntheticClassRegistry.java b/src/main/java/org/spongepowered/asm/service/ISyntheticClassRegistry.java new file mode 100644 index 00000000..bf41770f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ISyntheticClassRegistry.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +/** + * Registry for synthetic classes, used internally to track which classes need + * to be generated at runtime by the mixin pipeline. + */ +public interface ISyntheticClassRegistry { + + /** + * Look up a registered synthetic class. Returns either information about + * the synthetic class, or null if no class with the specified name + * is registered. + * + * @param name Class name to look up + * @return Returns information about the named synthetic class or + * null if no synthetic class is found matching the specified + * name + */ + public abstract ISyntheticClassInfo findSyntheticClass(String name); + +} diff --git a/src/main/java/org/spongepowered/asm/service/ITransformer.java b/src/main/java/org/spongepowered/asm/service/ITransformer.java index 99336d66..15d6b577 100644 --- a/src/main/java/org/spongepowered/asm/service/ITransformer.java +++ b/src/main/java/org/spongepowered/asm/service/ITransformer.java @@ -28,5 +28,24 @@ package org.spongepowered.asm.service; * Base interface for transformer types */ public interface ITransformer { + + /** + * Get the identifier for this transformer, usually the class name but for + * wrapped transformers this is the class name of the wrapped transformer + * + * @return transformer's identifying name + */ + public abstract String getName(); + + /** + * Get whether this transformer is excluded from delegation. Some + * transformers (such as the mixin transformer itself) should not be + * included in the delegation list because they are re-entrant or do not + * need to run on incoming bytecode. + * + * @return true if this transformer should be excluded from the + * transformer delegation list + */ + public abstract boolean isDelegationExcluded(); } diff --git a/src/main/java/org/spongepowered/asm/service/ITreeClassTransformer.java b/src/main/java/org/spongepowered/asm/service/ITreeClassTransformer.java new file mode 100644 index 00000000..02d33249 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ITreeClassTransformer.java @@ -0,0 +1,46 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +import org.objectweb.asm.tree.ClassNode; + +/** + * Adapter interface for tree class transformers. Legacy class transformers + * operate on ASM tree structures (ClassNode). + */ +public interface ITreeClassTransformer extends ITransformer { + + /** + * Transform a class in byte array form. + * + * @param name Class original name + * @param transformedName Class name after being processed by the class name + * transformer + * @param classNode class tree + * @return true if transformations were applied + */ + public abstract boolean transformClassNode(String name, String transformedName, ClassNode classNode); + +} diff --git a/src/main/java/org/spongepowered/asm/service/MixinService.java b/src/main/java/org/spongepowered/asm/service/MixinService.java index c2d51d55..fcf932e0 100644 --- a/src/main/java/org/spongepowered/asm/service/MixinService.java +++ b/src/main/java/org/spongepowered/asm/service/MixinService.java @@ -65,6 +65,11 @@ public final class MixinService { */ private IMixinService service = null; + /** + * Global Property Service + */ + private IGlobalPropertyService propertyService; + /** * Singleton pattern */ @@ -78,8 +83,11 @@ public final class MixinService { try { bootService.bootstrap(); this.bootedServices.add(bootService.getServiceClassName()); + } catch (ServiceInitialisationException ex) { + // Expected if service cannot start + MixinService.logger.debug("Mixin bootstrap service {} is not available: {}", bootService.getClass().getName(), ex.getMessage()); } catch (Throwable th) { - MixinService.logger.catching(th); + MixinService.logger.throwing(th); } } } @@ -109,9 +117,6 @@ public final class MixinService { private synchronized IMixinService getServiceInstance() { if (this.service == null) { this.service = this.initService(); - if (this.service == null) { - throw new ServiceNotAvailableError("No mixin host service is available"); - } } return this.service; } @@ -129,12 +134,48 @@ public final class MixinService { return service; } } catch (ServiceConfigurationError serviceError) { - serviceError.printStackTrace(); +// serviceError.printStackTrace(); } catch (Throwable th) { - th.printStackTrace(); +// th.printStackTrace(); } } - return null; + throw new ServiceNotAvailableError("No mixin host service is available"); } + /** + * Blackboard + */ + public static IGlobalPropertyService getGlobalPropertyService() { + return MixinService.getInstance().getGlobalPropertyServiceInstance(); + } + + /** + * Retrieves the GlobalPropertyService Instance... FactoryProviderBean... + * Observer...InterfaceStream...Function...Broker... help me why won't it + * stop + */ + private IGlobalPropertyService getGlobalPropertyServiceInstance() { + if (this.propertyService == null) { + this.propertyService = this.initPropertyService(); + } + return this.propertyService; + } + + private IGlobalPropertyService initPropertyService() { + ServiceLoader serviceLoader = ServiceLoader.load(IGlobalPropertyService.class, + this.getClass().getClassLoader()); + + Iterator iter = serviceLoader.iterator(); + while (iter.hasNext()) { + try { + IGlobalPropertyService service = iter.next(); + return service; + } catch (ServiceConfigurationError serviceError) { +// serviceError.printStackTrace(); + } catch (Throwable th) { +// th.printStackTrace(); + } + } + throw new ServiceNotAvailableError("No mixin global property service is available"); + } } diff --git a/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java new file mode 100644 index 00000000..4ae544b3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/MixinServiceAbstract.java @@ -0,0 +1,203 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spongepowered.asm.launch.platform.IMixinPlatformAgent; +import org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; +import org.spongepowered.asm.mixin.MixinEnvironment.Phase; +import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.IConsumer; +import org.spongepowered.asm.util.ReEntranceLock; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; + +/** + * Mixin Service base class + */ +public abstract class MixinServiceAbstract implements IMixinService { + + // Consts + protected static final String LAUNCH_PACKAGE = "org.spongepowered.asm.launch."; + protected static final String MIXIN_PACKAGE = "org.spongepowered.asm.mixin."; + + /** + * Logger + */ + protected static final Logger logger = LogManager.getLogger("mixin"); + + /** + * Transformer re-entrance lock, shared between the mixin transformer and + * the metadata service + */ + protected final ReEntranceLock lock = new ReEntranceLock(1); + + /** + * Service agent instances + */ + private List serviceAgents; + + /** + * Detected side name + */ + private String sideName; + + @Override + public void prepare() { + } + + @Override + public Phase getInitialPhase() { + return Phase.PREINIT; + } + + @Override + public void beginPhase() { + } + + @Override + public void checkEnv(Object bootSource) { + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#init() + */ + @Override + public void init() { + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + agent.init(); + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getReEntranceLock() + */ + @Override + public ReEntranceLock getReEntranceLock() { + return this.lock; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getMixinContainers() + */ + @Override + public Collection getMixinContainers() { + Builder list = ImmutableList.builder(); + this.getContainersFromAgents(list); + return list.build(); + } + + /** + * Collect mixin containers from platform agents + */ + protected final void getContainersFromAgents(Builder list) { + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + Collection containers = agent.getMixinContainers(); + if (containers != null) { + list.addAll(containers); + } + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getSideName() + */ + @Override + public final String getSideName() { + if (this.sideName != null) { + return this.sideName; + } + + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + try { + String side = agent.getSideName(); + if (side != null) { + return this.sideName = side; + } + } catch (Exception ex) { + MixinServiceAbstract.logger.catching(ex); + } + } + + return Constants.SIDE_UNKNOWN; + } + + private List getServiceAgents() { + if (this.serviceAgents != null) { + return this.serviceAgents; + } + this.serviceAgents = new ArrayList(); + for (String agentClassName : this.getPlatformAgents()) { + try { + @SuppressWarnings("unchecked") + Class agentClass = (Class)this.getClassProvider().findClass(agentClassName, false); + IMixinPlatformAgent agent = agentClass.newInstance(); + if (agent instanceof IMixinPlatformServiceAgent) { + this.serviceAgents.add((IMixinPlatformServiceAgent)agent); + } + } catch (Exception ex) { + // Bad? + ex.printStackTrace(); + } + } + return this.serviceAgents; + } + + // AMS - TEMP WIRING TO AVOID THE COMPLEXITY OF MERGING MULTIPHASE WITH 0.8 + + /** + * Temp wiring. Called when the initial phase is spun up in the environment. + * + * @param phase Initial phase + * @param phaseConsumer Delegate for the service (or agents) to trigger + * later phases + * @deprecated temporary + */ + @Deprecated + public void wire(Phase phase, IConsumer phaseConsumer) { + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + agent.wire(phase, phaseConsumer); + } + } + + /** + * Temp wiring. Called when the default phase is started in the environment. + * @deprecated temporary + */ + @Deprecated + public void unwire() { + for (IMixinPlatformServiceAgent agent : this.getServiceAgents()) { + agent.unwire(); + } + } + +} diff --git a/src/main/java/org/spongepowered/asm/service/ServiceInitialisationException.java b/src/main/java/org/spongepowered/asm/service/ServiceInitialisationException.java new file mode 100644 index 00000000..39a7fda3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ServiceInitialisationException.java @@ -0,0 +1,51 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +/** + * Exception thrown when a service fails during initialisation, expected if the + * service is missing a dependency or is attempting to boot in an incompatible + * environment + */ +public class ServiceInitialisationException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ServiceInitialisationException() { + } + + public ServiceInitialisationException(String message) { + super(message); + } + + public ServiceInitialisationException(Throwable cause) { + super(cause); + } + + public ServiceInitialisationException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/org/spongepowered/asm/service/ServiceVersionError.java b/src/main/java/org/spongepowered/asm/service/ServiceVersionError.java new file mode 100644 index 00000000..94ef0f04 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ServiceVersionError.java @@ -0,0 +1,38 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +/** + * Error to throw when loaded service is out of date or mismatched + */ +public class ServiceVersionError extends Error { + + private static final long serialVersionUID = 1L; + + public ServiceVersionError(String message) { + super(message); + } + +} diff --git a/src/main/java/org/spongepowered/asm/transformers/MixinClassWriter.java b/src/main/java/org/spongepowered/asm/transformers/MixinClassWriter.java index 2a2583a0..a6c70516 100644 --- a/src/main/java/org/spongepowered/asm/transformers/MixinClassWriter.java +++ b/src/main/java/org/spongepowered/asm/transformers/MixinClassWriter.java @@ -24,8 +24,8 @@ */ package org.spongepowered.asm.transformers; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.ClassWriter; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; import org.spongepowered.asm.mixin.transformer.ClassInfo; /** diff --git a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java index dbc75b5f..8e07d2e9 100644 --- a/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java +++ b/src/main/java/org/spongepowered/asm/transformers/TreeTransformer.java @@ -24,9 +24,9 @@ */ package org.spongepowered.asm.transformers; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.service.ILegacyClassTransformer; /** diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index 28a0ff70..91c88b7b 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -27,14 +27,22 @@ package org.spongepowered.asm.util; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; +import java.util.Iterator; import java.util.List; import java.util.ListIterator; +import java.util.regex.Pattern; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AnnotationNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FieldNode; -import org.spongepowered.asm.lib.tree.MethodNode; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.Debug; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Intrinsic; +import org.spongepowered.asm.mixin.Overwrite; import com.google.common.base.Function; import com.google.common.base.Preconditions; @@ -45,6 +53,20 @@ import com.google.common.collect.Lists; */ public final class Annotations { + /** + * Annotations which are eligible for merge via {@link #mergeAnnotations} + */ + private static final Class[] MERGEABLE_MIXIN_ANNOTATIONS = new Class[] { + Overwrite.class, + Intrinsic.class, + Final.class, + Debug.class + }; + + private static Pattern mergeableAnnotationPattern = Annotations.getMergeableAnnotationPattern(); + + private static final Logger logger = LogManager.getLogger("mixin"); + private Annotations() { // Utility class } @@ -187,6 +209,7 @@ public final class Annotations { * @param annotationClasses Types of annotation to search for * @return the annotation, or null if not present */ + @SuppressWarnings("unchecked") // @SafeVarargs will not compile on Java 6 public static AnnotationNode getSingleVisible(MethodNode method, Class... annotationClasses) { return Annotations.getSingle(method.visibleAnnotations, annotationClasses); } @@ -199,6 +222,7 @@ public final class Annotations { * @param annotationClasses Types of annotation to search for * @return the annotation, or null if not present */ + @SuppressWarnings("unchecked") // @SafeVarargs will not compile on Java 6 public static AnnotationNode getSingleInvisible(MethodNode method, Class... annotationClasses) { return Annotations.getSingle(method.invisibleAnnotations, annotationClasses); } @@ -207,7 +231,7 @@ public final class Annotations { * Get a runtime-visible annotation of the specified class from the supplied * class node * - * @param classNode Source classNode + * @param classNode Source ClassNode * @param annotationClass Type of annotation to search for * @return the annotation, or null if not present */ @@ -219,7 +243,7 @@ public final class Annotations { * Get an invisible annotation of the specified class from the supplied * class node * - * @param classNode Source classNode + * @param classNode Source ClassNode * @param annotationClass Type of annotation to search for * @return the annotation, or null if not present */ @@ -467,6 +491,153 @@ public final class Annotations { return Collections.emptyList(); } + /** + * Set the value of an annotation node and do pseudo-duck-typing via Java's + * crappy generics + * + * @param annotation Annotation node to modify + * @param key Key to set + * @param value Value to set + * {@link ClassCastException} if your duck is actually a rooster + */ + public static void setValue(AnnotationNode annotation, String key, Object value) { + if (annotation == null) { + return; + } + + 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 (existingIndex > 0) { + annotation.values.set(existingIndex, Annotations.packValue(value)); + return; + } + + annotation.values.add(key); + annotation.values.add(Annotations.packValue(value)); + } + + private static Object packValue(Object value) { + Class type = value.getClass(); + if (type.isEnum()) { + return new String[] { Type.getDescriptor(type), value.toString()}; + } + return value; + } + + /** + * Merge annotations from the specified source ClassNode to the destination + * ClassNode, replaces annotations of the equivalent type on the target with + * annotations from the source. If the source node has no annotations then + * no action will take place, if the target node has no annotations then a + * new annotation list will be created. Annotations from the mixin package + * are not merged. + * + * @param from ClassNode to merge annotations from + * @param to ClassNode to merge annotations to + */ + public static void merge(ClassNode from, ClassNode to) { + to.visibleAnnotations = Annotations.merge(from.visibleAnnotations, to.visibleAnnotations, "class", from.name); + to.invisibleAnnotations = Annotations.merge(from.invisibleAnnotations, to.invisibleAnnotations, "class", from.name); + } + + /** + * Merge annotations from the specified source MethodNode to the destination + * MethodNode, replaces annotations of the equivalent type on the target + * with annotations from the source. If the source node has no annotations + * then no action will take place, if the target node has no annotations + * then a new annotation list will be created. Annotations from the mixin + * package are not merged. + * + * @param from MethodNode to merge annotations from + * @param to MethodNode to merge annotations to + */ + public static void merge(MethodNode from, MethodNode to) { + to.visibleAnnotations = Annotations.merge(from.visibleAnnotations, to.visibleAnnotations, "method", from.name); + to.invisibleAnnotations = Annotations.merge(from.invisibleAnnotations, to.invisibleAnnotations, "method", from.name); + } + + /** + * Merge annotations from the specified source FieldNode to the destination + * FieldNode, replaces annotations of the equivalent type on the target with + * annotations from the source. If the source node has no annotations then + * no action will take place, if the target node has no annotations then a + * new annotation list will be created. Annotations from the mixin package + * are not merged. + * + * @param from FieldNode to merge annotations from + * @param to FieldNode to merge annotations to + */ + public static void merge(FieldNode from, FieldNode to) { + to.visibleAnnotations = Annotations.merge(from.visibleAnnotations, to.visibleAnnotations, "field", from.name); + to.invisibleAnnotations = Annotations.merge(from.invisibleAnnotations, to.invisibleAnnotations, "field", from.name); + } + + /** + * Merge annotations from the source list to the target list. Returns the + * target list or a new list if the target list was null. + * + * @param from Annotations to merge + * @param to Annotation list to merge into + * @param type Type of element being merged + * @param name Name of the item being merged, for debugging purposes + * @return The merged list (or a new list if the target list was null) + */ + private static List merge(List from, List to, String type, String name) { + try { + if (from == null) { + return to; + } + + if (to == null) { + to = new ArrayList(); + } + + for (AnnotationNode annotation : from) { + if (!Annotations.isMergeableAnnotation(annotation)) { + continue; + } + + for (Iterator iter = to.iterator(); iter.hasNext();) { + if (iter.next().desc.equals(annotation.desc)) { + iter.remove(); + break; + } + } + + to.add(annotation); + } + } catch (Exception ex) { + Annotations.logger.warn("Exception encountered whilst merging annotations for {} {}", type, name); + } + + return to; + } + + private static boolean isMergeableAnnotation(AnnotationNode annotation) { + if (annotation.desc.startsWith("L" + Constants.MIXIN_PACKAGE_REF)) { + return Annotations.mergeableAnnotationPattern.matcher(annotation.desc).matches(); + } + return true; + } + + private static Pattern getMergeableAnnotationPattern() { + StringBuilder sb = new StringBuilder("^L("); + for (int i = 0; i < Annotations.MERGEABLE_MIXIN_ANNOTATIONS.length; i++) { + if (i > 0) { + sb.append('|'); + } + sb.append(Annotations.MERGEABLE_MIXIN_ANNOTATIONS[i].getName().replace('.', '/')); + } + return Pattern.compile(sb.append(");$").toString()); + } + private static > T toEnumValue(Class enumClass, String[] value) { if (!enumClass.getName().equals(Type.getType(value[0]).getClassName())) { throw new IllegalArgumentException("The supplied enum class does not match the stored enum value"); diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 9ccacc16..16b38032 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -33,22 +33,16 @@ import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; -import java.util.regex.Pattern; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.spongepowered.asm.lib.ClassReader; -import org.spongepowered.asm.lib.ClassWriter; -import org.spongepowered.asm.lib.MethodVisitor; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.*; -import org.spongepowered.asm.lib.util.CheckClassAdapter; -import org.spongepowered.asm.lib.util.TraceClassVisitor; -import org.spongepowered.asm.mixin.Debug; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Intrinsic; -import org.spongepowered.asm.mixin.Overwrite; +import org.objectweb.asm.Attribute; +import org.objectweb.asm.ClassReader; +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.*; +import org.objectweb.asm.util.CheckClassAdapter; +import org.objectweb.asm.util.TraceClassVisitor; import org.spongepowered.asm.util.throwables.SyntheticBridgeException; import org.spongepowered.asm.util.throwables.SyntheticBridgeException.Problem; @@ -98,6 +92,17 @@ public final class Bytecode { this.access = access; } + /** + * Get whether this visibility level represents a level which is the + * same or greater than the supplied level + * + * @param other level to compare to + * @return true if greater or equal + */ + public boolean isAtLeast(Visibility other) { + return other == null || other.ordinal() <= this.ordinal(); + } + } /** @@ -138,6 +143,8 @@ public final class Bytecode { return this.isSuper ? "super" : "this"; } } + + public static final int ASM_API_VERSION = Opcodes.ASM6; /** * Integer constant opcodes @@ -238,20 +245,6 @@ public final class Bytecode { null }; - /** - * Annotations which are eligible for merge via {@link #mergeAnnotations} - */ - private static final Class[] MERGEABLE_MIXIN_ANNOTATIONS = new Class[] { - Overwrite.class, - Intrinsic.class, - Final.class, - Debug.class - }; - - private static Pattern mergeableAnnotationPattern = Bytecode.getMergeableAnnotationPattern(); - - private static final Logger logger = LogManager.getLogger("mixin"); - private Bytecode() { // utility class } @@ -359,7 +352,7 @@ public final class Bytecode { /** * Dumps the output of CheckClassAdapter.verify to System.out * - * @param classNode the classNode to verify + * @param classNode the ClassNode to verify */ public static void dumpClass(ClassNode classNode) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); @@ -520,7 +513,7 @@ public final class Bytecode { * @param method method node * @return true if the method has the {@link Opcodes#ACC_STATIC} flag */ - public static boolean methodIsStatic(MethodNode method) { + public static boolean isStatic(MethodNode method) { return (method.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC; } @@ -530,7 +523,7 @@ public final class Bytecode { * @param field field node * @return true if the field has the {@link Opcodes#ACC_STATIC} flag */ - public static boolean fieldIsStatic(FieldNode field) { + public static boolean isStatic(FieldNode field) { return (field.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC; } @@ -719,7 +712,7 @@ public final class Bytecode { * @return modified descriptor; */ public static String changeDescriptorReturnType(String desc, String returnType) { - if (desc == null) { + if (desc == null || !desc.startsWith("(") || desc.lastIndexOf(')') < 1) { return null; } else if (returnType == null) { return desc; @@ -737,6 +730,16 @@ public final class Bytecode { public static String getSimpleName(Class annotationType) { return annotationType.getSimpleName(); } + + /** + * Returns the simple name of a type representing a class + * + * @param type type + * @return annotation's simple name + */ + public static String getSimpleName(Type type) { + return type.getSort() < Type.ARRAY ? type.getDescriptor() : Bytecode.getSimpleName(type.getClassName()); + } /** * Returns the simple name of an annotation, mainly used for printing @@ -820,9 +823,9 @@ public final class Bytecode { } else if (cst instanceof Double) { return Type.getType("D"); } else if (cst instanceof String) { - return Type.getType(Constants.STRING); + return Type.getType(Constants.STRING_DESC); } else if (cst instanceof Type) { - return Type.getType(Constants.CLASS); + return Type.getType(Constants.CLASS_DESC); } throw new IllegalArgumentException("LdcInsnNode with invalid payload type " + cst.getClass() + " in getConstant"); } @@ -890,6 +893,18 @@ public final class Bytecode { return Bytecode.hasFlag(f1, flag) == Bytecode.hasFlag(f2, flag); } + /** + * Checks whether the supplied method is virtual. Specifically this method + * returns true if the method is non-static and has an access level greater + * than private. + * + * @param method Method to test + * @return true if virtual + */ + public static boolean isVirtual(MethodNode method) { + return method != null && !Bytecode.isStatic(method) && Bytecode.getVisibility(method).isAtLeast(Visibility.PROTECTED); + } + /** * Returns the ordinal visibility of the supplied argument where a * higher value equals higher "visibility": @@ -1044,113 +1059,6 @@ public final class Bytecode { return type == null ? null : Bytecode.UNBOXING_METHODS[type.getSort()]; } - /** - * Merge annotations from the specified source ClassNode to the destination - * ClassNode, replaces annotations of the equivalent type on the target with - * annotations from the source. If the source node has no annotations then - * no action will take place, if the target node has no annotations then a - * new annotation list will be created. Annotations from the mixin package - * are not merged. - * - * @param from ClassNode to merge annotations from - * @param to ClassNode to merge annotations to - */ - public static void mergeAnnotations(ClassNode from, ClassNode to) { - to.visibleAnnotations = Bytecode.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, "class", from.name); - to.invisibleAnnotations = Bytecode.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, "class", from.name); - } - - /** - * Merge annotations from the specified source MethodNode to the destination - * MethodNode, replaces annotations of the equivalent type on the target - * with annotations from the source. If the source node has no annotations - * then no action will take place, if the target node has no annotations - * then a new annotation list will be created. Annotations from the mixin - * package are not merged. - * - * @param from MethodNode to merge annotations from - * @param to MethodNode to merge annotations to - */ - public static void mergeAnnotations(MethodNode from, MethodNode to) { - to.visibleAnnotations = Bytecode.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, "method", from.name); - to.invisibleAnnotations = Bytecode.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, "method", from.name); - } - - /** - * Merge annotations from the specified source FieldNode to the destination - * FieldNode, replaces annotations of the equivalent type on the target with - * annotations from the source. If the source node has no annotations then - * no action will take place, if the target node has no annotations then a - * new annotation list will be created. Annotations from the mixin package - * are not merged. - * - * @param from FieldNode to merge annotations from - * @param to FieldNode to merge annotations to - */ - public static void mergeAnnotations(FieldNode from, FieldNode to) { - to.visibleAnnotations = Bytecode.mergeAnnotations(from.visibleAnnotations, to.visibleAnnotations, "field", from.name); - to.invisibleAnnotations = Bytecode.mergeAnnotations(from.invisibleAnnotations, to.invisibleAnnotations, "field", from.name); - } - - /** - * Merge annotations from the source list to the target list. Returns the - * target list or a new list if the target list was null. - * - * @param from Annotations to merge - * @param to Annotation list to merge into - * @param type Type of element being merged - * @param name Name of the item being merged, for debugging purposes - * @return The merged list (or a new list if the target list was null) - */ - private static List mergeAnnotations(List from, List to, String type, String name) { - try { - if (from == null) { - return to; - } - - if (to == null) { - to = new ArrayList(); - } - - for (AnnotationNode annotation : from) { - if (!Bytecode.isMergeableAnnotation(annotation)) { - continue; - } - - for (Iterator iter = to.iterator(); iter.hasNext();) { - if (iter.next().desc.equals(annotation.desc)) { - iter.remove(); - break; - } - } - - to.add(annotation); - } - } catch (Exception ex) { - Bytecode.logger.warn("Exception encountered whilst merging annotations for {} {}", type, name); - } - - return to; - } - - private static boolean isMergeableAnnotation(AnnotationNode annotation) { - if (annotation.desc.startsWith("L" + Constants.MIXIN_PACKAGE_REF)) { - return Bytecode.mergeableAnnotationPattern.matcher(annotation.desc).matches(); - } - return true; - } - - private static Pattern getMergeableAnnotationPattern() { - StringBuilder sb = new StringBuilder("^L("); - for (int i = 0; i < Bytecode.MERGEABLE_MIXIN_ANNOTATIONS.length; i++) { - if (i > 0) { - sb.append('|'); - } - sb.append(Bytecode.MERGEABLE_MIXIN_ANNOTATIONS[i].getName().replace('.', '/')); - } - return Pattern.compile(sb.append(");$").toString()); - } - /** * Compares two synthetic bridge methods and throws an exception if they are * not compatible. @@ -1199,5 +1107,113 @@ public final class Bytecode { throw new SyntheticBridgeException(Problem.BAD_LENGTH, a.name, a.desc, index, null, null); } } + + /** + * Perform a naïve merge of ClassNode members onto a target ClassNode + * + * @param source Source ClassNode to merge from + * @param dest Destination ClassNode to merge to + */ + public static void merge(ClassNode source, ClassNode dest) { + if (source == null) { + return; + } + + if (dest == null) { + throw new NullPointerException("Target ClassNode for merge must not be null"); + } + + dest.version = Math.max(source.version, dest.version); + + dest.interfaces = Bytecode.merge(source.interfaces, dest.interfaces); + dest.invisibleAnnotations = Bytecode.merge(source.invisibleAnnotations, dest.invisibleAnnotations); + dest.visibleAnnotations = Bytecode.merge(source.visibleAnnotations, dest.visibleAnnotations); + dest.visibleTypeAnnotations = Bytecode.merge(source.visibleTypeAnnotations, dest.visibleTypeAnnotations); + dest.invisibleTypeAnnotations = Bytecode.merge(source.invisibleTypeAnnotations, dest.invisibleTypeAnnotations); + dest.attrs = Bytecode.merge(source.attrs, dest.attrs); + dest.innerClasses = Bytecode.merge(source.innerClasses, dest.innerClasses); + dest.fields = Bytecode.merge(source.fields, dest.fields); + dest.methods = Bytecode.merge(source.methods, dest.methods); + + } + /** + * Replace all values in a target ClassNode with values from the Source + * + * @param source Source ClassNode to merge from + * @param dest Destination ClassNode to merge to + */ + public static void replace(ClassNode source, ClassNode dest) { + if (source == null) { + return; + } + + if (dest == null) { + throw new NullPointerException("Target ClassNode for replace must not be null"); + } + + dest.name = source.name; + dest.signature = source.signature; + dest.superName = source.superName; + + dest.version = source.version; + dest.access = source.access; + dest.sourceDebug = source.sourceDebug; + + dest.sourceFile = source.sourceFile; + dest.module = source.module; + dest.outerClass = source.outerClass; + dest.outerMethod = source.outerMethod; + dest.outerMethodDesc = source.outerMethodDesc; + + Bytecode.clear(dest.interfaces); + Bytecode.clear(dest.visibleAnnotations); + Bytecode.clear(dest.invisibleAnnotations); + Bytecode.clear(dest.visibleTypeAnnotations); + Bytecode.clear(dest.invisibleTypeAnnotations); + Bytecode.clear(dest.attrs); + Bytecode.clear(dest.innerClasses); + Bytecode.clear(dest.fields); + Bytecode.clear(dest.methods); + + + // TODO Java 10 +// dest.nestHostClassExperimental = source.nestHostClassExperimental; +// Bytecode.clear(dest.nestMembersExperimental); +// dest.nestMembersExperimental = Bytecode.merge(source.nestMembersExperimental, dest.nestMembersExperimental); + + Bytecode.merge(source, dest); + + } + + /** + * Helper function to clear a list if it is not null + */ + private static void clear(List list) { + if (list != null) { + list.clear(); + } + } + + /** + * Helper function to merge all values of a source list into a destination + * taking into account that the source or destination are allowed to be null + * + * @param source source list + * @param destination destination list + * @return destination list populated with source values, new list if the + * destination was null, or null if both are null or empty + */ + private static List merge(List source, List destination) { + if (source == null || source.isEmpty()) { + return destination; + } + + if (destination == null) { + return new ArrayList(source); + } + + destination.addAll(source); + return destination; + } } diff --git a/src/main/java/org/spongepowered/asm/util/ClassSignature.java b/src/main/java/org/spongepowered/asm/util/ClassSignature.java index 8afdc819..0785536c 100644 --- a/src/main/java/org/spongepowered/asm/util/ClassSignature.java +++ b/src/main/java/org/spongepowered/asm/util/ClassSignature.java @@ -35,11 +35,10 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.signature.SignatureReader; -import org.spongepowered.asm.lib.signature.SignatureVisitor; -import org.spongepowered.asm.lib.signature.SignatureWriter; -import org.spongepowered.asm.lib.tree.ClassNode; +import org.objectweb.asm.signature.SignatureReader; +import org.objectweb.asm.signature.SignatureVisitor; +import org.objectweb.asm.signature.SignatureWriter; +import org.objectweb.asm.tree.ClassNode; /** * Represents an object-oriented view of a generic class signature. We use ASM's @@ -661,7 +660,7 @@ public class ClassSignature { abstract class SignatureElement extends SignatureVisitor { public SignatureElement() { - super(Opcodes.ASM5); + super(Bytecode.ASM_API_VERSION); } } @@ -898,7 +897,7 @@ public class ClassSignature { private FormalParamElement param; SignatureParser() { - super(Opcodes.ASM5); + super(Bytecode.ASM_API_VERSION); } @Override diff --git a/src/main/java/org/spongepowered/asm/util/Constants.java b/src/main/java/org/spongepowered/asm/util/Constants.java index 0e089294..8003e865 100644 --- a/src/main/java/org/spongepowered/asm/util/Constants.java +++ b/src/main/java/org/spongepowered/asm/util/Constants.java @@ -40,15 +40,24 @@ public abstract class Constants { public static final String MIXIN_PACKAGE = Mixin.class.getPackage().getName(); public static final String MIXIN_PACKAGE_REF = Constants.MIXIN_PACKAGE.replace('.', '/'); - public static final String STRING = "Ljava/lang/String;"; - public static final String OBJECT = "Ljava/lang/Object;"; - public static final String CLASS = "Ljava/lang/Class;"; + public static final String STRING = "java/lang/String"; + public static final String OBJECT = "java/lang/Object"; + public static final String CLASS = "java/lang/Class"; + + public static final String STRING_DESC = "L" + Constants.STRING + ";"; + public static final String OBJECT_DESC = "L" + Constants.OBJECT + ";"; + public static final String CLASS_DESC = "L" + Constants.CLASS + ";"; public static final String SYNTHETIC_PACKAGE = "org.spongepowered.asm.synthetic"; public static final char UNICODE_SNOWMAN = '\u2603'; public static final File DEBUG_OUTPUT_DIR = new File(Constants.DEBUG_OUTPUT_PATH); + public static final String SIDE_DEDICATEDSERVER = "DEDICATEDSERVER"; + public static final String SIDE_SERVER = "SERVER"; + public static final String SIDE_CLIENT = "CLIENT"; + public static final String SIDE_UNKNOWN = "UNKNOWN"; + private Constants() {} /** diff --git a/src/main/java/org/spongepowered/asm/util/ConstraintParser.java b/src/main/java/org/spongepowered/asm/util/ConstraintParser.java index 794ba973..0479dc67 100644 --- a/src/main/java/org/spongepowered/asm/util/ConstraintParser.java +++ b/src/main/java/org/spongepowered/asm/util/ConstraintParser.java @@ -24,10 +24,11 @@ */ package org.spongepowered.asm.util; +import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.spongepowered.asm.lib.tree.AnnotationNode; +import org.objectweb.asm.tree.AnnotationNode; import org.spongepowered.asm.util.throwables.ConstraintViolationException; import org.spongepowered.asm.util.throwables.InvalidConstraintException; @@ -286,7 +287,7 @@ public final class ConstraintParser { return Constraint.NONE; } - String[] exprs = expr.replaceAll("\\s", "").toUpperCase().split(";"); + String[] exprs = expr.replaceAll("\\s", "").toUpperCase(Locale.ROOT).split(";"); Constraint head = null; for (String subExpr : exprs) { Constraint next = new Constraint(subExpr); diff --git a/src/main/java/org/spongepowered/asm/util/IConsumer.java b/src/main/java/org/spongepowered/asm/util/IConsumer.java new file mode 100644 index 00000000..616dc555 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/IConsumer.java @@ -0,0 +1,41 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util; + +/** + * No Java 8 here but I need this interface + * + * @param Consumed item type + */ +public interface IConsumer { + + /** + * Accept the supplied item + * + * @param item item to consume + */ + public abstract void accept(TItem item); + +} diff --git a/src/main/java/org/spongepowered/asm/util/JavaVersion.java b/src/main/java/org/spongepowered/asm/util/JavaVersion.java index 731e996b..83731a81 100644 --- a/src/main/java/org/spongepowered/asm/util/JavaVersion.java +++ b/src/main/java/org/spongepowered/asm/util/JavaVersion.java @@ -48,9 +48,13 @@ public abstract class JavaVersion { private static double resolveCurrentVersion() { String version = System.getProperty("java.version"); - Matcher matcher = Pattern.compile("[0-9]+\\.[0-9]+").matcher(version); - if (matcher.find()) { - return Double.parseDouble(matcher.group()); + Matcher decimalMatcher = Pattern.compile("[0-9]+\\.[0-9]+").matcher(version); + if (decimalMatcher.find()) { + return Double.parseDouble(decimalMatcher.group()); + } + Matcher numberMatcher = Pattern.compile("[0-9]+").matcher(version); + if (numberMatcher.find()) { + return Double.parseDouble(numberMatcher.group()); } return 1.6; } diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index 1205fcc9..dae2721b 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -30,26 +30,26 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.ClassNode; -import org.spongepowered.asm.lib.tree.FrameNode; -import org.spongepowered.asm.lib.tree.InsnList; -import org.spongepowered.asm.lib.tree.LabelNode; -import org.spongepowered.asm.lib.tree.LineNumberNode; -import org.spongepowered.asm.lib.tree.LocalVariableNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; -import org.spongepowered.asm.lib.tree.analysis.Analyzer; -import org.spongepowered.asm.lib.tree.analysis.AnalyzerException; -import org.spongepowered.asm.lib.tree.analysis.BasicValue; -import org.spongepowered.asm.lib.tree.analysis.Frame; +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.FrameNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LineNumberNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; +import org.objectweb.asm.tree.analysis.Analyzer; +import org.objectweb.asm.tree.analysis.AnalyzerException; +import org.objectweb.asm.tree.analysis.BasicValue; +import org.objectweb.asm.tree.analysis.Frame; import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.ClassInfo.FrameData; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.util.asm.MixinVerifier; -import org.spongepowered.asm.util.throwables.LVTGeneratorException; +import org.spongepowered.asm.util.throwables.LVTGeneratorError; /** * Utility methods for working with local variables using ASM @@ -134,11 +134,11 @@ public final class Locals { ClassInfo classInfo = ClassInfo.forName(classNode.name); if (classInfo == null) { - throw new LVTGeneratorException("Could not load class metadata for " + classNode.name + " generating LVT for " + method.name); + throw new LVTGeneratorError("Could not load class metadata for " + classNode.name + " generating LVT for " + method.name); } Method methodInfo = classInfo.findMethod(method); if (methodInfo == null) { - throw new LVTGeneratorException("Could not locate method metadata for " + method.name + " generating LVT in " + classNode.name); + throw new LVTGeneratorError("Could not locate method metadata for " + method.name + " generating LVT in " + classNode.name); } List frames = methodInfo.getFrames(); @@ -147,7 +147,7 @@ public final class Locals { // Initialise implicit "this" reference in non-static methods if ((method.access & Opcodes.ACC_STATIC) == 0) { - frame[local++] = new LocalVariableNode("this", classNode.name, null, null, null, 0); + frame[local++] = new LocalVariableNode("this", Type.getObjectType(classNode.name).toString(), null, null, null, 0); } // Initialise method arguments @@ -191,7 +191,7 @@ public final class Locals { frame[framePos] = null; // TOP } } else { - throw new LVTGeneratorException("Unrecognised locals opcode " + localType + " in locals array at position " + localPos + throw new LVTGeneratorError("Unrecognised locals opcode " + localType + " in locals array at position " + localPos + " in " + classNode.name + "." + method.name + method.desc); } } else if (localType == null) { @@ -199,7 +199,7 @@ public final class Locals { frame[framePos] = null; } } else { - throw new LVTGeneratorException("Invalid value " + localType + " in locals array at position " + localPos + throw new LVTGeneratorError("Invalid value " + localType + " in locals array at position " + localPos + " in " + classNode.name + "." + method.name + method.desc); } } @@ -341,7 +341,7 @@ public final class Locals { // Use Analyzer to generate the bytecode frames Analyzer analyzer = new Analyzer( - new MixinVerifier(Type.getObjectType(classNode.name), objectType, interfaces, false)); + new MixinVerifier(Bytecode.ASM_API_VERSION, Type.getObjectType(classNode.name), objectType, interfaces, false)); try { analyzer.analyze(classNode.name, method); } catch (AnalyzerException ex) { diff --git a/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java b/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java index 3fdab6d0..5cc35490 100644 --- a/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java +++ b/src/main/java/org/spongepowered/asm/util/ReEntranceLock.java @@ -25,7 +25,8 @@ package org.spongepowered.asm.util; /** - * Re-entrance semaphore used to share re-entrance data with the TreeInfo + * Re-entrance semaphore used to share re-entrance data with the metadata + * service */ public class ReEntranceLock { diff --git a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java index 2d06d71f..37e7225c 100644 --- a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java +++ b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java @@ -24,11 +24,11 @@ */ package org.spongepowered.asm.util; -import org.spongepowered.asm.lib.Opcodes; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.LocalVariableNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import com.google.common.base.Strings; @@ -78,8 +78,8 @@ public class SignaturePrinter { this.setModifiers(method); } - public SignaturePrinter(MemberInfo member) { - this(member.name, member.desc); + public SignaturePrinter(ITargetSelectorByName member) { + this(member.getName(), member.getDesc()); } public SignaturePrinter(String name, String desc) { diff --git a/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java b/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java new file mode 100644 index 00000000..aa213c3e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/ElementNode.java @@ -0,0 +1,303 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.asm; + +import java.util.ArrayList; +import java.util.List; + +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.MethodNode; + +/** + * Holder for {@link FieldNode} and {@link MethodNode} for consumers which can + * handle both types (since they have a lot in common), with common accessors + * for overlapping properties. + * + * @param node type + */ +public abstract class ElementNode { + + /** + * ElementNode for MethodNode + */ + static class ElementNodeMethod extends ElementNode { + + private MethodNode method; + + ElementNodeMethod(ClassNode owner, MethodNode method) { + super(owner); + this.method = method; + } + + @Override + public boolean isMethod() { + return true; + } + + @Override + public MethodNode getMethod() { + return this.method; + } + + @Override + public String getName() { + return this.method.name; + } + + @Override + public String getDesc() { + return this.method.desc; + } + + @Override + public String getSignature() { + return this.method.signature; + } + + @Override + public MethodNode get() { + return this.method; + } + + @Override + public String toString() { + return String.format("MethodElement[%s%s]", this.method.name, this.method.desc); + } + + } + + /** + * ElementNode for FieldNode + */ + static class ElementNodeField extends ElementNode { + + private FieldNode field; + + ElementNodeField(ClassNode owner, FieldNode field) { + super(owner); + this.field = field; + } + + @Override + public boolean isField() { + return true; + } + + @Override + public FieldNode getField() { + return this.field; + } + + @Override + public String getName() { + return this.field.name; + } + + @Override + public String getDesc() { + return this.field.desc; + } + + @Override + public String getSignature() { + return this.field.signature; + } + + @Override + public FieldNode get() { + return this.field; + } + + @Override + public String toString() { + return String.format("FieldElement[%s:%s]", this.field.name, this.field.desc); + } + + } + + /** + * The class which owns this element, can be null + */ + private final ClassNode owner; + + protected ElementNode(ClassNode owner) { + this.owner = owner; + } + + /** + * Get whether this element is a method + */ + public boolean isMethod() { + return false; + } + + /** + * get whether this element is a field + */ + public boolean isField() { + return false; + } + + /** + * Get the {@link MethodNode} if this member is a method, otherwise returns + * null + */ + public MethodNode getMethod() { + return null; + } + + /** + * Get the {@link FieldNode} if this member is a field, otherwise returns + * null + */ + public FieldNode getField() { + return null; + } + + /** + * Get the element's owner, can be null + */ + public ClassNode getOwner() { + return this.owner; + } + + /** + * Get the element owner's name, if this element has an owner, otherwise + * returns null + */ + public String getOwnerName() { + return this.owner != null ? this.owner.name : null; + } + + /** + * Get the element name + */ + public abstract String getName(); + + /** + * Get the element descriptor + */ + public abstract String getDesc(); + + /** + * Get the element signature, can be null + */ + public abstract String getSignature(); + + /** + * Returns the node with horrible duck typing + */ + public abstract TNode get(); + + /** + * Create an ElementNode wrapper for the supplied method node + * + * @param owner class which owns the method or null + * @param method Method node to wrap + * @return ElementNode + */ + public static ElementNode of(ClassNode owner, MethodNode method) { + return new ElementNodeMethod(owner, method); + } + + /** + * Create an ElementNode wrapper for the supplied field node + * + * @param owner class which owns the field or null + * @param field Field node to wrap + * @return ElementNode + */ + public static ElementNode of(ClassNode owner, FieldNode field) { + return new ElementNodeField(owner, field); + } + + /** + * Create an ElementNode wrapper for the supplied node object + * + * @param owner class which owns the node or null + * @param node Node to wrap + * @param Node type + * @return ElementNode + * @throws IllegalArgumentException if the supplied argument is not a + * {@link MethodNode} or {@link FieldNode} + */ + @SuppressWarnings("unchecked") + public static ElementNode of(ClassNode owner, TNode node) { + if (node instanceof MethodNode) { + return (ElementNode)new ElementNodeMethod(owner, (MethodNode)node); + } else if (node instanceof FieldNode) { + return (ElementNode)new ElementNodeField(owner, (FieldNode)node); + } + throw new IllegalArgumentException("Could not create ElementNode for unknown node type: " + node.getClass().getName()); + } + + /** + * Convert the supplied list of nodes to a list of wrapped ElementNodes + * + * @param owner Owner of the supplied nodes, can be null + * @param list List of nodes + * @param Node type + * @return List of wrapped nodes + */ + public static List> listOf(ClassNode owner, List list) { + List> nodes = new ArrayList>(); + for (TNode node : list) { + nodes.add(ElementNode.of(owner, node)); + } + return nodes; + } + + /** + * Get a list of wrapped ElementNodes for the fields of the supplied owner + * class + * + * @param owner Class to get fields, must not be null + * @return List of wrapped nodes + */ + public static List> fieldList(ClassNode owner) { + List> fields = new ArrayList>(); + for (FieldNode field : owner.fields) { + fields.add(new ElementNodeField(owner, field)); + } + return fields; + } + + /** + * Get a list of wrapped ElementNodes for the methods of the supplied owner + * class + * + * @param owner Class to get methods, must not be null + * @return List of wrapped nodes + */ + public static List> methodList(ClassNode owner) { + List> methods = new ArrayList>(); + for (MethodNode method : owner.methods) { + methods.add(new ElementNodeMethod(owner, method)); + } + return methods; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/MethodVisitorEx.java b/src/main/java/org/spongepowered/asm/util/asm/MethodVisitorEx.java index e8a6f6e8..78ca1a13 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/MethodVisitorEx.java +++ b/src/main/java/org/spongepowered/asm/util/asm/MethodVisitorEx.java @@ -24,8 +24,8 @@ */ package org.spongepowered.asm.util.asm; -import org.spongepowered.asm.lib.MethodVisitor; -import org.spongepowered.asm.lib.Opcodes; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; import org.spongepowered.asm.util.Bytecode; /** @@ -34,7 +34,7 @@ import org.spongepowered.asm.util.Bytecode; public class MethodVisitorEx extends MethodVisitor { public MethodVisitorEx(MethodVisitor mv) { - super(Opcodes.ASM5, mv); + super(Bytecode.ASM_API_VERSION, mv); } /** diff --git a/src/main/java/org/spongepowered/asm/util/asm/MixinVerifier.java b/src/main/java/org/spongepowered/asm/util/asm/MixinVerifier.java index 5cc276c1..8519887b 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/MixinVerifier.java +++ b/src/main/java/org/spongepowered/asm/util/asm/MixinVerifier.java @@ -26,9 +26,10 @@ package org.spongepowered.asm.util.asm; import java.util.List; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.analysis.SimpleVerifier; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.analysis.SimpleVerifier; import org.spongepowered.asm.mixin.transformer.ClassInfo; +import org.spongepowered.asm.mixin.transformer.ClassInfo.TypeLookup; /** * Verifier which handles class info lookups via {@link ClassInfo} @@ -40,8 +41,8 @@ public class MixinVerifier extends SimpleVerifier { private List currentClassInterfaces; private boolean isInterface; - public MixinVerifier(Type currentClass, Type currentSuperClass, List currentClassInterfaces, boolean isInterface) { - super(currentClass, currentSuperClass, currentClassInterfaces, isInterface); + public MixinVerifier(int api, Type currentClass, Type currentSuperClass, List currentClassInterfaces, boolean isInterface) { + super(api, currentClass, currentSuperClass, currentClassInterfaces, isInterface); this.currentClass = currentClass; this.currentSuperClass = currentSuperClass; this.currentClassInterfaces = currentClassInterfaces; @@ -53,7 +54,7 @@ public class MixinVerifier extends SimpleVerifier { if (this.currentClass != null && type.equals(this.currentClass)) { return this.isInterface; } - return ClassInfo.forType(type).isInterface(); + return ClassInfo.forType(type, TypeLookup.ELEMENT_TYPE).isInterface(); } @Override @@ -61,7 +62,7 @@ public class MixinVerifier extends SimpleVerifier { if (this.currentClass != null && type.equals(this.currentClass)) { return this.currentSuperClass; } - ClassInfo c = ClassInfo.forType(type).getSuperClass(); + ClassInfo c = ClassInfo.forType(type, TypeLookup.ELEMENT_TYPE).getSuperClass(); return c == null ? null : Type.getType("L" + c.getName() + ";"); } @@ -93,13 +94,13 @@ public class MixinVerifier extends SimpleVerifier { } return false; } - ClassInfo typeInfo = ClassInfo.forType(type); + ClassInfo typeInfo = ClassInfo.forType(type, TypeLookup.ELEMENT_TYPE); if (typeInfo == null) { return false; } if (typeInfo.isInterface()) { typeInfo = ClassInfo.forName("java/lang/Object"); } - return ClassInfo.forType(other).hasSuperClass(typeInfo); + return ClassInfo.forType(other, TypeLookup.ELEMENT_TYPE).hasSuperClass(typeInfo); } } diff --git a/src/main/java/org/spongepowered/asm/util/perf/Profiler.java b/src/main/java/org/spongepowered/asm/util/perf/Profiler.java index f4000383..d3843e43 100644 --- a/src/main/java/org/spongepowered/asm/util/perf/Profiler.java +++ b/src/main/java/org/spongepowered/asm/util/perf/Profiler.java @@ -24,9 +24,12 @@ */ package org.spongepowered.asm.util.perf; +import java.lang.reflect.Method; import java.text.DecimalFormat; import java.util.*; +import java.util.Map.Entry; +import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.PrettyPrinter; import org.spongepowered.asm.util.PrettyPrinter.Alignment; @@ -37,6 +40,8 @@ import com.google.common.base.Joiner; */ public final class Profiler { + private static final String METRONOME_AGENT_CLASS = "org.spongepowered.metronome.Agent"; + /** * Flag to indicate a root section. Root sections are always recorded at the * root wherever they occur, but may appear under other sections in order to @@ -779,5 +784,108 @@ public final class Profiler { printer.tr(values); } + + /** + * Print summary of mixin performance to the console + */ + public void printSummary() { + + DecimalFormat threedp = new DecimalFormat("(###0.000"); + DecimalFormat onedp = new DecimalFormat("(###0.0"); + PrettyPrinter printer = this.printer(false, false); + + long prepareTime = this.get("mixin.prepare").getTotalTime(); + long readTime = this.get("mixin.read").getTotalTime(); + long applyTime = this.get("mixin.apply").getTotalTime(); + long writeTime = this.get("mixin.write").getTotalTime(); + long totalMixinTime = this.get("mixin").getTotalTime(); + + long loadTime = this.get("class.load").getTotalTime(); + long transformTime = this.get("class.transform").getTotalTime(); + long exportTime = this.get("mixin.debug.export").getTotalTime(); + long actualTime = totalMixinTime - loadTime - transformTime - exportTime; + double timeSliceMixin = ((double)actualTime / (double)totalMixinTime) * 100.0D; + double timeSliceLoad = ((double)loadTime / (double)totalMixinTime) * 100.0D; + double timeSliceTransform = ((double)transformTime / (double)totalMixinTime) * 100.0D; + double timeSliceExport = ((double)exportTime / (double)totalMixinTime) * 100.0D; + + long worstTransformerTime = 0L; + Section worstTransformer = null; + + for (Section section : this.getSections()) { + long transformerTime = section.getName().startsWith("class.transform.") ? section.getTotalTime() : 0L; + if (transformerTime > worstTransformerTime) { + worstTransformerTime = transformerTime; + worstTransformer = section; + } + } + + printer.hr().add("Summary").hr().add(); + + String format = "%9d ms %12s seconds)"; + printer.kv("Total mixin time", format, totalMixinTime, threedp.format(totalMixinTime * 0.001)).add(); + printer.kv("Preparing mixins", format, prepareTime, threedp.format(prepareTime * 0.001)); + printer.kv("Reading input", format, readTime, threedp.format(readTime * 0.001)); + printer.kv("Applying mixins", format, applyTime, threedp.format(applyTime * 0.001)); + printer.kv("Writing output", format, writeTime, threedp.format(writeTime * 0.001)).add(); + + printer.kv("of which",""); + printer.kv("Time spent loading from disk", format, loadTime, threedp.format(loadTime * 0.001)); + printer.kv("Time spent transforming classes", format, transformTime, threedp.format(transformTime * 0.001)).add(); + + if (worstTransformer != null) { + printer.kv("Worst transformer", worstTransformer.getName()); + printer.kv("Class", worstTransformer.getInfo()); + printer.kv("Time spent", "%s seconds", worstTransformer.getTotalSeconds()); + printer.kv("called", "%d times", worstTransformer.getTotalCount()).add(); + } + + printer.kv(" Time allocation: Processing mixins", "%9d ms %10s%% of total)", actualTime, onedp.format(timeSliceMixin)); + printer.kv("Loading classes", "%9d ms %10s%% of total)", loadTime, onedp.format(timeSliceLoad)); + printer.kv("Running transformers", "%9d ms %10s%% of total)", transformTime, onedp.format(timeSliceTransform)); + if (exportTime > 0L) { + printer.kv("Exporting classes (debug)", "%9d ms %10s%% of total)", exportTime, onedp.format(timeSliceExport)); + } + printer.add(); + + try { + Class agent = MixinService.getService().getClassProvider().findAgentClass(Profiler.METRONOME_AGENT_CLASS, false); + Method mdGetTimes = agent.getDeclaredMethod("getTimes"); + + @SuppressWarnings("unchecked") + Map times = (Map)mdGetTimes.invoke(null); + + printer.hr().add("Transformer Times").hr().add(); + + int longest = 10; + for (Entry entry : times.entrySet()) { + longest = Math.max(longest, entry.getKey().length()); + } + + for (Entry entry : times.entrySet()) { + String name = entry.getKey(); + long mixinTime = 0L; + for (Section section : this.getSections()) { + if (name.equals(section.getInfo())) { + mixinTime = section.getTotalTime(); + break; + } + } + + if (mixinTime > 0L) { + printer.add("%-" + longest + "s %8s ms %8s ms in mixin)", name, entry.getValue() + mixinTime, "(" + mixinTime); + } else { + printer.add("%-" + longest + "s %8s ms", name, entry.getValue()); + } + } + + printer.add(); + + } catch (Throwable th) { + // Metronome agent not loaded + } + + printer.print(); + } } diff --git a/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorException.java b/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorError.java similarity index 86% rename from src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorException.java rename to src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorError.java index 06646449..caef6e83 100644 --- a/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorException.java +++ b/src/main/java/org/spongepowered/asm/util/throwables/LVTGeneratorError.java @@ -24,21 +24,21 @@ */ package org.spongepowered.asm.util.throwables; -import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.mixin.throwables.MixinError; /** * Exception thrown when something goes horribly wrong whilst summoning the * antichrist generating the LVT for a target method. */ -public class LVTGeneratorException extends MixinException { +public class LVTGeneratorError extends MixinError { private static final long serialVersionUID = 1L; - public LVTGeneratorException(String message) { + public LVTGeneratorError(String message) { super(message); } - public LVTGeneratorException(String message, Throwable cause) { + public LVTGeneratorError(String message, Throwable cause) { super(message, cause); } diff --git a/src/main/java/org/spongepowered/asm/util/throwables/SyntheticBridgeException.java b/src/main/java/org/spongepowered/asm/util/throwables/SyntheticBridgeException.java index 40ddfbc0..0138c6bd 100644 --- a/src/main/java/org/spongepowered/asm/util/throwables/SyntheticBridgeException.java +++ b/src/main/java/org/spongepowered/asm/util/throwables/SyntheticBridgeException.java @@ -27,12 +27,12 @@ package org.spongepowered.asm.util.throwables; import java.util.Iterator; import java.util.ListIterator; -import org.spongepowered.asm.lib.Type; -import org.spongepowered.asm.lib.tree.AbstractInsnNode; -import org.spongepowered.asm.lib.tree.MethodInsnNode; -import org.spongepowered.asm.lib.tree.MethodNode; -import org.spongepowered.asm.lib.tree.TypeInsnNode; -import org.spongepowered.asm.lib.tree.VarInsnNode; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.mixin.transformer.ClassInfo; diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/IClassInterceptor.java b/src/modlauncher/java/org/spongepowered/asm/launch/IClassInterceptor.java new file mode 100644 index 00000000..c1b8e656 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/IClassInterceptor.java @@ -0,0 +1,32 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +/** + * Class interceptor. Decorator interface only. Blatant h4x. + */ +public interface IClassInterceptor extends IClassProcessor { + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/IClassProcessNominator.java b/src/modlauncher/java/org/spongepowered/asm/launch/IClassProcessNominator.java new file mode 100644 index 00000000..97a7c2d2 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/IClassProcessNominator.java @@ -0,0 +1,45 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +//package org.spongepowered.asm.launch; +// +//import org.objectweb.asm.Type; +// +///** +// * Callback for nominating whether the mixin pipeline needs to operate on a +// * class +// */ +//@FunctionalInterface +//public interface IClassProcessNominator { +// +// /** +// * Notify that a class has begun to travel through the transformer chain +// * +// * @param classType Class info +// * @param isEmpty True if the class needs to be synthesized +// * @return True if the class should be processed +// */ +// public abstract boolean onBeginProcessing(Type classType, boolean isEmpty); +// +//} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/IClassProcessor.java b/src/modlauncher/java/org/spongepowered/asm/launch/IClassProcessor.java new file mode 100644 index 00000000..2b64e5b3 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/IClassProcessor.java @@ -0,0 +1,63 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +import java.util.EnumSet; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; + +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; + +/** + * Interface for shunting classes through other parts of the Mixin subsystem + * when they arrive at the plugin + */ +public interface IClassProcessor { + + /** + * If this class processor wants to receive the {@link ClassNode} into + * {@link #processClass}. Returning null is allowed in delegate to + * later processors. + * + * @param classType the class to consider + * @param isEmpty if the class is empty at present (indicates no backing + * file found) + * @return the set of Phases the plugin wishes to be called back with + */ + public abstract EnumSet handlesClass(Type classType, boolean isEmpty); + + + /** + * Callback from the mixin plugin + * + * @param phase The phase of the supplied class node + * @param classNode the classnode to process + * @param classType the name of the class + * @return true if the class was processed + */ + public abstract boolean processClass(Phase phase, ClassNode classNode, Type classType); + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java b/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java new file mode 100644 index 00000000..11bd46a2 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/MixinLaunchPlugin.java @@ -0,0 +1,166 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.service.IClassBytecodeProvider; +import org.spongepowered.asm.service.IMixinService; +import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.service.modlauncher.MixinServiceModLauncher; + +import cpw.mods.modlauncher.api.IEnvironment; +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService; + +/** + * Mixin launch plugin + */ +public class MixinLaunchPlugin implements ILaunchPluginService { + + /** + * Name used for ModLauncher mixin service components + */ + public static final String NAME = "mixin"; + + /** + * Interceptor if present + */ + private IClassInterceptor interceptor; + + /** + * Class processing components + */ + private List processors = new ArrayList(); + + /* (non-Javadoc) + * @see cpw.mods.modlauncher.serviceapi.ILaunchPluginService#name() + */ + @Override + public String name() { + return MixinLaunchPlugin.NAME; + } + + /* (non-Javadoc) + * @see cpw.mods.modlauncher.serviceapi.ILaunchPluginService + * #handlesClass(org.objectweb.asm.Type, boolean) + */ + @Override + public EnumSet handlesClass(Type classType, boolean isEmpty) { + if (this.interceptor != null) { + // If the interceptor wants to handle this class, it has executive + // power since this entry is almost certainly simulated. If it's + // not a simulated entry then something is probably not right. RIP? + EnumSet interceptorVote = this.interceptor.handlesClass(classType, isEmpty); + if (interceptorVote != null) { + return interceptorVote; + } + } + + // All processors can nominate phases, we aggregate the results + EnumSet phases = EnumSet.noneOf(Phase.class); + synchronized (this.processors) { + for (IClassProcessor postProcessor : this.processors) { + EnumSet processorVote = postProcessor.handlesClass(classType, isEmpty); + if (processorVote != null) { + phases.addAll(processorVote); + } + } + } + + return phases; + } + + /* (non-Javadoc) + * @see cpw.mods.modlauncher.serviceapi.ILaunchPluginService + * #processClass( + * cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase, + * org.objectweb.asm.tree.ClassNode, org.objectweb.asm.Type) + */ + @Override + public boolean processClass(Phase phase, ClassNode classNode, Type classType) { + if (this.interceptor != null) { + if (this.interceptor.processClass(phase, classNode, classType)) { + // If the interceptor handles the class, then this is likely a + // simulated entry. Return immediately and don't delegate to + // other processors + return true; + } + } + + boolean processed = false; + + synchronized (this.processors) { + for (IClassProcessor postProcessor : this.processors) { + processed |= postProcessor.processClass(phase, classNode, classType); + } + } + + return processed; + } + + /* (non-Javadoc) + * @see cpw.mods.modlauncher.serviceapi.ILaunchPluginService#addResource( + * java.nio.file.Path, java.lang.String) + */ + @Override + public void addResource(Path resource, String name) { + // This is never called, I'm not sure what it's for + } + + /* (non-Javadoc) + * @see cpw.mods.modlauncher.serviceapi.ILaunchPluginService#getExtension() + */ + @Override + public T getExtension() { + return null; + } + + /** + * Initialisation routine, called as a lifecycle event from the + * transformation service + */ + void init(IEnvironment environment, Runnable startupListener) { + IMixinService service = MixinService.getService(); + if (!(service instanceof MixinServiceModLauncher)) { + throw new IllegalStateException("Unsupported service type for ModLauncher Mixin Service"); + } + IClassBytecodeProvider bytecodeProvider = service.getBytecodeProvider(); + if (bytecodeProvider instanceof IClassInterceptor) { + this.interceptor = (IClassInterceptor)bytecodeProvider; + } + MixinServiceModLauncher modLauncherService = (MixinServiceModLauncher)service; + synchronized (this.processors) { + this.processors.addAll(modLauncherService.getProcessors()); + } + modLauncherService.onInit(startupListener); + } + +} + \ No newline at end of file diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/MixinTransformationService.java b/src/modlauncher/java/org/spongepowered/asm/launch/MixinTransformationService.java new file mode 100644 index 00000000..af9d720a --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/MixinTransformationService.java @@ -0,0 +1,104 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.BiFunction; + +import org.spongepowered.asm.launch.platform.CommandLineOptions; + +import com.google.common.collect.ImmutableList; + +import cpw.mods.modlauncher.api.IEnvironment; +import cpw.mods.modlauncher.api.ITransformationService; +import cpw.mods.modlauncher.api.ITransformer; +import cpw.mods.modlauncher.api.IncompatibleEnvironmentException; +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService; +import joptsimple.ArgumentAcceptingOptionSpec; +import joptsimple.OptionSpecBuilder; + +/** + * Service for handling transforms mixin under ModLauncher + */ +public class MixinTransformationService implements ITransformationService { + + private ArgumentAcceptingOptionSpec mixinsArgument; + private List commandLineMixins; + private MixinLaunchPlugin plugin; + + @Override + public String name() { + return MixinLaunchPlugin.NAME; + } + + @Override + public void arguments(BiFunction argumentBuilder) { + this.mixinsArgument = argumentBuilder.apply("config", "a mixin config to load") + .withRequiredArg().ofType(String.class); + } + + @Override + public void argumentValues(OptionResult option) { + this.commandLineMixins = option.values(this.mixinsArgument); + } + + @Override + public void onLoad(IEnvironment environment, Set otherServices) throws IncompatibleEnvironmentException { + } + + @Override + public void initialize(IEnvironment environment) { + Optional plugin = environment.findLaunchPlugin(MixinLaunchPlugin.NAME); + if (!plugin.isPresent()) { + throw new MixinInitialisationError("Mixin Launch Plugin Service could not be located"); + } + ILaunchPluginService launchPlugin = plugin.get(); + if (!(launchPlugin instanceof MixinLaunchPlugin)) { + throw new MixinInitialisationError("Mixin Launch Plugin Service is present but not compatible"); + } + this.plugin = (MixinLaunchPlugin)launchPlugin; + + MixinBootstrap.start(); + this.plugin.init(environment, this::onStartup); + } + + private void onStartup() { + MixinBootstrap.doInit(CommandLineOptions.of(this.commandLineMixins)); + MixinBootstrap.inject(); + } + + @Override + public void beginScanning(IEnvironment environment) { + } + + @SuppressWarnings("rawtypes") + @Override + public List transformers() { + return ImmutableList.of(); + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/Phases.java b/src/modlauncher/java/org/spongepowered/asm/launch/Phases.java new file mode 100644 index 00000000..a1205679 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/Phases.java @@ -0,0 +1,43 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch; + +import java.util.EnumSet; + +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; + +/** + * Pre-built enumsets for returns + */ +public final class Phases { + + private Phases() { + } + + public static final EnumSet NONE = EnumSet.noneOf(Phase.class); + public static final EnumSet BEFORE_ONLY = EnumSet.of(Phase.BEFORE); + public static final EnumSet AFTER_ONLY = EnumSet.of(Phase.AFTER); + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java new file mode 100644 index 00000000..62f37831 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/platform/MixinPlatformAgentMinecraftForge.java @@ -0,0 +1,151 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform; + +import java.lang.reflect.Method; +import java.nio.file.Path; +import java.util.Collection; +import java.util.List; +import java.util.Locale; + +import org.spongepowered.asm.launch.platform.container.ContainerHandleURI; +import org.spongepowered.asm.launch.platform.container.ContainerHandleVirtual; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; +import org.spongepowered.asm.util.Constants; + +import com.google.common.collect.ImmutableSet; + +import cpw.mods.modlauncher.Environment; +import cpw.mods.modlauncher.Launcher; +import cpw.mods.modlauncher.api.IEnvironment; + +/** + * Platform agent for minecraft forge under ModLauncher + */ +public class MixinPlatformAgentMinecraftForge extends MixinPlatformAgentAbstract implements IMixinPlatformServiceAgent { + + private static final String FML_LOADING_PACKAGE = "net.minecraftforge.fml.loading."; + private static final String FML_DISCOVERY_PACKAGE = MixinPlatformAgentMinecraftForge.FML_LOADING_PACKAGE + "moddiscovery."; + + private static final String LAUNCHER_VERSION_CLASS = MixinPlatformAgentMinecraftForge.FML_LOADING_PACKAGE + "LauncherVersion"; + private static final String LOADING_MOD_LIST_CLASS = MixinPlatformAgentMinecraftForge.FML_LOADING_PACKAGE + "LoadingModList"; + private static final String MOD_FILE_INFO_CLASS = MixinPlatformAgentMinecraftForge.FML_DISCOVERY_PACKAGE + "ModFileInfo"; + private static final String MOD_FILE_CLASS = MixinPlatformAgentMinecraftForge.FML_DISCOVERY_PACKAGE + "ModFile"; + + private static final String GET_MOD_LIST_METHOD = "get"; + private static final String GET_MOD_FILES_METHOD = "getModFiles"; + private static final String GET_MOD_FILE_METHOD = "getFile"; + private static final String GET_FILE_PATH_METHOD = "getFilePath"; + + private ContainerHandleVirtual rootContainer; + + @Override + public void init() { + try { + Class.forName(MixinPlatformAgentMinecraftForge.LAUNCHER_VERSION_CLASS); + } catch (Exception ex) { + MixinPlatformAgentAbstract.logger.debug("FML Launcher Version class was not found, assuming FML is not present"); + return; + } + + String activity = "Initialising FML containers"; + try { + // Normally I'd cache these reflection objects, but this should only get called once + activity = "Resolving FML LoadingModList class"; + Class clModList = Class.forName(MixinPlatformAgentMinecraftForge.LOADING_MOD_LIST_CLASS); + activity = "Resolving FML ModFileInfo class"; + Class clModFileInfo = Class.forName(MixinPlatformAgentMinecraftForge.MOD_FILE_INFO_CLASS); + activity = "Resolving FML ModFile class"; + Class clModFile = Class.forName(MixinPlatformAgentMinecraftForge.MOD_FILE_CLASS); + + activity = "Resolving FML LoadingModList::get method"; + Method mdGetModListInstance = clModList.getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_MOD_LIST_METHOD); + activity = "Resolving FML LoadingModList::getModFiles method"; + Method mdGetModFiles = clModList.getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_MOD_FILES_METHOD); + activity = "Resolving FML ModFileInfo::getFile method"; + Method mdGetModFile = clModFileInfo.getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_MOD_FILE_METHOD); + activity = "Resolving FML ModFile::getFilePath method"; + Method mdGetFilePath = clModFile.getDeclaredMethod(MixinPlatformAgentMinecraftForge.GET_FILE_PATH_METHOD); + + activity = "Calling FML LoadingModList::get method to obtain LoadingModList singleton"; + Object loadingModList = mdGetModListInstance.invoke(null); + activity = "Calling FML LoadingModList::getModFiles method to obtain list of mod candidates"; + List modlist = (List)mdGetModFiles.invoke(loadingModList); + for (Object modFileInfo : modlist) { + activity = "Calling ModFileInfo::getFile method to obtain mod file info"; + Object modFile = mdGetModFile.invoke(modFileInfo); + activity = "Calling ModFile::getFilePath method to obtain mod file location"; + Path path = (Path)mdGetFilePath.invoke(modFile); + activity = "Creating ContainerHandleURI instance to contain FML mod: " + path; + this.rootContainer.add(new ContainerHandleURI(path.toUri())); + } + + } catch (Exception ex) { + MixinPlatformAgentAbstract.logger.error("Error reading FML mod list contents during activity: {}", activity); + MixinPlatformAgentAbstract.logger.catching(ex); + } + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.MixinPlatformAgentAbstract + * #accept(org.spongepowered.asm.launch.platform.MixinPlatformManager, + * org.spongepowered.asm.launch.platform.container.IContainerHandle) + */ + @Override + public boolean accept(MixinPlatformManager manager, IContainerHandle handle) { + // No containers plz + return false; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformAgent + * #getSideName() + */ + @Override + public String getSideName() { + Environment environment = Launcher.INSTANCE.environment(); + final String launchTarget = environment.getProperty(IEnvironment.Keys.LAUNCHTARGET.get()).orElse("missing").toLowerCase(Locale.ROOT); + if (launchTarget.contains("server")) { + return Constants.SIDE_SERVER; + } + if (launchTarget.contains("client")) { + return Constants.SIDE_CLIENT; + } + return null; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.platform.IMixinPlatformServiceAgent + * #getMixinContainers() + */ + @Override + public Collection getMixinContainers() { + if (this.rootContainer == null) { + this.rootContainer = new ContainerHandleVirtual("forge"); + } + return ImmutableSet.of(this.rootContainer); + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/launch/platform/container/ContainerHandleModLauncher.java b/src/modlauncher/java/org/spongepowered/asm/launch/platform/container/ContainerHandleModLauncher.java new file mode 100644 index 00000000..49ac4b8b --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/launch/platform/container/ContainerHandleModLauncher.java @@ -0,0 +1,41 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.launch.platform.container; + +/** + * ModLauncher root container + */ +public class ContainerHandleModLauncher extends ContainerHandleVirtual { + + public ContainerHandleModLauncher(String name) { + super(name); + } + + @Override + public String toString() { + return String.format("ModLauncher Root Container(%x)", this.hashCode()); + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java b/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java new file mode 100644 index 00000000..c8b1cfde --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java @@ -0,0 +1,111 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer; + +import java.util.EnumSet; + +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.mixin.MixinEnvironment; +import org.spongepowered.asm.service.ISyntheticClassInfo; +import org.spongepowered.asm.service.ISyntheticClassRegistry; + +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; + +/** + * Class Processor which delegates to the main Mixin pipeline for mixin + * application, post processing and synthetic class generation + */ +public class MixinTransformationHandler implements IClassProcessor { + + /** + * Lock for initialising the transformer + */ + private final Object initialisationLock = new Object(); + + /** + * Transformer pipeline instance + */ + private MixinTransformer transformer; + + /** + * Synthetic class registry, used so the processor knows when to respond to + * empty class population requests + */ + private ISyntheticClassRegistry registry; + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.IClassProcessor#handlesClass( + * org.objectweb.asm.Type, boolean) + */ + @Override + public EnumSet handlesClass(Type classType, boolean isEmpty) { + if (!isEmpty) { + return Phases.AFTER_ONLY; + } + + if (this.registry == null) { + return null; + } + + ISyntheticClassInfo syntheticClass = this.registry.findSyntheticClass(classType.getClassName()); + return syntheticClass != null ? Phases.AFTER_ONLY : null; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.IClassProcessor + * #processClass( + * cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase, + * org.objectweb.asm.tree.ClassNode, org.objectweb.asm.Type) + */ + @Override + public synchronized boolean processClass(Phase phase, ClassNode classNode, Type classType) { + if (phase == Phase.BEFORE) { + return false; + } + + MixinTransformer transformer = null; + if (this.transformer == null) { + synchronized (this.initialisationLock) { + transformer = this.transformer; + if (transformer == null) { + transformer = this.transformer = new MixinTransformer(); + this.registry = transformer.getExtensions().getSyntheticClassRegistry(); + } + } + } else { + transformer = this.transformer; + } + + MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); + ISyntheticClassInfo syntheticClass = this.registry.findSyntheticClass(classType.getClassName()); + if (syntheticClass != null) { + return transformer.generateClass(environment, classType.getClassName(), classNode); + } + return transformer.transformClass(environment, classType.getClassName(), classNode); + } +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/Blackboard.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/Blackboard.java new file mode 100644 index 00000000..042c593c --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/Blackboard.java @@ -0,0 +1,112 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import java.util.HashMap; +import java.util.Map; + +import org.spongepowered.asm.service.IGlobalPropertyService; +import org.spongepowered.asm.service.IPropertyKey; + +import cpw.mods.modlauncher.Launcher; +import cpw.mods.modlauncher.api.TypesafeMap; + +/** + * Global property service backed by ModLauncher blackboard + */ +public class Blackboard implements IGlobalPropertyService { + + /** + * Type safe property key + * + * @param value type + */ + class Key implements IPropertyKey { + + final TypesafeMap.Key key; + + public Key(TypesafeMap owner, String name, Class clazz) { + this.key = TypesafeMap.Key.getOrCreate(owner, name, clazz); + } + + } + + private final Map keys = new HashMap(); + + private final TypesafeMap blackboard; + + public Blackboard() { + this.blackboard = Launcher.INSTANCE.blackboard(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IGlobalPropertyService#resolveKey( + * java.lang.String) + */ + @Override + public IPropertyKey resolveKey(String name) { + return this.keys.computeIfAbsent(name, key -> new Key(this.blackboard, key, Object.class)); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IGlobalPropertyService#getProperty( + * org.spongepowered.asm.service.IPropertyKey) + */ + @Override + public T getProperty(IPropertyKey key) { + return this.getProperty(key, null); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IGlobalPropertyService#setProperty( + * org.spongepowered.asm.service.IPropertyKey, java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public void setProperty(IPropertyKey key, Object value) { + this.blackboard.computeIfAbsent(((Key)key).key, k -> value); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IGlobalPropertyService + * #getPropertyString(org.spongepowered.asm.service.IPropertyKey, + * java.lang.String) + */ + @Override + public String getPropertyString(IPropertyKey key, String defaultValue) { + return this.getProperty(key, defaultValue); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IGlobalPropertyService#getProperty( + * org.spongepowered.asm.service.IPropertyKey, java.lang.Object) + */ + @SuppressWarnings("unchecked") + @Override + public T getProperty(IPropertyKey key, T defaultValue) { + return this.blackboard.get(((Key)key).key).orElse(defaultValue); + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/Internals.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/Internals.java new file mode 100644 index 00000000..7abbcb63 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/Internals.java @@ -0,0 +1,305 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.jar.Manifest; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; + +import cpw.mods.modlauncher.ClassTransformer; +import cpw.mods.modlauncher.Launcher; +import cpw.mods.modlauncher.TransformingClassLoader; + +/** + * Shim for accessing resources inside modlauncher that Mixin needs to operate. + * Ideally in the long run facilities can be provided directly within + * modlauncher to make this shim unnecessary. + */ +class Internals { + + /** + * Temporary + */ + static class MixinAppender extends AbstractAppender { + + private final List startupListeners = new ArrayList(); + + MixinAppender() { + super("MixinLogWatcherAppender", null, null); + this.start(); + } + + void addListener(Runnable listener) { + synchronized (this.startupListeners) { + this.startupListeners.add(listener); + } + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() != Level.INFO || !event.getMessage().getFormat().startsWith("Launching target '")) { + return; + } + + // transition to DEFAULT + synchronized (this.startupListeners) { + for (Runnable listener : this.startupListeners) { + listener.run(); + } + } + } + + } + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + private static MixinAppender appender; + private static org.apache.logging.log4j.core.Logger launcherLogger; + + private static Internals instance; + + private static final String FD_CLASSLOADER = "classLoader"; + private static final String FD_CLASSTRANSFORMER = "classTransformer"; + + private static final String FD_MANIFESTFINDER = "manifestFinder"; + private static final String FD_CLASSBYTESFINDER = "classBytesFinder"; + + private static final String MD_TRANSFORM = "transform"; + +// private static final String MD_LOADCLASS = "loadClass"; + + private TransformingClassLoader transformingClassLoader; + private ClassTransformer classTransformer; + + private Function manifestFinder; + private Function classBytesFinder; + +// private Method mdLoadClass; + private Method mdTransform; + + TransformingClassLoader getTransformingClassLoader() { + if (this.transformingClassLoader == null) { + this.transformingClassLoader = Internals.getField(Launcher.class, Launcher.INSTANCE, + Internals.FD_CLASSLOADER); + } + return this.transformingClassLoader; + } + + ClassTransformer getClassTransformer() { + if (this.classTransformer == null) { + this.classTransformer = Internals.getField(TransformingClassLoader.class, + this.getTransformingClassLoader(), Internals.FD_CLASSTRANSFORMER); + } + return this.classTransformer; + } + + Function getManifestFinder() { + if (this.manifestFinder == null) { + this.manifestFinder = Internals.>getField(TransformingClassLoader.class, + this.getTransformingClassLoader(), Internals.FD_MANIFESTFINDER); + } + return this.manifestFinder; + } + + Function getClassBytesFinder() { + if (this.classBytesFinder == null) { + this.classBytesFinder = Internals.>getField(TransformingClassLoader.class, + this.getTransformingClassLoader(), Internals.FD_CLASSBYTESFINDER); + } + return this.classBytesFinder; + } + +// /** +// * Invokes 'loadClass' on the Transforming classloader +// * +// * @param name class name to load +// * @param resolve If true then resolve the class +// * @return loaded class +// * @throws ClassNotFoundException propagated +// */ +// public Class findClass(String name, boolean resolve) throws ClassNotFoundException { +// if (this.mdLoadClass == null) { +// this.mdLoadClass = Internals.getMethod(TransformingClassLoader.class, Internals.MD_LOADCLASS); +// } +// if (this.mdLoadClass != null) { +// try { +// return (Class)this.mdLoadClass.invoke(this.getTransformingClassLoader(), name, resolve); +// } catch (ReflectiveOperationException ex) { +// ex.printStackTrace(); +// } +// } +// return Class.forName("name"); +// } + + byte[] simulateClassLoad(String name, boolean runTransformers) throws ClassNotFoundException { + Function classBytesFinder = this.getClassBytesFinder(); + + final String path = name.replace('.', '/').concat(".class"); + final URL classResource = classBytesFinder.apply(path); + byte[] classBytes; + if (classResource != null) { + try (AutoURLConnection urlConnection = new AutoURLConnection(classResource, this.getManifestFinder())) { + final int length = urlConnection.getContentLength(); + final InputStream is = urlConnection.getInputStream(); + classBytes = new byte[length]; + int pos = 0, remain = length, read; + while ((read = is.read(classBytes, pos, remain)) != -1 && remain > 0) { + pos += read; + remain -= read; + } + @SuppressWarnings("unused") + Manifest jarManifest = urlConnection.getJarManifest(); + } catch (IOException e) { + throw new ClassNotFoundException("Failed to find class bytes for " + name, e); + } + } else { + classBytes = new byte[0]; + } + return this.transform(classBytes, name); + } + + /** + * Copied directly from ModLauncher, ideally won't be necessary in the long + * run + */ + static class AutoURLConnection implements AutoCloseable { + private final URLConnection urlConnection; + private final InputStream inputStream; + private final Function manifestFinder; + + AutoURLConnection(URL url, Function manifestFinder) throws IOException { + this.urlConnection = url.openConnection(); + this.inputStream = this.urlConnection.getInputStream(); + this.manifestFinder = manifestFinder; + } + + @Override + public void close() throws IOException { + this.inputStream.close(); + } + + int getContentLength() { + return this.urlConnection.getContentLength(); + } + + InputStream getInputStream() { + return this.inputStream; + } + + Manifest getJarManifest() { + return this.manifestFinder.apply(this.urlConnection); + } + } + + private byte[] transform(byte[] inputClass, String className) { + if (this.mdTransform == null) { + this.mdTransform = Internals.getMethod(ClassTransformer.class, Internals.MD_TRANSFORM, byte[].class, String.class); + } + if (this.mdTransform == null) { + return inputClass; + } + try { + return (byte[])this.mdTransform.invoke(this.getClassTransformer(), inputClass, className); + } catch (InvocationTargetException ex) { + Throwable cause = ex.getCause(); + if (cause instanceof RuntimeException) { + throw (RuntimeException)cause; + } + throw new RuntimeException(cause); + } catch (ReflectiveOperationException ex) { + Internals.logger.catching(ex); + } + return inputClass; + } + + @SuppressWarnings("unchecked") + private static T getField(Class clazz, C instance, String fieldName) { + try { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return (T)field.get(instance); + } catch (Exception ex) { +// ex.printStackTrace(); + } + return null; + } + + private static Method getMethod(Class clazz, String methodName, Class... parameterTypes) { + try { + Method method = clazz.getDeclaredMethod(methodName, parameterTypes); + method.setAccessible(true); + return method; + } catch (Exception ex) { +// ex.printStackTrace(); + } + return null; + } + + void registerStartupListener(Runnable listener) { + if (Internals.appender == null) { + Logger launcherLog = LogManager.getLogger("cpw.mods.modlauncher.LaunchServiceHandler"); + if (!(launcherLog instanceof org.apache.logging.log4j.core.Logger)) { + return; + } + + Internals.appender = new MixinAppender(); + Internals.launcherLogger = (org.apache.logging.log4j.core.Logger)launcherLog; + Internals.launcherLogger.addAppender(Internals.appender); + } + + Internals.appender.addListener(listener); + } + + void destroyLogWatcher() { + if (Internals.launcherLogger != null) { + Internals.launcherLogger.removeAppender(Internals.appender); + } + } + + static synchronized Internals getInstance() { + if (Internals.instance == null) { + Internals.instance = new Internals(); + } + return Internals.instance; + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java new file mode 100644 index 00000000..401d6431 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java @@ -0,0 +1,309 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import java.io.InputStream; +import java.util.Collection; +import java.util.Iterator; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; + +import org.spongepowered.asm.launch.IClassProcessor; +import org.spongepowered.asm.launch.platform.container.ContainerHandleModLauncher; +import org.spongepowered.asm.launch.platform.container.IContainerHandle; +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.MixinServiceAbstract; +import org.spongepowered.asm.service.modlauncher.ext.IModLauncherClassBytecodeProvider; +import org.spongepowered.asm.service.modlauncher.ext.IModLauncherClassProvider; +import org.spongepowered.asm.util.IConsumer; + +import com.google.common.collect.ImmutableList; + +import cpw.mods.modlauncher.Launcher; +import cpw.mods.modlauncher.TransformingClassLoader; +import cpw.mods.modlauncher.api.ITransformationService; + +/** + * Mixin service for ModLauncher + */ +public class MixinServiceModLauncher extends MixinServiceAbstract { + + /** + * Specification version to check for at startup + */ + private static final String MODLAUNCHER_SPECIFICATION_VERSION = "1.0"; + + /** + * Class provider, either uses hacky internals or provided service + */ + private IModLauncherClassProvider classProvider; + + /** + * Bytecode provider, either uses hacky internals or provided service + */ + private IModLauncherClassBytecodeProvider bytecodeProvider; + + /** + * Container for the mixin pipeline which is called by the launch plugin + */ + private MixinTransformationHandler transformationHandler; + + /** + * Class tracker, tracks class loads and registered invalid classes + */ + private ModLauncherClassTracker classTracker; + + /** + * Environment phase consumer, TEMP + */ + private IConsumer phaseConsumer; + + /** + * Only allow onInit to be called once + */ + private volatile boolean initialised; + + /** + * Begin init + * + * @param startupListener Lifecyle listener + */ + public void onInit(Runnable startupListener) { + if (this.initialised) { + throw new IllegalStateException("Already initialised"); + } + this.initialised = true; + Internals.getInstance().registerStartupListener(startupListener); + Internals.getInstance().registerStartupListener(MixinServiceModLauncher.this::onStartup); + } + + /** + * Lifecycle event + */ + private void onStartup() { + this.phaseConsumer.accept(Phase.DEFAULT); + } + + // TEMP + @SuppressWarnings("deprecation") + @Override + public void wire(Phase phase, IConsumer phaseConsumer) { + super.wire(phase, phaseConsumer); + this.phaseConsumer = phaseConsumer; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getName() + */ + @Override + public String getName() { + return "ModLauncher"; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#isValid() + */ + @Override + public boolean isValid() { + try { + Launcher.INSTANCE.hashCode(); + final Package pkg = ITransformationService.class.getPackage(); + if (!pkg.isCompatibleWith(MixinServiceModLauncher.MODLAUNCHER_SPECIFICATION_VERSION)) { + return false; + } + } catch (Throwable th) { + return false; + } + return true; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassProvider() + */ + @Override + public IClassProvider getClassProvider() { + if (this.classProvider == null) { + this.classProvider = MixinServiceModLauncher.createClassProvider(); + } + return this.classProvider; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getBytecodeProvider() + */ + @Override + public IClassBytecodeProvider getBytecodeProvider() { + if (this.bytecodeProvider == null) { + this.bytecodeProvider = MixinServiceModLauncher.createBytecodeProvider(); + } + return this.bytecodeProvider; + } + + /** + * Get (or create) the transformation handler + */ + private IClassProcessor getTransformationHandler() { + if (this.transformationHandler == null) { + this.transformationHandler = new MixinTransformationHandler(); + } + 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() + */ + @Override + public Collection getPlatformAgents() { + return ImmutableList.of( + "org.spongepowered.asm.launch.platform.MixinPlatformAgentMinecraftForge" + ); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getPrimaryContainer() + */ + @Override + public IContainerHandle getPrimaryContainer() { + return new ContainerHandleModLauncher(this.getName()); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getResourceAsStream( + * java.lang.String) + */ + @Override + public InputStream getResourceAsStream(String name) { + TransformingClassLoader tcl = Internals.getInstance().getTransformingClassLoader(); + if (tcl != null) { + return tcl.getResourceAsStream(name); + } + + // Probably not what we want :/ + 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 getTransformers() { + return ImmutableList.of(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService + * #getDelegatedTransformers() + */ + @Override + public Collection getDelegatedTransformers() { + return ImmutableList.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 + */ + public Collection getProcessors() { + return ImmutableList.of( + this.getTransformationHandler(), + this.getClassTracker() + ); + } + + private static IModLauncherClassProvider createClassProvider() { + IModLauncherClassProvider service = + MixinServiceModLauncher.loadFirstAvailableService(IModLauncherClassProvider.class); + return service != null ? service : new ModLauncherClassProvider(); + } + + private static IModLauncherClassBytecodeProvider createBytecodeProvider() { + IModLauncherClassBytecodeProvider service = + MixinServiceModLauncher.loadFirstAvailableService(IModLauncherClassBytecodeProvider.class); + return service != null ? service : new ModLauncherBytecodeProvider(); + } + + private static TService loadFirstAvailableService(Class serviceClass) { + Iterator loader = ServiceLoader.load(serviceClass).iterator(); + if (loader.hasNext()) { + try { + return loader.next(); + } catch (ServiceConfigurationError ex) { + ex.printStackTrace(); + } + } + return null; + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncherBootstrap.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncherBootstrap.java new file mode 100644 index 00000000..81f6c417 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncherBootstrap.java @@ -0,0 +1,56 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import org.spongepowered.asm.service.IMixinServiceBootstrap; +import org.spongepowered.asm.service.ServiceInitialisationException; + +import cpw.mods.modlauncher.Launcher; + +/** + * Ain't nobody here 'cept us chickens... + */ +public class MixinServiceModLauncherBootstrap implements IMixinServiceBootstrap { + + @Override + public String getName() { + return "ModLauncher"; + } + + @Override + public String getServiceClassName() { + return "org.spongepowered.asm.service.modlauncher.MixinServiceModLauncher"; + } + + @Override + public void bootstrap() { + try { + Launcher.INSTANCE.hashCode(); + } catch (Throwable th) { + throw new ServiceInitialisationException(this.getName() + " is not available"); + } + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherBytecodeProvider.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherBytecodeProvider.java new file mode 100644 index 00000000..97132532 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherBytecodeProvider.java @@ -0,0 +1,159 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import java.io.IOException; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.launch.IClassInterceptor; +import org.spongepowered.asm.service.modlauncher.ext.IModLauncherClassBytecodeProvider; + +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; + +/** + * Bytecode provider for ModLauncher environment. + */ +class ModLauncherBytecodeProvider implements IModLauncherClassBytecodeProvider, IClassInterceptor { + + /** + * Exception thrown by the interceptor to terminate the transformation + * pipeline once we have obtained a ClassNode in the state we want it. + */ + static class CaptureException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + ClassNode captured; + + CaptureException(ClassNode captured) { + this.captured = captured; + } + + } + + /** + * Filthy hacks + */ + private final Internals internals = Internals.getInstance(); + + /** + * Class names we want to capture + */ + private final Map captures = new HashMap(); + + /** + * Classes which are initially empty + */ + private final Set emptyClasses = new HashSet(); + + ModLauncherBytecodeProvider() { + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassBytecodeProvider#getClassNode( + * java.lang.String) + */ + @Override + public synchronized ClassNode getClassNode(String name) throws ClassNotFoundException, IOException { + return this.getClassNode(name, true, true); + } + + @Override + public EnumSet handlesClass(Type classType, boolean isEmpty) { + synchronized (this.captures) { + String internalName = classType.getInternalName(); + Phase capturePhase = this.captures.get(internalName); + if (capturePhase != null) { + if (isEmpty) { + this.emptyClasses.add(internalName); + } + return EnumSet.of(capturePhase); + } + } + return null; + } + + @Override + public boolean processClass(Phase phase, ClassNode classNode, Type classType) { + synchronized (this.captures) { + Phase capturePhase = this.captures.get(classType.getInternalName()); + if (capturePhase != null && phase == capturePhase) { + throw new CaptureException(classNode); + } + } + return false; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassBytecodeProvider#getClassNode( + * java.lang.String, boolean) + */ + @Override + public synchronized ClassNode getClassNode(String name, boolean runTransformers) throws ClassNotFoundException, IOException { + return this.getClassNode(name, runTransformers, false); + } + + private synchronized ClassNode getClassNode(String name, boolean runTransformers, boolean ignoreEmpty) + throws ClassNotFoundException { + + String internalName = name.replace('.', '/'); + + synchronized (this.captures) { + this.emptyClasses.remove(internalName); + this.captures.put(internalName, runTransformers ? Phase.AFTER : Phase.BEFORE); + } + + ClassNode captured = null; + try { + this.internals.simulateClassLoad(name, runTransformers); + } catch (CaptureException ex) { + captured = ex.captured; + synchronized (this.captures) { + if (this.emptyClasses.contains(internalName)) { + if (!ignoreEmpty) { + throw new ClassNotFoundException(name); + } + } + } + } finally { + synchronized (this.captures) { + this.captures.remove(internalName); + } + } + + if (captured == null) { + throw new ClassNotFoundException("Unable to obtain ClassNode for: " + name); + } + + return captured; + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassProvider.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassProvider.java new file mode 100644 index 00000000..ba7429a1 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassProvider.java @@ -0,0 +1,89 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import java.net.URL; + +import org.spongepowered.asm.service.modlauncher.ext.IModLauncherClassProvider; + +import cpw.mods.gross.Java9ClassLoaderUtil; +import cpw.mods.modlauncher.Launcher; +import cpw.mods.modlauncher.TransformingClassLoader; + +/** + * Class provider for use under ModLauncher + */ +class ModLauncherClassProvider implements IModLauncherClassProvider { + + /** + * Here be dragons + */ + private final Internals internals = Internals.getInstance(); + + ModLauncherClassProvider() { + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassProvider#getClassPath() + */ + @Override + @Deprecated + public URL[] getClassPath() { + return Java9ClassLoaderUtil.getSystemClassPathURLs(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassProvider#findClass( + * java.lang.String) + */ + @Override + public Class findClass(String name) throws ClassNotFoundException { + return Class.forName(name, true, this.getClassLoader()); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassProvider#findClass( + * java.lang.String, boolean) + */ + @Override + public Class findClass(String name, boolean initialize) throws ClassNotFoundException { + return Class.forName(name, initialize, this.getClassLoader()); + } + + private ClassLoader getClassLoader() { + TransformingClassLoader tcl = this.internals.getTransformingClassLoader(); + return tcl != null ? tcl : Launcher.class.getClassLoader(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassProvider#findAgentClass( + * java.lang.String, boolean) + */ + @Override + public Class findAgentClass(String name, boolean initialize) throws ClassNotFoundException { + return Class.forName(name, initialize, Launcher.class.getClassLoader()); + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java new file mode 100644 index 00000000..7f5f3e26 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java @@ -0,0 +1,95 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher; + +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Set; + +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.launch.IClassProcessor; +import org.spongepowered.asm.launch.Phases; + +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; + +/** + * Tracks invalid (unloadable) classes so we can throw an exception inside the + * TCL and class load events so we can report when classes were loaded before + * we could transform them + */ +public class ModLauncherClassTracker implements IClassProcessor { + + private final Set invalidClasses = new HashSet(); + + private final Set loadedClasses = new HashSet(); + + void registerInvalidClass(String className) { + synchronized (this.invalidClasses) { + this.invalidClasses.add(className); + } + } + + boolean isClassLoaded(String className) { + synchronized (this.loadedClasses) { + return this.loadedClasses.contains(className); + } + } + + String getClassRestrictions(String className) { + return ""; // TODO ? + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.IClassProcessor#handlesClass( + * org.objectweb.asm.Type, boolean) + */ + @Override + public EnumSet handlesClass(Type classType, boolean isEmpty) { + String name = classType.getClassName(); + synchronized (this.invalidClasses) { + if (this.invalidClasses.contains(name)) { + throw new NoClassDefFoundError(String.format("%s is invalid", name)); + } + } + + synchronized (this.loadedClasses) { + this.loadedClasses.add(name); + } + + return Phases.NONE; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.launch.IClassProcessor#processClass( + * cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase, + * org.objectweb.asm.tree.ClassNode, org.objectweb.asm.Type) + */ + @Override + public boolean processClass(Phase phase, ClassNode classNode, Type classType) { + return false; + } + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ext/IModLauncherClassBytecodeProvider.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ext/IModLauncherClassBytecodeProvider.java new file mode 100644 index 00000000..3bb3bed5 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ext/IModLauncherClassBytecodeProvider.java @@ -0,0 +1,34 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher.ext; + +import org.spongepowered.asm.service.IClassBytecodeProvider; + +/** + * Service-loadable interface for modlauncher class bytecode provider + */ +public interface IModLauncherClassBytecodeProvider extends IClassBytecodeProvider { + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ext/IModLauncherClassProvider.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ext/IModLauncherClassProvider.java new file mode 100644 index 00000000..49a7a365 --- /dev/null +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ext/IModLauncherClassProvider.java @@ -0,0 +1,34 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service.modlauncher.ext; + +import org.spongepowered.asm.service.IClassProvider; + +/** + * Service-loadable interface for modlauncher class provider + */ +public interface IModLauncherClassProvider extends IClassProvider { + +} diff --git a/src/modlauncher/resources/META-INF/services/cpw.mods.modlauncher.api.ITransformationService b/src/modlauncher/resources/META-INF/services/cpw.mods.modlauncher.api.ITransformationService new file mode 100644 index 00000000..43d16497 --- /dev/null +++ b/src/modlauncher/resources/META-INF/services/cpw.mods.modlauncher.api.ITransformationService @@ -0,0 +1 @@ +org.spongepowered.asm.launch.MixinTransformationService \ No newline at end of file diff --git a/src/modlauncher/resources/META-INF/services/cpw.mods.modlauncher.serviceapi.ILaunchPluginService b/src/modlauncher/resources/META-INF/services/cpw.mods.modlauncher.serviceapi.ILaunchPluginService new file mode 100644 index 00000000..dee143bf --- /dev/null +++ b/src/modlauncher/resources/META-INF/services/cpw.mods.modlauncher.serviceapi.ILaunchPluginService @@ -0,0 +1 @@ +org.spongepowered.asm.launch.MixinLaunchPlugin \ No newline at end of file diff --git a/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IGlobalPropertyService b/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IGlobalPropertyService new file mode 100644 index 00000000..ff439f9d --- /dev/null +++ b/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IGlobalPropertyService @@ -0,0 +1 @@ +org.spongepowered.asm.service.modlauncher.Blackboard \ No newline at end of file diff --git a/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IMixinService b/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IMixinService new file mode 100644 index 00000000..bf9225cb --- /dev/null +++ b/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IMixinService @@ -0,0 +1 @@ +org.spongepowered.asm.service.modlauncher.MixinServiceModLauncher \ No newline at end of file diff --git a/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IMixinServiceBootstrap b/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IMixinServiceBootstrap new file mode 100644 index 00000000..ab02dda9 --- /dev/null +++ b/src/modlauncher/resources/META-INF/services/org.spongepowered.asm.service.IMixinServiceBootstrap @@ -0,0 +1 @@ +org.spongepowered.asm.service.modlauncher.MixinServiceModLauncherBootstrap \ No newline at end of file