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

@@ -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());
}
}
}
}