Support private mixin targets, AP improvements & minor fixes, closes #7

This commit is contained in:
Mumfrey committed 2015-01-18 00:05:51 +00:00
1 parent 2ef7cad8a9
commit 0f27299597
17 files changed
+566 -113

No files matched your search

+2 -2
View File
@@ -160,8 +160,8 @@ shadowJar {
include(dependency('net.minecraftforge.srg2source:Srg2Source'))
include(dependency('net.sf.jopt-simple:jopt-simple'))
}
// classifier = new Date().format('yyyyMMddHHmmss') // for dev
classifier = 'processor'
classifier = new Date().format('yyyyMMddHHmmss') // for dev
// classifier = 'processor'
}
build.dependsOn(shadowJar)
@@ -167,30 +167,19 @@ public abstract class MirrorUtils {
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 ERROR:
// TODO figure out a better way to not crash when we get here
return "Ljava/lang/Object;";
case VOID:
return "V";
case ARRAY: return "[" + MirrorUtils.getInternalName(((ArrayType)type).getComponentType());
case DECLARED: return "L" + MirrorUtils.getInternalName((DeclaredType)type) + ";";
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 VOID: return "V";
// TODO figure out a better way to not crash when we get here
case ERROR: return "Ljava/lang/Object;";
default:
}
@@ -26,6 +26,8 @@ package org.spongepowered.tools.obfuscation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -37,6 +39,7 @@ 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.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
@@ -48,6 +51,7 @@ 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;
import org.spongepowered.tools.obfuscation.validation.IMixinValidator;
/**
@@ -115,6 +119,11 @@ class AnnotatedMixin {
private static final String CTOR = "<init>";
/**
* Mixin annotation
*/
private final AnnotationMirror annotation;
/**
* Manager
*/
private final AnnotatedMixins mixins;
@@ -127,7 +136,7 @@ class AnnotatedMixin {
/**
* Specified targets
*/
private final List<String> targets = new ArrayList<String>();
private final List<TypeElement> targets = new ArrayList<TypeElement>();
/**
* Target "reference" (bytecode name)
@@ -158,34 +167,88 @@ class AnnotatedMixin {
* Stored (ordered) method mappings
*/
private final Set<String> methodMappings = new LinkedHashSet<String>();
public AnnotatedMixin(AnnotatedMixins mixins, TypeElement type) {
AnnotationMirror annotation = MirrorUtils.getAnnotation(type, Mixin.class);
public AnnotatedMixin(AnnotatedMixins mixins, TypeElement type, Collection<IMixinValidator> validators) {
this.annotation = MirrorUtils.getAnnotation(type, Mixin.class);
this.mixins = mixins;
this.mixin = type;
this.classRef = type.getQualifiedName().toString().replace('.', '/');
this.remap = AnnotatedMixins.getRemapValue(annotation);
String targetRef = null;
TypeElement targetType = null;
TypeMirror primaryTarget = this.initTargets();
if (primaryTarget != null) {
this.targetRef = MirrorUtils.getInternalName((DeclaredType)primaryTarget);
this.targetType = (TypeElement)((DeclaredType)primaryTarget).asElement();
} else {
this.targetRef = null;
this.targetType = null;
}
this.remap = AnnotatedMixins.getRemapValue(this.annotation) && this.targets.size() > 0;
for (IMixinValidator validator : validators) {
if (!validator.validate(type, this.annotation, this.targets)) {
return;
}
}
}
private TypeMirror initTargets() {
TypeMirror primaryTarget = null;
// Public targets, referenced by class
try {
List<AnnotationValue> targetList = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(annotation);
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();
List<AnnotationValue> publiTargets = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(this.annotation, "value",
Collections.<AnnotationValue>emptyList());
for (TypeMirror target : MirrorUtils.<TypeMirror>unfold(publiTargets)) {
TypeElement element = (TypeElement)((DeclaredType)target).asElement();
if (this.targets.contains(element)) {
continue;
}
this.targets.add(element);
if (primaryTarget == null) {
primaryTarget = target;
}
}
} catch (Exception ex) {
this.mixins.printMessage(Kind.WARNING, "Error processing target list: " + ex.getClass().getSimpleName() + ": "+ ex.getMessage(), type);
this.mixins.printMessage(Kind.WARNING, "Error processing public targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this);
}
this.targetRef = targetRef;
this.targetType = targetType;
// Private targets, referenced by name
try {
List<AnnotationValue> privateTargets = MirrorUtils.<List<AnnotationValue>>getAnnotationValue(this.annotation, "targets",
Collections.<AnnotationValue>emptyList());
for (String privateTarget : MirrorUtils.<String>unfold(privateTargets)) {
TypeElement element = this.mixins.getTypeElement(privateTarget);
if (this.targets.contains(element)) {
continue;
}
if (element == null) {
this.mixins.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this);
return null;
} else if (element.getModifiers().contains(Modifier.PUBLIC)) {
this.mixins.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " is public and must be specified in value", this);
return null;
}
TypeMirror target = element.asType();
this.targets.add(element);
if (primaryTarget == null) {
primaryTarget = target;
}
}
} catch (Exception ex) {
this.mixins.printMessage(Kind.WARNING, "Error processing private targets: " + ex.getClass().getName() + ": " + ex.getMessage(), this);
}
if (primaryTarget == null) {
this.mixins.printMessage(Kind.ERROR, "Mixin has no targets", this);
}
return primaryTarget;
}
public AnnotationMirror getAnnotation() {
return this.annotation;
}
/**
@@ -198,7 +261,7 @@ class AnnotatedMixin {
/**
* Get the mixin's targets
*/
public List<String> getTargets() {
public List<TypeElement> getTargets() {
return this.targets;
}
@@ -236,8 +299,9 @@ class AnnotatedMixin {
* only a single target is registered. Mixins containing annotated methods with these annotations cannot be multi-targetted.
*/
private boolean validateSingleTarget(String annotation, Element element) {
if (this.targetRef == null) {
this.mixins.printMessage(Kind.ERROR, "Mixin has multiple targets. " + annotation + " is not supported!", element);
if (this.targetRef == null || this.targets.size() > 1) {
this.mixins.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", element);
this.mixins.printMessage(Kind.ERROR, "Mixin with " + annotation + " members must have exactly one target.", this.mixin);
return false;
}
return true;
@@ -287,7 +351,7 @@ class AnnotatedMixin {
String obfField = this.mixins.getObfField(this.targetRef + "/" + name);
if (obfField == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field);
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow field", field, shadow);
return;
}
@@ -307,7 +371,7 @@ class AnnotatedMixin {
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", method);
this.mixins.printMessage(Kind.WARNING, "Unable to locate obfuscation mapping for @Shadow method", method, shadow);
return;
}
@@ -330,14 +394,14 @@ class AnnotatedMixin {
String desc = this.findDescriptor(this.targetType, targetMember);
if (desc == null) {
this.mixins.printMessage(Kind.WARNING, "Unable to determine signature for @Inject target method", method);
this.mixins.printMessage(Kind.WARNING, "Unable to determine signature for @Inject target method", method, inject);
return;
}
MethodData obfMethod = this.mixins.getObfMethod(new MethodData(this.targetRef + "/" + targetMember.name, desc));
if (obfMethod == null) {
Kind error = AnnotatedMixin.CTOR.equals(targetMember.name) ? Kind.WARNING : Kind.ERROR;
this.mixins.printMessage(error, "No obfuscation mapping for @Inject target " + targetMember.name, method);
this.mixins.printMessage(error, "No obfuscation mapping for @Inject target " + targetMember.name, method, inject);
return;
}
@@ -350,10 +414,10 @@ class AnnotatedMixin {
/**
* Register a {@link org.spongepowered.asm.mixin.injection.At} annotation and process the references
*/
public void registerInjectionPoint(AnnotationMirror at, Element element) {
public void registerInjectionPoint(Element element, AnnotationMirror inject, AnnotationMirror at) {
String type = MirrorUtils.<String>getAnnotationValue(at, "value");
String target = MirrorUtils.<String>getAnnotationValue(at, "target");
this.remapReference(type + ".<target>", target, element);
this.remapReference(type + ".<target>", target, element, inject, at);
// Pattern for replacing references in args, not used yet
// if ("SOMETYPE".equals(type)) {
@@ -362,7 +426,7 @@ class AnnotatedMixin {
// }
}
private void remapReference(String key, String target, Element element) {
private void remapReference(String key, String target, Element element, AnnotationMirror inject, AnnotationMirror at) {
if (target == null) {
return;
}
@@ -370,7 +434,7 @@ class AnnotatedMixin {
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, element);
this.mixins.printMessage(Kind.ERROR, "@At(" + key + ") is not fully qualified, " + missing, element, inject);
return;
}
@@ -378,14 +442,14 @@ class AnnotatedMixin {
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, element);
this.mixins.printMessage(Kind.WARNING, "Cannot find field mapping for @At(" + key + ") '" + target, element, inject);
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, element);
this.mixins.printMessage(Kind.WARNING, "Cannot find method mapping for @At(" + key + ") '" + target, element, inject);
return;
}
remappedReference = MemberInfo.fromSrgMethod(obfMethod);
@@ -34,6 +34,7 @@ import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
@@ -48,6 +49,11 @@ import javax.tools.StandardLocation;
import org.spongepowered.asm.mixin.injection.struct.ReferenceMapper;
import org.spongepowered.tools.MirrorUtils;
import org.spongepowered.tools.obfuscation.validation.IMixinValidator;
import org.spongepowered.tools.obfuscation.validation.ParentValidator;
import org.spongepowered.tools.obfuscation.validation.TargetValidator;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.srg2source.rangeapplier.MethodData;
import net.minecraftforge.srg2source.rangeapplier.SrgContainer;
@@ -56,7 +62,7 @@ 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 {
class AnnotatedMixins implements Messager {
static enum CompilerEnvironment {
/**
@@ -100,13 +106,18 @@ class AnnotatedMixins {
/**
* File containing the reobfd srgs
*/
private final File reobfSrgFile;
private final String reobfSrgFileName;
/**
* Reference mapper for reference mapping
*/
private final ReferenceMapper refMapper = new ReferenceMapper();
/**
* Rule validators
*/
private final List<IMixinValidator> validators;
/**
* SRG container for mcp->srg mappings
*/
@@ -124,18 +135,18 @@ class AnnotatedMixins {
this.env = this.detectEnvironment(processingEnv);
this.processingEnv = processingEnv;
String outSrgFileName = processingEnv.getOptions().get("outSrgFile");
this.outSrgFileName = (outSrgFileName != null) ? outSrgFileName : "mixins.srg";
this.reobfSrgFileName = processingEnv.getOptions().get("reobfSrgFile");
this.outSrgFileName = processingEnv.getOptions().get("outSrgFile");
this.outRefMapFileName = processingEnv.getOptions().get("outRefMapFile");
String outRefMapFileName = processingEnv.getOptions().get("outRefMapFile");
this.outRefMapFileName = (outRefMapFileName != null) ? outRefMapFileName : ReferenceMapper.DEFAULT_RESOURCE;
String reobfSrgFileName = processingEnv.getOptions().get("reobfSrgFile");
if (reobfSrgFileName == null) {
this.printMessage(Kind.ERROR, "The reobfSrgFile argument was not supplied, processing cannot continue");
if (this.reobfSrgFileName == null) {
this.printMessage(Kind.ERROR, "The reobfSrgFile argument was not supplied, obfuscation processing will not occur");
}
this.reobfSrgFile = new File(reobfSrgFileName);
this.validators = ImmutableList.<IMixinValidator>of(
new ParentValidator(processingEnv),
new TargetValidator(processingEnv)
);
}
private CompilerEnvironment detectEnvironment(ProcessingEnvironment processingEnv) {
@@ -153,9 +164,14 @@ class AnnotatedMixins {
if (!this.initDone) {
this.initDone = true;
if (this.reobfSrgFileName == null) {
return false;
}
try {
this.printMessage(Kind.NOTE, "Loading SRGs from " + this.reobfSrgFile.getAbsolutePath());
this.srgs = new SrgContainer().readSrg(this.reobfSrgFile);
File reobfSrgFile = new File(this.reobfSrgFileName);
this.printMessage(Kind.NOTE, "Loading SRGs from " + reobfSrgFile.getAbsolutePath());
this.srgs = new SrgContainer().readSrg(reobfSrgFile);
} catch (Exception ex) {
ex.printStackTrace();
this.printMessage(Kind.ERROR, "The specified SRG file could not be read, processing cannot continue");
@@ -170,6 +186,10 @@ class AnnotatedMixins {
* Write out generated srgs
*/
public void writeSrgs() {
if (this.outSrgFileName == null) {
return;
}
Set<String> fieldMappings = new LinkedHashSet<String>();
Set<String> methodMappings = new LinkedHashSet<String>();
@@ -181,7 +201,7 @@ class AnnotatedMixins {
PrintWriter writer = null;
try {
writer = this.openSrgFileWriter();
writer = this.openFileWriter(this.outSrgFileName, "output SRGs");
for (String fieldMapping : fieldMappings) {
writer.println(fieldMapping);
}
@@ -202,19 +222,19 @@ class AnnotatedMixins {
}
/**
* Open a writer for the output SRG file
* Open a writer for an output file
*/
private PrintWriter openSrgFileWriter() throws IOException {
if (this.outSrgFileName.matches("^.*[\\\\/:].*$")) {
File outSrgFile = new File(this.outSrgFileName);
private PrintWriter openFileWriter(String fileName, String description) throws IOException {
if (fileName.matches("^.*[\\\\/:].*$")) {
File outSrgFile = new File(fileName);
outSrgFile.getParentFile().mkdirs();
this.printMessage(Kind.NOTE, "Writing output SRGs to " + outSrgFile.getAbsolutePath());
this.printMessage(Kind.NOTE, "Writing " + description + " to " + outSrgFile.getAbsolutePath());
return new PrintWriter(outSrgFile);
}
Filer filer = this.processingEnv.getFiler();
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", this.outSrgFileName);
this.printMessage(Kind.NOTE, "Writing output SRGs to " + new File(outSrg.toUri()).getAbsolutePath());
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
this.printMessage(Kind.NOTE, "Writing " + description + " to " + new File(outSrg.toUri()).getAbsolutePath());
return new PrintWriter(outSrg.openWriter());
}
@@ -222,12 +242,14 @@ class AnnotatedMixins {
* Write out stored mappings
*/
public void writeRefs() {
if (this.outRefMapFileName == null) {
return;
}
PrintWriter writer = null;
try {
Filer filer = this.processingEnv.getFiler();
FileObject outSrg = filer.createResource(StandardLocation.CLASS_OUTPUT, "", this.outRefMapFileName);
writer = new PrintWriter(outSrg.openWriter());
writer = this.openFileWriter(this.outRefMapFileName, "refmap");
this.refMapper.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
@@ -264,7 +286,7 @@ class AnnotatedMixins {
String name = mixinType.getQualifiedName().toString();
if (!this.mixins.containsKey(name)) {
this.mixins.put(name, new AnnotatedMixin(this, mixinType));
this.mixins.put(name, new AnnotatedMixin(this, mixinType, this.validators));
}
}
@@ -365,18 +387,18 @@ class AnnotatedMixins {
at = ((AnnotationValue)at).getValue();
}
if (at instanceof AnnotationMirror) {
mixinClass.registerInjectionPoint((AnnotationMirror)at, method);
mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)at);
} else {
this.printMessage(Kind.WARNING, "No annotation mirror on " + at.getClass().getName());
}
}
} else if (ats instanceof AnnotationMirror) {
mixinClass.registerInjectionPoint((AnnotationMirror)ats, method);
mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)ats);
} else if (ats instanceof AnnotationValue) {
// Fix for JDT
Object mirror = ((AnnotationValue)ats).getValue();
if (mirror instanceof AnnotationMirror) {
mixinClass.registerInjectionPoint((AnnotationMirror)mirror, method);
mixinClass.registerInjectionPoint(method, inject, (AnnotationMirror)mirror);
}
}
}
@@ -396,8 +418,9 @@ class AnnotatedMixins {
/**
* Print a message to the AP messager
*/
@Override
public void printMessage(Diagnostic.Kind kind, CharSequence msg) {
if (this.env == CompilerEnvironment.JAVAC && kind != Kind.NOTE) {
if (this.env == CompilerEnvironment.JAVAC || kind != Kind.NOTE) {
this.processingEnv.getMessager().printMessage(kind, msg);
}
}
@@ -405,9 +428,40 @@ class AnnotatedMixins {
/**
* Print a message to the AP messager
*/
@Override
public void printMessage(Diagnostic.Kind kind, CharSequence msg, Element element) {
this.processingEnv.getMessager().printMessage(kind, msg, element);
}
/**
* Print a message to the AP messager
*/
@Override
public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation) {
this.processingEnv.getMessager().printMessage(kind, msg, element, annotation);
}
/**
* Print a message to the AP messager
*/
@Override
public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value) {
this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value);
}
/**
* Print a message to the AP messager
*/
public void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) {
this.processingEnv.getMessager().printMessage(kind, msg, mixin.getMixin(), mixin.getAnnotation());
}
/**
* Get a TypeElement representing another type in the current processing environment
*/
public TypeElement getTypeElement(String name) {
return this.processingEnv.getElementUtils().getTypeElement(name);
}
/**
* Get an obfuscation mapping for a method
@@ -54,7 +54,7 @@ import org.spongepowered.tools.MirrorUtils;
"org.spongepowered.asm.mixin.injection.Redirect",
"org.spongepowered.asm.mixin.injection.At"
})
@SupportedOptions({ "reobfSrgFile", "outSrgFile" })
@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile" })
public class InjectionObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
@@ -48,7 +48,7 @@ import org.spongepowered.tools.MirrorUtils;
*/
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes({ "org.spongepowered.asm.mixin.Mixin", "org.spongepowered.asm.mixin.Shadow", "org.spongepowered.asm.mixin.Overwrite" })
@SupportedOptions({ "reobfSrgFile", "outSrgFile" })
@SupportedOptions({ "reobfSrgFile", "outSrgFile", "outRefMapFile" })
public class TargetObfuscationProcessor extends MixinProcessor {
/* (non-Javadoc)
@@ -0,0 +1,36 @@
/*
* 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.validation;
import java.util.Collection;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
public interface IMixinValidator {
public abstract boolean validate(TypeElement mixin, AnnotationMirror annotation, Collection<TypeElement> targets);
}
@@ -0,0 +1,51 @@
/*
* 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.validation;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic.Kind;
public abstract class MixinValidator implements IMixinValidator {
protected final ProcessingEnvironment processingEnv;
public MixinValidator(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
protected final void note(String note, Element element) {
this.processingEnv.getMessager().printMessage(Kind.NOTE, note, element);
}
protected final void warning(String warning, Element element) {
this.processingEnv.getMessager().printMessage(Kind.WARNING, warning, element);
}
protected final void error(String error, Element element) {
this.processingEnv.getMessager().printMessage(Kind.ERROR, error, element);
}
}
@@ -0,0 +1,50 @@
/*
* 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.validation;
import java.util.Collection;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
public class ParentValidator extends MixinValidator {
public ParentValidator(ProcessingEnvironment processingEnv) {
super(processingEnv);
}
@Override
public boolean validate(TypeElement mixin, AnnotationMirror annotation, Collection<TypeElement> targets) {
if (mixin.getEnclosingElement().getKind() != ElementKind.PACKAGE && !mixin.getModifiers().contains(Modifier.STATIC)) {
this.error("Inner class mixin must be declared static", mixin);
}
return true;
}
}
@@ -0,0 +1,54 @@
/*
* 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.validation;
import java.util.Collection;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
public class TargetValidator extends MixinValidator {
public TargetValidator(ProcessingEnvironment processingEnv) {
super(processingEnv);
}
@Override
public boolean validate(TypeElement mixin, AnnotationMirror annotation, Collection<TypeElement> targets) {
TypeMirror superClass = mixin.getSuperclass();
for (TypeElement target : targets) {
TypeMirror targetType = target.asType();
if (!this.processingEnv.getTypeUtils().isAssignable(targetType, superClass)) {
this.error("Superclass " + superClass + " of " + mixin + " was not found in the hierarchy of target class " + targetType, mixin);
}
}
return true;
}
}
@@ -39,7 +39,14 @@ public @interface Mixin {
/**
* Target class(es) for this mixin
*/
public Class<?>[] value();
public Class<?>[] value() default { };
/**
* Since specifying targets in {@link #value} requires that the classes be publicly visible, this property is provided to allow package-private,
* anonymous innner, and private inner classes to be referenced. Referencing an otherwise public class using this property is an error condition
* and will throw an exception at runtime. It is completely fine to specify both public and private targets for the same mixin however.
*/
public String[] targets() default { };
/**
* Priority for the mixin, relative to other mixins targetting the same classes
@@ -132,7 +132,7 @@ public abstract class InjectionInfo {
MemberInfo targetMember = MemberInfo.parse(method, this.mixin);
if (targetMember.owner != null && targetMember.owner.equals(this.mixin.getTargetClassRef())) {
if (targetMember.owner != null && !targetMember.owner.equals(this.mixin.getTargetClassRef())) {
throw new InvalidInjectionException(type + " annotation on " + this.method.name + " specifies a target class '"
+ targetMember.owner + "', which is not supported");
}
@@ -32,6 +32,7 @@ import java.util.Map;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.collect.ImmutableList;
@@ -65,6 +66,11 @@ class ClassInfo extends TreeInfo {
*/
private final String superName;
/**
* Outer class name
*/
private final String outerName;
/**
* Interfaces
*/
@@ -75,15 +81,25 @@ class ClassInfo extends TreeInfo {
*/
private final List<String> methods;
/**
* True if this is an interface
*/
private final boolean isInterface;
/**
* Access flags
*/
private final int access;
/**
* Superclass reference, not initialised until required
*/
private ClassInfo superClass;
/**
* True if this is an interface
* Outer class reference, not initialised until required
*/
private boolean isInterface;
private ClassInfo outerClass;
/**
* Private constructor used to initialise the ClassInfo for {@link Object}
@@ -91,6 +107,7 @@ class ClassInfo extends TreeInfo {
private ClassInfo() {
this.name = ClassInfo.JAVA_LANG_OBJECT;
this.superName = null;
this.outerName = null;
this.methods = ImmutableList.<String>of(
"getClass()Ljava/lang/Class;",
"hashCode()I",
@@ -106,6 +123,7 @@ class ClassInfo extends TreeInfo {
);
this.isInterface = false;
this.interfaces = Collections.<String>emptyList();
this.access = Opcodes.ACC_PUBLIC;
}
/**
@@ -119,6 +137,7 @@ class ClassInfo extends TreeInfo {
this.methods = new ArrayList<String>();
this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
this.interfaces = Collections.unmodifiableList(classNode.interfaces);
this.access = classNode.access;
for (MethodNode method : classNode.methods) {
if (!method.name.startsWith("<")
@@ -127,6 +146,34 @@ class ClassInfo extends TreeInfo {
this.methods.add(method.name + method.desc);
}
}
String outerName = classNode.outerClass;
if (outerName == null) {
for (FieldNode field : classNode.fields) {
if ((field.access & Opcodes.ACC_SYNTHETIC) != 0 && field.name.startsWith("this$")) {
outerName = field.desc;
if (outerName.startsWith("L")) {
outerName = outerName.substring(1, outerName.length() - 1);
}
}
}
}
this.outerName = outerName ;
}
/**
* Get whether this class has ACC_PUBLIC
*/
public boolean isPublic() {
return (this.access & Opcodes.ACC_PUBLIC) != 0;
}
/**
* Get whether this class is an inner class
*/
public boolean isInner() {
return this.outerName != null;
}
/**
@@ -143,6 +190,15 @@ class ClassInfo extends TreeInfo {
return this.interfaces;
}
@Override
public String toString() {
return this.name;
}
public int getAccess() {
return this.access;
}
/**
* Get the class name (binary name)
*/
@@ -168,6 +224,24 @@ class ClassInfo extends TreeInfo {
return this.superClass;
}
/**
* Get the name of the outer class, or null if this is not an inner class
*/
public String getOuterName() {
return this.outerName;
}
/**
* Get the outer class info, can return null if the outer class cannot be resolved or if this is not an inner class
*/
public ClassInfo getOuterClass() {
if (this.outerClass == null && this.outerName != null) {
this.outerClass = ClassInfo.forName(this.outerName);
}
return this.outerClass;
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
@@ -239,6 +313,25 @@ class ClassInfo extends TreeInfo {
return this.methods.contains(name + desc);
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof ClassInfo)) {
return false;
}
return ((ClassInfo)other).name.equals(this.name);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.name.hashCode();
}
/**
* Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for the class was already defined, then the original ClassInfo is
* returned from the internal cache. Otherwise a new ClassInfo is created and returned.
@@ -108,7 +108,7 @@ class MixinConfig implements Comparable<MixinConfig> {
/**
* True to set the sourceFile property when applying mixins
*/
@SerializedName("referenceMap")
@SerializedName("refmap")
private String refMapperConfig;
/**
@@ -240,7 +240,7 @@ class MixinConfig implements Comparable<MixinConfig> {
if (mixin.getTargetClasses().size() > 0) {
MixinConfig.globalMixinList.add(mixinClass);
for (String targetClass : mixin.getTargetClasses()) {
this.mixinsFor(targetClass).add(mixin);
this.mixinsFor(targetClass.replace('/', '.')).add(mixin);
}
}
} catch (Exception ex) {
@@ -40,6 +40,10 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
/**
* Runtime information bundle about a mixin
*/
@@ -83,7 +87,12 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Mixin targets, read from the {@link Mixin} annotation on the mixin class
*/
private final List<String> targetClasses;
private final List<ClassInfo> targetClasses;
/**
* Names of target classes
*/
private final List<String> targetClassNames;
/**
* True if the superclass of the mixin is <b>not</b> the direct superclass of one or more targets
@@ -126,12 +135,30 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
this.mixinBytes = this.loadMixinClass(this.className, runTransformers);
ClassNode classNode = this.getClassNode(0);
this.classInfo = ClassInfo.fromClassNode(classNode);
this.classInfo = this.readInfo(classNode);
this.priority = this.readPriority(classNode);
this.targetClasses = this.readTargetClasses(classNode, suppressPlugin);
this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction()));
this.detachedSuper = this.validateTargetClasses(classNode);
}
/**
* Initialises the class info and performs some pre-flight checks on the mixin
*
* @param classNode
* @return
*/
private ClassInfo readInfo(ClassNode classNode) {
ClassInfo classInfo = ClassInfo.fromClassNode(classNode);
// isInner (shouldn't) return true for static inner classes
if (classInfo.isInner()) {
throw new InvalidMixinException("Inner class mixin must be declared static");
}
return classInfo;
}
/**
* Read the target class names from the {@link Mixin} annotation
*
@@ -139,24 +166,52 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
* @param suppressPlugin
* @return
*/
private List<String> readTargetClasses(ClassNode classNode, boolean suppressPlugin) {
private List<ClassInfo> readTargetClasses(ClassNode classNode, boolean suppressPlugin) {
AnnotationNode mixin = ASMHelper.getInvisibleAnnotation(classNode, Mixin.class);
if (mixin == null) {
throw new InvalidMixinException(String.format("The mixin '%s' is missing an @Mixin annotation", this.className));
}
List<Type> targetClasses = ASMHelper.getAnnotationValue(mixin);
List<String> targetClassNames = new ArrayList<String>();
for (Type targetClass : targetClasses) {
String targetClassName = targetClass.getClassName();
if (this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetClassName, this.className)) {
targetClassNames.add(targetClassName);
}
List<ClassInfo> targetClassNames = new ArrayList<ClassInfo>();
List<Type> publicTargets = ASMHelper.getAnnotationValue(mixin, "value");
List<String> privateTargets = ASMHelper.getAnnotationValue(mixin, "targets");
if (publicTargets != null) {
this.readTargets(targetClassNames, Lists.transform(publicTargets, new Function<Type, String>() {
@Override
public String apply(Type input) {
return input.getClassName();
};
}), suppressPlugin, false);
}
if (privateTargets != null) {
this.readTargets(targetClassNames, privateTargets, suppressPlugin, true);
}
return targetClassNames;
}
/**
* Reads a target list into the outTargets list
*/
private void readTargets(List<ClassInfo> outTargets, List<String> inTargets, boolean suppressPlugin, boolean checkPublic) {
for (String targetClassName : inTargets) {
if (this.plugin == null || suppressPlugin || this.plugin.shouldApplyMixin(targetClassName, this.className)) {
ClassInfo targetInfo = ClassInfo.forName(targetClassName);
if (targetInfo.isInterface()) {
throw new InvalidMixinException("@Mixin target " + targetClassName + " is an interface in " + this);
}
if (checkPublic && targetInfo.isPublic()) {
throw new InvalidMixinException("@Mixin target " + targetClassName + " is public in " + this + " and must be specified in value");
}
if (!outTargets.contains(targetInfo)) {
outTargets.add(targetInfo);
}
}
}
}
/**
* Read the priority from the {@link Mixin} annotation
*
@@ -176,8 +231,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
private boolean validateTargetClasses(ClassNode classNode) {
boolean detached = false;
for (String targetClassName : this.targetClasses) {
ClassInfo targetClass = ClassInfo.forName(targetClassName);
for (ClassInfo targetClass : this.targetClasses) {
if (classNode.superName.equals(targetClass.getSuperName())) {
continue;
@@ -185,7 +239,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
if (!targetClass.hasSuperClass(classNode.superName)) {
throw new InvalidMixinException("Super class '" + classNode.superName.replace('/', '.') + "' of " + this.name
+ " was not found in the hierarchy of target class '" + targetClassName + "'");
+ " was not found in the hierarchy of target class '" + targetClass + "'");
}
detached = true;
@@ -254,7 +308,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
*/
@Override
public List<String> getTargetClasses() {
return Collections.unmodifiableList(this.targetClasses);
return this.targetClassNames;
}
/**
@@ -60,7 +60,6 @@ import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.transformers.TreeTransformer;
import org.spongepowered.asm.util.ASMHelper;
@@ -45,9 +45,11 @@ import com.google.common.collect.ImmutableSet;
*/
abstract class TreeInfo {
private static final Set<String> reEntrantTransformers = ImmutableSet.<String>of(
private static final Set<String> excludeTransformers = ImmutableSet.<String>of(
"net.minecraftforge.fml.common.asm.transformers.EventSubscriptionTransformer",
"cpw.mods.fml.common.asm.transformers.EventSubscriptionTransformer"
"cpw.mods.fml.common.asm.transformers.EventSubscriptionTransformer",
"net.minecraftforge.fml.common.asm.transformers.TerminalTransformer",
"cpw.mods.fml.common.asm.transformers.TerminalTransformer"
);
private static IClassNameTransformer nameTransformer;
@@ -126,13 +128,13 @@ abstract class TreeInfo {
*
* @param name
* @param basicClass
* @return class bytecode after processing by all registered transformers except re-entrant transformers
* @return class bytecode after processing by all registered transformers except the excluded transformers
*/
private static byte[] applyTransformers(String name, byte[] basicClass) {
final List<IClassTransformer> transformers = Launch.classLoader.getTransformers();
for (final IClassTransformer transformer : transformers) {
if (!(transformer instanceof MixinTransformer) && !TreeInfo.reEntrantTransformers.contains(transformer.getClass().getName())) {
if (!(transformer instanceof MixinTransformer) && !TreeInfo.excludeTransformers.contains(transformer.getClass().getName())) {
basicClass = transformer.transform(name, name, basicClass);
}
}