Initial impl of Annotation Processor, references #4

This commit is contained in:
Mumfrey committed 2015-01-04 18:20:57 +00:00
1 parent e3211bbfee
commit 9bdcf084ca
17 files changed
+1565 -24

No files matched your search

+32 -3
View File
@@ -44,6 +44,16 @@ targetCompatibility = '1.6'
// Project repositories
repositories {
mavenCentral()
maven {
// for srg2source
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
maven {
// because Srg2Source needs an eclipse dependency.
name = "eclipse"
url = "https://repo.eclipse.org/content/groups/eclipse/"
}
maven {
name = 'minecraft'
url = 'https://libraries.minecraft.net/'
@@ -54,6 +64,14 @@ configurations {
deployerJars // maven stuff
}
// Include annotation processor sourceSet
sourceSets {
ap {
compileClasspath += main.output
}
}
// Project dependencies
dependencies {
compile 'org.slf4j:slf4j-api:1.7.7'
@@ -68,6 +86,10 @@ dependencies {
// maven
deployerJars 'org.apache.maven.wagon:wagon-ftp:2.7'
// for annotation processor
compile 'net.minecraftforge.srg2source:Srg2Source:3.2-SNAPSHOT'
apCompile 'net.minecraftforge.srg2source:Srg2Source:3.2-SNAPSHOT'
}
// Filter, process, and include resources
@@ -104,23 +126,30 @@ checkstyle {
}
// Source compiler configuration
configure([compileJava, compileTestJava]) {
tasks.withType(JavaCompile) {
options.compilerArgs += ['-Xlint:all', '-Xlint:-path']
options.deprecation = true
options.encoding = 'utf8'
}
// JAR manifest configuration
jar.manifest.mainAttributes(
jar {
// Include annotation processor
from sourceSets.ap.output
// JAR manifest configuration
manifest.mainAttributes(
"Built-By": System.properties['user.name'],
"Created-By": System.properties['java.vm.version'] + " (" + System.properties['java.vm.vendor'] + ")",
"Implementation-Title": name,
"Implementation-Version": version + "+" + ciSystem + "-b" + buildNumber + ".git-" + commit,
"Implementation-Vendor": url)
}
task sourceJar(type: Jar) {
from sourceSets.main.java
from sourceSets.main.resources
from sourceSets.ap.java
from sourceSets.ap.resources
classifier = "sources"
}
@@ -0,0 +1,212 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
/**
* Convenience functions for mirror
*/
public abstract class MirrorUtils {
// No instances for you
private MirrorUtils() {}
public static AnnotationMirror getAnnotation(Element elem, Class<? extends Annotation> annotationClass) {
List<? extends AnnotationMirror> annotations = elem.getAnnotationMirrors();
if (annotations == null) {
return null;
}
for (AnnotationMirror annotation : annotations) {
Element element = annotation.getAnnotationType().asElement();
if (!(element instanceof TypeElement)) {
continue;
}
TypeElement annotationElement = (TypeElement)element;
if (annotationElement.getQualifiedName().contentEquals(annotationClass.getName())) {
return annotation;
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <T> T getAnnotationValue(AnnotationMirror annotation, String key, T defaultValue) {
if (annotation == null) {
return defaultValue;
}
AnnotationValue value = MirrorUtils.getAnnotationValue0(annotation, key);
return value != null ? (T)value.getValue() : defaultValue;
}
public static <T> T getAnnotationValue(TypeElement elem, Class<? extends Annotation> annotationClass, String key, T defaultValue) {
AnnotationMirror annotation = MirrorUtils.getAnnotation(elem, annotationClass);
return MirrorUtils.getAnnotationValue(annotation, key, defaultValue);
}
public static <T> T getAnnotationValue(AnnotationMirror annotation) {
return MirrorUtils.getAnnotationValue(annotation, "value", null);
}
public static <T> T getAnnotationValue(AnnotationMirror annotation, String key) {
return MirrorUtils.getAnnotationValue(annotation, key, null);
}
public static <T> T getAnnotationValue(TypeElement elem, Class<? extends Annotation> annotationClass) {
return MirrorUtils.getAnnotationValue(elem, annotationClass, "value");
}
public static <T> T getAnnotationValue(TypeElement elem, Class<? extends Annotation> annotationClass, String key) {
AnnotationMirror annotation = MirrorUtils.getAnnotation(elem, annotationClass);
return MirrorUtils.getAnnotationValue(annotation, key, null);
}
private static AnnotationValue getAnnotationValue0(AnnotationMirror annotation, String key) {
for (ExecutableElement elem : annotation.getElementValues().keySet()) {
if (elem.getSimpleName().contentEquals(key)) {
return annotation.getElementValues().get(elem);
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <T> List<T> unfold(List<AnnotationValue> list) {
if (list == null) {
return Collections.<T>emptyList();
}
List<T> unfolded = new ArrayList<T>(list.size());
for (AnnotationValue value : list) {
unfolded.add((T)value.getValue());
}
return unfolded;
}
public static PackageElement getPackage(TypeElement elem) {
Element parent = elem.getEnclosingElement();
while (parent != null && !(parent instanceof PackageElement)) {
parent = parent.getEnclosingElement();
}
return (PackageElement)parent;
}
public static String getElementType(Element parent) {
if (parent instanceof TypeElement) {
return "TypeElement";
} else if (parent instanceof ExecutableElement) {
return "ExecutableElement";
} else if (parent instanceof VariableElement) {
return "VariableElement";
} else if (parent instanceof PackageElement) {
return "PackageElement";
} else if (parent instanceof TypeParameterElement) {
return "TypeParameterElement";
}
return parent.getClass().getSimpleName();
}
public static String generateSignature(ExecutableElement method) {
StringBuilder signature = new StringBuilder();
for (VariableElement var : method.getParameters()) {
signature.append(MirrorUtils.getInternalName(var));
}
return String.format("(%s)%s", signature, MirrorUtils.getInternalName(method.getReturnType()));
}
public static String getInternalName(VariableElement var) {
return MirrorUtils.getInternalName(var.asType());
}
public static String getInternalName(TypeMirror type) {
switch (type.getKind()) {
case ARRAY: return "[" + MirrorUtils.getInternalName(((ArrayType)type).getComponentType());
case BOOLEAN:
return "Z";
case BYTE:
return "B";
case CHAR:
return "C";
case DOUBLE:
return "D";
case FLOAT:
return "F";
case INT:
return "I";
case LONG:
return "J";
case SHORT:
return "S";
case DECLARED:
return "L" + MirrorUtils.getInternalName((DeclaredType)type) + ";";
case VOID:
return "V";
default:
}
throw new IllegalArgumentException("Unable to parse type symbol " + type + " to equivalent bytecode type");
}
public static String getInternalName(DeclaredType type) {
TypeElement elem = (TypeElement)type.asElement();
StringBuilder reference = new StringBuilder();
reference.append(elem.getSimpleName());
Element parent = elem.getEnclosingElement();
while (parent != null) {
if (parent instanceof TypeElement) {
reference.insert(0, "$").insert(0, parent.getSimpleName());
} else if (parent instanceof PackageElement) {
reference.insert(0, "/").insert(0, ((PackageElement)parent).getQualifiedName().toString().replace('.', '/'));
}
parent = parent.getEnclosingElement();
}
return reference.toString();
}
}
@@ -0,0 +1,421 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.tools.MirrorUtils;
/**
* Information about a mixin stored during processing
*/
class AnnotatedMixin {
/**
* Convenience class to store information about an {@link org.spongepowered.asm.mixin.Shadow}ed member's names
*/
class ShadowElementName {
private final boolean hasPrefix;
private final String prefix;
private final String baseName;
private final String originalName;
private String obfuscated;
ShadowElementName(Element method, AnnotationMirror shadow) {
boolean hasPrefix = false;
this.prefix = MirrorUtils.<String>getAnnotationValue(shadow, "prefix", "shadow$");
String name = this.originalName = method.getSimpleName().toString();
if (name.startsWith(this.prefix)) {
hasPrefix = true;
name = name.substring(this.prefix.length());
}
this.hasPrefix = hasPrefix;
this.obfuscated = this.baseName = name;
}
@Override
public String toString() {
return this.baseName;
}
public ShadowElementName setObfuscatedName(String name) {
this.obfuscated = name.substring(name.lastIndexOf('/') + 1);
return this;
}
public String originalName() {
return this.originalName;
}
public String prefix() {
return this.hasPrefix ? this.prefix : "";
}
public String name() {
return this.prefix(this.baseName);
}
public String obfuscated() {
return this.prefix(this.obfuscated);
}
public String prefix(String name) {
return this.hasPrefix ? this.prefix + name : name;
}
}
/**
* Manager
*/
private final AnnotatedMixins mixins;
/**
* Mixin class
*/
private final TypeElement mixin;
/**
* Specified targets
*/
private final List<String> targets = new ArrayList<String>();
/**
* Target "reference" (bytecode name)
*/
private final String targetRef;
/**
* Target type (for single-target mixins)
*/
private final TypeElement targetType;
/**
* Mixin class "reference" (bytecode name)
*/
private final String classRef;
/**
* Stored (ordered) field mappings
*/
private final Set<String> fieldMappings = new LinkedHashSet<String>();
/**
* Stored (ordered) method mappings
*/
private final Set<String> methodMappings = new LinkedHashSet<String>();
public AnnotatedMixin(AnnotatedMixins mixins, TypeElement type) {
this.mixins = mixins;
this.mixin = type;
this.classRef = type.getQualifiedName().toString().replace('.', '/');
String targetRef = null;
TypeElement targetType = null;
List<AnnotationValue> targetList = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(type, Mixin.class);
for (TypeMirror target : MirrorUtils.<TypeMirror>unfold(targetList)) {
Element element = ((DeclaredType)target).asElement();
String targetName = ((TypeElement)element).getQualifiedName().toString();
this.targets.add(targetName);
if (targetRef == null) {
targetRef = MirrorUtils.getInternalName((DeclaredType)target);
targetType = (TypeElement) ((DeclaredType)target).asElement();
}
}
this.targetRef = targetRef;
this.targetType = targetType;
}
/**
* Get the mixin class
*/
public TypeElement getMixin() {
return this.mixin;
}
/**
* Get the mixin's targets
*/
public List<String> getTargets() {
return this.targets;
}
/**
* Get stored field mappings
*/
public Set<String> getFieldMappings() {
return this.fieldMappings;
}
/**
* Get stored method mappings
*/
public Set<String> getMethodMappings() {
return this.methodMappings;
}
/**
* Clear all stored mappings
*/
public void clear() {
this.fieldMappings.clear();
this.methodMappings.clear();
}
/**
* Validate method for {@link org.spongepowered.asm.mixin.Shadow} and {@link org.spongepowered.asm.mixin.Overwrite} registrations to check that
* only a single target is registered. Mixins containing annotated methods with these annotations cannot be multi-targetted.
*/
private boolean validateSingleTarget(String annotation) {
if (this.targetRef == null) {
this.mixins.printMessage(Kind.ERROR, "Mixin class " + this.mixin + " has multiple targets. " + annotation + " is not supported!");
return false;
}
return true;
}
/**
* Register an {@link org.spongepowered.asm.mixin.Overwrite} method
*/
public void registerOverwrite(ExecutableElement method) {
if (!this.validateSingleTarget("@Overwrite")) {
return;
}
String mcpName = method.getSimpleName().toString();
String mcpSignature = MirrorUtils.generateSignature(method);
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + mcpName, mcpSignature));
if (obfMethod == null) {
this.mixins.printMessage(Kind.ERROR, "No obfuscation mapping for @Overwrite method " + mcpName + " in " + this.mixin);
return;
}
this.addMethodMapping(mcpName, obfMethod.name, mcpSignature, obfMethod.sig);
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} field
*/
public void registerShadow(VariableElement field, AnnotationMirror shadow) {
if (!this.validateSingleTarget("@Shadow")) {
return;
}
ShadowElementName name = new ShadowElementName(field, shadow);
String obfField = this.mixins.getObfField(this.targetRef + "/" + name);
if (obfField == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field " + name + " in " + this.mixin);
return;
}
this.addFieldMapping(name.setObfuscatedName(obfField));
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} method
*/
public void registerShadow(ExecutableElement method, AnnotationMirror shadow) {
if (!this.validateSingleTarget("@Shadow")) {
return;
}
ShadowElementName name = new ShadowElementName(method, shadow);
String mcpSignature = MirrorUtils.generateSignature(method);
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + name, mcpSignature));
if (obfMethod == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method " + name + " in " + this.mixin);
return;
}
this.addMethodMapping(name.setObfuscatedName(obfMethod.name), mcpSignature, obfMethod.sig);
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.Inject} method
*/
public void registerInjector(ExecutableElement method, AnnotationMirror inject) {
if (!this.validateSingleTarget("@Inject")) {
return;
}
String originalReference = MirrorUtils.<String>getAnnotationValue(inject, "method");
MemberInfo targetMember = MemberInfo.parse(originalReference);
if (targetMember.name == null) {
return;
}
String desc = AnnotatedMixin.findDescriptor(this.targetType, targetMember);
if (desc == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to parse signature for @Inject target " + targetMember.name + " in " + this.mixin);
return;
}
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc));
if (obfMethod == null) {
this.mixins.printMessage(Kind.ERROR, "No obfuscation mapping for @Inject target " + targetMember.name + " in " + this.mixin);
return;
}
String obfName = obfMethod.name.substring(obfMethod.name.lastIndexOf('/') + 1);
MemberInfo remappedReference = new MemberInfo(obfName, this.targetRef, obfMethod.sig, false);
this.mixins.getReferenceMapper().addMapping(this.classRef, originalReference, remappedReference.toString());
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.At} annotation and process the references
*/
public void registerInjectionPoint(AnnotationMirror at) {
String type = MirrorUtils.<String>getAnnotationValue(at, "value");
String target = MirrorUtils.<String>getAnnotationValue(at, "target");
this.remapReference(type + ".<target>", target);
// Pattern for replacing references in args, not used yet
// if ("SOMETYPE".equals(type)) {
// Map<String, String> args = AnnotatedMixin.getAtArgs(at);
// this.remapReference(type + ".args[target]", args.get("target"));
// }
}
private void remapReference(String key, String target) {
if (target == null) {
return;
}
MemberInfo targetMember = MemberInfo.parse(target);
if (!targetMember.isFullyQualified()) {
String missing = "missing " + (targetMember.owner == null ? (targetMember.desc == null ? "owner and signature" : "owner") : "signature");
this.mixins.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing + " in \"" + target + "\" in " + this.mixin);
return;
}
MemberInfo remappedReference = null;
if (targetMember.isField()) {
String obfField = this.mixins.getObfField(targetMember.toSrg());
if (obfField == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") \"" + target + "\" in " + this.mixin);
return;
}
remappedReference = MemberInfo.fromSrgField(obfField, targetMember.desc);
} else {
MethodData obfMethod = this.mixins.getObfMethod(targetMember.asMethodData());
if (obfMethod == null) {
this.mixins.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") \"" + target + "\" in " + this.mixin);
return;
}
remappedReference = MemberInfo.fromSrgMethod(obfMethod);
}
this.mixins.getReferenceMapper().addMapping(this.classRef, target, remappedReference.toString());
}
/**
* Add a field mapping to the local table
*/
private void addFieldMapping(ShadowElementName name) {
String mapping = String.format("FD: %s %s", this.classRef + "/" + name.name(), this.classRef + "/" + name.obfuscated());
this.fieldMappings.add(mapping);
}
/**
* Add a method mapping to the local table
*/
private void addMethodMapping(ShadowElementName name, String mcpSignature, String obfSignature) {
this.addMethodMapping(name.name(), name.obfuscated(), mcpSignature, obfSignature);
}
/**
* Add a method mapping to the local table
*/
private void addMethodMapping(String mcpName, String obfName, String mcpSignature, String obfSignature) {
String mapping = String.format("MD: %s %s %s %s", this.classRef + "/" + mcpName, mcpSignature, this.classRef + "/" + obfName, obfSignature);
this.methodMappings.add(mapping);
}
static String findDescriptor(TypeElement targetType, MemberInfo memberInfo) {
String desc = memberInfo.desc;
if (desc == null) {
for (Element child : targetType.getEnclosedElements()) {
if (child.getKind() != ElementKind.METHOD) {
continue;
}
if (child.getSimpleName().toString().equals(memberInfo.name)) {
desc = MirrorUtils.generateSignature((ExecutableElement)child);
break;
}
}
}
return desc;
}
static Map<String, String> getAtArgs(AnnotationMirror at) {
Map<String, String> args = new HashMap<String, String>();
List<AnnotationValue> argv = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(at, "args");
if (argv != null) {
for (AnnotationValue av : argv) {
String arg = (String)av.getValue();
if (arg == null) {
continue;
}
int eqPos = arg.indexOf('=');
if (eqPos > -1) {
args.put(arg.substring(0, eqPos), arg.substring(eqPos + 1));
} else {
args.put(arg, "");
}
}
}
return args;
}
}
@@ -0,0 +1,328 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.tools.MirrorUtils;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import net.minecraftforge.srg2source.rangeapplier.SrgContainer;
/**
* Mixin info manager, stores all of the mixin info during processing and also manages access to the srgs
*/
class AnnotatedMixins {
/**
* Singleton instances for each ProcessingEnvironment
*/
private static Map<ProcessingEnvironment, AnnotatedMixins> instances = new HashMap<ProcessingEnvironment, AnnotatedMixins>();
/**
* Local processing environment
*/
private final ProcessingEnvironment processingEnv;
/**
* Mixins during processing phase
*/
private final Map<String, AnnotatedMixin> mixins = new HashMap<String, AnnotatedMixin>();
/**
* Name of the resource to write generated srgs to
*/
private final String outSrgFileName;
/**
* File containing the reobfd srgs
*/
private final File reobfSrgFile;
/**
* SRG container for mcp->srg mappings
*/
private final SrgContainer srgs = new SrgContainer();
/**
* Reference mapper for reference mapping
*/
private final ReferenceMapper refMapper = new ReferenceMapper();
/**
* Private constructor, get instances using {@link #getMixinsForEnvironment}
*/
private AnnotatedMixins(ProcessingEnvironment processingEnv) {
String outSrgFileName = processingEnv.getOptions().get("outSrgFile");
this.outSrgFileName = (outSrgFileName != null) ? outSrgFileName : "mixins.srg";
String reobfSrgFileName = processingEnv.getOptions().get("reobfSrgFile");
if (reobfSrgFileName == null) {
processingEnv.getMessager().printMessage(Kind.ERROR, "The reobfSrgFile argument was not supplied, processing cannot continue");
}
this.processingEnv = processingEnv;
this.reobfSrgFile = new File(reobfSrgFileName);
try {
this.srgs.readSrg(this.reobfSrgFile);
} catch (Exception ex) {
ex.printStackTrace();
processingEnv.getMessager().printMessage(Kind.ERROR, "The specified SRG file could not be read, processing cannot continue");
}
}
/**
* Write out generated srgs
*/
public void writeSrgs() {
Set<String> fieldMappings = new LinkedHashSet<String>();
Set<String> methodMappings = new LinkedHashSet<String>();
for (AnnotatedMixin mixin : this.mixins.values()) {
fieldMappings.addAll(mixin.getFieldMappings());
methodMappings.addAll(mixin.getMethodMappings());
}
PrintWriter writer = null;
try {
Filer filer = this.processingEnv.getFiler();
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", this.outSrgFileName);
writer = new PrintWriter(outSrg.openWriter());
for (String fieldMapping : fieldMappings) {
writer.println(fieldMapping);
}
for (String methodMapping : methodMappings) {
writer.println(methodMapping);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ex) {
// oh well
}
}
}
}
/**
* Write out stored mappings
*/
public void writeRefs() {
PrintWriter writer = null;
try {
Filer filer = this.processingEnv.getFiler();
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", ReferenceMapper.DEFAULT_RESOURCE);
writer = new PrintWriter(outSrg.openWriter());
this.refMapper.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception ex) {
// oh well
}
}
}
}
/**
* Get the reference mapper
*/
public ReferenceMapper getReferenceMapper() {
return this.refMapper;
}
/**
* Clear all registered mixins
*/
public void clear() {
this.mixins.clear();
}
/**
* Register a new mixin class
*/
public void registerMixin(TypeElement mixinType) {
String name = mixinType.getQualifiedName().toString();
if (!this.mixins.containsKey(name)) {
this.mixins.put(name, new AnnotatedMixin(this, mixinType));
}
}
/**
* Get a registered mixin
*/
public AnnotatedMixin getMixin(TypeElement mixinType) {
return this.getMixin(mixinType.getQualifiedName().toString());
}
/**
* Get a registered mixin
*/
public AnnotatedMixin getMixin(String mixinType) {
return this.mixins.get(mixinType);
}
/**
* Register an {@link org.spongepowered.asm.mixin.Overwrite} method
*
* @param mixinType Mixin class
* @param method Overwrite method
*/
public void registerOverwrite(TypeElement mixinType, ExecutableElement method) {
AnnotatedMixin mixinClass = this.getMixin(mixinType);
if (mixinClass == null) {
this.processingEnv.getMessager().printMessage(Kind.ERROR,
"Found @Overwrite annotation on a non-mixin method " + method + " in " + mixinType);
return;
}
mixinClass.registerOverwrite(method);
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} field
*
* @param mixinType Mixin class
* @param method Shadow field
* @param shadow {@link org.spongepowered.asm.mixin.Shadow} annotation
*/
public void registerShadow(TypeElement mixinType, VariableElement field, AnnotationMirror shadow) {
AnnotatedMixin mixinClass = this.getMixin(mixinType);
if (mixinClass == null) {
this.processingEnv.getMessager().printMessage(Kind.ERROR,
"Found @Shadow annotation on a non-mixin field " + field + " in " + mixinType);
return;
}
mixinClass.registerShadow(field, shadow);
}
/**
* Register a {@link org.spongepowered.asm.mixin.Shadow} method
*
* @param mixinType Mixin class
* @param method Shadow method
* @param shadow {@link org.spongepowered.asm.mixin.Shadow} annotation
*/
public void registerShadow(TypeElement mixinType, ExecutableElement method, AnnotationMirror shadow) {
AnnotatedMixin mixinClass = this.getMixin(mixinType);
if (mixinClass == null) {
this.processingEnv.getMessager().printMessage(Kind.ERROR,
"Found @Shadow annotation on a non-mixin method " + method + " in " + mixinType);
return;
}
mixinClass.registerShadow(method, shadow);
}
/**
* Register a {@link org.spongepowered.asm.mixin.injection.Inject} method
*
* @param mixinType Mixin class
* @param method Injector method
* @param inject {@link org.spongepowered.asm.mixin.injection.Inject} annotation
*/
public void registerInjector(TypeElement mixinType, ExecutableElement method, AnnotationMirror inject) {
AnnotatedMixin mixinClass = this.getMixin(mixinType);
if (mixinClass == null) {
this.processingEnv.getMessager().printMessage(Kind.ERROR,
"Found @Inject annotation on a non-mixin method " + method + " in " + mixinType);
return;
}
mixinClass.registerInjector(method, inject);
List<AnnotationMirror> annotationValue = MirrorUtils.<List<AnnotationMirror>>getAnnotationValue(inject, "at");
for (AnnotationMirror at : annotationValue) {
mixinClass.registerInjectionPoint(at);
}
}
/**
* Print a message to the AP messager
*/
public void printMessage(Diagnostic.Kind kind, CharSequence msg) {
this.processingEnv.getMessager().printMessage(kind, msg);
}
/**
* Get an obfuscation mapping for a method
*/
public MethodData getObfMethod(MethodData method) {
if (this.srgs == null) {
return null;
}
return this.srgs.methodMap.get(method);
}
/**
* Get an obfuscation mapping for a field
*/
public String getObfField(String field) {
if (this.srgs == null) {
return null;
}
return this.srgs.fieldMap.get(field);
}
/**
* Get the mixin manager instance for this environment
*/
public static AnnotatedMixins getMixinsForEnvironment(ProcessingEnvironment processingEnv) {
AnnotatedMixins mixins = AnnotatedMixins.instances.get(processingEnv);
if (mixins == null) {
mixins = new AnnotatedMixins(processingEnv);
AnnotatedMixins.instances.put(processingEnv, mixins);
}
return mixins;
}
}
@@ -0,0 +1,94 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.tools.MirrorUtils;
/**
* Annotation processor which finds {@link Inject} and {@link At} annotations in mixin classes and generates SRG mappings
*/
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.injection.Inject", "org.spongepowered.asm.mixin.injection.At" })
@SupportedOptions({ "reobfSrgFile", "outSrgFile" })
public class InjectionObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
* @see javax.annotation.processing.AbstractProcessor#process(java.util.Set, javax.annotation.processing.RoundEnvironment)
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
this.processMixins(roundEnv);
this.processInjectors(roundEnv);
try {
this.mixins.writeRefs();
} catch (Exception ex) {
ex.printStackTrace();
}
return true;
}
/**
* Searches for {@link Inject} annotations and registers them with their parent mixins
*/
private void processInjectors(RoundEnvironment roundEnv) {
for (Element elem : roundEnv.getElementsAnnotatedWith(Inject.class)) {
Element parent = elem.getEnclosingElement();
if (!(parent instanceof TypeElement)) {
throw new IllegalStateException("@Shadow element has unexpected parent with type " + MirrorUtils.getElementType(parent));
}
AnnotationMirror inject = MirrorUtils.getAnnotation(elem, Inject.class);
if (elem.getKind() == ElementKind.METHOD) {
this.mixins.registerInjector((TypeElement)parent, (ExecutableElement)elem, inject);
} else {
this.processingEnv.getMessager().printMessage(Kind.WARNING,
"Found an @Inject annotation on an element which is not a method: " + elem.toString());
}
}
}
}
@@ -0,0 +1,67 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.Mixin;
public abstract class MixinProcessor extends AbstractProcessor {
/**
* Mixin info manager
*/
protected AnnotatedMixins mixins;
/* (non-Javadoc)
* @see javax.annotation.processing.AbstractProcessor#init(javax.annotation.processing.ProcessingEnvironment)
*/
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.mixins = AnnotatedMixins.getMixinsForEnvironment(processingEnv);
}
/**
* Searches and catalogues all annotated mixin classes
*/
protected void processMixins(RoundEnvironment roundEnv) {
for (Element elem1 : roundEnv.getElementsAnnotatedWith(Mixin.class)) {
if (elem1.getKind() == ElementKind.CLASS) {
this.mixins.registerMixin((TypeElement)elem1);
} else {
this.processingEnv.getMessager().printMessage(Kind.WARNING,
"Found an @Mixin annotation on an element which is not a class: " + elem1.toString());
}
}
}
}
@@ -0,0 +1,117 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation;
import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic.Kind;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.tools.MirrorUtils;
/**
* Annotation processor which finds {@link Shadow} and {@link Overwrite} annotations in mixin classes and generates SRG mappings
*/
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.Mixin", "org.spongepowered.asm.mixin.Shadow", "org.spongepowered.asm.mixin.Overwrite" })
@SupportedOptions({ "reobfSrgFile", "outSrgFile" })
public class TargetObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
* @see javax.annotation.processing.AbstractProcessor#process(java.util.Set, javax.annotation.processing.RoundEnvironment)
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
this.processMixins(roundEnv);
this.processShadows(roundEnv);
this.processOverwrites(roundEnv);
try {
this.mixins.writeSrgs();
} catch (Exception ex) {
ex.printStackTrace();
}
return true;
}
/**
* Searches for {@link Shadow} annotations and registers them with their parent mixins
*/
private void processShadows(RoundEnvironment roundEnv) {
for (Element elem : roundEnv.getElementsAnnotatedWith(Shadow.class)) {
Element parent = elem.getEnclosingElement();
if (!(parent instanceof TypeElement)) {
throw new IllegalStateException("@Shadow element has unexpected parent with type " + MirrorUtils.getElementType(parent));
}
AnnotationMirror shadow = MirrorUtils.getAnnotation(elem, Shadow.class);
if (elem.getKind() == ElementKind.FIELD) {
this.mixins.registerShadow((TypeElement)parent, (VariableElement)elem, shadow);
} else if (elem.getKind() == ElementKind.METHOD) {
this.mixins.registerShadow((TypeElement)parent, (ExecutableElement)elem, shadow);
} else {
this.processingEnv.getMessager().printMessage(Kind.WARNING,
"Found an @Shadow annotation on an element which is not a method or field: " + elem.toString());
}
}
}
/**
* Searches for {@link Overwrite} annotations and registers them with their parent mixins
*/
private void processOverwrites(RoundEnvironment roundEnv) {
for (Element elem : roundEnv.getElementsAnnotatedWith(Overwrite.class)) {
Element parent = elem.getEnclosingElement();
if (!(parent instanceof TypeElement)) {
throw new IllegalStateException("@Overwrite element has unexpected parent with type " + MirrorUtils.getElementType(parent));
}
if (elem.getKind() == ElementKind.METHOD) {
this.mixins.registerOverwrite((TypeElement)parent, (ExecutableElement)elem);
} else {
this.processingEnv.getMessager().printMessage(Kind.WARNING,
"Found an @Overwrite annotation on an element which is not a method: " + elem.toString());
}
}
}
}
@@ -0,0 +1,2 @@
org.spongepowered.tools.obfuscation.TargetObfuscationProcessor
org.spongepowered.tools.obfuscation.InjectionObfuscationProcessor
@@ -81,7 +81,8 @@ public @interface At {
public String[] args() default { };
/**
* Target member used by INVOKE, INVOKE_STRING and FIELD
* Target member used by INVOKE, INVOKE_STRING and FIELD. This <b>must be specified as a fully-qualified member path</b> including the class name
* and signature. Failing to fully-qualify the target member will result in an error at obfuscation time.
*/
public String target() default "";
@@ -42,6 +42,7 @@ import org.spongepowered.asm.mixin.injection.points.BeforeStringInvoke;
import org.spongepowered.asm.mixin.injection.points.JumpInsnPoint;
import org.spongepowered.asm.mixin.injection.points.MethodHead;
import org.spongepowered.asm.mixin.injection.struct.InjectionPointData;
import org.spongepowered.asm.mixin.transformer.MixinData;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Joiner;
@@ -262,14 +263,14 @@ public abstract class InjectionPoint {
/**
* Parse an InjectionPoint from the supplied {@link At} annotation
*/
public static InjectionPoint parse(At at) {
return InjectionPoint.parse(at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
public static InjectionPoint parse(MixinData mixin, At at) {
return InjectionPoint.parse(mixin, at.value(), at.shift(), at.by(), Arrays.asList(at.args()), at.target(), at.ordinal(), at.opcode());
}
/**
* Parse an InjectionPoint from the supplied {@link At} annotation supplied as an AnnotationNode instance
*/
public static InjectionPoint parse(AnnotationNode node) {
public static InjectionPoint parse(MixinData mixin, AnnotationNode node) {
String at = ASMHelper.<String>getAnnotationValue(node, "value");
List<String> args = ASMHelper.<List<String>>getAnnotationValue(node, "args");
String target = ASMHelper.<String>getAnnotationValue(node, "target", "");
@@ -282,14 +283,14 @@ public abstract class InjectionPoint {
args = ImmutableList.<String>of();
}
return InjectionPoint.parse(at, shift, by, args, target, ordinal, opcode);
return InjectionPoint.parse(mixin, at, shift, by, args, target, ordinal, opcode);
}
/**
* Parse and instantiate an InjectionPoint from the supplied information. Returns null if an InjectionPoint could not be created.
*/
public static InjectionPoint parse(String at, At.Shift shift, int by, List<String> args, String target, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(args, target, ordinal, opcode);
public static InjectionPoint parse(MixinData mixin, String at, At.Shift shift, int by, List<String> args, String target, int ordinal, int opcode) {
InjectionPointData data = new InjectionPointData(mixin, args, target, ordinal, opcode);
InjectionPoint point = null;
if (BeforeFieldAccess.CODE.equals(at)) {
@@ -38,6 +38,7 @@ import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionPoint;
import org.spongepowered.asm.mixin.injection.InvalidInjectionException;
import org.spongepowered.asm.mixin.injection.callback.CallbackInjector;
import org.spongepowered.asm.mixin.transformer.MixinData;
import org.spongepowered.asm.util.ASMHelper;
@@ -55,7 +56,7 @@ public class InjectionInfo {
* Annotated method
*/
private final MethodNode method;
/**
* Annotated method is static
*/
@@ -93,17 +94,17 @@ public class InjectionInfo {
* @param method Method
* @param injectAnnotation Annotation to parse
*/
public InjectionInfo(ClassNode classNode, MethodNode method, AnnotationNode injectAnnotation) {
public InjectionInfo(ClassNode classNode, MethodNode method, MixinData mixin, AnnotationNode injectAnnotation) {
this.classNode = classNode;
this.method = method;
this.isStatic = ASMHelper.methodIsStatic(method);
this.parse(injectAnnotation);
this.parse(mixin, injectAnnotation);
}
/**
* Parse the info from the supplied annotation
*/
private void parse(AnnotationNode injectAnnotation) {
private void parse(MixinData mixin, AnnotationNode injectAnnotation) {
if (injectAnnotation == null) {
return;
}
@@ -118,9 +119,9 @@ public class InjectionInfo {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " is missing 'at' value(s)");
}
MemberInfo targetMember = MemberInfo.parse(method);
MemberInfo targetMember = MemberInfo.parse(method, mixin);
if (targetMember.owner != null) {
if (targetMember.owner != null && targetMember.owner.equals(mixin.getTargetClassRef())) {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " specifies a target class '" + targetMember.owner
+ "', which is not supported");
}
@@ -128,14 +129,14 @@ public class InjectionInfo {
this.findMethods(targetMember);
if (this.targets.size() == 0) {
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " could not find specified method '" + method + "'");
throw new InvalidInjectionException("@Inject annotation on " + this.method.name + " could not find '" + targetMember.name + "'");
}
this.cancellable = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "cancellable", false);
this.captureLocals = ASMHelper.<Boolean>getAnnotationValue(injectAnnotation, "captureLocals", false);
for (AnnotationNode at : ats) {
InjectionPoint injectionPoint = InjectionPoint.parse(at);
InjectionPoint injectionPoint = InjectionPoint.parse(mixin, at);
if (injectionPoint != null) {
this.injectionPoints.add(injectionPoint);
}
@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.transformer.MixinData;
/**
@@ -41,6 +42,11 @@ public class InjectionPointData {
*/
private final Map<String, String> args = new HashMap<String, String>();
/**
* Mixin
*/
private final MixinData mixin;
/**
* Target
*/
@@ -56,7 +62,8 @@ public class InjectionPointData {
*/
private final int opcode;
public InjectionPointData(List<String> args, String target, int ordinal, int opcode) {
public InjectionPointData(MixinData mixin, List<String> args, String target, int ordinal, int opcode) {
this.mixin = mixin;
this.target = target;
this.ordinal = Math.max(-1, ordinal);
this.opcode = opcode;
@@ -95,7 +102,7 @@ public class InjectionPointData {
}
public MemberInfo get(String key) {
return MemberInfo.parse(this.get(key, ""));
return MemberInfo.parse(this.get(key, ""), this.mixin);
}
private int parseInt(String string, int defaultValue) {
@@ -115,7 +122,7 @@ public class InjectionPointData {
}
public MemberInfo getTarget() {
return MemberInfo.parse(this.target);
return MemberInfo.parse(this.target, this.mixin);
}
public int getOrdinal() {
@@ -24,9 +24,12 @@
*/
package org.spongepowered.asm.mixin.injection.struct;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.transformer.MixinData;
/**
@@ -137,12 +140,69 @@ public class MemberInfo {
}
}
/**
* Initialise a MemberInfo using the supplied MethodData object
*/
public MemberInfo(MethodData methodData) {
int slashPos = methodData.name.lastIndexOf('/');
this.owner = methodData.name.substring(0, slashPos);
this.name = methodData.name.substring(slashPos + 1);
this.desc = methodData.sig;
this.matchAll = false;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("[OWNER=%s,NAME=%s,DESC=%s,ALL=%s]", this.owner, this.name, this.desc, this.matchAll);
String owner = this.owner != null ? "L" + this.owner + ";" : "";
String name = this.name != null ? this.name : "";
String qualifier = this.matchAll ? "*" : "";
String desc = this.desc != null ? this.desc : "";
String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : "");
return owner + name + qualifier + separator + desc;
}
/**
* Return this MemberInfo as an SRG mapping
*/
public String toSrg() {
if (!this.isFullyQualified()) {
throw new RuntimeException("Cannot convert unqalified reference to SRG mapping");
}
if (this.desc.startsWith("(")) {
return this.owner + "/" + this.name + " " + this.desc;
}
return this.owner + "/" + this.name;
}
public MethodData asMethodData() {
if (!this.isFullyQualified()) {
throw new RuntimeException("Cannot convert unqalified reference to MethodData");
}
if (this.isField()) {
throw new RuntimeException("Cannot convert a non-method reference to MethodData");
}
return new MethodData(this.owner + "/" + this.name, this.desc);
}
/**
* Get whether this reference is fully qualified
*/
public boolean isFullyQualified() {
return this.owner != null && this.name != null && this.desc != null;
}
/**
* Get whether this MemberInfo is definitely a field, the output of this method is undefined if {@link #isFullyQualified} returns false
*/
public boolean isField() {
return this.desc != null && !this.desc.startsWith("(");
}
/**
@@ -188,9 +248,36 @@ public class MemberInfo {
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name) {
return MemberInfo.parse(name, null, null);
}
/**
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name, MixinData mixin) {
return MemberInfo.parse(name, mixin.getReferenceMapper(), mixin.getClassRef());
}
/**
* Parse a MemberInfo from a string
*/
public static MemberInfo parse(String name, ReferenceMapper refMapper, String mixinClass) {
String desc = null;
String owner = null;
String n = name;
if (refMapper != null) {
name = refMapper.remap(mixinClass, name);
}
System.err.println("==============================================================================");
System.err.println("==============================================================================");
System.err.println("==============================================================================");
System.err.println("Remapped [" + n + "] to [" + name + "] for " + mixinClass);
System.err.println("==============================================================================");
System.err.println("==============================================================================");
System.err.println("==============================================================================");
int lastDotPos = name.lastIndexOf('.');
int semiColonPos = name.indexOf(';');
if (lastDotPos > -1) {
@@ -207,7 +294,7 @@ public class MemberInfo {
desc = name.substring(parenPos);
name = name.substring(0, parenPos);
} else if (colonPos > -1) {
desc = name.substring(colonPos);
desc = name.substring(colonPos + 1);
name = name.substring(0, colonPos);
}
@@ -222,4 +309,15 @@ public class MemberInfo {
return new MemberInfo(name, owner, desc, matchAll);
}
public static MemberInfo fromSrgField(String srgName, String desc) {
int slashPos = srgName.lastIndexOf('/');
String owner = srgName.substring(0, slashPos);
String name = srgName.substring(slashPos + 1);
return new MemberInfo(name, owner, desc, false);
}
public static MemberInfo fromSrgMethod(MethodData methodData) {
return new MemberInfo(methodData);
}
}
@@ -0,0 +1,103 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.struct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class ReferenceMapper implements Serializable {
private static final long serialVersionUID = 1L;
public static final String DEFAULT_RESOURCE = "mixin.refmap.json";
private final Map<String, Map<String, String>> mappings;
public ReferenceMapper() {
this(new HashMap<String, Map<String, String>>());
}
public ReferenceMapper(Map<String, Map<String, String>> mappings) {
this.mappings = mappings;
}
public String remap(String className, String reference) {
if (className == null) {
for (Map<String, String> mappings : this.mappings.values()) {
if (mappings.containsKey(reference)) {
return mappings.get(reference);
}
}
}
Map<String, String> classMappings = this.mappings.get(className);
if (classMappings == null) {
return reference;
}
return classMappings.get(reference);
}
public void addMapping(String className, String reference, String newReference) {
Map<String, String> classMappings = this.mappings.get(className);
if (classMappings == null) {
classMappings = new HashMap<String, String>();
this.mappings.put(className, classMappings);
}
classMappings.put(reference, newReference);
}
public void write(Appendable writer) {
new GsonBuilder().setPrettyPrinting().create().toJson(this, writer);
}
public static ReferenceMapper read(String resource) {
Reader reader = null;
try {
reader = new InputStreamReader(ReferenceMapper.class.getResourceAsStream("/" + resource));
return ReferenceMapper.read(reader);
} catch (Exception ex) {
return new ReferenceMapper();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// don't really care
}
}
}
}
public static ReferenceMapper read(Reader reader) {
return new Gson().fromJson(reader, ReferenceMapper.class);
}
}
@@ -30,6 +30,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
@@ -62,6 +64,17 @@ class MixinConfig {
@SerializedName("setSourceFile")
private boolean setSourceFile = false;
/**
* True to set the sourceFile property when applying mixins
*/
@SerializedName("referenceMap")
private String refMapperConfig;
/**
* Reference mapper for injectors
*/
private transient ReferenceMapper refMapper;
/**
* Keep track of initialisation state
*/
@@ -98,6 +111,12 @@ class MixinConfig {
ex.printStackTrace();
}
}
if (this.refMapperConfig == null) {
this.refMapperConfig = ReferenceMapper.DEFAULT_RESOURCE;
}
this.refMapper = ReferenceMapper.read(this.refMapperConfig);
}
/**
@@ -121,6 +140,13 @@ class MixinConfig {
return this.setSourceFile;
}
/**
* Get the reference remapper for injectors
*/
public ReferenceMapper getReferenceMapper() {
return this.refMapper;
}
/**
* Check whether this configuration bundle has a mixin for the specified class
*
@@ -39,7 +39,9 @@ import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.InvalidMixinException;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.asm.util.ASMHelper;
@@ -91,6 +93,31 @@ public class MixinData {
public ClassNode getClassNode() {
return this.classNode;
}
/**
* Get the mixin class name
*/
public String getClassName() {
return this.info.getClassName();
}
/**
* Get the internal mixin class name
*/
public String getClassRef() {
return this.info.getClassRef();
}
/**
* Get the target class reference
*/
public String getTargetClassRef() {
List<String> targetClasses = this.info.getTargetClasses();
if (targetClasses.size() != 1) {
throw new InvalidMixinException("Multiple targets found for " + this.getClassName() + " but exactly one is required");
}
return targetClasses.get(0);
}
/**
* Get all interfaces for this mixin
@@ -105,6 +132,13 @@ public class MixinData {
public boolean shouldSetSourceFile() {
return this.info.getParent().shouldSetSourceFile();
}
/**
* Get the reference mapper for this mixin
*/
public ReferenceMapper getReferenceMapper() {
return this.info.getParent().getReferenceMapper();
}
/**
* Prepare the mixin, applies any pre-processing transformations
@@ -390,7 +390,7 @@ public class MixinTransformer extends TreeTransformer {
continue;
}
InjectionInfo injectInfo = new InjectionInfo(targetClass, method, injectAnnotation);
InjectionInfo injectInfo = new InjectionInfo(targetClass, method, mixin, injectAnnotation);
if (injectInfo.isValid()) {
injectInfo.inject();
}