diff --git a/checkstyle.xml b/checkstyle.xml index 030d77ac..ea6a9e1d 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -94,8 +94,6 @@ - - @@ -108,7 +106,6 @@ - diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index c831b057..cfd9eb66 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -60,6 +60,7 @@ import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.util.ITokenProvider; import org.spongepowered.asm.util.VersionNumber; +import org.spongepowered.asm.util.logging.MessageRouter; import org.spongepowered.tools.obfuscation.interfaces.IJavadocProvider; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; @@ -144,9 +145,12 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider private AnnotatedMixins(ProcessingEnvironment processingEnv) { this.env = this.detectEnvironment(processingEnv); this.processingEnv = processingEnv; + + MessageRouter.setMessager(processingEnv.getMessager()); - this.printMessage(Kind.NOTE, "SpongePowered MIXIN Annotation Processor Version=" + MixinBootstrap.VERSION); - this.checkPluginVersion(this.getOption(SupportedOptions.PLUGIN_VERSION)); + String pluginVersion = this.checkPluginVersion(this.getOption(SupportedOptions.PLUGIN_VERSION)); + String pluginVersionString = pluginVersion != null ? String.format(" (MixinGradle Version=%s)", pluginVersion) : ""; + this.printMessage(Kind.NOTE, "SpongePowered MIXIN Annotation Processor Version=" + MixinBootstrap.VERSION + pluginVersionString); this.targets = this.initTargetMap(); this.obf = new ObfuscationManager(this); @@ -165,9 +169,9 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider * the user if the version of MixinGradle is out of date relative to the * Mixin library version */ - private void checkPluginVersion(String version) { + private String checkPluginVersion(String version) { if (version == null) { - return; + return null; } VersionNumber pluginVersion = VersionNumber.parse(version); @@ -176,6 +180,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider this.printMessage(Kind.WARNING, String.format("MixinGradle version %s is out of date. Update to the recommended version %s", pluginVersion, recommendedVersion)); } + return pluginVersion.toString(); } protected TargetMap initTargetMap() { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java index 3bbb16f6..a7787c1d 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/MixinObfuscationProcessorInjection.java @@ -25,10 +25,10 @@ package org.spongepowered.tools.obfuscation; import java.lang.annotation.Annotation; +import java.util.HashSet; import java.util.Set; import javax.annotation.processing.RoundEnvironment; -import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; @@ -37,26 +37,25 @@ import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.ModifyArgs; -import org.spongepowered.asm.mixin.injection.ModifyConstant; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.tools.obfuscation.mirror.AnnotationHandle; import org.spongepowered.tools.obfuscation.mirror.TypeUtils; /** - * Annotation processor which finds {@link Inject} and {@link At} annotations in - * mixin classes and generates obfuscation mappings + * Annotation processor which finds injector annotations in mixin classes and + * generates obfuscation mappings */ -@SupportedAnnotationTypes({ - "org.spongepowered.asm.mixin.injection.Inject", - "org.spongepowered.asm.mixin.injection.ModifyArg", - "org.spongepowered.asm.mixin.injection.ModifyArgs", - "org.spongepowered.asm.mixin.injection.Redirect", - "org.spongepowered.asm.mixin.injection.At" -}) public class MixinObfuscationProcessorInjection extends MixinObfuscationProcessor { + + @Override + public Set getSupportedAnnotationTypes() { + Set supportedAnnotationTypes = new HashSet(); + supportedAnnotationTypes.add(At.class.getName()); + for (Class annotationType : InjectionInfo.getRegisteredAnnotations()) { + supportedAnnotationTypes.add(annotationType.getName()); + } + return supportedAnnotationTypes; + } /* (non-Javadoc) * @see javax.annotation.processing.AbstractProcessor @@ -71,12 +70,9 @@ public class MixinObfuscationProcessorInjection extends MixinObfuscationProcesso } this.processMixins(roundEnv); - this.processInjectors(roundEnv, Inject.class); - this.processInjectors(roundEnv, ModifyArg.class); - this.processInjectors(roundEnv, ModifyArgs.class); - this.processInjectors(roundEnv, Redirect.class); - this.processInjectors(roundEnv, ModifyVariable.class); - this.processInjectors(roundEnv, ModifyConstant.class); + for (Class annotationType : InjectionInfo.getRegisteredAnnotations()) { + this.processInjectors(roundEnv, annotationType); + } this.postProcess(roundEnv); return true; @@ -115,4 +111,5 @@ public class MixinObfuscationProcessorInjection extends MixinObfuscationProcesso } } } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java index e7d1de21..7369df7f 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java @@ -64,7 +64,8 @@ public final class SupportedOptions { SupportedOptions.OVERWRITE_ERROR_LEVEL, SupportedOptions.DEFAULT_OBFUSCATION_ENV, SupportedOptions.DEPENDENCY_TARGETS_FILE, - SupportedOptions.MAPPING_TYPES + SupportedOptions.MAPPING_TYPES, + SupportedOptions.PLUGIN_VERSION ); options.addAll( ObfuscationServices.getInstance().getSupportedOptions() diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index f15aa07d..d0f14737 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -455,7 +455,7 @@ public class AccessorInfo extends SpecialMethodInfo { public String toString() { String typeString = this.type != null ? this.type.toString() : "UNPARSED_ACCESSOR"; return String.format("%s->@%s[%s]::%s%s", this.mixin, Bytecode.getSimpleName(this.annotation), typeString, - this.method.name, this.method.desc); + this.methodName, this.method.desc); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 23e962ff..3f0da671 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -33,8 +33,8 @@ import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.Map.Entry; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import javax.tools.Diagnostic.Kind; + import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; @@ -67,8 +67,11 @@ import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.asm.ASM; import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.asm.MethodNodeEx; +import org.spongepowered.asm.util.logging.MessageRouter; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableSet; /** * Contructs information about an injection from an {@link Inject} annotation @@ -637,7 +640,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } static String describeInjector(IMixinContext mixin, AnnotationNode annotation, MethodNode method) { - return String.format("%s->@%s::%s%s", mixin.toString(), Bytecode.getSimpleName(annotation), method.name, method.desc); + return String.format("%s->@%s::%s%s", mixin.toString(), Bytecode.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc); } /** @@ -662,7 +665,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } return sb.toString(); } - + /** * Register an injector info class. The supplied class must be decorated * with an {@link AnnotationType} annotation for registration purposes. @@ -675,8 +678,6 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC throw new IllegalArgumentException("Injection info class " + type + " is not annotated with @AnnotationType"); } - Logger logger = LogManager.getLogger("mixin"); - InjectorEntry entry; try { entry = new InjectorEntry(annotationType.value(), type); @@ -684,11 +685,12 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC throw new MixinError("InjectionInfo class " + type.getName() + " is missing a valid constructor"); } InjectorEntry existing = InjectionInfo.registry.get(entry.simpleName); - if (existing != null && !existing.type.equals(type)) { - logger.debug("WARNING: Overriding InjectionInfo for {} with {} (previously {})", annotationType.value().getSimpleName(), type.getName(), - existing.type.getName()); + if (existing != null) { // && !existing.type.equals(type)) { + MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding InjectionInfo for @%s with %s (previously %s)", + annotationType.value().getSimpleName(), type.getName(), existing.type.getName())); } else { - logger.debug("Registering new injector for {} with {}", annotationType.value().getSimpleName(), type.getName()); + MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new injector for @%s with %s", + annotationType.value().getSimpleName(), type.getName())); } InjectionInfo.registry.put(entry.simpleName, entry); @@ -699,5 +701,9 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } InjectionInfo.registeredAnnotations = annotations.toArray(InjectionInfo.registeredAnnotations); } + + public static Set> getRegisteredAnnotations() { + return ImmutableSet.>copyOf(InjectionInfo.registeredAnnotations); + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java index 924d7651..b745dde7 100644 --- a/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java +++ b/src/main/java/org/spongepowered/asm/mixin/refmap/ReferenceMapper.java @@ -31,10 +31,11 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import javax.tools.Diagnostic.Kind; + import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; +import org.spongepowered.asm.util.logging.MessageRouter; import com.google.common.collect.Maps; import com.google.common.io.Closeables; @@ -252,7 +253,6 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { * @return new refmap or {@link #DEFAULT_MAPPER} if reading fails */ public static ReferenceMapper read(String resourcePath) { - Logger logger = LogManager.getLogger("mixin"); Reader reader = null; try { IMixinService service = MixinService.getService(); @@ -264,9 +264,11 @@ public final class ReferenceMapper implements IReferenceMapper, Serializable { return mapper; } } catch (JsonParseException ex) { - logger.error("Invalid REFMAP JSON in " + resourcePath + ": " + ex.getClass().getName() + " " + ex.getMessage()); + MessageRouter.getMessager().printMessage(Kind.ERROR, String.format("Invalid REFMAP JSON in %s: %s %s", + resourcePath, ex.getClass().getName(), ex.getMessage())); } catch (Exception ex) { - logger.error("Failed reading REFMAP JSON from " + resourcePath + ": " + ex.getClass().getName() + " " + ex.getMessage()); + MessageRouter.getMessager().printMessage(Kind.ERROR, String.format("Failed reading REFMAP JSON from %s: %s %s", + resourcePath, ex.getClass().getName(), ex.getMessage())); } finally { Closeables.closeQuietly(reader); } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java index 409a7e3a..2a91ad0c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -74,7 +74,7 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext { this.annotation = annotation; this.annotationType = this.annotation != null ? "@" + Bytecode.getSimpleName(this.annotation) : "Undecorated injector"; this.classNode = mixin.getTargetClassNode(); - this.methodName = method instanceof MethodNodeEx ? ((MethodNodeEx)this.method).getOriginalName() : method.name; + this.methodName = MethodNodeEx.getName(method); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/throwables/ClassMetadataNotFoundException.java b/src/main/java/org/spongepowered/asm/mixin/throwables/ClassMetadataNotFoundException.java new file mode 100644 index 00000000..c9eaf10a --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/throwables/ClassMetadataNotFoundException.java @@ -0,0 +1,65 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.throwables; + +import org.spongepowered.asm.mixin.transformer.ActivityStack; +import org.spongepowered.asm.mixin.transformer.ClassInfo; + +/** + * Since it's inconvenient to throw the (checked) {@link ClassNotFoundException} + * this exception can be selectively thrown when {@link ClassInfo#forName} + * returns null (indicating class couldn't be loaded or was not found) + * in situations where we actually care about it failing and want to throw + * something. + */ +public class ClassMetadataNotFoundException extends MixinException { + + private static final long serialVersionUID = 1L; + + public ClassMetadataNotFoundException(String message) { + super(message); + } + + public ClassMetadataNotFoundException(String message, ActivityStack context) { + super(message, context); + } + + public ClassMetadataNotFoundException(Throwable cause) { + super(cause); + } + + public ClassMetadataNotFoundException(Throwable cause, ActivityStack context) { + super(cause, context); + } + + public ClassMetadataNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public ClassMetadataNotFoundException(String message, Throwable cause, ActivityStack context) { + super(message, cause, context); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java index d6b333a3..283801b4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinClassGenerator.java @@ -82,7 +82,9 @@ public class MixinClassGenerator { boolean success = generator.generate(name, classNode); genTimer.end(); if (success) { - this.auditTrail.onGenerate(name, generator.getName()); + if (this.auditTrail != null) { + this.auditTrail.onGenerate(name, generator.getName()); + } this.extensions.export(environment, name.replace('.', '/'), false, classNode); return true; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index c7005e64..e87253e3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -44,6 +44,7 @@ import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; import org.spongepowered.asm.mixin.struct.MemberRef; +import org.spongepowered.asm.mixin.throwables.ClassMetadataNotFoundException; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; @@ -576,7 +577,7 @@ class MixinPreProcessorStandard { Activity fieldActivity = this.activities.begin("?"); for (Iterator iter = this.classNode.getFields().iterator(); iter.hasNext();) { FieldNode mixinField = iter.next(); - fieldActivity.next(String.format("%s:%s", mixinField.name, mixinField.desc)); + fieldActivity.next("%s:%s", mixinField.name, mixinField.desc); AnnotationNode shadow = Annotations.getVisible(mixinField, Shadow.class); boolean isShadow = shadow != null; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index f2e79c74..baf044df 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -60,6 +60,7 @@ import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.struct.MemberRef; import org.spongepowered.asm.mixin.struct.SourceMap.File; +import org.spongepowered.asm.mixin.throwables.ClassMetadataNotFoundException; import org.spongepowered.asm.mixin.transformer.ActivityStack.Activity; import org.spongepowered.asm.mixin.transformer.ClassInfo.Field; import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; @@ -444,7 +445,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { this.validateMethod(method); activity.next("Transform Descriptor"); this.transformDescriptor(method); - activity.next("Transform LVTs"); + activity.next("Transform LVT"); this.transformLVT(method); // Offset line numbers per the stratum @@ -532,13 +533,16 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { return; } + Activity localVarActivity = this.activities.begin("?"); for (LocalVariableNode local : method.localVariables) { if (local == null || local.desc == null) { continue; } + localVarActivity.next("var=%s", local.name); local.desc = this.transformSingleDescriptor(Type.getType(local.desc)); } + localVarActivity.end(); } /** @@ -906,6 +910,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { } private String transformSingleDescriptor(String desc, boolean isObject) { + Activity descriptorActivity = this.activities.begin("desc=%s", desc); String type = desc; while (type.startsWith("[") || type.startsWith("L")) { if (type.startsWith("[")) { @@ -915,27 +920,30 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { type = type.substring(1, type.indexOf(";")); isObject = true; } - if (!isObject) { + descriptorActivity.end(); return desc; } - String innerClassName = this.innerClasses.get(type); if (innerClassName != null) { + descriptorActivity.end(); return desc.replace(type, innerClassName); } - if (this.innerClasses.inverse().containsKey(type)) { + descriptorActivity.end(); return desc; } - ClassInfo typeInfo = ClassInfo.forName(type); - + if (typeInfo == null) { + throw new ClassMetadataNotFoundException(type.replace('/', '.')); + } if (!typeInfo.isMixin() || typeInfo.isLoadable()) { + descriptorActivity.end(); return desc; } - - return desc.replace(type, this.findRealType(typeInfo).toString()); + String realDesc = desc.replace(type, this.findRealType(typeInfo).toString()); + descriptorActivity.end(); + return realDesc; } private String transformMethodDescriptor(String desc) { @@ -1165,16 +1173,26 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * @param targetClass Target class */ void postApply(String transformedName, ClassNode targetClass) { + this.activities.clear(); + try { + Activity activity = this.activities.begin("Validating Injector Groups"); this.injectorGroups.validateAll(); + activity.next("Plugin Post-Application"); + this.mixin.postApply(transformedName, targetClass); + activity.end(); } catch (InjectionValidationException ex) { InjectorGroupInfo group = ex.getGroup(); throw new InjectionError( String.format("Critical injection failure: Callback group %s in %s failed injection check: %s", group, this.mixin, ex.getMessage())); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst transforming the mixin class:", ex, + this.activities); } - - this.mixin.postApply(transformedName, targetClass); } /** @@ -1206,20 +1224,38 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * injectors */ void prepareInjections() { - this.injectors.clear(); + this.activities.clear(); - for (MethodNode method : this.mergedMethods) { - InjectionInfo injectInfo = InjectionInfo.parse(this, method); - if (injectInfo == null) { - continue; + try { + this.injectors.clear(); + + Activity prepareActivity = this.activities.begin("?"); + for (MethodNode method : this.mergedMethods) { + prepareActivity.next("%s%s", method.name, method.desc); + Activity methodActivity = this.activities.begin("Parse"); + InjectionInfo injectInfo = InjectionInfo.parse(this, method); + if (injectInfo == null) { + continue; + } + + methodActivity.next("Validate"); + if (injectInfo.isValid()) { + methodActivity.next("Prepare"); + injectInfo.prepare(); + this.injectors.add(injectInfo); + } + + methodActivity.next("Undecorate"); + method.visibleAnnotations.remove(injectInfo.getAnnotation()); + methodActivity.end(); } - - if (injectInfo.isValid()) { - injectInfo.prepare(); - this.injectors.add(injectInfo); - } - - method.visibleAnnotations.remove(injectInfo.getAnnotation()); + prepareActivity.end(); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst transforming the mixin class:", ex, + this.activities); } } @@ -1227,15 +1263,32 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * Apply injectors discovered in the {@link #prepareInjections()} pass */ void applyInjections() { - for (InjectionInfo injectInfo : this.injectors) { - injectInfo.inject(); - } + this.activities.clear(); - for (InjectionInfo injectInfo : this.injectors) { - injectInfo.postInject(); + try { + Activity applyActivity = this.activities.begin("Inject"); + Activity injectActivity = this.activities.begin("?"); + for (InjectionInfo injectInfo : this.injectors) { + injectActivity.next(injectInfo.toString()); + injectInfo.inject(); + } + + applyActivity.next("PostInject"); + Activity postInjectActivity = this.activities.begin("?"); + for (InjectionInfo injectInfo : this.injectors) { + postInjectActivity.next(injectInfo.toString()); + injectInfo.postInject(); + } + + applyActivity.end(); + this.injectors.clear(); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst transforming the mixin class:", ex, + this.activities); } - - this.injectors.clear(); } /** @@ -1243,16 +1296,32 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { * method bodies */ List generateAccessors() { - for (AccessorInfo accessor : this.accessors) { - accessor.locate(); - } - + this.activities.clear(); List methods = new ArrayList(); - for (AccessorInfo accessor : this.accessors) { - MethodNode generated = accessor.generate(); - this.getTarget().addMixinMethod(generated); - methods.add(generated); + try { + Activity accessorActivity = this.activities.begin("Locate"); + Activity locateActivity = this.activities.begin("?"); + for (AccessorInfo accessor : this.accessors) { + locateActivity.next(accessor.toString()); + accessor.locate(); + } + + accessorActivity.next("Generate"); + Activity generateActivity = this.activities.begin("?"); + for (AccessorInfo accessor : this.accessors) { + generateActivity.next(accessor.toString()); + MethodNode generated = accessor.generate(); + this.getTarget().addMixinMethod(generated); + methods.add(generated); + } + accessorActivity.end(); + } catch (InvalidMixinException ex) { + ex.prepend(this.activities); + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, "Unexpecteded " + ex.getClass().getSimpleName() + " whilst transforming the mixin class:", ex, + this.activities); } return methods; diff --git a/src/main/java/org/spongepowered/asm/service/MixinService.java b/src/main/java/org/spongepowered/asm/service/MixinService.java index 883094d4..dfc5d7c1 100644 --- a/src/main/java/org/spongepowered/asm/service/MixinService.java +++ b/src/main/java/org/spongepowered/asm/service/MixinService.java @@ -130,7 +130,8 @@ public final class MixinService { private IMixinService initService() { this.serviceLoader = ServiceLoader.load(IMixinService.class, this.getClass().getClassLoader()); Iterator iter = this.serviceLoader.iterator(); - List rejectedServices = new ArrayList(); + List badServices = new ArrayList(); + int brokenServiceCount = 0; while (iter.hasNext()) { try { IMixinService service = iter.next(); @@ -140,14 +141,22 @@ public final class MixinService { if (service.isValid()) { return service; } - rejectedServices.add(service.getName()); - } catch (ServiceConfigurationError serviceError) { -// serviceError.printStackTrace(); + MixinService.logger.debug("MixinService [{}] is not valid", service.getName()); + badServices.add(String.format("INVALID[%s]", service.getName())); + } catch (ServiceConfigurationError sce) { +// sce.printStackTrace(); + brokenServiceCount++; } catch (Throwable th) { + String faultingClassName = th.getStackTrace()[0].getClassName(); + MixinService.logger.debug("MixinService [{}] failed initialisation: {}", faultingClassName, th.getMessage()); + int pos = faultingClassName.lastIndexOf('.'); + badServices.add(String.format("ERROR[%s]", pos < 0 ? faultingClassName : faultingClassName.substring(pos + 1))); // th.printStackTrace(); } } - throw new ServiceNotAvailableError("No mixin host service is available. Rejected services: " + Joiner.on(", ").join(rejectedServices)); + + String brokenServiceNote = brokenServiceCount == 0 ? "" : " and " + brokenServiceCount + " other invalid services."; + throw new ServiceNotAvailableError("No mixin host service is available. Services: " + Joiner.on(", ").join(badServices) + brokenServiceNote); } /** diff --git a/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java b/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java index f8869159..78a247f0 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java +++ b/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java @@ -59,4 +59,8 @@ public class MethodNodeEx extends MethodNode { return this.owner; } + public static String getName(MethodNode method) { + return method instanceof MethodNodeEx ? ((MethodNodeEx)method).getOriginalName() : method.name; + } + } diff --git a/src/main/java/org/spongepowered/asm/util/logging/MessageRouter.java b/src/main/java/org/spongepowered/asm/util/logging/MessageRouter.java new file mode 100644 index 00000000..70d18538 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/logging/MessageRouter.java @@ -0,0 +1,165 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.logging; + +import javax.annotation.processing.Messager; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.tools.Diagnostic.Kind; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * Logging router for objects which may need to log messages during standard + * runtime or during Annotation Processor sessions. Provides a single interface + * to obtain a {@link Messager} to write log entries in either environment. + */ +public final class MessageRouter { + + /** + * Implementation of Messager which writes to a logger + */ + static class LoggingMessager implements Messager { + + /** + * Logger + */ + private static final Logger logger = LogManager.getLogger("mixin"); + + @Override + public void printMessage(Kind kind, CharSequence msg) { + LoggingMessager.logger.log(LoggingMessager.messageKindToLoggingLevel(kind), msg); + } + + @Override + public void printMessage(Kind kind, CharSequence msg, Element e) { + LoggingMessager.logger.log(LoggingMessager.messageKindToLoggingLevel(kind), msg); + } + + @Override + public void printMessage(Kind kind, CharSequence msg, Element e, AnnotationMirror a) { + LoggingMessager.logger.log(LoggingMessager.messageKindToLoggingLevel(kind), msg); + } + + @Override + public void printMessage(Kind kind, CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v) { + LoggingMessager.logger.log(LoggingMessager.messageKindToLoggingLevel(kind), msg); + } + + private static Level messageKindToLoggingLevel(Kind kind) { + switch (kind) { + case ERROR: + return Level.ERROR; + case WARNING: + case MANDATORY_WARNING: + return Level.WARN; + case NOTE: + return Level.INFO; + case OTHER: + default: + return Level.DEBUG; + } + } + + } + + /** + * Debug-level messages are expressed as {@link Kind#OTHER} but we don't + * want to emit them. This wrapper just intercepts debug messages so they + * don't spam the compiler output. + */ + static class DebugInterceptingMessager implements Messager { + + private final Messager wrapped; + + DebugInterceptingMessager(Messager messager) { + this.wrapped = messager; + } + + @Override + public void printMessage(Kind kind, CharSequence msg) { + if (kind != Kind.OTHER) { + this.wrapped.printMessage(kind, msg); + } + } + + @Override + public void printMessage(Kind kind, CharSequence msg, Element e) { + if (kind != Kind.OTHER) { + this.wrapped.printMessage(kind, msg, e); + } + } + + @Override + public void printMessage(Kind kind, CharSequence msg, Element e, AnnotationMirror a) { + if (kind != Kind.OTHER) { + this.wrapped.printMessage(kind, msg, e, a); + } + } + + @Override + public void printMessage(Kind kind, CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v) { + if (kind != Kind.OTHER) { + this.wrapped.printMessage(kind, msg, e, a, v); + } + } + + } + + /** + * Current message sink + */ + private static Messager messager; + + /** + * Utility class + */ + private MessageRouter() {} + + /** + * Get the current messager. If no messager is available the returned + * Messager sinks messages to a log4j2 logger + */ + public static Messager getMessager() { + if (MessageRouter.messager == null) { + MessageRouter.messager = new LoggingMessager(); + } + return MessageRouter.messager; + } + + /** + * Set the messager to use, this should only be called by the AP + * + * @param messager new messager to sink messages, can be null to revert to + * log4j2 logging + */ + public static void setMessager(Messager messager) { + MessageRouter.messager = messager == null ? null : new DebugInterceptingMessager(messager); + } + +}