From 5c995b21de24c94569bd891fbc11682e273e3093 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 14 Oct 2019 17:44:35 +0100 Subject: [PATCH 01/16] Clean CallbackInfo from locals and fix CallbackInjector local args logic Fixes #337 --- .../mixin/injection/callback/CallbackInjector.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index 53a09727..72c24889 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -170,7 +170,7 @@ public class CallbackInjector extends Injector { this.node = node; this.locals = locals; this.localTypes = locals != null ? new Type[locals.length] : null; - this.frameSize = Bytecode.getFirstNonArgLocalIndex(target.arguments, !CallbackInjector.this.isStatic()); + this.frameSize = Bytecode.getFirstNonArgLocalIndex(target.arguments, !target.isStatic); List argNames = null; if (locals != null) { @@ -190,7 +190,8 @@ public class CallbackInjector extends Injector { } // Calc number of args for the handler method, additional 1 is to ignore the CallbackInfo arg - this.extraArgs = Math.max(0, Bytecode.getFirstNonArgLocalIndex(this.handler) - (this.frameSize + 1)); + Type[] handlerArgs = Type.getArgumentTypes(this.handler.desc); + this.extraArgs = Math.max(0, handlerArgs.length - target.arguments.length - 1); this.argNames = argNames != null ? argNames.toArray(new String[argNames.size()]) : null; this.canCaptureLocals = captureLocals && locals != null && locals.length > this.frameSize; this.isAtReturn = this.node.getCurrentTarget() instanceof InsnNode && this.isValueReturnOpcode(this.node.getCurrentTarget().getOpcode()); @@ -426,6 +427,11 @@ public class CallbackInjector extends Injector { if (this.localCapture.isCaptureLocals() || this.localCapture.isPrintLocals()) { locals = Locals.getLocalsAt(this.classNode, target.method, node.getCurrentTarget()); + for (int j = 0; j < locals.length; j++) { + if (locals[j] != null && locals[j].desc != null && locals[j].desc.startsWith("Lorg/spongepowered/asm/mixin/injection/callback/")) { + locals[j] = null; + } + } } this.inject(new Callback(this.methodNode, target, node, locals, this.localCapture.isCaptureLocals())); @@ -524,7 +530,7 @@ public class CallbackInjector extends Injector { private String generateBadLVTMessage(final Callback callback) { int position = callback.target.indexOf(callback.node); List expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1); - List found = CallbackInjector.summariseLocals(callback.getDescriptorWithAllLocals(), callback.frameSize); + List found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0)); return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s", callback.target, position, this, expected, found); } From 4120c80a8a0ed380431e1ead938ae364089085d3 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 14 Oct 2019 17:45:40 +0100 Subject: [PATCH 02/16] Allow Coerce annotation to coerce args to interfaces too. Update README --- README.MD | 6 ++++++ .../spongepowered/asm/mixin/injection/code/Injector.java | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/README.MD b/README.MD index 73435e67..a9b3ea41 100644 --- a/README.MD +++ b/README.MD @@ -97,10 +97,16 @@ plugin developed by [DemonWav](https://github.com/demonwav).
  • Fixed issue in LVT generator folded in from FabricMC
  • Fail-fast when a final method is accidentally hidden by a mixin
  • +
  • Fix the appearance of stray CallbackInfo instances in + local capture injector LVTs
  • Apache Commons-IO Dependency removed
  • Renamed shaded ASM removed
  • +
  • Improved resolution of local variables for local variable capture + injections
  • +
  • @Coerce on callback injectors and redirects can now + resolve super interfaces including mixed-in interfaces
  • diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index f8f69cf1..2b4c3257 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -55,6 +55,7 @@ import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.transformer.ClassInfo; +import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal; import org.spongepowered.asm.mixin.transformer.ClassInfo.TypeLookup; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; @@ -421,7 +422,7 @@ public abstract class Injector { * @return true if from can be coerced to to */ private static boolean canCoerce(ClassInfo from, ClassInfo to) { - return from != null && to != null && (to == from || to.hasSuperClass(from)); + return from != null && to != null && (to == from || to.hasSuperClass(from, Traversal.NONE, true)); } } From 7567dec1d8e9734518f3b4a487f17392b2b1d792 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Tue, 15 Oct 2019 15:20:22 +0100 Subject: [PATCH 03/16] Continue applying mixins if an optional mixin is invalid, fixes #313 --- .../transformer/MixinApplicatorStandard.java | 45 +++++++++++++++---- .../asm/mixin/transformer/MixinInfo.java | 7 +++ .../MixinPreProcessorStandard.java | 2 +- .../asm/mixin/transformer/MixinProcessor.java | 17 +++---- .../mixin/transformer/MixinTargetContext.java | 7 +++ .../mixin/transformer/TargetClassContext.java | 16 +++++++ .../spongepowered/asm/util/PrettyPrinter.java | 22 +++++++-- 7 files changed, 92 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java index c1f8f540..4feb0847 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinApplicatorStandard.java @@ -271,9 +271,18 @@ class MixinApplicatorStandard { final void apply(SortedSet mixins) { List mixinContexts = new ArrayList(); - for (MixinInfo mixin : mixins) { - this.logger.log(mixin.getLoggingLevel(), "Mixing {} from {} into {}", mixin.getName(), mixin.getParent(), this.targetName); - mixinContexts.add(mixin.createContextFor(this.context)); + for (Iterator iter = mixins.iterator(); iter.hasNext();) { + MixinInfo mixin = iter.next(); + try { + this.logger.log(mixin.getLoggingLevel(), "Mixing {} from {} into {}", mixin.getName(), mixin.getParent(), this.targetName); + mixinContexts.add(mixin.createContextFor(this.context)); + } catch (InvalidMixinException ex) { + if (mixin.isRequired()) { + throw ex; + } + this.context.addSuppressed(ex); + iter.remove(); // Do not process this mixin further + } } MixinTargetContext current = null; @@ -292,9 +301,18 @@ class MixinApplicatorStandard { activity.next("%s Applicator Phase", pass); Section timer = this.profiler.begin("pass", pass.name().toLowerCase(Locale.ROOT)); Activity applyActivity = this.activities.begin("Mixin"); - for (MixinTargetContext context : mixinContexts) { - applyActivity.next(context.toString()); - this.applyMixin(current = context, pass); + for (Iterator iter = mixinContexts.iterator(); iter.hasNext();) { + current = iter.next(); + applyActivity.next(current.toString()); + try { + this.applyMixin(current, pass); + } catch (InvalidMixinException ex) { + if (current.isRequired()) { + throw ex; + } + this.context.addSuppressed(ex); + iter.remove(); // Do not process this mixin further + } } applyActivity.end(); timer.end(); @@ -302,9 +320,18 @@ class MixinApplicatorStandard { activity.next("PostApply Phase"); Activity postApplyActivity = this.activities.begin("Mixin"); - for (MixinTargetContext context : mixinContexts) { - postApplyActivity.next(context.toString()); - (current = context).postApply(this.targetName, this.targetClass); + for (Iterator iter = mixinContexts.iterator(); iter.hasNext();) { + current = iter.next(); + postApplyActivity.next(current.toString()); + try { + current.postApply(this.targetName, this.targetClass); + } catch (InvalidMixinException ex) { + if (current.isRequired()) { + throw ex; + } + this.context.addSuppressed(ex); + iter.remove(); + } } activity.end(); } catch (InvalidMixinException ex) { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index d1baa24d..eac3e63b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -1071,6 +1071,13 @@ class MixinInfo implements Comparable, IMixinInfo { return this.type.isLoadable(); } + /** + * True if the parent mixin config is marked as required + */ + public boolean isRequired() { + return this.parent.isRequired(); + } + /** * Get the logging level for this mixin */ diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java index 00bbe66b..a10a06ea 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -603,7 +603,7 @@ class MixinPreProcessorStandard { target = context.findRemappedField(mixinField); if (target == null) { // If this field is a shadow field but is NOT found in the target class, that's bad, mmkay - throw new InvalidMixinException(this.mixin, String.format("Shadow field %s was not located in the target class %s. %s%s", + throw new InvalidMixinException(this.mixin, String.format("@Shadow field %s was not located in the target class %s. %s%s", mixinField.name, context.getTarget(), context.getReferenceMapper().getStatus(), MixinPreProcessorStandard.getDynamicInfo(mixinField))); } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 9367d287..50e8474f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -539,7 +539,7 @@ public class MixinProcessor { Section timer = this.profiler.begin("preapply"); this.extensions.preApply(context); timer = timer.next("apply"); - this.apply(context); + context.applyMixins(); timer = timer.next("postapply"); boolean export = false; try { @@ -554,15 +554,9 @@ public class MixinProcessor { if (export) { this.extensions.export(this.currentEnvironment, context.getClassName(), context.isExportForced(), context.getClassNode()); } - } - - /** - * Apply the mixins to the target class - * - * @param context Target class context - */ - private void apply(TargetClassContext context) { - context.applyMixins(); + for (InvalidMixinException suppressed : context.getSuppressedExceptions()) { + this.handleMixinApplyError(context.getClassName(), suppressed, environment); + } } private void handleMixinPrepareError(MixinConfig config, InvalidMixinException ex, MixinEnvironment environment) throws MixinPrepareError { @@ -589,6 +583,7 @@ public class MixinProcessor { if (environment.getOption(Option.DEBUG_VERBOSE)) { new PrettyPrinter() + .wrapTo(160) .add("Invalid Mixin").centre() .hr('-') .kvWidth(10) @@ -602,7 +597,7 @@ public class MixinProcessor { .addWrapped(" %s", ex.getMessage()) .hr('-') .add(ex, 8) - .trace(action.logLevel); + .log(action.logLevel); } for (IMixinErrorHandler handler : this.getErrorHandlers(mixin.getPhase())) { 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 48377cd8..f2e79c74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -1048,6 +1048,13 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { MixinInfo getInfo() { return this.mixin; } + + /** + * True if the parent mixin config is marked as required + */ + boolean isRequired() { + return this.mixin.isRequired(); + } /** * Get the mixin priority diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java index bee05de9..59667d63 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/TargetClassContext.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.mixin.transformer; +import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -45,6 +46,7 @@ import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.struct.SourceMap; import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext; +import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.ClassSignature; @@ -116,6 +118,12 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte * target class. */ private final Set mixinMethods = new HashSet(); + + /** + * Exceptions which were suppressed during mixin application because they + * were raised by an optional mixin + */ + private final List suppressedExceptions = new ArrayList(); /** * True once mixins have been applied to this class @@ -383,4 +391,12 @@ final class TargetClassContext extends ClassContext implements ITargetClassConte } } + void addSuppressed(InvalidMixinException ex) { + this.suppressedExceptions.add(ex); + } + + List getSuppressedExceptions() { + return this.suppressedExceptions; + } + } diff --git a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java index 6f95d544..37f7dc6b 100644 --- a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java +++ b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java @@ -378,6 +378,11 @@ public class PrettyPrinter { } + /** + * Minimum allowed width + */ + private static final int MIN_WIDTH = 40; + /** * Horizontal rule */ @@ -421,7 +426,8 @@ public class PrettyPrinter { } public PrettyPrinter(int width) { - this.width = width; + this.width = Math.max(PrettyPrinter.MIN_WIDTH, width); + this.wrapWidth = this.width - 20; } /** @@ -684,7 +690,7 @@ public class PrettyPrinter { */ public PrettyPrinter add(Throwable th, int indent) { while (th != null) { - this.add("%s: %s", th.getClass().getName(), th.getMessage()); + this.addWrapped(" %s: %s", th.getClass().getName(), th.getMessage()); this.add(th.getStackTrace(), indent); th = th.getCause(); } @@ -783,7 +789,7 @@ public class PrettyPrinter { try { for (String wrappedLine : this.getWrapped(width, line, indent)) { - this.addLine(wrappedLine); + this.add(wrappedLine); } } catch (Exception ex) { this.add(line); @@ -1099,6 +1105,16 @@ public class PrettyPrinter { return this.log(logger, Level.INFO); } + /** + * Write this printer to the specified logger at {@link Level#INFO} + * + * @param level log level + * @return fluent interface + */ + public PrettyPrinter log(Level level) { + return this.log(LogManager.getLogger(PrettyPrinter.getDefaultLoggerName()), level); + } + /** * Write this printer to the specified logger * From 22909dcfa214927f9e6042d0992593f513a9a1af Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 16 Oct 2019 16:31:10 +0100 Subject: [PATCH 04/16] Detect & report transformer reentrance during config prepare, fixes #333 --- .../asm/mixin/transformer/MixinConfig.java | 41 +++- .../asm/mixin/transformer/MixinInfo.java | 218 +++++++++++++----- .../asm/mixin/transformer/MixinProcessor.java | 19 +- .../throwables/ReEntrantTransformerError.java | 46 ++++ 4 files changed, 255 insertions(+), 69 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/mixin/transformer/throwables/ReEntrantTransformerError.java diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index 14fb753e..50d128fc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -159,6 +159,11 @@ final class MixinConfig implements Comparable, IMixinConfig { */ private final transient Set unhandledTargets = new HashSet(); + /** + * Mixins which have been parsed but not yet prepared + */ + private final transient List pendingMixins = new ArrayList(); + /** * All mixins loaded by this config */ @@ -688,7 +693,7 @@ final class MixinConfig implements Comparable, IMixinConfig { } } - private void prepareMixins(List mixinClasses, boolean suppressPlugin) { + private void prepareMixins(List mixinClasses, boolean ignorePlugin) { if (mixinClasses == null) { return; } @@ -703,9 +708,25 @@ final class MixinConfig implements Comparable, IMixinConfig { MixinInfo mixin = null; try { - mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, suppressPlugin); + this.pendingMixins.add(mixin = new MixinInfo(this.service, this, mixinClass, this.plugin, ignorePlugin)); + MixinConfig.globalMixinList.add(fqMixinClass); + } catch (InvalidMixinException ex) { + if (this.required) { + throw ex; + } + this.logger.error(ex.getMessage(), ex); + } catch (Exception ex) { + if (this.required) { + throw new InvalidMixinException(mixin, "Error initialising mixin " + mixin + " - " + ex.getClass() + ": " + ex.getMessage(), ex); + } + this.logger.error(ex.getMessage(), ex); + } + } + + for (MixinInfo mixin : this.pendingMixins) { + try { + mixin.parseTargets(); if (mixin.getTargetClasses().size() > 0) { - MixinConfig.globalMixinList.add(fqMixinClass); for (String targetClass : mixin.getTargetClasses()) { String targetClassName = targetClass.replace('/', '.'); this.mixinsFor(targetClassName).add(mixin); @@ -728,6 +749,8 @@ final class MixinConfig implements Comparable, IMixinConfig { this.logger.error(ex.getMessage(), ex); } } + + this.pendingMixins.clear(); } void postApply(String transformedName, ClassNode targetClass) { @@ -964,6 +987,18 @@ final class MixinConfig implements Comparable, IMixinConfig { return this.mixinMapping.containsKey(targetClass); } + boolean hasPendingMixinsFor(String targetClass) { + if (this.packageMatch(targetClass)) { + return false; + } + for (MixinInfo pendingMixin : this.pendingMixins) { + if (pendingMixin.hasDeclaredTarget(targetClass)) { + return true; + } + } + return false; + } + /** * Get mixins for the specified target class * diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index eac3e63b..1ba207f1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -39,6 +39,7 @@ import org.apache.logging.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; @@ -71,8 +72,8 @@ import org.spongepowered.asm.util.asm.ASM; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; -import com.google.common.base.Function; import com.google.common.base.Functions; +import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** @@ -670,6 +671,37 @@ class MixinInfo implements Comparable, IMixinInfo { } + /** + * Handle for a declared target on a mixin. + */ + static final class DeclaredTarget { + + final String name; + + final boolean isPrivate; + + private DeclaredTarget(String name, boolean isPrivate) { + this.name = name; + this.isPrivate = isPrivate; + } + + @Override + public String toString() { + return this.name; + } + + static DeclaredTarget of(Object target, MixinInfo info) { + if (target instanceof String) { + String remappedName = info.remapClassName((String)target); + return remappedName != null ? new DeclaredTarget(remappedName, true) : null; + } else if (target instanceof Type) { + return new DeclaredTarget(((Type)target).getClassName(), false); + } + return null; + } + + } + /** * Mixin service */ @@ -718,13 +750,19 @@ class MixinInfo implements Comparable, IMixinInfo { /** * Mixin targets, read from the {@link Mixin} annotation on the mixin class + * but not yet parsed in the current environment */ - private final List targetClasses; + private final transient List declaredTargets; + + /** + * Mixin targets, read from the {@link Mixin} annotation on the mixin class + */ + private final transient List targetClasses = new ArrayList(); /** * Names of target classes */ - private final List targetClassNames; + private final List targetClassNames = new ArrayList(); /** * Intrinsic order (for sorting mixins with identical priority) @@ -777,10 +815,10 @@ class MixinInfo implements Comparable, IMixinInfo { * @param parent configuration which owns this mixin, the parent * @param name name of this mixin (class name stub) * @param plugin mixin config companion plugin handle - * @param suppressPlugin true to suppress the plugin from filtering targets - * of this mixin + * @param ignorePlugin true to prevent the plugin from filtering targets of + * this mixin */ - MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean suppressPlugin) { + MixinInfo(IMixinService service, MixinConfig parent, String name, PluginHandle plugin, boolean ignorePlugin) { this.service = service; this.parent = parent; this.name = name; @@ -812,8 +850,22 @@ class MixinInfo implements Comparable, IMixinInfo { try { this.priority = this.readPriority(this.pendingState.getClassNode()); this.virtual = this.readPseudo(this.pendingState.getValidationClassNode()); - this.targetClasses = this.readTargetClasses(this.pendingState.getValidationClassNode(), suppressPlugin); - this.targetClassNames = Collections.unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction())); + this.declaredTargets = this.readDeclaredTargets(this.pendingState.getValidationClassNode(), ignorePlugin); + } catch (InvalidMixinException ex) { + throw ex; + } catch (Exception ex) { + throw new InvalidMixinException(this, ex); + } + } + + /** + * Parse the declared targets from the annotation into ClassInfo instances + * and perform initial validation of each target + */ + void parseTargets() { + try { + this.targetClasses.addAll(this.readTargetClasses(this.declaredTargets)); + this.targetClassNames.addAll(Lists.transform(this.targetClasses, Functions.toStringFunction())); } catch (InvalidMixinException ex) { throw ex; } catch (Exception ex) { @@ -838,15 +890,15 @@ class MixinInfo implements Comparable, IMixinInfo { } /** - * Read the target class names from the {@link Mixin} annotation + * Read the declared target class names from the {@link Mixin} annotation * * @param classNode mixin classnode - * @param suppressPlugin true to suppress plugin filtering targets + * @param ignorePlugin true to suppress plugin filtering targets * @return target class list read from classNode */ - protected List readTargetClasses(MixinClassNode classNode, boolean suppressPlugin) { + protected List readDeclaredTargets(MixinClassNode classNode, boolean ignorePlugin) { if (classNode == null) { - return Collections.emptyList(); + return Collections.emptyList(); } AnnotationNode mixin = Annotations.getInvisible(classNode, Mixin.class); @@ -854,75 +906,97 @@ class MixinInfo implements Comparable, IMixinInfo { throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className)); } - List targets = new ArrayList(); - List publicTargets = Annotations.getValue(mixin, "value"); - List privateTargets = Annotations.getValue(mixin, "targets"); - - if (publicTargets != null) { - this.readTargets(targets, Lists.transform(publicTargets, new Function() { - @Override - public String apply(org.objectweb.asm.Type input) { - return input.getClassName(); - } - }), suppressPlugin, false); - } - - if (privateTargets != null) { - this.readTargets(targets, Lists.transform(privateTargets, new Function() { - @Override - public String apply(String input) { - return MixinInfo.this.getParent().remapClassName(MixinInfo.this.getClassRef(), input); - } - }), suppressPlugin, true); - } - - return targets; - } - - /** - * Reads a target list into the outTargets list - */ - private void readTargets(Collection outTargets, Collection inTargets, boolean suppressPlugin, boolean checkPublic) { - for (String targetRef : inTargets) { - String targetName = targetRef.replace('/', '.'); - if (MixinInfo.classLoaderUtil.isClassLoaded(targetName) && !this.isReloading()) { - String message = String.format("Critical problem: %s target %s was loaded too early.", this, targetName); + List declaredTargets = new ArrayList(); + for (Object target : this.readTargets(mixin)) { + DeclaredTarget declaredTarget = DeclaredTarget.of(target, this); + if (declaredTarget == null) { + continue; + } + if (MixinInfo.classLoaderUtil.isClassLoaded(declaredTarget.name) && !this.isReloading()) { + String message = String.format("Critical problem: %s target %s was loaded too early.", this, declaredTarget.name); if (this.parent.isRequired()) { - throw new MixinTargetAlreadyLoadedException(this, message, targetName); + throw new MixinTargetAlreadyLoadedException(this, message, declaredTarget.name); } this.logger.error(message); } - if (this.shouldApplyMixin(suppressPlugin, targetName)) { - ClassInfo targetInfo = this.getTarget(targetName, checkPublic); - if (targetInfo != null && !outTargets.contains(targetInfo)) { - outTargets.add(targetInfo); - targetInfo.addMixin(this); - } + if (this.shouldApplyMixin(ignorePlugin, declaredTarget.name)) { + declaredTargets.add(declaredTarget); } } + return declaredTargets; } - private boolean shouldApplyMixin(boolean suppressPlugin, String targetName) { + /** + * Combine the public and private mixin targets from the supplied annotation + * and return them as an interable collection + * + * @param mixin mixin annotation + * @return target list + */ + private Iterable readTargets(AnnotationNode mixin) { + Iterable publicTargets = Annotations.getValue(mixin, "value"); + Iterable privateTargets = Annotations.getValue(mixin, "targets"); + if (publicTargets == null && privateTargets == null) { + return Collections.emptyList(); + } + if (publicTargets == null) { + return privateTargets; + } + return privateTargets == null ? publicTargets : Iterables.concat(publicTargets, privateTargets); + } + + /** + * Check whether this mixin should apply to the specified taret + * + * @param ignorePlugin true to ignore the config plugin + * @param targetName target class name + * @return true if the mixin should be a pplied + */ + private boolean shouldApplyMixin(boolean ignorePlugin, String targetName) { Section pluginTimer = this.profiler.begin("plugin"); - boolean result = suppressPlugin || this.plugin.shouldApplyMixin(targetName, this.className); + boolean result = ignorePlugin || this.plugin.shouldApplyMixin(targetName, this.className); pluginTimer.end(); return result; } - private ClassInfo getTarget(String targetName, boolean checkPublic) throws InvalidMixinException { - ClassInfo targetInfo = ClassInfo.forName(targetName); + /** + * Read and parse target classes from the supplied class node + * + * @param classNode class node to parse + * @param ignorePlugin true to ignore the config plugin when deciding + * whether to apply declared targets + * @return new list of target classes + */ + List readTargetClasses(MixinClassNode classNode, boolean ignorePlugin) { + return this.readTargetClasses(this.readDeclaredTargets(classNode, ignorePlugin)); + } + + private List readTargetClasses(List declaredTargets) throws InvalidMixinException { + List targetClasses = new ArrayList(); + for (DeclaredTarget target : declaredTargets) { + ClassInfo targetClass = this.getTargetClass(target); + if (targetClass != null) { + targetClasses.add(targetClass); + targetClass.addMixin(this); + } + } + return targetClasses; + } + + private ClassInfo getTargetClass(DeclaredTarget target) throws InvalidMixinException { + ClassInfo targetInfo = ClassInfo.forName(target.name); if (targetInfo == null) { if (this.isVirtual()) { - this.logger.debug("Skipping virtual target {} for {}", targetName, this); + this.logger.debug("Skipping virtual target {} for {}", target.name, this); } else { - this.handleTargetError(String.format("@Mixin target %s was not found %s", targetName, this)); + this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this)); } return null; } - this.type.validateTarget(targetName, targetInfo); - if (checkPublic && targetInfo.isPublic() && !this.isVirtual()) { - this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", targetName, this)); + this.type.validateTarget(target.name, targetInfo); + if (target.isPrivate && targetInfo.isPublic() && !this.isVirtual()) { + this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this)); } return targetInfo; } @@ -962,6 +1036,19 @@ class MixinInfo implements Comparable, IMixinInfo { private boolean isReloading() { return this.pendingState instanceof Reloaded; } + + String remapClassName(String className) { + return this.parent.remapClassName(this.getClassRef(), className); + } + + public boolean hasDeclaredTarget(String targetClass) { + for (DeclaredTarget declaredTarget : this.declaredTargets) { + if (targetClass.equals(declaredTarget.name)) { + return true; + } + } + return false; + } /** * Current state, either the validated state or the uninitialised state if @@ -1101,12 +1188,19 @@ class MixinInfo implements Comparable, IMixinInfo { return this.getState().createClassNode(flags); } + /** + * Get the target class names as declared for this mixin + */ + List getDeclaredTargetClasses() { + return Collections.unmodifiableList(Lists.transform(this.declaredTargets, Functions.toStringFunction())); + } + /** * Get the target class names for this mixin */ @Override public List getTargetClasses() { - return this.targetClassNames; + return Collections.unmodifiableList(this.targetClassNames); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 50e8474f..66cfb19b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -53,6 +53,7 @@ import org.spongepowered.asm.mixin.transformer.ext.extensions.ExtensionClassExpo import org.spongepowered.asm.mixin.transformer.meta.MixinMerged; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; +import org.spongepowered.asm.mixin.transformer.throwables.ReEntrantTransformerError; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.PrettyPrinter; @@ -282,7 +283,15 @@ public class MixinProcessor { boolean locked = this.lock.push().check(); Section mixinTimer = this.profiler.begin("mixin"); - if (!locked) { + if (locked) { + for (MixinConfig config : this.pendingConfigs) { + if (config.hasPendingMixinsFor(name)) { + ReEntrantTransformerError error = new ReEntrantTransformerError("Re-entrance error."); + MixinProcessor.logger.warn("Re-entrance detected during prepare phase, this will cause serious problems.", error); + throw error; + } + } + } else { try { this.checkSelect(environment); } catch (Exception ex) { @@ -321,15 +330,16 @@ public class MixinProcessor { mixins.addAll(config.getMixinsFor(name)); } } - + if (invalidRef) { throw new NoClassDefFoundError(String.format("%s is a mixin class and cannot be referenced directly", name)); } if (mixins != null) { + // Re-entrance is "safe" as long as we don't need to apply any mixins, if there are mixins then we need to panic now if (locked) { - MixinApplyError error = new MixinApplyError("Re-entrance error."); + ReEntrantTransformerError error = new ReEntrantTransformerError("Re-entrance error."); MixinProcessor.logger.warn("Re-entrance detected, this will cause serious problems.", error); throw error; } @@ -353,7 +363,8 @@ public class MixinProcessor { this.handleMixinApplyError(name, th, environment); } } - + } catch (MixinTransformerError er) { + throw er; } catch (Throwable th) { th.printStackTrace(); this.dumpClassOnFailure(name, targetClassNode, environment); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/ReEntrantTransformerError.java b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/ReEntrantTransformerError.java new file mode 100644 index 00000000..a756dd06 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/throwables/ReEntrantTransformerError.java @@ -0,0 +1,46 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.mixin.transformer.throwables; + +/** + * Error thrown when transformer re-entrance is detected + */ +public class ReEntrantTransformerError extends MixinTransformerError { + + private static final long serialVersionUID = 7073583236491579255L; + + public ReEntrantTransformerError(String message) { + super(message); + } + + public ReEntrantTransformerError(Throwable cause) { + super(cause); + } + + public ReEntrantTransformerError(String message, Throwable cause) { + super(message, cause); + } + +} From 03e8ad59f0ba2ae481bfafe8e6f594cfa94a7709 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 16 Oct 2019 17:17:43 +0100 Subject: [PATCH 05/16] Refactor some elements of mixin service into new smaller components The main goal here is to reduce the amount of boilerplate required when providing out simple implementations of the mixin service. Some mixin end users are using extremely simple environments and this reduces the boilerplate code in those implementations. --- .../service/mojang/LaunchClassLoaderUtil.java | 28 +++++- .../mojang/MixinServiceLaunchWrapper.java | 54 ++++-------- .../asm/mixin/MixinEnvironment.java | 9 +- .../asm/mixin/transformer/MixinInfo.java | 24 ++--- .../asm/service/IClassTracker.java | 62 +++++++++++++ .../asm/service/IMixinService.java | 61 +++---------- .../asm/service/ITransformerProvider.java | 54 ++++++++++++ .../modlauncher/MixinServiceModLauncher.java | 87 +++++-------------- .../modlauncher/ModLauncherClassTracker.java | 24 ++++- 9 files changed, 235 insertions(+), 168 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/service/IClassTracker.java create mode 100644 src/main/java/org/spongepowered/asm/service/ITransformerProvider.java diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java index 45169565..0d779483 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/LaunchClassLoaderUtil.java @@ -29,6 +29,8 @@ import java.util.Collections; import java.util.Map; import java.util.Set; +import org.spongepowered.asm.service.IClassTracker; + import net.minecraft.launchwrapper.LaunchClassLoader; /** @@ -37,7 +39,7 @@ import net.minecraft.launchwrapper.LaunchClassLoader; * them to perform some validation tasks, and insert entries for mixin "classes" * into the invalid classes set. */ -final class LaunchClassLoaderUtil { +final class LaunchClassLoaderUtil implements IClassTracker { private static final String CACHED_CLASSES_FIELD = "cachedClasses"; private static final String INVALID_CLASSES_FIELD = "invalidClasses"; @@ -67,7 +69,7 @@ final class LaunchClassLoaderUtil { this.classLoaderExceptions = LaunchClassLoaderUtil.>getField(classLoader, LaunchClassLoaderUtil.CLASS_LOADER_EXCEPTIONS_FIELD); this.transformerExceptions = LaunchClassLoaderUtil.>getField(classLoader, LaunchClassLoaderUtil.TRANSFORMER_EXCEPTIONS_FIELD); } - + /** * Get the classloader */ @@ -82,10 +84,27 @@ final class LaunchClassLoaderUtil { * @param name class name * @return true if the class name exists in the cache */ - boolean isClassLoaded(String name) { + @Override + public boolean isClassLoaded(String name) { return this.cachedClasses.containsKey(name); } + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassRestrictions( + * java.lang.String) + */ + @Override + public String getClassRestrictions(String className) { + String restrictions = ""; + if (this.isClassClassLoaderExcluded(className, null)) { + restrictions = "PACKAGE_CLASSLOADER_EXCLUSION"; + } + if (this.isClassTransformerExcluded(className, null)) { + restrictions = (restrictions.length() > 0 ? restrictions + "," : "") + "PACKAGE_TRANSFORMER_EXCLUSION"; + } + return restrictions; + } + /** * Get whether the specified name or transformedName exist in either of the * exclusion lists @@ -143,7 +162,8 @@ final class LaunchClassLoaderUtil { * * @param name class name */ - void registerInvalidClass(String name) { + @Override + public void registerInvalidClass(String name) { if (this.invalidClasses != null) { this.invalidClasses.add(name); } diff --git a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java index d043533e..707ec5c5 100644 --- a/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java +++ b/src/launchwrapper/java/org/spongepowered/asm/service/mojang/MixinServiceLaunchWrapper.java @@ -52,8 +52,10 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.service.IClassBytecodeProvider; import org.spongepowered.asm.service.IClassProvider; +import org.spongepowered.asm.service.IClassTracker; import org.spongepowered.asm.service.ILegacyClassTransformer; import org.spongepowered.asm.service.ITransformer; +import org.spongepowered.asm.service.ITransformerProvider; import org.spongepowered.asm.service.MixinServiceAbstract; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.perf.Profiler; @@ -72,7 +74,7 @@ import net.minecraft.launchwrapper.Launch; /** * Mixin service for launchwrapper */ -public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements IClassProvider, IClassBytecodeProvider { +public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements IClassProvider, IClassBytecodeProvider, ITransformerProvider { // Blackboard keys public static final Keys BLACKBOARD_KEY_TWEAKCLASSES = Keys.of("TweakClasses"); @@ -259,6 +261,22 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I return this; } + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getTransformerProvider() + */ + @Override + public ITransformerProvider getTransformerProvider() { + return this; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassTracker() + */ + @Override + public IClassTracker getClassTracker() { + return this.classLoaderUtil; + } + /* (non-Javadoc) * @see org.spongepowered.asm.service.IClassProvider#findClass( * java.lang.String) @@ -315,40 +333,6 @@ public class MixinServiceLaunchWrapper extends MixinServiceAbstract implements I return Launch.classLoader.getResourceAsStream(name); } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#registerInvalidClass( - * java.lang.String) - */ - @Override - public void registerInvalidClass(String className) { - this.classLoaderUtil.registerInvalidClass(className); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#isClassLoaded( - * java.lang.String) - */ - @Override - public boolean isClassLoaded(String className) { - return this.classLoaderUtil.isClassLoaded(className); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#getClassRestrictions( - * java.lang.String) - */ - @Override - public String getClassRestrictions(String className) { - String restrictions = ""; - if (this.classLoaderUtil.isClassClassLoaderExcluded(className, null)) { - restrictions = "PACKAGE_CLASSLOADER_EXCLUSION"; - } - if (this.classLoaderUtil.isClassTransformerExcluded(className, null)) { - restrictions = (restrictions.length() > 0 ? restrictions + "," : "") + "PACKAGE_TRANSFORMER_EXCLUSION"; - } - return restrictions; - } - /* (non-Javadoc) * @see org.spongepowered.asm.service.IClassProvider#getClassPath() */ diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index 2f73ccfa..dc6a75af 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -47,6 +47,7 @@ import org.spongepowered.asm.mixin.transformer.IMixinTransformer; import org.spongepowered.asm.obfuscation.RemapperChain; import org.spongepowered.asm.service.IMixinService; import org.spongepowered.asm.service.ITransformer; +import org.spongepowered.asm.service.ITransformerProvider; import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.service.MixinServiceAbstract; import org.spongepowered.asm.util.Constants; @@ -1263,7 +1264,8 @@ public final class MixinEnvironment implements ITokenProvider { @Deprecated public List getTransformers() { MixinEnvironment.logger.warn("MixinEnvironment::getTransformers is deprecated!"); - return (List)this.service.getTransformers(); + ITransformerProvider transformers = this.service.getTransformerProvider(); + return transformers != null ? (List)transformers.getTransformers() : Collections.emptyList(); } /** @@ -1275,7 +1277,10 @@ public final class MixinEnvironment implements ITokenProvider { @Deprecated public void addTransformerExclusion(String name) { MixinEnvironment.logger.warn("MixinEnvironment::addTransformerExclusion is deprecated!"); - this.service.addTransformerExclusion(name); + ITransformerProvider transformers = this.service.getTransformerProvider(); + if (transformers != null) { + transformers.addTransformerExclusion(name); + } } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index 1ba207f1..ae53c0b9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -64,8 +64,8 @@ import org.spongepowered.asm.mixin.transformer.ClassInfo.Method; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException; import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException; +import org.spongepowered.asm.service.IClassTracker; import org.spongepowered.asm.service.IMixinService; -import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.asm.ASM; @@ -702,11 +702,6 @@ class MixinInfo implements Comparable, IMixinInfo { } - /** - * Mixin service - */ - private static final IMixinService classLoaderUtil = MixinService.getService(); - /** * Global order of mixin infos, used to determine ordering between mixins * with equivalent priority @@ -843,7 +838,10 @@ class MixinInfo implements Comparable, IMixinInfo { // Inject the mixin class name into the LaunchClassLoader's invalid // classes set so that any classes referencing the mixin directly will // cause the game to crash - MixinInfo.classLoaderUtil.registerInvalidClass(this.className); + IClassTracker tracker = this.service.getClassTracker(); + if (tracker != null) { + tracker.registerInvalidClass(this.className); + } } // Read the class bytes and transform @@ -906,13 +904,14 @@ class MixinInfo implements Comparable, IMixinInfo { throw new InvalidMixinException(this, String.format("The mixin '%s' is missing an @Mixin annotation", this.className)); } + IClassTracker tracker = this.service.getClassTracker(); List declaredTargets = new ArrayList(); for (Object target : this.readTargets(mixin)) { DeclaredTarget declaredTarget = DeclaredTarget.of(target, this); if (declaredTarget == null) { continue; } - if (MixinInfo.classLoaderUtil.isClassLoaded(declaredTarget.name) && !this.isReloading()) { + if (tracker != null && tracker.isClassLoaded(declaredTarget.name) && !this.isReloading()) { String message = String.format("Critical problem: %s target %s was loaded too early.", this, declaredTarget.name); if (this.parent.isRequired()) { throw new MixinTargetAlreadyLoadedException(this, message, declaredTarget.name); @@ -1265,9 +1264,12 @@ class MixinInfo implements Comparable, IMixinInfo { ClassNode classNode = null; try { - String restrictions = this.service.getClassRestrictions(mixinClassName); - if (restrictions.length() > 0) { - this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName); + IClassTracker tracker = this.service.getClassTracker(); + if (tracker != null) { + String restrictions = tracker.getClassRestrictions(mixinClassName); + if (restrictions.length() > 0) { + this.logger.error("Classloader restrictions [{}] encountered loading {}, name: {}", restrictions, this, mixinClassName); + } } classNode = this.service.getBytecodeProvider().getClassNode(mixinClassName, true); } catch (ClassNotFoundException ex) { diff --git a/src/main/java/org/spongepowered/asm/service/IClassTracker.java b/src/main/java/org/spongepowered/asm/service/IClassTracker.java new file mode 100644 index 00000000..6e1e2513 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/IClassTracker.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +/** + * Class trackers are responsible for interacting with the class loading process + * to for the purposes of tracking class load activity and class load + * restrictions. This service component is entirely optional and services can + * elect to return null if the platform does not support this + * functionality. + */ +public interface IClassTracker { + + /** + * Register an invalid class with the service classloader + * + * @param className invalid class name + */ + public abstract void registerInvalidClass(String className); + + /** + * Check whether the specified class was already loaded by the service + * classloader + * + * @param className class name to check + * @return true if the class was already loaded + */ + public abstract boolean isClassLoaded(String className); + + /** + * Check whether the specified class name is subject to any restrictions in + * the context of this service + * + * @param className class name to check + * @return comma-separated list of restrictions, empty string if no + * restrictions apply + */ + public abstract String getClassRestrictions(String className); + +} diff --git a/src/main/java/org/spongepowered/asm/service/IMixinService.java b/src/main/java/org/spongepowered/asm/service/IMixinService.java index 147a34ea..b17f1024 100644 --- a/src/main/java/org/spongepowered/asm/service/IMixinService.java +++ b/src/main/java/org/spongepowered/asm/service/IMixinService.java @@ -97,10 +97,20 @@ public interface IMixinService { */ public abstract IClassBytecodeProvider getBytecodeProvider(); -// /** -// * Return the synthetic class registry for this service -// */ -// public abstract ISyntheticClassRegistry getSyntheticClassRegistry(); + /** + * Return the transformer provider for this service. Note that unlike + * other service components, this component is allowed to be null + * for services which do not support transformers, or don't support + * interacting with them! + */ + public abstract ITransformerProvider getTransformerProvider(); + + /** + * Return the class tracker for this service. Note that unlike + * other service components, this component is allowed to be null + * for services which do not support this functionality! + */ + public abstract IClassTracker getClassTracker(); /** * Get additional platform agents for this service @@ -130,49 +140,6 @@ public interface IMixinService { */ public abstract InputStream getResourceAsStream(String name); - /** - * Register an invalid class with the service classloader - * - * @param className invalid class name - */ - public abstract void registerInvalidClass(String className); - - /** - * Check whether the specified class was already loaded by the service - * classloader - * - * @param className class name to check - * @return true if the class was already loaded - */ - public abstract boolean isClassLoaded(String className); - - /** - * Check whether the specified class name is subject to any restrictions in - * the context of this service - * - * @param className class name to check - * @return comma-separated list of restrictions, empty string if no - * restrictions apply - */ - public abstract String getClassRestrictions(String className); - - /** - * Get currently available transformers in the environment - */ - public abstract Collection getTransformers(); - - /** - * Get currently available transformers in the environment - */ - public abstract Collection getDelegatedTransformers(); - - /** - * Adds a transformer to the transformer exclusions list - * - * @param name Class transformer exclusion to add - */ - public abstract void addTransformerExclusion(String name); - /** * Get the detected side name for this environment */ diff --git a/src/main/java/org/spongepowered/asm/service/ITransformerProvider.java b/src/main/java/org/spongepowered/asm/service/ITransformerProvider.java new file mode 100644 index 00000000..0a5a397d --- /dev/null +++ b/src/main/java/org/spongepowered/asm/service/ITransformerProvider.java @@ -0,0 +1,54 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.service; + +import java.util.Collection; + +/** + * Interface for interacting with transforming classloaders. This service + * component is entirely optional and services can elect to return null + * if the platform does not support interacting with the transformer chain (or + * doesn't have a transformer chain!) + */ +public interface ITransformerProvider { + + /** + * Get currently available transformers in the environment + */ + public abstract Collection getTransformers(); + + /** + * Get currently available transformers in the environment + */ + public abstract Collection getDelegatedTransformers(); + + /** + * Adds a transformer to the transformer exclusions list + * + * @param name Class transformer exclusion to add + */ + public abstract void addTransformerExclusion(String name); + +} diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java index 6c287d07..0bf45dd3 100644 --- a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/MixinServiceModLauncher.java @@ -34,7 +34,8 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Phase; import org.spongepowered.asm.mixin.transformer.MixinTransformationHandler; import org.spongepowered.asm.service.IClassBytecodeProvider; import org.spongepowered.asm.service.IClassProvider; -import org.spongepowered.asm.service.ITransformer; +import org.spongepowered.asm.service.IClassTracker; +import org.spongepowered.asm.service.ITransformerProvider; import org.spongepowered.asm.service.MixinServiceAbstract; import org.spongepowered.asm.util.IConsumer; @@ -171,6 +172,25 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { } return this.bytecodeProvider; } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getTransformerProvider() + */ + @Override + public ITransformerProvider getTransformerProvider() { + return null; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IMixinService#getClassTracker() + */ + @Override + public IClassTracker getClassTracker() { + if (this.classTracker == null) { + this.classTracker = new ModLauncherClassTracker(); + } + return this.classTracker; + } /** * Get (or create) the transformation handler @@ -181,16 +201,6 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { } return this.transformationHandler; } - - /** - * Get (or create) the class tracker - */ - private ModLauncherClassTracker getClassTracker() { - if (this.classTracker == null) { - this.classTracker = new ModLauncherClassTracker(); - } - return this.classTracker; - } /* (non-Javadoc) * @see org.spongepowered.asm.service.IMixinService#getPlatformAgents() @@ -219,59 +229,6 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { return Thread.currentThread().getContextClassLoader().getResourceAsStream(name); } - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#registerInvalidClass( - * java.lang.String) - */ - @Override - public void registerInvalidClass(String className) { - this.getClassTracker().registerInvalidClass(className); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#isClassLoaded( - * java.lang.String) - */ - @Override - public boolean isClassLoaded(String className) { - return this.getClassTracker().isClassLoaded(className); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#getClassRestrictions( - * java.lang.String) - */ - @Override - public String getClassRestrictions(String className) { - return this.getClassTracker().getClassRestrictions(className); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#getTransformers() - */ - @Override - public Collection getTransformers() { - return ImmutableList.of(); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService - * #getDelegatedTransformers() - */ - @Override - public Collection getDelegatedTransformers() { - return ImmutableList.of(); - } - - /* (non-Javadoc) - * @see org.spongepowered.asm.service.IMixinService#addTransformerExclusion( - * java.lang.String) - */ - @Override - public void addTransformerExclusion(String name) { - // TODO ? - } - /** * Internal method to retrieve the class processors which will be called by * the launch plugin @@ -279,7 +236,7 @@ public class MixinServiceModLauncher extends MixinServiceAbstract { public Collection getProcessors() { return ImmutableList.of( this.getTransformationHandler(), - this.getClassTracker() + (IClassProcessor)this.getClassTracker() ); } diff --git a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java index e9fdc56b..8280d386 100644 --- a/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java +++ b/src/modlauncher/java/org/spongepowered/asm/service/modlauncher/ModLauncherClassTracker.java @@ -32,6 +32,7 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.launch.IClassProcessor; import org.spongepowered.asm.launch.Phases; +import org.spongepowered.asm.service.IClassTracker; import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; @@ -40,25 +41,40 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService.Phase; * TCL and class load events so we can report when classes were loaded before * we could transform them */ -public class ModLauncherClassTracker implements IClassProcessor { +public class ModLauncherClassTracker implements IClassProcessor, IClassTracker { private final Set invalidClasses = new HashSet(); private final Set loadedClasses = new HashSet(); - void registerInvalidClass(String className) { + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassTracker#registerInvalidClass( + * java.lang.String) + */ + @Override + public void registerInvalidClass(String className) { synchronized (this.invalidClasses) { this.invalidClasses.add(className); } } - boolean isClassLoaded(String className) { + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassTracker#isClassLoaded( + * java.lang.String) + */ + @Override + public boolean isClassLoaded(String className) { synchronized (this.loadedClasses) { return this.loadedClasses.contains(className); } } - String getClassRestrictions(String className) { + /* (non-Javadoc) + * @see org.spongepowered.asm.service.IClassTracker#getClassRestrictions( + * java.lang.String) + */ + @Override + public String getClassRestrictions(String className) { return ""; // TODO ? } From 7b37a681ee237bcb2c8b9ed30e01494445055cb0 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Wed, 23 Oct 2019 18:43:23 +0100 Subject: [PATCH 06/16] Overhaul RedirectInjector for more consistent coerce behaviour Also improve some javadoc. Closes #350 --- .../spongepowered/asm/mixin/Implements.java | 1 + .../spongepowered/asm/mixin/Interface.java | 6 +- .../asm/mixin/MixinEnvironment.java | 14 + .../org/spongepowered/asm/mixin/Shadow.java | 1 + .../spongepowered/asm/mixin/injection/At.java | 2 + .../asm/mixin/injection/Coerce.java | 24 +- .../asm/mixin/injection/Constant.java | 2 + .../asm/mixin/injection/Inject.java | 67 +++ .../asm/mixin/injection/Redirect.java | 87 +++- .../asm/mixin/injection/Slice.java | 2 + .../injection/callback/CallbackInjector.java | 7 +- .../asm/mixin/injection/code/Injector.java | 13 +- .../injection/invoke/InvokeInjector.java | 199 ++++++++- .../invoke/ModifyConstantInjector.java | 15 +- .../injection/invoke/RedirectInjector.java | 403 +++++++++--------- .../modify/ModifyVariableInjector.java | 11 +- .../injection/selectors/ITargetSelector.java | 9 +- .../mixin/injection/struct/InjectionInfo.java | 18 +- .../mixin/injection/struct/MemberInfo.java | 5 + .../throwables/InvalidInjectionException.java | 31 ++ .../asm/mixin/struct/SpecialMethodInfo.java | 14 + .../asm/mixin/transformer/MixinInfo.java | 21 +- .../extensions/ExtensionClassExporter.java | 16 +- .../mixin/transformer/meta/MixinInner.java | 3 +- .../mixin/transformer/meta/MixinMerged.java | 3 +- .../mixin/transformer/meta/MixinProxy.java | 3 +- .../mixin/transformer/meta/MixinRenamed.java | 3 +- .../spongepowered/asm/util/Annotations.java | 26 +- .../org/spongepowered/asm/util/Bytecode.java | 78 +++- .../spongepowered/asm/util/PrettyPrinter.java | 11 +- .../asm/util/SignaturePrinter.java | 25 +- .../asm/util/asm/MethodNodeEx.java | 62 +++ 32 files changed, 856 insertions(+), 326 deletions(-) create mode 100644 src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java diff --git a/src/main/java/org/spongepowered/asm/mixin/Implements.java b/src/main/java/org/spongepowered/asm/mixin/Implements.java index 6cecf88b..0547eaf9 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Implements.java +++ b/src/main/java/org/spongepowered/asm/mixin/Implements.java @@ -43,4 +43,5 @@ public @interface Implements { * @return list of interfaces to implement */ public Interface[] value(); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/Interface.java b/src/main/java/org/spongepowered/asm/mixin/Interface.java index e68ed706..63b7b149 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Interface.java +++ b/src/main/java/org/spongepowered/asm/mixin/Interface.java @@ -24,15 +24,15 @@ */ package org.spongepowered.asm.mixin; -import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * I'm probably going to the special hell for this + * This annotation is used to define information for a soft-implemented + * interface. See {@link Implements} for details. */ -@Target(ElementType.TYPE) +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.CLASS) public @interface Interface { diff --git a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java index dc6a75af..5a859929 100644 --- a/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java +++ b/src/main/java/org/spongepowered/asm/mixin/MixinEnvironment.java @@ -1029,6 +1029,20 @@ public final class MixinEnvironment implements ITokenProvider { return mixinConfigs; } + /** + * Add a mixin configuration to the blackboard + * + * @param config Name of configuration resource to add + * @return fluent interface + * @deprecated use Mixins::addConfiguration instead + */ + @Deprecated + public MixinEnvironment addConfiguration(String config) { + MixinEnvironment.logger.warn("MixinEnvironment::addConfiguration is deprecated and will be removed. Use Mixins::addConfiguration instead!"); + Mixins.addConfiguration(config, this); + return this; + } + void registerConfig(String config) { List configs = this.getMixinConfigs(); if (!configs.contains(config)) { diff --git a/src/main/java/org/spongepowered/asm/mixin/Shadow.java b/src/main/java/org/spongepowered/asm/mixin/Shadow.java index 79aadd1f..f30884aa 100644 --- a/src/main/java/org/spongepowered/asm/mixin/Shadow.java +++ b/src/main/java/org/spongepowered/asm/mixin/Shadow.java @@ -125,4 +125,5 @@ public @interface Shadow { * @return Aliases for this member */ public String[] aliases() default { }; + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/At.java b/src/main/java/org/spongepowered/asm/mixin/injection/At.java index 1e502fb9..789843a5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/At.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/At.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.points.*; @@ -44,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.points.*; * should be consulted for the meaning of the argument to that particular class. * A general description of each parameter is provided below. */ +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.RUNTIME) public @interface At { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java b/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java index d512d18a..e2cef9e0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Coerce.java @@ -33,13 +33,16 @@ import java.lang.annotation.Target; *

    This annotation has two usages applicable to Callback Injectors (defined * using {@link Inject @Inject}. For local capture injectors, it indicates * that the injector should coerce top-level primitive types (int) to covariant - * types defined on the handler. For other injectors, it can be used on a - * reference type to indicate that the intended type is covariant over the - * argument type (or that the argument type is contravariant on the target class - * type). This can be used for multi-target injectors with a bounded type - * argument on the class or target method.

    + * types defined on the handler. It can also be used on a reference type to + * indicate that the intended type is covariant over the argument type (or that + * the argument type is contravariant on the target class type). This can be + * used for multi-target injectors with a bounded type argument on the class or + * target method. It is also acceptable to use an interface directly or + * indirectly implemented by the relevant class, including interfaces applied by + * other mixins.

    * - *

    During LVT generation it is not always possible to inflect the exact local + *

    @Coerce also has an important usage with primitive types. It + * is not always possible during LVT generation to determine the exact local * type for types represented internally as integers, for example booleans and * shorts. However adding a surrogate for these cases is overkill when the type * is known for certain by the injector. Since the bytecode for all types stored @@ -56,8 +59,15 @@ import java.lang.annotation.Target; * indicate that an incoming parameter can be consumed as a valid supertype, up * to and including {@link Object}. This is particularly useful when an argument * on the target method invocation is inaccessible or unknown.

    + * + *

    Since Mixin 0.8 it is also possible to use @Coerce + * on the return type of a field gettter or method invocation + * redirector. To do so simply annotate the method itself. Note that doing so + * will cast the return type back to the original return type as part of the + * injection, so the object must be of an appropriate type regardless of + * visibility.

    */ -@Target({ ElementType.PARAMETER }) +@Target({ ElementType.PARAMETER, ElementType.METHOD }) public @interface Coerce { } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java index c8764dab..83da5fdc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Constant.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import org.objectweb.asm.Opcodes; @@ -39,6 +40,7 @@ import org.objectweb.asm.Opcodes; * appropriate argument. Specifying values of different types will cause an * error to be raised by the injector.

    */ +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.RUNTIME) public @interface Constant { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java index 3e11f64b..1fcaf47a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Inject.java @@ -31,6 +31,7 @@ import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; @@ -41,6 +42,65 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * Specifies that this mixin method should inject a callback (or * callbacks) to itself in the target method(s) identified by * {@link #method}. + * + *

    Callbacks are simple injectors which simply inject a call to the decorated + * method (the handler) in the target method (or methods) + * selected by the selectors specified in {@link #method}. Callback Injectors + * can also capture arguments and local variables from the target for + * use in the handler.

    + * + *

    Callback handler methods should always return void and should + * have the same static-ness as their target (though it is allowable to + * have a static callback injected into an instance method, and for + * obvious reasons the inverse is not permitted).

    + * + *

    Basic usage

    + * + *

    The simplest usage of @Inject captures no context from the + * target scope. This is particularly useful if the injector is targetting + * multiple methods with different signatures. In this case only the + * {@link CallbackInfo} (or {@link CallbackInfoReturnable} as appropriate) is + * required.

    + * + *
    private void onSomeEvent(CallbackInfo ci)
    + * + *

    Capture target arguments

    + * + *

    Callbacks can also capture the arguments passed to the target method. To + * do so specify the target arguments before the {@link CallbackInfo}:

    + * + *
    private void onSomeEvent(int arg1, String arg2, + * CallbackInfo ci)
    + * + *

    Surrogate methods

    + * + *

    If injecting into multiple methods with different target arguments it is + * obviously possible to ignore the target arguments (see "Basic Usage" above) + * but this may be unsuitable if arguments from the target are required. If you + * need to inject into multiple methods but also wish to capture method + * arguments you may provide a surrogate method with the alternative + * signature. In fact you may provide as many surrogates as required by the + * injection. Surrogate methods much have the same name as the handler method + * and must be decorated with {@link Surrogate}. A surrogate may also be + * required where the LVT of a method with local capture (see below) is + * known to change between different environments or injection points.

    + * + *

    Capture local variables

    + * + *

    In addition to capturing the target method arguments, it may be desirable + * to capture locally-scoped variables from the target method at the point of + * injection. This is usually executed in two stages:

    + * + *
      + *
    1. Set the {@link #locals()} value of your injection to + * {@link LocalCapture#PRINT} and run the application.
    2. + *
    3. When the injector is processed, a listing of the LVT is produced + * accompanied by a generated signature for your handler method including + * the discovered args. Modify your handler signature accordingly.
    4. + *
    + * + *

    For more details see {@link #locals()}.

    + * */ @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @@ -114,6 +174,13 @@ public @interface Inject { * surrogate targets for the orphaned injector by annotating them with an * {@link Surrogate} annotation.

    * + *

    You can improve the robustness of your local capture injection by only + * specifying locals up to the last variable you wish to use. For example if + * the target LVT contains <int, int, int, float, String> and + * you only need the float value, you can choose to omit the unused + * String and changes to the LVT beyond that point will not affect + * your injection.

    + * *

    It is also important to nominate the failure behaviour to follow when * local capture fails and so all {@link LocalCapture} behaviours which * specify a capture action imply a particular behaviour for handling diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 0821599d..39309c28 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -31,6 +31,8 @@ import java.lang.annotation.Target; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; +import org.spongepowered.asm.mixin.injection.points.BeforeInvoke; +import org.spongepowered.asm.mixin.injection.points.BeforeNew; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -41,7 +43,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * method call, field access or object construction (via the new * keyword) to the method decorated with this annotation.

    * - *

    Method Redirect Mode

    + *

    Method Redirect Mode

    * *

    The handler method signature must match the hooked method precisely * but prepended with an arg of the owning object's type to accept the @@ -65,7 +67,8 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * * *

    For obvious reasons this does not apply for static methods, for static - * methods it is sufficient that the signature simply match the hooked method. + * methods it is sufficient that the signature simply match the redirected + * method. *

    * *

    It is also possible to capture the arguments of the target method in @@ -78,7 +81,12 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * int someInt, String someString) * * - *

    Field Access Redirect Mode

    + *

    All arguments of a method redirect handler, and the return type, can be + * decorated with {@link Coerce} if - for example - a package-private class + * needs to be coerced to a duck interface or to (for example) Object. + *

    + * + *

    Field Access Redirect Mode

    * *

    The handler method signature varies depending on whether the redirector is * handling a field write (PUTFIELD, PUTSTATIC) or a @@ -91,21 +99,22 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * * * Read static field (GETSTATIC) - * private FieldType getFieldValue() + * private static FieldType getFieldValue() * * * Read instance field (GETFIELD) * private FieldType getFieldValue(OwnerType - * owner) + * owner) * * * Write static field (PUTSTATIC) - * private void setFieldValue(FieldType value) + * private static void setFieldValue(FieldType value) + * * * * Write instance field (PUTFIELD) * private void setFieldValue(OwnerType - * owner, FieldType value) + * owner, FieldType value) * * * @@ -114,7 +123,13 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * the code above this would be the someInt and someString * arguments) by appending the arguments to the method signature.

    * - *

    Array Element Access Redirect Mode

    + *

    All arguments of a field redirect handler, including the field type + * itself, can be decorated with {@link Coerce} if - for example - a + * package-private class needs to be coerced to a duck interface or to (for + * example) Object. + *

    + * + *

    Array Element Access Redirect Mode

    * *

    For fields of an array type, it is possible to redirect the access to the * actual array field itself using the behaviour above. However it is also @@ -155,7 +170,7 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * {@link BeforeFieldAccess BeforeFieldAccess args} for details * on matching array accesses using the FIELD injection point.

    * - *

    Array Length Redirect Mode

    + *

    Array Length Redirect Mode

    * *

    For fields of an array type, it is possible to redirect the call to the * builtin pseudo-property length. To do so, specify the argument @@ -174,28 +189,68 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * private int getLength(ElementType[][] array, int baseDim) * * - *

    Constructor Redirect Mode

    + *

    New Object Redirect Mode (Factory Mode)

    + * + *

    Redirecting object creation requires redirection of the NEW + * operation and constructor call. Your handler method should target the NEW + * opcode using the {@link BeforeNew} Injection Point and construct an + * appropriate object. The factory method must return a new object and + * must not return null since the contract of the new + * opcode does not allow for the possibility of null. Your factory may + * throw an exception however.

    + * + *

    Note that {@link BeforeNew} differs from {@link BeforeInvoke} in that the + * shape of target should contain only an owner (to + * target any ctor of the specified class) or only a descriptor + * consisting of the constructor descriptor with the return type changed + * from void (V) to the type of object being constructed. In + * other words to redirect an object creation for an object Foo:

    + * + *
    package baz.bar;
    + * 
    + *class Foo {
    + *    private final int x, y;
    + *  
    + *    // ctor we wish to hook
    + *    Foo(int x, int y) {
    + *        this.x = x;
    + *        this.y = y;
    + *    }
    + *}
    + *
    + * + *

    Valid signatures for this ctor would be:

    + * + *
      + *
    • Lbaz/bar/Foo; - valid because Foo only has one ctor
    • + *
    • (II)Lbaz/bar/Foo; - includes signature of specific ctor
    • + *
    * *

    The handler method signature must match the constructor being redirected * and the return type must match the type of object being constructed. For - * example to redirect the following constructor call:

    + * example to redirect the following object creation call:

    * - *
    public void baz(int someInt, String someString) {
    + * 
    public void exampleFunc(String someString, int dx, int dy) {
      *    // Hooking this constructor
    - *    Foo someObject = new Foo("bar");
    + *    Foo someFoo = new Foo(dx * 10, dy * 10);
      *}
    *
    * *

    The signature of the handler method should be:

    * *
    - *
    public Foo constructFoo(String arg1)
    + *
    public Foo constructFoo(int x, int y)
    *
    * *

    Note that like other redirectors, it is possible to capture the target - * method's arguments by appending them to the handler method's signature.

    + * method's arguments by appending them to the handler method's signature:

    * - *

    A note on static modifiers for handler methods

    + *
    + * public Foo constructFoo(int x, int y, String someString, int dx, + * int dy) + *
    + * + *

    A note on static modifiers for handler methods

    * *

    In general, when declaring a redirect handler the static modifier * of the handler method must always match the target method. The exception to diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java index 2624ab2e..769b1555 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Slice.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; @@ -123,6 +124,7 @@ import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; * can distinguish different slices using {@link #id} and then specify the slice * to use in the {@link At#slice} argument.

    */ +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.RUNTIME) public @interface Slice { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java index 72c24889..d36ed952 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/callback/CallbackInjector.java @@ -531,6 +531,9 @@ public class CallbackInjector extends Injector { int position = callback.target.indexOf(callback.node); List expected = CallbackInjector.summariseLocals(this.methodNode.desc, callback.target.arguments.length + 1); List found = CallbackInjector.summariseLocals(callback.getDescriptor(), callback.frameSize + (callback.target.isStatic ? 1 : 0)); + if (expected.equals(found)) { + return String.format("Invalid descriptor on %s! Expected %s but found %s", this.info, callback.getDescriptor(), this.methodNode.desc); + } return String.format("LVT in %s has incompatible changes at opcode %d in callback %s.\nExpected: %s\n Found: %s", callback.target, position, this, expected, found); } @@ -564,7 +567,7 @@ public class CallbackInjector extends Injector { private void printLocals(final Callback callback) { Type[] args = Type.getArgumentTypes(callback.getDescriptorWithAllLocals()); SignaturePrinter methodSig = new SignaturePrinter(callback.target.method, callback.argNames); - SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, callback.target.returnType, args, callback.argNames); + SignaturePrinter handlerSig = new SignaturePrinter(this.info.getMethodName(), callback.target.returnType, args, callback.argNames); handlerSig.setModifiers(this.methodNode); PrettyPrinter printer = new PrettyPrinter(); @@ -572,7 +575,7 @@ public class CallbackInjector extends Injector { printer.kv("Target Method", methodSig); printer.kv("Target Max LOCALS", callback.target.getMaxLocals()); printer.kv("Initial Frame Size", callback.frameSize); - printer.kv("Callback Name", this.methodNode.name); + printer.kv("Callback Name", this.info.getMethodName()); printer.kv("Instruction", "%s %s", callback.node.getClass().getSimpleName(), Bytecode.getOpcodeName(callback.node.getCurrentTarget().getOpcode())); printer.hr(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 2b4c3257..dd8f6bd4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -49,8 +49,8 @@ import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -161,7 +161,7 @@ public abstract class Injector { @Override public String toString() { - return String.format("%s::%s", this.classNode.name, this.methodNode.name); + return String.format("%s::%s", this.classNode.name, this.info.getMethodName()); } /** @@ -377,7 +377,12 @@ public abstract class Injector { * @return true if from can be coerced to to */ public static boolean canCoerce(Type from, Type to) { - if (from.getSort() == Type.OBJECT && to.getSort() == Type.OBJECT) { + int fromSort = from.getSort(); + int toSort = to.getSort(); + if (fromSort >= Type.ARRAY && toSort >= Type.ARRAY && fromSort == toSort) { + if (fromSort == Type.ARRAY && from.getDimensions() != to.getDimensions()) { + return false; + } return Injector.canCoerce(ClassInfo.forType(from, TypeLookup.ELEMENT_TYPE), ClassInfo.forType(to, TypeLookup.ELEMENT_TYPE)); } @@ -422,7 +427,7 @@ public abstract class Injector { * @return true if from can be coerced to to */ private static boolean canCoerce(ClassInfo from, ClassInfo to) { - return from != null && to != null && (to == from || to.hasSuperClass(from, Traversal.NONE, true)); + return from != null && to != null && (to == from || to.hasSuperClass(from, Traversal.ALL, true)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java index be64c0f2..a8e77817 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java @@ -24,25 +24,95 @@ */ package org.spongepowered.asm.mixin.injection.invoke; +import java.util.Arrays; import java.util.List; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.VarInsnNode; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.struct.Target.Extension; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; +import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.SignaturePrinter; + +import com.google.common.collect.ObjectArrays; /** * Base class for injectors which inject at method invokes */ public abstract class InvokeInjector extends Injector { + + /** + * Redirection data bundle base. No this isn't meant to be pretty, it's a + * way of passing a bunch of state around the injector without having dumb + * method signatures. + */ + static class InjectorData { + + /** + * Redirect target + */ + final Target target; + + /** + * Mutable description. The bundle is be passed to different types of + * handler and the handler decorates the bundle with a description of + * the type of injection, purely for use in error messages. + */ + String description; + + /** + * When passing through {@link RedirectInjector#validateParams} this + * switch determines whether coercion is supported for both the primary + * handler args and captured target args, or for target args only. + */ + boolean allowCoerceArgs; + + /** + * Number of arguments to capture from the target, determined by the + * number of extra args on the handler method + */ + int captureTargetArgs = 0; + + /** + * True if the method itself is decorated with {@link Coerce} and the + * return type is coerced. Instructs the injector to add a CHECKCAST + * following the handler. + */ + boolean coerceReturnType = false; + + InjectorData(Target target) { + this(target, "handler"); + } + + InjectorData(Target target, String description) { + this(target, description, true); + } + + InjectorData(Target target, String description, boolean allowCoerceArgs) { + this.target = target; + this.description = description; + this.allowCoerceArgs = allowCoerceArgs; + } + + @Override + public String toString() { + return this.description; + } + + } /** * @param info Information about this injection @@ -154,6 +224,7 @@ public abstract class InvokeInjector extends Injector { /** * Load args onto the stack from their positions allocated in argMap + * * @param args argument types * @param insns instruction list to generate insns into * @param argMap generated argmap containing local indices for all args @@ -161,8 +232,134 @@ public abstract class InvokeInjector extends Injector { * @param end Ending index */ protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { - for (int arg = start; arg < end; arg++) { + this.pushArgs(args, insns, argMap, start, end, null); + } + + /** + * Load args onto the stack from their positions allocated in argMap + * + * @param args argument types + * @param insns instruction list to generate insns into + * @param argMap generated argmap containing local indices for all args + * @param start Starting index + * @param end Ending index + */ + protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end, Extension extension) { + for (int arg = start; arg < end && arg < args.length; arg++) { insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg])); + if (extension != null) { + extension.add(args[arg].getSize()); + } } } + + /** + * Collects all the logic from old validateParams/checkDescriptor so that we + * can consistently apply coercion logic to method params, and also provide + * more detailed errors when something doesn't line up. + * + *

    The supplied return type and argument list will be verified first. Any + * arguments on the handler beyond the base arguments consume arguments from + * the target. The flag allowCoerceArgs on the redirect + * instance determines whether coercion is supported for the base args and + * return type, coercion is always allowed for captured target args.

    + * + *

    Following validation, the captureTargetArgs and + * coerceReturnType values will be set on the bundle and the + * calling injector function should adjust itself accordingly.

    + * + * @param injector Data bundle for the injector + * @param returnType Return type for the handler, must not be null + * @param args Array of handler args, must not be null + */ + protected final void validateParams(InjectorData injector, Type returnType, Type... args) { + String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext()); + int argIndex = 0; + try { + injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs); + + for (Type arg : args) { + if (arg != null) { + this.checkCoerce(argIndex, arg, description, injector.allowCoerceArgs); + argIndex++; + } + } + + if (argIndex == this.methodArgs.length) { + return; + } + + for (int targetArg = 0; targetArg < injector.target.arguments.length && argIndex < this.methodArgs.length; targetArg++, argIndex++) { + this.checkCoerce(argIndex, injector.target.arguments[targetArg], description, true); + injector.captureTargetArgs++; + } + } catch (InvalidInjectionException ex) { + String expected = this.methodArgs.length > args.length + ? Bytecode.generateDescriptor(returnType, ObjectArrays.concat(args, injector.target.arguments, Type.class)) + : Bytecode.generateDescriptor(returnType, args); + throw new InvalidInjectionException(this.info, String.format("%s. Handler signature: %s Expected signature: %s", ex.getMessage(), + this.methodNode.desc, expected)); + } + + if (argIndex < this.methodArgs.length) { + Type[] extraArgs = Arrays.copyOfRange(this.methodArgs, argIndex, this.methodArgs.length); + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Found %d unexpected additional method arguments: %s", + description, this.methodArgs.length - argIndex, new SignaturePrinter(extraArgs).getFormattedArgs())); + } + } + + /** + * Called inside {@link #validateParams} but can also be used directly. This + * method checks whether the supplied type is compatible with the specified + * handler argument, apply coercion logic where necessary. + * + * @param index Handler argument index, pass in a negative value (by + * convention -1) to specify handler return type + * @param toType Desired type based on the injector contract + * @param description human-readable description of the handler method, used + * in raised exception + * @param allowCoercion True if coercion logic can be applied to this + * argument, false to only allow a precise match + * @return false if the argument matched perfectly, true + * if coercion is required for the argument + */ + protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) { + Type fromType = index < 0 ? this.returnType : this.methodArgs[index]; + if (index >= this.methodArgs.length) { + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Not enough arguments: expected argument type %s at index %d", + description, SignaturePrinter.getTypeName(toType), index)); + } + + AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index); + boolean isReturn = index < 0; + String argType = isReturn ? "return" : "argument"; + Object argIndex = isReturn ? "" : " at index " + index; + + if (fromType.equals(toType)) { + if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex, + SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType)); + } + return false; + } + + if (coerce == null || !allowCoercion) { + String coerceWarning = coerce != null ? ". @Coerce not allowed here" : ""; + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Found unexpected %s type %s%s, expected %s%s", description, argType, + SignaturePrinter.getTypeName(fromType), argIndex, SignaturePrinter.getTypeName(toType), coerceWarning)); + } + + boolean canCoerce = Injector.canCoerce(fromType, toType); + if (!canCoerce) { + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Cannot @Coerce %s type %s%s to %s", description, argType, + SignaturePrinter.getTypeName(toType), argIndex, SignaturePrinter.getTypeName(fromType))); + } + + return true; + } + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java index 35732fb2..f851544f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -33,6 +33,7 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.code.Injector; @@ -82,6 +83,11 @@ public class ModifyConstantInjector extends RedirectInjector { return; } + if (targetNode instanceof TypeInsnNode) { + // TODO inject at type constant + throw new InvalidInjectionException(this.info, "Inject at TypeInsnNode not implemented"); + } + if (Bytecode.isConstant(targetNode)) { this.checkTargetModifiers(target, false); this.injectConstantModifier(target, targetNode); @@ -130,17 +136,16 @@ public class ModifyConstantInjector extends RedirectInjector { } private AbstractInsnNode invokeConstantHandler(Type constantType, Target target, Extension extraStack, InsnList before, InsnList after) { - final String handlerDesc = Bytecode.generateDescriptor(constantType, constantType); - final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); + InjectorData handler = new InjectorData(target, "constant modifier"); + this.validateParams(handler, constantType, constantType); if (!this.isStatic) { before.insert(new VarInsnNode(Opcodes.ALOAD, 0)); extraStack.add(); } - if (withArgs) { - this.pushArgs(target.arguments, after, target.getArgIndices(), 0, target.arguments.length); - extraStack.add(target.arguments); + if (handler.captureTargetArgs > 0) { + this.pushArgs(target.arguments, after, target.getArgIndices(), 0, handler.captureTargetArgs, extraStack); } return this.invokeHandler(after); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index d7e1c347..90175d46 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -31,26 +31,31 @@ import java.util.Set; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import org.objectweb.asm.tree.*; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.MixinEnvironment.Option; -import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.InjectionPoint; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; +import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.points.BeforeFieldAccess; import org.spongepowered.asm.mixin.injection.points.BeforeNew; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; -import org.spongepowered.asm.mixin.injection.struct.Target.Extension; import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.injection.struct.Target.Extension; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; -import com.google.common.base.Joiner; import com.google.common.collect.ObjectArrays; import com.google.common.primitives.Ints; @@ -90,6 +95,8 @@ import com.google.common.primitives.Ints; */ public class RedirectInjector extends InvokeInjector { + private static final String NPE = "java/lang/NullPointerException"; + private static final String KEY_NOMINATORS = "nominators"; private static final String KEY_FUZZ = "fuzz"; private static final String KEY_OPCODE = "opcode"; @@ -129,36 +136,94 @@ public class RedirectInjector extends InvokeInjector { public static final String KEY = "ctor"; - public boolean wildcard = false; + boolean wildcard = false; - public int injected = 0; + int injected = 0; + + InvalidInjectionException lastException; + + public void throwOrCollect(InvalidInjectionException ex) { + if (!this.wildcard) { + throw ex; + } + this.lastException = ex; + } } /** * Data bundle for invoke redirectors */ - static class RedirectedInvoke { + static class RedirectedInvokeData extends InjectorData { - final Target target; final MethodInsnNode node; final Type returnType; - final Type[] args; - final Type[] locals; + final Type[] targetArgs; + final Type[] handlerArgs; - boolean captureTargetArgs = false; - - RedirectedInvoke(Target target, MethodInsnNode node) { - this.target = target; + RedirectedInvokeData(Target target, MethodInsnNode node) { + super(target); this.node = node; this.returnType = Type.getReturnType(node.desc); - this.args = Type.getArgumentTypes(node.desc); - this.locals = node.getOpcode() == Opcodes.INVOKESTATIC - ? this.args - : ObjectArrays.concat(Type.getType("L" + node.owner + ";"), this.args); + this.targetArgs = Type.getArgumentTypes(node.desc); + this.handlerArgs = node.getOpcode() == Opcodes.INVOKESTATIC + ? this.targetArgs + : ObjectArrays.concat(Type.getObjectType(node.owner), this.targetArgs); } + } + /** + * Data bundle for field redirectors + */ + static class RedirectedFieldData extends InjectorData { + + final FieldInsnNode node; + final int opcode; + final Type owner; + final Type type; + final int dimensions; + final boolean isStatic; + final boolean isGetter; + final boolean isSetter; + + // This is actually the return type for array access, might be int for + // array length redirectors + Type elementType; + int extraDimensions = 1; + + RedirectedFieldData(Target target, FieldInsnNode node) { + super(target); + this.node = node; + this.opcode = node.getOpcode(); + this.owner = Type.getObjectType(node.owner); + this.type = Type.getType(node.desc); + this.dimensions = (this.type.getSort() == Type.ARRAY) ? this.type.getDimensions() : 0; + this.isStatic = this.opcode == Opcodes.GETSTATIC || this.opcode == Opcodes.PUTSTATIC; + this.isGetter = this.opcode == Opcodes.GETSTATIC || this.opcode == Opcodes.GETFIELD; + this.isSetter = this.opcode == Opcodes.PUTSTATIC || this.opcode == Opcodes.PUTFIELD; + this.description = this.isGetter ? "field getter" : this.isSetter ? "field setter" : "handler"; + } + + int getTotalDimensions() { + return this.dimensions + this.extraDimensions; + } + + Type[] getArrayArgs(Type... extra) { + int dimensions = this.getTotalDimensions(); + Type[] args = new Type[dimensions + extra.length]; + for (int i = 0; i < args.length; i++) { + args[i] = i == 0 ? this.type : i < dimensions ? Type.INT_TYPE : extra[dimensions - i]; + } + return args; + } + + } + + /** + * Meta is used to decorate the target node with information about this + * injection + */ protected Meta meta; private Map ctorRedirectors = new HashMap(); @@ -297,7 +362,8 @@ public class RedirectInjector extends InvokeInjector { if (node.getOriginalTarget() instanceof TypeInsnNode && node.getOriginalTarget().getOpcode() == Opcodes.NEW) { ConstructorRedirectData meta = node.getDecoration(ConstructorRedirectData.KEY); if (meta.wildcard && meta.injected == 0) { - throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target)); + throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target), + meta.lastException); } } } @@ -307,150 +373,99 @@ public class RedirectInjector extends InvokeInjector { */ @Override protected void injectAtInvoke(Target target, InjectionNode node) { - RedirectedInvoke invoke = new RedirectedInvoke(target, (MethodInsnNode)node.getCurrentTarget()); + RedirectedInvokeData invoke = new RedirectedInvokeData(target, (MethodInsnNode)node.getCurrentTarget()); - this.validateParams(invoke); + this.validateParams(invoke, invoke.returnType, invoke.handlerArgs); InsnList insns = new InsnList(); - Extension extraLocals = target.extendLocals().add(invoke.locals).add(1); + Extension extraLocals = target.extendLocals().add(invoke.handlerArgs).add(1); Extension extraStack = target.extendStack().add(1); // Normally only need 1 extra stack pos to store target ref - int[] argMap = this.storeArgs(target, invoke.locals, insns, 0); - if (invoke.captureTargetArgs) { - int argSize = Bytecode.getArgsSize(target.arguments); + int[] argMap = this.storeArgs(target, invoke.handlerArgs, insns, 0); + if (invoke.captureTargetArgs > 0) { + int argSize = Bytecode.getArgsSize(target.arguments, 0, invoke.captureTargetArgs); extraLocals.add(argSize); extraStack.add(argSize); + // No need to truncate target arg indices, pushArgs ignores args which don't exist argMap = Ints.concat(argMap, target.getArgIndices()); } - AbstractInsnNode insn = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap); - target.replaceNode(invoke.node, insn, insns); + AbstractInsnNode champion = this.invokeHandlerWithArgs(this.methodArgs, insns, argMap); + if (invoke.coerceReturnType && invoke.returnType.getSort() >= Type.ARRAY) { + insns.add(new TypeInsnNode(Opcodes.CHECKCAST, invoke.returnType.getInternalName())); + } + target.replaceNode(invoke.node, champion, insns); extraLocals.apply(); extraStack.apply(); } - /** - * Perform validation of an invoke handler parameters, each parameter in the - * handler must match the expected type or be annotated with {@link Coerce} - * and be a supported supertype of the incoming type. - * - * @param invoke invocation being redirected - */ - protected void validateParams(RedirectedInvoke invoke) { - int argc = this.methodArgs.length; - - String description = String.format("%s handler method %s", this.annotationType, this); - if (!invoke.returnType.equals(this.returnType)) { - throw new InvalidInjectionException(this.info, String.format("%s has an invalid signature. Expected return type %s found %s", - description, this.returnType, invoke.returnType)); - } - - for (int index = 0; index < argc; index++) { - Type toType = null; - if (index >= this.methodArgs.length) { - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Not enough arguments found for capture of target method args, expected %d but found %d", - description, argc, this.methodArgs.length)); - } - - Type fromType = this.methodArgs[index]; - - if (index < invoke.locals.length) { - toType = invoke.locals[index]; - } else { - invoke.captureTargetArgs = true; - argc = Math.max(argc, invoke.locals.length + invoke.target.arguments.length); - int arg = index - invoke.locals.length; - if (arg >= invoke.target.arguments.length) { - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Found unexpected additional target argument with type %s at index %d", - description, fromType, index)); - } - toType = invoke.target.arguments[arg]; - } - - AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index); - - if (fromType.equals(toType)) { - if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { - Injector.logger.warn("Redundant @Coerce on {} argument {}, {} is identical to {}", description, index, toType, fromType); - } - - continue; - } - - boolean canCoerce = Injector.canCoerce(fromType, toType); - if (coerce == null) { - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Found unexpected argument type %s at index %d, expected %s", - description, fromType, index, toType)); - } - - if (!canCoerce) { - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Cannot @Coerce argument type %s at index %d to %s", - description, toType, index, fromType)); - } - } - } - /** * Redirect a field get or set operation, or an array element access */ private void injectAtFieldAccess(Target target, InjectionNode node) { - final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget(); - final int opCode = fieldNode.getOpcode(); - final Type ownerType = Type.getType("L" + fieldNode.owner + ";"); - final Type fieldType = Type.getType(fieldNode.desc); + RedirectedFieldData field = new RedirectedFieldData(target, (FieldInsnNode)node.getCurrentTarget()); - int targetDimensions = (fieldType.getSort() == Type.ARRAY) ? fieldType.getDimensions() : 0; int handlerDimensions = (this.returnType.getSort() == Type.ARRAY) ? this.returnType.getDimensions() : 0; - if (handlerDimensions > targetDimensions) { + if (handlerDimensions > field.dimensions) { throw new InvalidInjectionException(this.info, "Dimensionality of handler method is greater than target array on " + this); - } else if (handlerDimensions == 0 && targetDimensions > 0) { + } else if (handlerDimensions == 0 && field.dimensions > 0) { int fuzz = node.getDecoration(RedirectInjector.KEY_FUZZ).intValue(); int opcode = node.getDecoration(RedirectInjector.KEY_OPCODE).intValue(); - this.injectAtArrayField(target, fieldNode, opCode, ownerType, fieldType, fuzz, opcode); + this.injectAtArrayField(field, fuzz, opcode); } else { - this.injectAtScalarField(target, fieldNode, opCode, ownerType, fieldType); + this.injectAtScalarField(field); } } /** * Redirect an array element access */ - private void injectAtArrayField(Target target, FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType, int fuzz, int opcode) { - Type elementType = fieldType.getElementType(); - if (opCode != Opcodes.GETSTATIC && opCode != Opcodes.GETFIELD) { + private void injectAtArrayField(RedirectedFieldData field, int fuzz, int opcode) { + Type elementType = field.type.getElementType(); + if (field.opcode != Opcodes.GETSTATIC && field.opcode != Opcodes.GETFIELD) { throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for array access %s", - Bytecode.getOpcodeName(opCode), this.info)); + Bytecode.getOpcodeName(field.opcode), this.info)); } else if (this.returnType.getSort() != Type.VOID) { if (opcode != Opcodes.ARRAYLENGTH) { opcode = elementType.getOpcode(Opcodes.IALOAD); } - AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, opcode, fuzz); - this.injectAtGetArray(target, fieldNode, varNode, ownerType, fieldType); + AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(field.target.insns, field.node, opcode, fuzz); + this.injectAtGetArray(field, varNode); } else { - AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(target.insns, fieldNode, elementType.getOpcode(Opcodes.IASTORE), fuzz); - this.injectAtSetArray(target, fieldNode, varNode, ownerType, fieldType); + AbstractInsnNode varNode = BeforeFieldAccess.findArrayNode(field.target.insns, field.node, elementType.getOpcode(Opcodes.IASTORE), fuzz); + this.injectAtSetArray(field, varNode); } } /** * Array element read (xALOAD) or array.length (ARRAYLENGTH) */ - private void injectAtGetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) { - String handlerDesc = RedirectInjector.getGetArrayHandlerDescriptor(varNode, this.returnType, fieldType); - boolean withArgs = this.checkDescriptor(handlerDesc, target, "array getter"); - this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array getter"); + private void injectAtGetArray(RedirectedFieldData field, AbstractInsnNode varNode) { + field.description = "array getter"; + field.elementType = field.type.getElementType(); + + if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) { + field.elementType = Type.INT_TYPE; + field.extraDimensions = 0; + } + + this.validateParams(field, field.elementType, field.getArrayArgs()); + this.injectArrayRedirect(field, varNode, "array getter"); } /** * Array element write (xASTORE) */ - private void injectAtSetArray(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, Type ownerType, Type fieldType) { - String handlerDesc = Bytecode.generateDescriptor(null, (Object[])RedirectInjector.getArrayArgs(fieldType, 1, fieldType.getElementType())); - boolean withArgs = this.checkDescriptor(handlerDesc, target, "array setter"); - this.injectArrayRedirect(target, fieldNode, varNode, withArgs, "array setter"); + private void injectAtSetArray(RedirectedFieldData field, AbstractInsnNode varNode) { + field.description = "array setter"; + Type elementType = field.type.getElementType(); + int valueArgIndex = field.getTotalDimensions(); + if (this.checkCoerce(valueArgIndex, elementType, String.format("%s array setter method %s from %s", + this.annotationType, this, this.info.getContext()), true)) { + elementType = this.methodArgs[valueArgIndex]; + } + + this.validateParams(field, Type.VOID_TYPE, field.getArrayArgs(elementType)); + this.injectArrayRedirect(field, varNode, "array setter"); } /** @@ -459,35 +474,38 @@ public class RedirectInjector extends InvokeInjector { * actual handler signature, the correct arguments are already on the stack * thanks to the nature of xALOAD and xASTORE. * + * @param varNode array access node + * @param type description of access type for use in error messages * @param target target method * @param fieldNode field node - * @param varNode array access node - * @param withArgs true if the descriptor includes captured arguments from - * the target method signature - * @param type description of access type for use in error messages */ - private void injectArrayRedirect(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, boolean withArgs, String type) { + private void injectArrayRedirect(RedirectedFieldData field, AbstractInsnNode varNode, String type) { if (varNode == null) { String advice = ""; throw new InvalidInjectionException(this.info, String.format( "Array element %s on %s could not locate a matching %s instruction in %s. %s", - this.annotationType, this, type, target, advice)); + this.annotationType, this, type, field.target, advice)); } - Extension extraStack = target.extendStack(); + Extension extraStack = field.target.extendStack(); if (!this.isStatic) { - target.insns.insertBefore(fieldNode, new VarInsnNode(Opcodes.ALOAD, 0)); + VarInsnNode loadThis = new VarInsnNode(Opcodes.ALOAD, 0); + field.target.insns.insert(field.node, loadThis); + field.target.insns.insert(loadThis, new InsnNode(Opcodes.SWAP)); extraStack.add(); } - InsnList invokeInsns = new InsnList(); - if (withArgs) { - this.pushArgs(target.arguments, invokeInsns, target.getArgIndices(), 0, target.arguments.length); - extraStack.add(target.arguments); + InsnList insns = new InsnList(); + if (field.captureTargetArgs > 0) { + this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack); } extraStack.apply(); - target.replaceNode(varNode, this.invokeHandler(invokeInsns), invokeInsns); + AbstractInsnNode champion = this.invokeHandler(insns); + if (field.coerceReturnType && field.type.getSort() >= Type.ARRAY) { + insns.add(new TypeInsnNode(Opcodes.CHECKCAST, field.elementType.getInternalName())); + } + field.target.replaceNode(varNode, champion, insns); } /** @@ -499,18 +517,19 @@ public class RedirectInjector extends InvokeInjector { * @param ownerType type of the field owner * @param fieldType field type */ - private void injectAtScalarField(Target target, final FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType) { + private void injectAtScalarField(RedirectedFieldData field) { AbstractInsnNode invoke = null; InsnList insns = new InsnList(); - if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) { - invoke = this.injectAtGetField(insns, target, fieldNode, opCode == Opcodes.GETSTATIC, ownerType, fieldType); - } else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) { - invoke = this.injectAtPutField(insns, target, fieldNode, opCode == Opcodes.PUTSTATIC, ownerType, fieldType); + if (field.isGetter) { + invoke = this.injectAtGetField(field, insns); + } else if (field.isSetter) { + invoke = this.injectAtPutField(field, insns); } else { - throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for %s", Bytecode.getOpcodeName(opCode), this.info)); + throw new InvalidInjectionException(this.info, String.format("Unspported opcode %s for %s", + Bytecode.getOpcodeName(field.opcode), this.info)); } - target.replaceNode(fieldNode, invoke, insns); + field.target.replaceNode(field.node, invoke, insns); } /** @@ -519,27 +538,29 @@ public class RedirectInjector extends InvokeInjector { * possible scenarios based on the possible combinations of static on the * handler and the field itself. */ - private AbstractInsnNode injectAtGetField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) { - final String handlerDesc = staticField ? Bytecode.generateDescriptor(fieldType) : Bytecode.generateDescriptor(fieldType, owner); - final boolean withArgs = this.checkDescriptor(handlerDesc, target, "getter"); + private AbstractInsnNode injectAtGetField(RedirectedFieldData field, InsnList insns) { + this.validateParams(field, field.type, field.isStatic ? null : field.owner); - Extension extraStack = target.extendStack(); + Extension extraStack = field.target.extendStack(); if (!this.isStatic) { extraStack.add(); insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); - if (!staticField) { + if (!field.isStatic) { insns.add(new InsnNode(Opcodes.SWAP)); } } - if (withArgs) { - this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length); - extraStack.add(target.arguments); + if (field.captureTargetArgs > 0) { + this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack); } extraStack.apply(); - return this.invokeHandler(insns); + AbstractInsnNode champion = this.invokeHandler(insns); + if (field.coerceReturnType && field.type.getSort() >= Type.ARRAY) { + insns.add(new TypeInsnNode(Opcodes.CHECKCAST, field.type.getInternalName())); + } + return champion; } /** @@ -548,60 +569,33 @@ public class RedirectInjector extends InvokeInjector { * possible scenarios based on the possible combinations of static on the * handler and the field itself. */ - private AbstractInsnNode injectAtPutField(InsnList insns, Target target, FieldInsnNode node, boolean staticField, Type owner, Type fieldType) { - String handlerDesc = staticField ? Bytecode.generateDescriptor(null, fieldType) : Bytecode.generateDescriptor(null, owner, fieldType); - boolean withArgs = this.checkDescriptor(handlerDesc, target, "setter"); + private AbstractInsnNode injectAtPutField(RedirectedFieldData field, InsnList insns) { + this.validateParams(field, Type.VOID_TYPE, field.isStatic ? null : field.owner, field.type); - Extension extraStack = target.extendStack(); + Extension extraStack = field.target.extendStack(); if (!this.isStatic) { - if (staticField) { + if (field.isStatic) { insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); insns.add(new InsnNode(Opcodes.SWAP)); } else { extraStack.add(); - int marshallVar = target.allocateLocals(fieldType.getSize()); - insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ISTORE), marshallVar)); + int marshallVar = field.target.allocateLocals(field.type.getSize()); + insns.add(new VarInsnNode(field.type.getOpcode(Opcodes.ISTORE), marshallVar)); insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); insns.add(new InsnNode(Opcodes.SWAP)); - insns.add(new VarInsnNode(fieldType.getOpcode(Opcodes.ILOAD), marshallVar)); + insns.add(new VarInsnNode(field.type.getOpcode(Opcodes.ILOAD), marshallVar)); } } - if (withArgs) { - this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length); - extraStack.add(target.arguments); + if (field.captureTargetArgs > 0) { + this.pushArgs(field.target.arguments, insns, field.target.getArgIndices(), 0, field.captureTargetArgs, extraStack); } extraStack.apply(); return this.invokeHandler(insns); } - /** - * Check that the handler descriptor matches the calculated descriptor for - * the access being redirected. - * - * @param desc computed descriptor - * @param target target method - * @param type redirector type in human-readable text, for error messages - * @return true if the descriptor was found and includes target method args, - * false if the descriptor was found and does not capture target args - */ - protected boolean checkDescriptor(String desc, Target target, String type) { - if (this.methodNode.desc.equals(desc)) { - return false; - } - - int pos = desc.indexOf(')'); - String alternateDesc = String.format("%s%s%s", desc.substring(0, pos), Joiner.on("").join(target.arguments), desc.substring(pos)); - if (this.methodNode.desc.equals(alternateDesc)) { - return true; - } - - throw new InvalidInjectionException(this.info, String.format("%s method %s %s has an invalid signature. Expected %s but found %s", - this.annotationType, type, this, desc, this.methodNode.desc)); - } - protected void injectAtConstructor(Target target, InjectionNode node) { ConstructorRedirectData meta = node.getDecoration(ConstructorRedirectData.KEY); @@ -616,22 +610,19 @@ public class RedirectInjector extends InvokeInjector { final MethodInsnNode initNode = target.findInitNodeFor(newNode); if (initNode == null) { - if (!meta.wildcard) { - throw new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", this.annotationType, target)); - } + meta.throwOrCollect(new InvalidInjectionException(this.info, String.format("%s ctor invocation was not found in %s", + this.annotationType, target))); return; } // True if the result of the object construction is being assigned boolean isAssigned = dupNode.getOpcode() == Opcodes.DUP; - String desc = initNode.desc.replace(")V", ")L" + newNode.desc + ";"); - boolean withArgs = false; + RedirectedInvokeData ctor = new RedirectedInvokeData(target, initNode); + ctor.description = "factory"; try { - withArgs = this.checkDescriptor(desc, target, "constructor"); + this.validateParams(ctor, Type.getObjectType(newNode.desc), ctor.targetArgs); } catch (InvalidInjectionException ex) { - if (!meta.wildcard) { - throw ex; - } + meta.throwOrCollect(ex); return; } @@ -647,12 +638,14 @@ public class RedirectInjector extends InvokeInjector { Extension extraStack = target.extendStack(); InsnList insns = new InsnList(); - if (withArgs) { - this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, target.arguments.length); - extraStack.add(target.arguments); + if (ctor.captureTargetArgs > 0) { + this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, ctor.captureTargetArgs, extraStack); } this.invokeHandler(insns); + if (ctor.coerceReturnType) { + insns.add(new TypeInsnNode(Opcodes.CHECKCAST, newNode.desc)); + } extraStack.apply(); if (isAssigned) { @@ -662,7 +655,7 @@ public class RedirectInjector extends InvokeInjector { LabelNode nullCheckSucceeded = new LabelNode(); insns.add(new InsnNode(Opcodes.DUP)); insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded)); - this.throwException(insns, "java/lang/NullPointerException", String.format("%s constructor handler %s returned null for %s", + this.throwException(insns, RedirectInjector.NPE, String.format("%s constructor handler %s returned null for %s", this.annotationType, this, newNode.desc.replace('/', '.'))); insns.add(nullCheckSucceeded); extraStack.add(); @@ -676,20 +669,4 @@ public class RedirectInjector extends InvokeInjector { meta.injected++; } - private static String getGetArrayHandlerDescriptor(AbstractInsnNode varNode, Type returnType, Type fieldType) { - if (varNode != null && varNode.getOpcode() == Opcodes.ARRAYLENGTH) { - return Bytecode.generateDescriptor(Type.INT_TYPE, (Object[])RedirectInjector.getArrayArgs(fieldType, 0)); - } - return Bytecode.generateDescriptor(returnType, (Object[])RedirectInjector.getArrayArgs(fieldType, 1)); - } - - private static Type[] getArrayArgs(Type fieldType, int extraDimensions, Type... extra) { - int dimensions = fieldType.getDimensions() + extraDimensions; - Type[] args = new Type[dimensions + extra.length]; - for (int i = 0; i < args.length; i++) { - args[i] = i == 0 ? fieldType : i < dimensions ? Type.INT_TYPE : extra[dimensions - i]; - } - return args; - } - } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 1678b293..3cf6a7af 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -147,7 +147,7 @@ public class ModifyVariableInjector extends Injector { Context context = new Context(this.returnType, this.discriminator.isArgsOnly(), target, node.getCurrentTarget()); if (this.discriminator.printLVT()) { - this.printLocals(context); + this.printLocals(target, context); } String handlerDesc = Bytecode.getDescriptor(new Type[] { this.returnType }, this.returnType); @@ -178,17 +178,18 @@ public class ModifyVariableInjector extends Injector { /** * Pretty-print local variable information to stderr */ - private void printLocals(final Context context) { - SignaturePrinter handlerSig = new SignaturePrinter(this.methodNode.name, this.returnType, this.methodArgs, new String[] { "var" }); + private void printLocals(Target target, Context context) { + SignaturePrinter handlerSig = new SignaturePrinter(this.info.getMethodName(), this.returnType, this.methodArgs, new String[] { "var" }); handlerSig.setModifiers(this.methodNode); new PrettyPrinter() .kvWidth(20) .kv("Target Class", this.classNode.name.replace('/', '.')) .kv("Target Method", context.target.method.name) - .kv("Callback Name", this.methodNode.name) + .kv("Callback Name", this.info.getMethodName()) .kv("Capture Type", SignaturePrinter.getTypeName(this.returnType, false)) - .kv("Instruction", "%s %s", context.node.getClass().getSimpleName(), Bytecode.getOpcodeName(context.node.getOpcode())).hr() + .kv("Instruction", "[%d] %s %s", target.insns.indexOf(context.node), context.node.getClass().getSimpleName(), + Bytecode.getOpcodeName(context.node.getOpcode())).hr() .kv("Match mode", this.discriminator.isImplicit(context) ? "IMPLICIT (match single)" : "EXPLICIT (match by criteria)") .kv("Match ordinal", this.discriminator.getOrdinal() < 0 ? "any" : this.discriminator.getOrdinal()) .kv("Match index", this.discriminator.getIndex() < context.baseArgIndex ? "any" : this.discriminator.getIndex()) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index 4760ff22..1dffd05b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -35,7 +35,7 @@ import org.spongepowered.asm.util.asm.ElementNode; * defining the query parameters. They are used by injectors and other * components which need to identify a target element using a string. * - *

    Explicit Target Selectors

    + *

    Explicit Target Selectors

    * *

    Explicit Target Selectors are handled internally using * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the @@ -43,6 +43,13 @@ import org.spongepowered.asm.util.asm.ElementNode; */ public interface ITargetSelector { + /** + * Get the next target selector in this path (or null if this + * selector is the last selector in the chain. Called at recurse points in + * the subject in order to match against the child subject. + */ + public abstract ITargetSelector next(); + /** * Configure and return a modified version of this selector by consuming the * supplied arguments. Results from this method should be idempotent in 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 ceee6ed4..3f93fe2c 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 @@ -278,7 +278,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected Set parseTargets(String type) { List methods = Annotations.getValue(this.annotation, "method", false); if (methods == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", type, this.method.name)); + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", type, this.methodName)); } Set selectors = new LinkedHashSet(); @@ -287,14 +287,14 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin)); } catch (InvalidMemberDescriptorException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", type, - this.method.name, method, this.mixin.getReferenceMapper().getStatus())); + this.methodName, method, this.mixin.getReferenceMapper().getStatus())); } catch (TargetNotSupportedException ex) { throw new InvalidInjectionException(this, - String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.method.name, + String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.methodName, ex.getMessage())); } catch (InvalidSelectorException ex) { throw new InvalidInjectionException(this, - String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.method.name, + String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.methodName, ex.getMessage())); } } @@ -304,7 +304,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected List readInjectionPoints(String type) { List ats = Annotations.getValue(this.annotation, this.atKey, false); if (ats == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", type, this.method.name, + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", type, this.methodName, this.atKey)); } return ats; @@ -385,17 +385,17 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC if ((this.mixin.getEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) { throw new InvalidInjectionException(this, String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. %s%s", description, - this.method.name, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, refMapStatus, + this.methodName, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, refMapStatus, dynamicInfo)); } else if (this.injectedCallbackCount < this.requiredCallbackCount) { throw new InjectionError( String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded. %s%s", description, - this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, refMapStatus, + this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, refMapStatus, dynamicInfo)); } else if (this.injectedCallbackCount > this.maxCallbackCount) { throw new InjectionError( String.format("Critical injection failure: %s %s%s in %s failed injection check, %d succeeded of %d allowed.%s", - description, this.method.name, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, dynamicInfo)); + description, this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.maxCallbackCount, dynamicInfo)); } } @@ -524,7 +524,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC if (this.targets.size() == 0) { throw new InvalidInjectionException(this, String.format("%s annotation on %s could not find any targets matching %s in the target class %s. %s%s", - type, this.method.name, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + type, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index d1eb26bf..e4a932fb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -261,6 +261,11 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.unparsed = null; } + @Override + public ITargetSelector next() { + return null; // Not supported yet + } + @Override public String getOwner() { return this.owner; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java index 129e3ea4..b80ddb07 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java @@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.throwables; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.transformer.ActivityStack; import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException; /** @@ -43,31 +44,61 @@ public class InvalidInjectionException extends InvalidMixinException { this.info = null; } + public InvalidInjectionException(IMixinContext context, String message, ActivityStack activityContext) { + super(context, message, activityContext); + this.info = null; + } + public InvalidInjectionException(InjectionInfo info, String message) { super(info.getContext(), message); this.info = info; } + public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) { + super(info.getContext(), message, activityContext); + this.info = info; + } + public InvalidInjectionException(IMixinContext context, Throwable cause) { super(context, cause); this.info = null; } + public InvalidInjectionException(IMixinContext context, Throwable cause, ActivityStack activityContext) { + super(context, cause, activityContext); + this.info = null; + } + public InvalidInjectionException(InjectionInfo info, Throwable cause) { super(info.getContext(), cause); this.info = info; } + public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) { + super(info.getContext(), cause, activityContext); + this.info = info; + } + public InvalidInjectionException(IMixinContext context, String message, Throwable cause) { super(context, message, cause); this.info = null; } + public InvalidInjectionException(IMixinContext context, String message, Throwable cause, ActivityStack activityContext) { + super(context, message, cause, activityContext); + this.info = null; + } + public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) { super(info.getContext(), message, cause); this.info = info; } + public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) { + super(info.getContext(), message, cause, activityContext); + this.info = info; + } + public InjectionInfo getInjectionInfo() { return this.info; } 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 e6f2a013..457df09c 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -30,6 +30,7 @@ import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.asm.MethodNodeEx; /** * Information about a special mixin method such as an injector or accessor @@ -50,6 +51,11 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext { * Annotated method */ protected final MethodNode method; + + /** + * Original name of the method, if available + */ + protected final String methodName; /** * Mixin data @@ -61,6 +67,7 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext { this.method = method; this.annotation = annotation; this.classNode = mixin.getTargetClassNode(); + this.methodName = method instanceof MethodNodeEx ? ((MethodNodeEx)this.method).getOriginalName() : method.name; } /** @@ -101,5 +108,12 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext { public final MethodNode getMethod() { return this.method; } + + /** + * Get the original name of the method, if available + */ + public String getMethodName() { + return this.methodName; + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index ae53c0b9..141d4f2b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -69,6 +69,7 @@ import org.spongepowered.asm.service.IMixinService; 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.MethodNodeEx; import org.spongepowered.asm.util.perf.Profiler; import org.spongepowered.asm.util.perf.Profiler.Section; @@ -84,22 +85,10 @@ class MixinInfo implements Comparable, IMixinInfo { /** * A MethodNode in a mixin */ - class MixinMethodNode extends MethodNode { - - private final String originalName; + class MixinMethodNode extends MethodNodeEx { public MixinMethodNode(int access, String name, String desc, String signature, String[] exceptions) { - super(ASM.API_VERSION, access, name, desc, signature, exceptions); - this.originalName = name; - } - - @Override - public String toString() { - return String.format("%s%s", this.originalName, this.desc); - } - - public String getOriginalName() { - return this.originalName; + super(access, name, desc, signature, exceptions, MixinInfo.this); } public boolean isInjector() { @@ -121,10 +110,6 @@ class MixinInfo implements Comparable, IMixinInfo { public AnnotationNode getInjectorAnnotation() { return InjectionInfo.getInjectorAnnotation(MixinInfo.this, this); } - - public IMixinInfo getOwner() { - return MixinInfo.this; - } } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java index 038a8586..2c40ee97 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionClassExporter.java @@ -158,7 +158,7 @@ public class ExtensionClassExporter implements IExtension { File outputFile = new File(this.classExportDir, fileName + ".class"); outputFile.getParentFile().mkdirs(); try { - byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode); + byte[] bytecode = ExtensionClassExporter.getClassBytes(classNode, true); if (bytecode != null) { Files.write(bytecode, outputFile); } @@ -168,12 +168,22 @@ public class ExtensionClassExporter implements IExtension { return outputFile; } - private static byte[] getClassBytes(ClassNode classNode) { + private static byte[] getClassBytes(ClassNode classNode, boolean computeFrames) { byte[] bytes = null; try { - MixinClassWriter cw = new MixinClassWriter(ClassWriter.COMPUTE_FRAMES); + MixinClassWriter cw = new MixinClassWriter(computeFrames ? ClassWriter.COMPUTE_FRAMES : 0); classNode.accept(cw); bytes = cw.toByteArray(); + } catch (NegativeArraySizeException ex) { + // Try again with compute frames turned off, this gives us a better chance + // of successful export when the class is corrupt which - given we are + // exporting for debugging purposes - is worthwhile so that we have a + // the bytecode to inspect! + if (computeFrames) { + ExtensionClassExporter.logger.warn("Exporting class {} with COMPUTE_FRAMES failed! Trying a raw export.", classNode.name); + return ExtensionClassExporter.getClassBytes(classNode, false); + } + ex.printStackTrace(); } catch (Exception ex) { // well, damn ex.printStackTrace(); diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinInner.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinInner.java index 8eb18428..b9372f7b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinInner.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinInner.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.transformer.meta; -import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @@ -33,7 +32,7 @@ import java.lang.annotation.Target; * Decoration annotation used by the mixin inner class generator to mark inner * classes which have been generated from an existing inner class in a mixin */ -@Target(ElementType.TYPE) +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.CLASS) public @interface MixinInner { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java index b38aac7c..ebdf1985 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinMerged.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.transformer.meta; -import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @@ -36,7 +35,7 @@ import java.lang.annotation.Target; *

    Decoration annotation used by the mixin applicator to mark methods in a * class which have been added or overwritten by a mixin.

    */ -@Target({ ElementType.METHOD }) +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.RUNTIME) public @interface MixinMerged { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java index 1fa78680..a3c57ed5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinProxy.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.transformer.meta; -import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @@ -33,7 +32,7 @@ import java.lang.annotation.Target; * Decoration annotation used by postprocessor to mark methods which have had * their contents replaced with a proxy. */ -@Target({ ElementType.METHOD }) +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.RUNTIME) public @interface MixinProxy { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java index 7a5634cf..c24fe140 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/meta/MixinRenamed.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.transformer.meta; -import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @@ -35,7 +34,7 @@ import java.lang.annotation.Target; *

    Decoration annotation used by MixinInfo and MixinPreProcessor to mark * methods in a mixin which have been renamed prior to being merged.

    */ -@Target({ ElementType.METHOD }) +@Target({ /* No targets allowed */ }) @Retention(RetentionPolicy.RUNTIME) public @interface MixinRenamed { diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index 91c88b7b..e50725f7 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -257,10 +257,14 @@ public final class Annotations { * * @param method Source method * @param annotationClass Type of annotation to search for - * @param paramIndex Index of the parameter to fetch annotation for + * @param paramIndex Index of the parameter to fetch annotation for, or the + * method itself if less than zero * @return the annotation, or null if not present */ public static AnnotationNode getVisibleParameter(MethodNode method, Class annotationClass, int paramIndex) { + if (paramIndex < 0) { + return Annotations.getVisible(method, annotationClass); + } return Annotations.getParameter(method.visibleParameterAnnotations, Type.getDescriptor(annotationClass), paramIndex); } @@ -270,10 +274,14 @@ public final class Annotations { * * @param method Source method * @param annotationClass Type of annotation to search for - * @param paramIndex Index of the parameter to fetch annotation for + * @param paramIndex Index of the parameter to fetch annotation for, or the + * method itself if less than zero * @return the annotation, or null if not present */ public static AnnotationNode getInvisibleParameter(MethodNode method, Class annotationClass, int paramIndex) { + if (paramIndex < 0) { + return Annotations.getInvisible(method, annotationClass); + } return Annotations.getParameter(method.invisibleParameterAnnotations, Type.getDescriptor(annotationClass), paramIndex); } @@ -506,12 +514,16 @@ public final class Annotations { } int existingIndex = 0; - for (int pos = 0; pos < annotation.values.size() - 1; pos += 2) { - String keyName = annotation.values.get(pos).toString(); - if (key.equals(keyName)) { - existingIndex = pos + 1; - break; + if (annotation.values != null) { + for (int pos = 0; pos < annotation.values.size() - 1; pos += 2) { + String keyName = annotation.values.get(pos).toString(); + if (key.equals(keyName)) { + existingIndex = pos + 1; + break; + } } + } else { + annotation.values = new ArrayList(); } if (existingIndex > 0) { diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 091ff60a..10c6ed0f 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -183,13 +183,15 @@ public final class Bytecode { Opcodes.LCONST_0, Opcodes.LCONST_1, Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2, Opcodes.DCONST_0, Opcodes.DCONST_1, - Opcodes.BIPUSH, // 15 - Opcodes.SIPUSH, // 16 - Opcodes.LDC, // 17 + Opcodes.BIPUSH, // 15 + Opcodes.SIPUSH, // 16 + Opcodes.LDC, // 17 + Opcodes.CHECKCAST, // 18 + Opcodes.INSTANCEOF // 19 }; private static final Object[] CONSTANTS_VALUES = { - null, + Type.VOID_TYPE, Integer.valueOf(-1), Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5), Long.valueOf(0L), Long.valueOf(1L), @@ -538,7 +540,7 @@ public final class Bytecode { * argument or "this" */ public static int getFirstNonArgLocalIndex(MethodNode method) { - return Bytecode.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), (method.access & Opcodes.ACC_STATIC) == 0); + return Bytecode.getFirstNonArgLocalIndex(Type.getArgumentTypes(method.desc), !Bytecode.isStatic(method)); } /** @@ -565,15 +567,29 @@ public final class Bytecode { * @return size of the specified arguments array in terms of stack slots */ public static int getArgsSize(Type[] args) { + return Bytecode.getArgsSize(args, 0, args.length); + } + + /** + * Get the size of the specified args array in local variable terms (eg. + * doubles and longs take two spaces) using startIndex (inclusive) and + * endIndex (exclusive) to determine which arguments to process. + * + * @param args Method argument types as array + * @param startIndex Start index in the array, not related to arg size + * @param endIndex End index (exclusive) in the array, not related to size + * @return size of the specified arguments array in terms of stack slots + */ + public static int getArgsSize(Type[] args, int startIndex, int endIndex) { int size = 0; - - for (Type type : args) { - size += type.getSize(); + + for (int index = startIndex; index < args.length && index < endIndex; index++) { + size += args[index].getSize(); } - + return size; } - + /** * Injects appropriate LOAD opcodes into the supplied InsnList appropriate * for each entry in the args array starting at pos @@ -588,7 +604,8 @@ public final class Bytecode { /** * Injects appropriate LOAD opcodes into the supplied InsnList appropriate - * for each entry in the args array starting at start and ending at end + * for each entry in the args array starting at start (inclusive) and ending + * at end (inclusive) * * @param args Argument types * @param insns Instruction List to inject into @@ -601,7 +618,8 @@ public final class Bytecode { /** * Injects appropriate LOAD opcodes into the supplied InsnList appropriate - * for each entry in the args array starting at start and ending at end + * for each entry in the args array starting at start (inclusive) and ending + * at end (inclusive) * * @param args Argument types * @param insns Instruction List to inject into @@ -610,18 +628,17 @@ public final class Bytecode { * @param casts Type casts array */ public static void loadArgs(Type[] args, InsnList insns, int start, int end, Type[] casts) { - int pos = start, index = 0; + int pos = start; - for (Type type : args) { - insns.add(new VarInsnNode(type.getOpcode(Opcodes.ILOAD), pos)); + for (int index = 0; index < args.length; index++) { + insns.add(new VarInsnNode(args[index].getOpcode(Opcodes.ILOAD), pos)); if (casts != null && index < casts.length && casts[index] != null) { insns.add(new TypeInsnNode(Opcodes.CHECKCAST, casts[index].getInternalName())); } - pos += type.getSize(); + pos += args[index].getSize(); if (end >= start && pos >= end) { return; } - index++; } } @@ -646,6 +663,17 @@ public final class Bytecode { return labels; } + /** + * Generate a bytecode descriptor from the supplied types. + * + * @param returnType the method return type, can be null for + * void + * @param args argument types + */ + public static String generateDescriptor(Type returnType, Type... args) { + return Bytecode.generateDescriptor(returnType, (Object[])args); + } + /** * Generate a bytecode descriptor from the supplied tokens. Each token can * be a {@link Type}, a {@link Class} or otherwise is converted in-place by @@ -783,7 +811,7 @@ public final class Bytecode { * * @param insn constant instruction to process * @return the constant value or null if the value cannot be parsed - * (or is null) + * (null constant is returned as Type.VOID_TYPE) */ public static Object getConstant(AbstractInsnNode insn) { if (insn == null) { @@ -796,6 +824,11 @@ public final class Bytecode { return Integer.valueOf(value); } throw new IllegalArgumentException("IntInsnNode with invalid opcode " + insn.getOpcode() + " in getConstant"); + } else if (insn instanceof TypeInsnNode) { + if (insn.getOpcode() < Opcodes.CHECKCAST) { + return null; // Don't treat NEW and ANEWARRAY as constants + } + return Type.getObjectType(((TypeInsnNode)insn).desc); } int index = Ints.indexOf(Bytecode.CONSTANTS_ALL, insn.getOpcode()); @@ -806,8 +839,8 @@ public final class Bytecode { * Returns the {@link Type} of a particular constant instruction's payload * * @param insn constant instruction - * @return type of constant or null if it cannot be parsed (or is - * null) + * @return type of constant or null if it cannot be parsed ( + * null constant is returned as Type.VOID_TYPE) */ public static Type getConstantType(AbstractInsnNode insn) { if (insn == null) { @@ -828,6 +861,11 @@ public final class Bytecode { return Type.getType(Constants.CLASS_DESC); } throw new IllegalArgumentException("LdcInsnNode with invalid payload type " + cst.getClass() + " in getConstant"); + } else if (insn instanceof TypeInsnNode) { + if (insn.getOpcode() < Opcodes.CHECKCAST) { + return null; // Don't treat NEW and ANEWARRAY as constants + } + return Type.getType(Constants.CLASS_DESC); } int index = Ints.indexOf(Bytecode.CONSTANTS_ALL, insn.getOpcode()); diff --git a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java index 37f7dc6b..110dff30 100644 --- a/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java +++ b/src/main/java/org/spongepowered/asm/util/PrettyPrinter.java @@ -782,8 +782,8 @@ public class PrettyPrinter { public PrettyPrinter addWrapped(int width, String format, Object... args) { String indent = ""; String line = String.format(format, args).replace("\t", " "); - Matcher indentMatcher = Pattern.compile("^(\\s+)(.*)$").matcher(line); - if (indentMatcher.matches()) { + Matcher indentMatcher = Pattern.compile("^(\\s+)[^\\s]").matcher(line); + if (indentMatcher.find()) { indent = indentMatcher.group(1); } @@ -801,7 +801,7 @@ public class PrettyPrinter { List lines = new ArrayList(); while (line.length() > width) { - int wrapPoint = line.lastIndexOf(' ', width); + int wrapPoint = PrettyPrinter.lastBreakIndex(line, width); if (wrapPoint < 10) { wrapPoint = width; } @@ -817,6 +817,11 @@ public class PrettyPrinter { return lines; } + private static int lastBreakIndex(String line, int width) { + int lineBreakPos = line.lastIndexOf('\n', width); + return lineBreakPos > -1 ? lineBreakPos : Math.max(line.lastIndexOf(' ', width), line.lastIndexOf('\t', width)); + } + /** * Add a formatted key/value pair to the output * diff --git a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java index 37e7225c..400a6b86 100644 --- a/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java +++ b/src/main/java/org/spongepowered/asm/util/SignaturePrinter.java @@ -85,7 +85,15 @@ public class SignaturePrinter { public SignaturePrinter(String name, String desc) { this(name, Type.getReturnType(desc), Type.getArgumentTypes(desc)); } + + public SignaturePrinter(Type[] args) { + this(null, null, args); + } + public SignaturePrinter(Type returnType, Type[] args) { + this(null, returnType, args); + } + public SignaturePrinter(String name, Type returnType, Type[] args) { this.name = name; this.returnType = returnType; @@ -193,7 +201,8 @@ public class SignaturePrinter { */ @Override public String toString() { - return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(this.name), false, true).toString(); + String name = this.name != null ? this.name : "method"; + return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(name), false, true).toString(); } /** @@ -254,6 +263,17 @@ public class SignaturePrinter { } return sb; } + + /** + * Get the source code name for the specified type + * + * @param type Type to generate a friendly name for + * @return String representation of the specified type, eg "int" for an + * integer primitive or "String" for java.lang.String + */ + public static String getTypeName(Type type) { + return SignaturePrinter.getTypeName(type, false, true); + } /** * Get the source code name for the specified type @@ -277,6 +297,9 @@ public class SignaturePrinter { * integer primitive or "String" for java.lang.String */ public static String getTypeName(Type type, boolean box, boolean fullyQualified) { + if (type == null) { + return "{null?}"; + } switch (type.getSort()) { case Type.VOID: return box ? "Void" : "void"; case Type.BOOLEAN: return box ? "Boolean" : "boolean"; diff --git a/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java b/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java new file mode 100644 index 00000000..f8869159 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/MethodNodeEx.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.asm.util.asm; + +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +/** + * MethodNode with some extra convenience functionality + */ +public class MethodNodeEx extends MethodNode { + + private final IMixinInfo owner; + + private final String originalName; + + public MethodNodeEx(int access, String name, String descriptor, String signature, String[] exceptions, IMixinInfo owner) { + super(ASM.API_VERSION, access, name, descriptor, signature, exceptions); + this.originalName = name; + this.owner = owner; + } + + @Override + public String toString() { + return String.format("%s%s", this.originalName, this.desc); + } + + public String getQualifiedName() { + return String.format("%s::%s", this.owner.getName(), this.originalName); + } + + public String getOriginalName() { + return this.originalName; + } + + public IMixinInfo getOwner() { + return this.owner; + } + +} From da74418eca58339031c480ac8764897f387dd034 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 24 Oct 2019 16:28:34 +0100 Subject: [PATCH 07/16] Update hotswapper agent for 0.8 --- .../spongepowered/tools/agent/MixinAgent.java | 5 ++- .../tools/agent/MixinAgentClassLoader.java | 25 +++++++++-- .../MixinPreProcessorStandard.java | 12 +++-- .../asm/mixin/transformer/MixinProcessor.java | 30 ++----------- .../mixin/transformer/MixinTransformer.java | 44 ++++++++++++++++--- .../asm/mixin/transformer/ext/IHotSwap.java | 8 ++-- .../MixinTransformationHandler.java | 1 + 7 files changed, 79 insertions(+), 46 deletions(-) diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java index 1587ff46..367d02e3 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgent.java @@ -182,8 +182,8 @@ public class MixinAgent implements IHotSwap { } @Override - public void registerTargetClass(String name, byte[] bytecode) { - MixinAgent.classLoader.addTargetClass(name, bytecode); + public void registerTargetClass(String name, ClassNode classNode) { + MixinAgent.classLoader.addTargetClass(name, classNode); } /** @@ -228,4 +228,5 @@ public class MixinAgent implements IHotSwap { public static void agentmain(String arg, Instrumentation instrumentation) { MixinAgent.init(instrumentation); } + } diff --git a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java index 192ac448..d93d575a 100644 --- a/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java +++ b/src/agent/java/org/spongepowered/tools/agent/MixinAgentClassLoader.java @@ -33,6 +33,7 @@ import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.util.Constants; @@ -78,10 +79,23 @@ class MixinAgentClassLoader extends ClassLoader { * Registers the bytecode for a class targeted by a mixin * * @param name Name of the target clas - * @param bytecode Bytecode of the target class + * @param classNode ASM tree node of the target class */ - void addTargetClass(String name, byte[] bytecode) { - this.targets.put(name, bytecode); + void addTargetClass(String name, ClassNode classNode) { + synchronized (this.targets) { + if (this.targets.containsKey(name)) { + return; + } + try { + ClassWriter cw = new ClassWriter(0); + classNode.accept(cw); + this.targets.put(name, cw.toByteArray()); + } catch (Exception ex) { + MixinAgentClassLoader.logger.error("Error storing original class bytecode for {} in mixin hotswap agent. {}: {}", + name, ex.getClass().getName(), ex.getMessage()); + MixinAgentClassLoader.logger.debug(ex); + } + } } /** @@ -101,7 +115,9 @@ class MixinAgentClassLoader extends ClassLoader { * @return Original bytecode */ byte[] getOriginalTargetBytecode(String name) { - return this.targets.get(name); + synchronized (this.targets) { + return this.targets.get(name); + } } /** @@ -127,4 +143,5 @@ class MixinAgentClassLoader extends ClassLoader { cw.visitEnd(); return cw.toByteArray(); } + } 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 a10a06ea..d54a9617 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPreProcessorStandard.java @@ -518,10 +518,14 @@ class MixinPreProcessorStandard { String type = method.isSynthetic() ? "synthetic" : "@Unique"; if (Bytecode.getVisibility(mixinMethod).ordinal() < Visibility.PUBLIC.ordinal()) { - String uniqueName = context.getUniqueName(mixinMethod, false); - MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming {} method {}{} to {} in {}", - type, mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); - mixinMethod.name = method.conform(uniqueName); + if (method.isConformed()) { + mixinMethod.name = method.getName(); + } else { + String uniqueName = context.getUniqueName(mixinMethod, false); + MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming {} method {}{} to {} in {}", + type, mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin); + mixinMethod.name = method.conform(uniqueName); + } return false; } diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java index 66cfb19b..87f000f4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinProcessor.java @@ -24,7 +24,6 @@ */ package org.spongepowered.asm.mixin.transformer; -import java.lang.reflect.Constructor; import java.text.DecimalFormat; import java.util.*; @@ -132,8 +131,6 @@ public class MixinProcessor { } } - - private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent"; /** * Log all the things @@ -210,36 +207,16 @@ public class MixinProcessor { /** * ctor */ - MixinProcessor(MixinEnvironment environment, Extensions extensions) { + MixinProcessor(MixinEnvironment environment, Extensions extensions, IHotSwap hotSwapper) { this.lock = this.service.getReEntranceLock(); this.extensions = extensions; - this.hotSwapper = this.initHotSwapper(environment); + this.hotSwapper = hotSwapper; this.postProcessor = new MixinPostProcessor(this.sessionId); this.profiler = MixinEnvironment.getProfiler(); } - private IHotSwap initHotSwapper(MixinEnvironment environment) { - if (!environment.getOption(Option.HOT_SWAP)) { - return null; - } - - try { - MixinProcessor.logger.info("Attempting to load Hot-Swap agent"); - @SuppressWarnings("unchecked") - Class clazz = - (Class)Class.forName(MixinProcessor.MIXIN_AGENT_CLASS); - Constructor ctor = clazz.getDeclaredConstructor(MixinProcessor.class); - return ctor.newInstance(this); - } catch (Throwable th) { - MixinProcessor.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}", - th.getClass().getSimpleName(), th.getMessage()); - } - - return null; - } - /** * Force-load all classes targetted by mixins but not yet applied * @@ -345,8 +322,7 @@ public class MixinProcessor { } if (this.hotSwapper != null) { - // TODO hotswapper -// this.hotSwapper.registerTargetClass(transformedName, basicClass); + this.hotSwapper.registerTargetClass(name, targetClassNode); } try { diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java index 01e21624..7d10ac0e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTransformer.java @@ -24,13 +24,16 @@ */ package org.spongepowered.asm.mixin.transformer; +import java.lang.reflect.Constructor; import java.util.List; import org.objectweb.asm.tree.ClassNode; import org.spongepowered.asm.mixin.MixinEnvironment; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.mixin.transformer.ext.IExtensionRegistry; +import org.spongepowered.asm.mixin.transformer.ext.IHotSwap; import org.spongepowered.asm.transformers.TreeTransformer; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.asm.ASM; @@ -40,10 +43,22 @@ import org.spongepowered.asm.util.asm.ASM; */ class MixinTransformer extends TreeTransformer implements IMixinTransformer { + private static final String MIXIN_AGENT_CLASS = "org.spongepowered.tools.agent.MixinAgent"; + + /** + * Synthetic class registry + */ + private final SyntheticClassRegistry syntheticClassRegistry; + /** * Transformer extensions */ private final Extensions extensions; + + /** + * Hotswap agent, if available + */ + private final IHotSwap hotSwapper; /** * Mixin processor which actually manages application of mixins @@ -55,11 +70,6 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { */ private final MixinClassGenerator generator; - /** - * Synthetic class registry - */ - private final SyntheticClassRegistry syntheticClassRegistry; - public MixinTransformer() { MixinEnvironment environment = MixinEnvironment.getCurrentEnvironment(); @@ -73,13 +83,35 @@ class MixinTransformer extends TreeTransformer implements IMixinTransformer { this.syntheticClassRegistry = new SyntheticClassRegistry(); this.extensions = new Extensions(this.syntheticClassRegistry); + + this.hotSwapper = this.initHotSwapper(environment); - this.processor = new MixinProcessor(environment, this.extensions); + this.processor = new MixinProcessor(environment, this.extensions, this.hotSwapper); this.generator = new MixinClassGenerator(environment, this.extensions); DefaultExtensions.create(environment, this.extensions, this.syntheticClassRegistry); } + private IHotSwap initHotSwapper(MixinEnvironment environment) { + if (!environment.getOption(Option.HOT_SWAP)) { + return null; + } + + try { + MixinProcessor.logger.info("Attempting to load Hot-Swap agent"); + @SuppressWarnings("unchecked") + Class clazz = + (Class)Class.forName(MixinTransformer.MIXIN_AGENT_CLASS); + Constructor ctor = clazz.getDeclaredConstructor(IMixinTransformer.class); + return ctor.newInstance(this); + } catch (Throwable th) { + MixinProcessor.logger.info("Hot-swap agent could not be loaded, hot swapping of mixins won't work. {}: {}", + th.getClass().getSimpleName(), th.getMessage()); + } + + return null; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.transformer.IMixinTransformer * #getExtensions() diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java index 7f72f773..14117a39 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/IHotSwap.java @@ -24,6 +24,8 @@ */ package org.spongepowered.asm.mixin.transformer.ext; +import org.objectweb.asm.tree.ClassNode; + /** * Interface to allow the hot-swap agent to be loaded on-demand */ @@ -42,11 +44,11 @@ public interface IHotSwap { * Registers a class targeted by at least one mixin. * *

    This is used to rollback the target class to a state before the - * mixin's were applied.

    + * mixins were applied.

    * * @param name Name of the class - * @param bytecode Bytecode of the class before mixin's have been applied + * @param classNode ASM tree of the class before mixins have been applied */ - public abstract void registerTargetClass(String name, byte[] bytecode); + public abstract void registerTargetClass(String name, ClassNode classNode); } diff --git a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java b/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java index 2c10fd4a..5f7193f5 100644 --- a/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java +++ b/src/modlauncher/java/org/spongepowered/asm/mixin/transformer/MixinTransformationHandler.java @@ -108,4 +108,5 @@ public class MixinTransformationHandler implements IClassProcessor { } return transformer.transformClass(environment, classType.getClassName(), classNode); } + } From 9b51cc79233aaddc7e741c966648ae0888578306 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 24 Oct 2019 17:54:29 +0100 Subject: [PATCH 08/16] Use expect/require values for targets, allowing injectors to be optional Fixes #297 --- .../mixin/injection/struct/InjectionInfo.java | 64 +++++++++++-------- .../struct/ModifyConstantInjectionInfo.java | 4 +- .../asm/mixin/struct/SpecialMethodInfo.java | 7 ++ 3 files changed, 48 insertions(+), 27 deletions(-) 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 3f93fe2c..23e962ff 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 @@ -204,6 +204,11 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * Map of lists of nodes enumerated by calling {@link #prepare} */ protected final Map> targetNodes = new LinkedHashMap>(); + + /** + * Number of target methods identified by the injection points + */ + protected int targetCount = 0; /** * Bytecode injector @@ -267,18 +272,18 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC return; } - String type = "@" + Bytecode.getSimpleName(this.annotation); - List injectionPoints = this.readInjectionPoints(type); - this.findMethods(this.parseTargets(type), type); - this.parseInjectionPoints(injectionPoints); + List injectionPoints = this.readInjectionPoints(); this.parseRequirements(); + this.findMethods(this.parseTargets()); + this.parseInjectionPoints(injectionPoints); this.injector = this.parseInjector(this.annotation); } - protected Set parseTargets(String type) { + protected Set parseTargets() { List methods = Annotations.getValue(this.annotation, "method", false); if (methods == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", type, this.methodName)); + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing method name", + this.annotationType, this.methodName)); } Set selectors = new LinkedHashSet(); @@ -286,26 +291,26 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC try { selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin)); } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", type, - this.methodName, method, this.mixin.getReferenceMapper().getStatus())); + throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", + this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus())); } catch (TargetNotSupportedException ex) { throw new InvalidInjectionException(this, - String.format("%s annotation on %s specifies a target class '%s', which is not supported", type, this.methodName, - ex.getMessage())); + String.format("%s annotation on %s specifies a target class '%s', which is not supported", + this.annotationType, this.methodName, ex.getMessage())); } catch (InvalidSelectorException ex) { throw new InvalidInjectionException(this, - String.format("%s annotation on %s is decorated with an invalid selector: %s", type, this.methodName, + String.format("%s annotation on %s is decorated with an invalid selector: %s", this.annotationType, this.methodName, ex.getMessage())); } } return selectors; } - protected List readInjectionPoints(String type) { + protected List readInjectionPoints() { List ats = Annotations.getValue(this.annotation, this.atKey, false); if (ats == null) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", type, this.methodName, - this.atKey)); + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing '%s' value(s)", + this.annotationType, this.methodName, this.atKey)); } return ats; } @@ -384,14 +389,14 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC String dynamicInfo = this.getDynamicInfo(); if ((this.mixin.getEnvironment().getOption(Option.DEBUG_INJECTORS) && this.injectedCallbackCount < this.expectedCallbackCount)) { throw new InvalidInjectionException(this, - String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. %s%s", description, - this.methodName, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, refMapStatus, - dynamicInfo)); + String.format("Injection validation failed: %s %s%s in %s expected %d invocation(s) but %d succeeded. Scanned %d target(s). %s%s", + description, this.methodName, this.method.desc, this.mixin, this.expectedCallbackCount, this.injectedCallbackCount, + this.targetCount, refMapStatus, dynamicInfo)); } else if (this.injectedCallbackCount < this.requiredCallbackCount) { throw new InjectionError( - String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded. %s%s", description, - this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, refMapStatus, - dynamicInfo)); + String.format("Critical injection failure: %s %s%s in %s failed injection check, (%d/%d) succeeded. Scanned %d target(s). %s%s", + description, this.methodName, this.method.desc, this.mixin, this.injectedCallbackCount, this.requiredCallbackCount, + this.targetCount, refMapStatus, dynamicInfo)); } else if (this.injectedCallbackCount > this.maxCallbackCount) { throw new InjectionError( String.format("Critical injection failure: %s %s%s in %s failed injection check, %d succeeded of %d allowed.%s", @@ -485,9 +490,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC * Finds methods in the target class which match searchFor * * @param selectors members to search for - * @param type annotation type */ - private void findMethods(Set selectors, String type) { + private void findMethods(Set selectors) { this.targets.clear(); // When remapping refmap is enabled this implies we are in a development @@ -521,10 +525,20 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC } } - if (this.targets.size() == 0) { + this.targetCount = this.targets.size(); + if (this.targetCount > 0) { + return; + } + + if ((this.mixin.getEnvironment().getOption(Option.DEBUG_INJECTORS) && this.expectedCallbackCount > 0)) { throw new InvalidInjectionException(this, - String.format("%s annotation on %s could not find any targets matching %s in the target class %s. %s%s", - type, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + String.format("Injection validation failed: %s annotation on %s could not find any targets matching %s in %s. %s%s", + this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), + this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); + } else if (this.requiredCallbackCount > 0) { + throw new InvalidInjectionException(this, + String.format("Critical injection failure: %s annotation on %s could not find any targets matching %s in %s. %s%s", + this.annotationType, this.methodName, InjectionInfo.namesOf(selectors), this.mixin.getTarget(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java index 859851c9..818b76ef 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -55,8 +55,8 @@ public class ModifyConstantInjectionInfo extends InjectionInfo { } @Override - protected List readInjectionPoints(String type) { - List ats = super.readInjectionPoints(type); + protected List readInjectionPoints() { + List ats = super.readInjectionPoints(); if (ats.isEmpty()) { AnnotationNode c = new AnnotationNode(ModifyConstantInjectionInfo.CONSTANT_ANNOTATION_CLASS); c.visit("log", Boolean.TRUE); 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 457df09c..409a7e3a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/SpecialMethodInfo.java @@ -30,6 +30,7 @@ import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.asm.MethodNodeEx; /** @@ -42,6 +43,11 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext { */ protected final AnnotationNode annotation; + /** + * Human-readable annotation type + */ + protected final String annotationType; + /** * Class */ @@ -66,6 +72,7 @@ public abstract class SpecialMethodInfo implements IInjectionPointContext { this.mixin = mixin; this.method = method; 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; } From 887354154c6b8544f9700014463fa00310625e63 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 24 Oct 2019 18:21:32 +0100 Subject: [PATCH 09/16] Put SuppressWarnings tokens into an enum for documentation/consistency --- .../tools/obfuscation/AnnotatedMixin.java | 4 +- .../AnnotatedMixinElementHandler.java | 18 +++-- .../AnnotatedMixinElementHandlerInjector.java | 6 +- ...AnnotatedMixinElementHandlerOverwrite.java | 6 +- .../tools/obfuscation/AnnotatedMixins.java | 11 +-- .../tools/obfuscation/SuppressedBy.java | 75 +++++++++++++++++++ .../interfaces/IMessagerSuppressible.java | 8 +- 7 files changed, 105 insertions(+), 23 deletions(-) create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index fa6ebde3..9261fa91 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import javax.annotation.processing.Messager; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; @@ -44,6 +43,7 @@ import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor. import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjector; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerOverwrite.AnnotatedElementOverwrite; +import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator.ValidationPass; @@ -68,7 +68,7 @@ class AnnotatedMixin { /** * Messager */ - private final Messager messager; + private final IMessagerSuppressible messager; /** * Type handle provider diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index b32dc0f5..53827a82 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -374,7 +374,7 @@ abstract class AnnotatedMixinElementHandler { this.ap.printMessage(Kind.ERROR, ex.getMessage(), method, annotation.asMirror()); } } catch (InvalidConstraintException ex) { - this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation.asMirror(), "constraints"); + this.ap.printMessage(Kind.WARNING, ex.getMessage(), method, annotation.asMirror(), SuppressedBy.CONSTRAINTS); } } @@ -421,7 +421,7 @@ abstract class AnnotatedMixinElementHandler { this.validateMethodVisibility(method, annotation, type, target, targetMethod); } } else if (!merge) { - this.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation, "target"); + this.printMessage(Kind.WARNING, "Cannot find target for " + type + " method in " + target, method, annotation, SuppressedBy.TARGET); } } } @@ -436,9 +436,11 @@ abstract class AnnotatedMixinElementHandler { Visibility visMethod = TypeUtils.getVisibility(method); String visibility = "visibility of " + visTarget + " method in " + target; if (visTarget.ordinal() > visMethod.ordinal()) { - this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation, "visibility"); + this.printMessage(Kind.WARNING, visMethod + " " + type + " method cannot reduce " + visibility, method, annotation, + SuppressedBy.VISIBILITY); } else if (visTarget == Visibility.PRIVATE && visMethod.ordinal() > visTarget.ordinal()) { - this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation, "visibility"); + this.printMessage(Kind.WARNING, visMethod + " " + type + " method will upgrade " + visibility, method, annotation, + SuppressedBy.VISIBILITY); } } @@ -469,7 +471,8 @@ abstract class AnnotatedMixinElementHandler { } if (targetField == null) { - this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, annotation.asMirror(), "target"); + this.ap.printMessage(Kind.WARNING, "Cannot find target for " + type + " field in " + target, field, annotation.asMirror(), + SuppressedBy.TARGET); } } } @@ -493,12 +496,13 @@ abstract class AnnotatedMixinElementHandler { MethodHandle targetMethod = target.findMethod(nameRef.getName(), signature); if (targetMethod == null) { - this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(), "target"); + this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(), + SuppressedBy.TARGET); } } } - private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation, String suppressedBy) { + private void printMessage(Kind kind, String msg, Element e, AnnotationHandle annotation, SuppressedBy suppressedBy) { if (annotation == null) { this.ap.printMessage(kind, msg, e, suppressedBy); } else { diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 5966ba34..6f94957a 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -294,7 +294,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); if (remapped.isEmpty()) { this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), - elem.getAnnotation().asMirror(), "mapping"); + elem.getAnnotation().asMirror(), SuppressedBy.MAPPING); return; } @@ -346,7 +346,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); if (obfFieldData.isEmpty()) { this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, "mapping"); + errorsOn, SuppressedBy.MAPPING); return; } this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData); @@ -355,7 +355,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (obfMethodData.isEmpty()) { if (targetMember.getOwner() == null || !targetMember.getOwner().startsWith("java/lang/")) { this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, "mapping"); + errorsOn, SuppressedBy.MAPPING); return; } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java index 1905baf7..ced0cb81 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerOverwrite.java @@ -86,16 +86,16 @@ class AnnotatedMixinElementHandlerOverwrite extends AnnotatedMixinElementHandler String javadoc = this.ap.getJavadocProvider().getJavadoc(elem.getElement()); if (javadoc == null) { - this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", elem.getElement(), "overwrite"); + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing javadoc comment", elem.getElement(), SuppressedBy.OVERWRITE); return; } if (!javadoc.toLowerCase(Locale.ROOT).contains("@author")) { - this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", elem.getElement(), "overwrite"); + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @author tag", elem.getElement(), SuppressedBy.OVERWRITE); } if (!javadoc.toLowerCase(Locale.ROOT).contains("@reason")) { - this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", elem.getElement(), "overwrite"); + this.ap.printMessage(overwriteErrorKind, "@Overwrite is missing an @reason tag", elem.getElement(), SuppressedBy.OVERWRITE); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index fbe9bf62..fdbfee26 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -513,11 +513,11 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider return annotation.getBoolean("remap", mixinClass.remap()); } - private static boolean shouldSuppress(Element element, String suppressedBy) { + private static boolean shouldSuppress(Element element, SuppressedBy suppressedBy) { if (element == null || suppressedBy == null) { return false; } - if (AnnotationHandle.of(element, SuppressWarnings.class).getList().contains(suppressedBy)) { + if (AnnotationHandle.of(element, SuppressWarnings.class).getList().contains(suppressedBy.getToken())) { return true; } return AnnotatedMixins.shouldSuppress(element.getEnclosingElement(), suppressedBy); @@ -545,7 +545,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider * Print a message to the AP messager */ @Override - public void printMessage(Kind kind, CharSequence msg, Element element, String suppressedBy) { + public void printMessage(Kind kind, CharSequence msg, Element element, SuppressedBy suppressedBy) { if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) { this.processingEnv.getMessager().printMessage(kind, msg, element); } @@ -563,7 +563,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider * Print a message to the AP messager */ @Override - public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, String suppressedBy) { + public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, SuppressedBy suppressedBy) { if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) { this.processingEnv.getMessager().printMessage(kind, msg, element, annotation); } @@ -581,7 +581,8 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider * Print a message to the AP messager */ @Override - public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value, String suppressedBy) { + public void printMessage(Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value, + SuppressedBy suppressedBy) { if (kind != Kind.WARNING || !AnnotatedMixins.shouldSuppress(element, suppressedBy)) { this.processingEnv.getMessager().printMessage(kind, msg, element, annotation, value); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java new file mode 100644 index 00000000..8fdcc74d --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java @@ -0,0 +1,75 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation; + +/** + * A centralised list of tokens supported by the AP for use in + * {@link SuppressWarnings} annotations. Collected here mainly for + * self-documentation purposes. + */ +public enum SuppressedBy { + + /** + * Suppress warnings for constraint violations + */ + CONSTRAINTS("constraints"), + + /** + * Suppress warnings about overwrite visibility upgrading/downgrading target + * visibility + */ + VISIBILITY("visibility"), + + /** + * Suppress warnings when an injector target cannot be found + */ + TARGET("target"), + + /** + * Suppress warnings when a class, method or field mapping cannot be located + */ + MAPPING("mapping"), + + /** + * Suppress warnings for when an @Overwrite method is missing + * javadoc, or author or reason tags + */ + OVERWRITE("overwrite"); + + private final String token; + + private SuppressedBy(String token) { + this.token = token; + } + + /** + * Get the string token which is used in the {@link SuppressWarnings} + * annotation + */ + public String getToken() { + return this.token; + } + +} diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java index 4295e676..9f4f8500 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/interfaces/IMessagerSuppressible.java @@ -30,6 +30,8 @@ import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.tools.Diagnostic; +import org.spongepowered.tools.obfuscation.SuppressedBy; + /** * An extended {@link Messager} which supports messages that can be suppressed * using the standard Java {@link SuppressWarnings} annotation. @@ -46,7 +48,7 @@ public interface IMessagerSuppressible extends Messager { * @param suppressedBy the {@link SuppressWarnings} value which will silence * this message */ - void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, String suppressedBy); + void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, SuppressedBy suppressedBy); /** * Prints a message of the specified kind at the location of the @@ -59,7 +61,7 @@ public interface IMessagerSuppressible extends Messager { * @param suppressedBy the {@link SuppressWarnings} value which will silence * this message */ - void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, String suppressedBy); + void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, SuppressedBy suppressedBy); /** * Prints a message of the specified kind at the location of the @@ -74,7 +76,7 @@ public interface IMessagerSuppressible extends Messager { * @param suppressedBy the {@link SuppressWarnings} value which will silence * this message */ - void printMessage(Diagnostic.Kind kind,CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v, String suppressedBy); + void printMessage(Diagnostic.Kind kind,CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v, SuppressedBy suppressedBy); } From 10af60bb2640a210de4aba2b22515e926c323536 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 24 Oct 2019 18:34:42 +0100 Subject: [PATCH 10/16] Allow warning about targets in the default package to be suppressed Fixes #338 --- .../tools/obfuscation/AnnotatedMixin.java | 20 +++++++++++++------ .../tools/obfuscation/SuppressedBy.java | 10 ++++++++-- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 9261fa91..27a50530 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -215,21 +215,22 @@ class AnnotatedMixin { // Private targets, referenced by name try { - for (String privateTarget : this.annotation.getList("targets")) { - TypeHandle type = this.typeProvider.getTypeHandle(privateTarget); + for (String softTarget : this.annotation.getList("targets")) { + TypeHandle type = this.typeProvider.getTypeHandle(softTarget); if (this.targets.contains(type)) { continue; } if (this.virtual) { - type = this.typeProvider.getSimulatedHandle(privateTarget, this.mixin.asType()); + type = this.typeProvider.getSimulatedHandle(softTarget, this.mixin.asType()); } else if (type == null) { - this.printMessage(Kind.ERROR, "Mixin target " + privateTarget + " could not be found", this); + this.printMessage(Kind.ERROR, "Mixin target " + softTarget + " could not be found", this); return null; } else if (type.isPublic()) { - this.printMessage(Kind.WARNING, "Mixin target " + privateTarget + " is public and must be specified in value", this); + SuppressedBy suppressedBy = (type.getPackage().isUnnamed()) ? SuppressedBy.DEFAULT_PACKAGE : null; + this.printMessage(Kind.WARNING, "Mixin target " + softTarget + " is public and must be specified in value", this, suppressedBy); return null; } - this.addSoftTarget(type, privateTarget); + this.addSoftTarget(type, softTarget); if (primaryTarget == null) { primaryTarget = type; } @@ -251,6 +252,13 @@ class AnnotatedMixin { private void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin) { this.messager.printMessage(kind, msg, this.mixin, this.annotation.asMirror()); } + + /** + * Print a suppressible message to the AP messager + */ + private void printMessage(Kind kind, CharSequence msg, AnnotatedMixin mixin, SuppressedBy suppressedBy) { + this.messager.printMessage(kind, msg, this.mixin, this.annotation.asMirror(), suppressedBy); + } private void addSoftTarget(TypeHandle type, String reference) { ObfuscationData obfClassData = this.obf.getDataProvider().getObfClass(type); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java index 8fdcc74d..b16f75d4 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SuppressedBy.java @@ -43,7 +43,7 @@ public enum SuppressedBy { VISIBILITY("visibility"), /** - * Suppress warnings when an injector target cannot be found + * Suppress warnings when an injector target cannot be found */ TARGET("target"), @@ -56,7 +56,13 @@ public enum SuppressedBy { * Suppress warnings for when an @Overwrite method is missing * javadoc, or author or reason tags */ - OVERWRITE("overwrite"); + OVERWRITE("overwrite"), + + /** + * Suppress warnings when a mixin target specified by name is located in the + * default package + */ + DEFAULT_PACKAGE("default-package"); private final String token; From 6efc4a563f12ca7ac4c5592b5f3146fefcf40d8c Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 28 Oct 2019 01:31:49 +0000 Subject: [PATCH 11/16] Fix incorrect format string in tsrg mapping writer --- .../tools/obfuscation/mapping/fg3/MappingWriterTSrg.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java index ece47054..d759f59c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mapping/fg3/MappingWriterTSrg.java @@ -66,7 +66,7 @@ public class MappingWriterTSrg extends MappingWriterSrg { @Override protected String formatFieldMapping(Pair field) { - return String.format("%s %s %s %s", field.from.getOwner(), field.from.getSimpleName(), field.to.getSimpleName()); + return String.format("%s %s %s", field.from.getOwner(), field.from.getSimpleName(), field.to.getSimpleName()); } @Override From dbe3a7e94d25ad2f7bb09028545c5bd02e43eb4d Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Mon, 28 Oct 2019 17:13:37 +0000 Subject: [PATCH 12/16] Suppress AP warnings for known-unmappable packages such as java. & sun. --- .../AnnotatedMixinElementHandlerInjector.java | 13 +-- .../obfuscation/ext/SpecialPackages.java | 79 +++++++++++++++++++ 2 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 6f94957a..afd76ceb 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -45,6 +45,7 @@ import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorExcep import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; +import org.spongepowered.tools.obfuscation.ext.SpecialPackages; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor.CompilerEnvironment; import org.spongepowered.tools.obfuscation.interfaces.IReferenceManager; @@ -292,7 +293,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler String desc = member.toCtorDesc(); MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); - if (remapped.isEmpty()) { + if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) { this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), elem.getAnnotation().asMirror(), SuppressedBy.MAPPING); return; @@ -345,19 +346,21 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (targetMember.isField()) { ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); if (obfFieldData.isEmpty()) { - this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, SuppressedBy.MAPPING); + if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) { + this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), + errorsOn, SuppressedBy.MAPPING); + } return; } this.obf.getReferenceManager().addFieldMapping(this.classRef, reference, targetMember, obfFieldData); } else { ObfuscationData obfMethodData = this.obf.getDataProvider().getObfMethodRecursive(targetMember); if (obfMethodData.isEmpty()) { - if (targetMember.getOwner() == null || !targetMember.getOwner().startsWith("java/lang/")) { + if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) { this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(), errorsOn, SuppressedBy.MAPPING); - return; } + return; } this.obf.getReferenceManager().addMethodMapping(this.classRef, reference, targetMember, obfMethodData); } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java b/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java new file mode 100644 index 00000000..ed5068ba --- /dev/null +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java @@ -0,0 +1,79 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package org.spongepowered.tools.obfuscation.ext; + +import java.util.HashSet; +import java.util.Set; + +/** + * Centralised registry of packages with special handling by the AP. This is + * public and centralised + */ +public final class SpecialPackages { + + private static final Set suppressWarningsForPackages = new HashSet(); + + static { + SpecialPackages.addExcludedPackage("java."); + SpecialPackages.addExcludedPackage("sun."); + SpecialPackages.addExcludedPackage("com.sun."); + } + + private SpecialPackages() { + } + + /** + * Add a package to exclude from remapping warnings. This only suppresses + * warnings if a mapping is not found and does not attempt to short-circuit + * the mapping process. Thus if a mapping is present for the element in + * question then the behaviour is preserved. Adding a package here simply + * suppresses warnings if no mapping is found. + * + * @param packageName Package name, including trailing period or slash + */ + public static final void addExcludedPackage(String packageName) { + String internalName = packageName.replace('.', '/'); + if (!internalName.endsWith("/")) { + internalName += "/"; + } + SpecialPackages.suppressWarningsForPackages.add(internalName); + } + + /** + * Check whether a package is in the exclusion set. + * + * @param internalName Internal class or package name + * @return true if warnings for the supplied package should be suppressed + */ + public static boolean isExcludedPackage(String internalName) { + for (String prefix : SpecialPackages.suppressWarningsForPackages) { + if (internalName.startsWith(prefix)) { + return true; + } + } + return false; + } + +} From 4570a8213e12c43908b3c99ed06b276102bec9bd Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 31 Oct 2019 19:33:08 +0000 Subject: [PATCH 13/16] Support for INSTANCEOF opcode in Redirect and ModifyConstant injectors Fixes #336 --- .../obfuscation/ext/SpecialPackages.java | 1 + .../asm/mixin/injection/Redirect.java | 37 +++++ .../invoke/ModifyConstantInjector.java | 28 +++- .../injection/invoke/RedirectInjector.java | 155 +++++++++++++++--- 4 files changed, 190 insertions(+), 31 deletions(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java b/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java index ed5068ba..08b9bbb7 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ext/SpecialPackages.java @@ -37,6 +37,7 @@ public final class SpecialPackages { static { SpecialPackages.addExcludedPackage("java."); + SpecialPackages.addExcludedPackage("javax."); SpecialPackages.addExcludedPackage("sun."); SpecialPackages.addExcludedPackage("com.sun."); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java index 39309c28..6df4b87f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Redirect.java @@ -250,6 +250,43 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * int dy) * * + *

    instanceof Redirect Mode

    + * + *

    An instanceof check is a boolean operation where an object on the + * stack is compared with a class literal compiled directly into the bytecode. + * The check can be redirected in one of two ways: logic redirection or class + * type redirection. For the following example code:

    + * + *
    if (reference instanceof Foo) {
    + * + *

    To perform a logic redirection, use a handler with the following + * signature returning boolean:

    + * + *
    public boolean onInstanceOf(Object reference, Class clFoo) {
    + *    return reference instanceof ADifferentClass;
    + *}
    + * + *

    Note that the entire check is moved into the redirect method, and the + * boolean return value is used in place of the previous instanceof + * check. To perform a class type redirection instead, construct + * your handler as follows:

    + * + *
    public Class onInstanceOf(Object reference, Class clFoo) {
    + *    return ADifferentClass.class;
    + *}
    + * + *

    Note that this results in the injected code being less efficient, because + * the instanceof opcode is replaced with discrete code similar to + * reference != null && yourClass.isAssignableFrom(reference.getClass()) in + * the target method body.

    + * + *

    The arguments to an instanceof redirect handler must always be + * Object, Class even if the variable type is known. This is + * because the type of variable on the stack cannot be determined without + * relatively expensive analysis, which is redundant given the redirect + * handler's role. If you need to cast-down the reference then you should do so + * inside your handler method.

    + * *

    A note on static modifiers for handler methods

    * *

    In general, when declaring a redirect handler the static modifier diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java index f851544f..3f60bb30 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -77,27 +77,37 @@ public class ModifyConstantInjector extends RedirectInjector { } AbstractInsnNode targetNode = node.getCurrentTarget(); + if (targetNode instanceof TypeInsnNode) { + this.checkTargetModifiers(target, false); + this.injectTypeConstantModifier(target, (TypeInsnNode)targetNode); + return; + } + if (targetNode instanceof JumpInsnNode) { this.checkTargetModifiers(target, false); this.injectExpandedConstantModifier(target, (JumpInsnNode)targetNode); return; } - if (targetNode instanceof TypeInsnNode) { - // TODO inject at type constant - throw new InvalidInjectionException(this.info, "Inject at TypeInsnNode not implemented"); - } - if (Bytecode.isConstant(targetNode)) { this.checkTargetModifiers(target, false); this.injectConstantModifier(target, targetNode); return; } - throw new InvalidInjectionException(this.info, this.annotationType + " annotation is targetting an invalid insn in " - + target + " in " + this); + throw new InvalidInjectionException(this.info, String.format("%s annotation is targetting an invalid insn in %s in %s", + this.annotationType, target, this)); } + private void injectTypeConstantModifier(Target target, TypeInsnNode typeNode) { + int opcode = typeNode.getOpcode(); + if (opcode != Opcodes.INSTANCEOF) { + throw new InvalidInjectionException(this.info, String.format("%s annotation does not support %s insn in %s in %s", + this.annotationType, Bytecode.getOpcodeName(opcode), target, this)); + } + this.injectAtInstanceOf(target, typeNode); + } + /** * Injects a constant modifier at an implied-zero * @@ -107,8 +117,8 @@ public class ModifyConstantInjector extends RedirectInjector { private void injectExpandedConstantModifier(Target target, JumpInsnNode jumpNode) { int opcode = jumpNode.getOpcode(); if (opcode < Opcodes.IFLT || opcode > Opcodes.IFLE) { - throw new InvalidInjectionException(this.info, this.annotationType + " annotation selected an invalid opcode " - + Bytecode.getOpcodeName(opcode) + " in " + target + " in " + this); + throw new InvalidInjectionException(this.info, String.format("%s annotation selected an invalid opcode %s in %s in %s", + this.annotationType, Bytecode.getOpcodeName(opcode), target, this)); } Extension extraStack = target.extendStack(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index 90175d46..a8aa0f47 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -31,15 +31,7 @@ import java.util.Set; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.FieldInsnNode; -import org.objectweb.asm.tree.InsnList; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.TypeInsnNode; -import org.objectweb.asm.tree.VarInsnNode; +import org.objectweb.asm.tree.*; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; @@ -55,6 +47,7 @@ import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionExceptio import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.SignaturePrinter; import com.google.common.collect.ObjectArrays; import com.google.common.primitives.Ints; @@ -95,6 +88,9 @@ import com.google.common.primitives.Ints; */ public class RedirectInjector extends InvokeInjector { + private static final String GET_CLASS_METHOD = "getClass"; + private static final String IS_ASSIGNABLE_FROM_METHOD = "isAssignableFrom"; + private static final String NPE = "java/lang/NullPointerException"; private static final String KEY_NOMINATORS = "nominators"; @@ -333,13 +329,20 @@ public class RedirectInjector extends InvokeInjector { return; } - if (node.getCurrentTarget() instanceof TypeInsnNode && node.getCurrentTarget().getOpcode() == Opcodes.NEW) { - if (!this.isStatic && target.isStatic) { - throw new InvalidInjectionException(this.info, String.format( - "non-static callback method %s has a static target which is not supported", this)); + if (node.getCurrentTarget() instanceof TypeInsnNode) { + int opcode = node.getCurrentTarget().getOpcode(); + if (opcode == Opcodes.NEW) { + if (!this.isStatic && target.isStatic) { + throw new InvalidInjectionException(this.info, String.format( + "non-static callback method %s has a static target which is not supported", this)); + } + this.injectAtConstructor(target, node); + return; + } else if (opcode == Opcodes.INSTANCEOF) { + this.checkTargetModifiers(target, false); + this.injectAtInstanceOf(target, node); + return; } - this.injectAtConstructor(target, node); - return; } throw new InvalidInjectionException(this.info, String.format("%s annotation on is targetting an invalid insn in %s in %s", @@ -652,13 +655,7 @@ public class RedirectInjector extends InvokeInjector { // Do a null-check following the redirect to ensure that the handler // didn't return null. Since NEW cannot return null, this would break // the contract of the target method! - LabelNode nullCheckSucceeded = new LabelNode(); - insns.add(new InsnNode(Opcodes.DUP)); - insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded)); - this.throwException(insns, RedirectInjector.NPE, String.format("%s constructor handler %s returned null for %s", - this.annotationType, this, newNode.desc.replace('/', '.'))); - insns.add(nullCheckSucceeded); - extraStack.add(); + this.doNullCheck(insns, extraStack, "constructor handler", newNode.desc.replace('/', '.')); } else { // Result is not assigned, so just pop it from the operand stack insns.add(new InsnNode(Opcodes.POP)); @@ -669,4 +666,118 @@ public class RedirectInjector extends InvokeInjector { meta.injected++; } + protected void injectAtInstanceOf(Target target, InjectionNode node) { + this.injectAtInstanceOf(target, (TypeInsnNode)node.getCurrentTarget()); + } + + protected void injectAtInstanceOf(Target target, TypeInsnNode typeNode) { + if (this.returnType.getSort() == Type.BOOLEAN) { + this.redirectInstanceOf(target, typeNode, false); + return; + } + + if (this.returnType.equals(Type.getType(Constants.CLASS_DESC))) { + this.redirectInstanceOf(target, typeNode, true); + return; + } + + // This syntax is neat but the inconsistency might be a step too far +// if (this.returnType.getSort() >= Type.ARRAY) { +// this.modifyInstanceOfType(target, typeNode); +// return; +// } + + throw new InvalidInjectionException(this.info, String.format("%s on %s has an invalid signature. Found unexpected return type %s. INSTANCEOF" + + " handler expects (Ljava/lang/Object;Ljava/lang/Class;)Z or (Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Class;", + this.annotationType, this, SignaturePrinter.getTypeName(this.returnType))); + } + + private void redirectInstanceOf(Target target, TypeInsnNode typeNode, boolean dynamic) { + Extension extraStack = target.extendStack(); + final InsnList insns = new InsnList(); + InjectorData handler = new InjectorData(target, "instanceof handler", false /* do not coerce args */); + this.validateParams(handler, this.returnType, Type.getType(Constants.OBJECT_DESC), Type.getType(Constants.CLASS_DESC)); + + if (dynamic) { + insns.add(new InsnNode(Opcodes.DUP)); + extraStack.add(); + } + + if (!this.isStatic) { + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + insns.add(new InsnNode(Opcodes.SWAP)); + extraStack.add(); + } + + // Add the class type from the original instanceof check + insns.add(new LdcInsnNode(Type.getObjectType(typeNode.desc))); + extraStack.add(); + + if (handler.captureTargetArgs > 0) { + this.pushArgs(target.arguments, insns, target.getArgIndices(), 0, handler.captureTargetArgs, extraStack); + } + + AbstractInsnNode champion = this.invokeHandler(insns); + + if (dynamic) { + // First null-check the class value returned by the handler, if it's + // null then the rest is going to go badly + this.doNullCheck(insns, extraStack, "instanceof handler", "class type"); + + // Now do a null-check on the reference and isAssignableFrom check + this.checkIsAssignableFrom(insns, extraStack); + } + + target.replaceNode(typeNode, champion, insns); + extraStack.apply(); + } + + private void checkIsAssignableFrom(final InsnList insns, Extension extraStack) { + LabelNode objectIsNull = new LabelNode(); + LabelNode checkComplete = new LabelNode(); + + // Swap the values (we duped the ref above) and check for null. If + // the reference is null, load FALSE per the contract of instanceof + insns.add(new InsnNode(Opcodes.SWAP)); + insns.add(new InsnNode(Opcodes.DUP)); + extraStack.add(); + insns.add(new JumpInsnNode(Opcodes.IFNULL, objectIsNull)); + // If it's not null, call getClass on the reference and then use + // isAssignableFrom on the result + insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Constants.OBJECT, RedirectInjector.GET_CLASS_METHOD, + "()" + Constants.CLASS_DESC, false)); + insns.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Constants.CLASS, RedirectInjector.IS_ASSIGNABLE_FROM_METHOD, + "(" + Constants.CLASS_DESC + ")Z", false)); + insns.add(new JumpInsnNode(Opcodes.GOTO, checkComplete)); + + insns.add(objectIsNull); + insns.add(new InsnNode(Opcodes.POP)); // remove ref + insns.add(new InsnNode(Opcodes.POP)); // remove class + insns.add(new InsnNode(Opcodes.ICONST_0)); + insns.add(checkComplete); + extraStack.add(); + } + +// private void modifyInstanceOfType(Target target, TypeInsnNode typeNode) { +// if (this.methodArgs.length > 0) { +// throw new InvalidInjectionException(this.info, String.format("%s on %s has an invalid signature. Found %d unexpected additional method" +// + "arguments, expected 0. INSTANCEOF handler expects ()Lthe/replacement/Type; or (Ljava/lang/Object;Ljava/lang/Class;)Z", +// this.annotationType, this, this.methodArgs.length)); +// } +// +// // Already know that returnType is an object or array so no need to check again +// typeNode.desc = this.returnType.getInternalName(); +// this.info.addCallbackInvocation(this.methodNode); +// } + + private void doNullCheck(InsnList insns, Extension extraStack, String type, String value) { + LabelNode nullCheckSucceeded = new LabelNode(); + insns.add(new InsnNode(Opcodes.DUP)); + insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded)); + this.throwException(insns, RedirectInjector.NPE, String.format("%s %s %s returned null for %s", + this.annotationType, type, this, value)); + insns.add(nullCheckSucceeded); + extraStack.add(); + } + } From 11e71bc3f2b481f1eca7b48f91a1262da9a7e29e Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Thu, 31 Oct 2019 19:33:48 +0000 Subject: [PATCH 14/16] Some build-script tweaks for maven publishing --- build.gradle | 53 ++++++++++++++++++---------------------------------- 1 file changed, 18 insertions(+), 35 deletions(-) diff --git a/build.gradle b/build.gradle index 0c03b85d..8e7f1d9a 100644 --- a/build.gradle +++ b/build.gradle @@ -107,15 +107,15 @@ dependencies { def guava = 'com.google.guava:guava:21.0' // from mc1.12 onwards def log4j2 = 'org.apache.logging.log4j:log4j-core:2.0-beta9' - compile guava - compile log4j2 + implementation guava + implementation log4j2 compile 'com.google.code.gson:gson:2.2.4' if (Float.parseFloat(asmVersion) < 6) { compile "org.ow2.asm:asm-debug-all:$asmVersion" } - compile "org.ow2.asm:asm-tree:$asmVersion" - compile "org.ow2.asm:asm-commons:$asmVersion" - compile "org.ow2.asm:asm-util:$asmVersion" + implementation "org.ow2.asm:asm-tree:$asmVersion" + implementation "org.ow2.asm:asm-commons:$asmVersion" + implementation "org.ow2.asm:asm-util:$asmVersion" thinJar "org.ow2.asm:asm-tree:$asmVersion" thinJar "org.ow2.asm:asm-util:$asmVersion" @@ -131,21 +131,25 @@ dependencies { // AP extension example exampleCompile configurations.compile + exampleImplementation configurations.implementation // Maven FTP deployerJars 'org.apache.maven.wagon:wagon-ftp:2.7' // Fernflower decompiler fernflowerCompile configurations.compile + fernflowerImplementation configurations.implementation fernflowerCompile 'org.jetbrains.java.decompiler:fernflower:sponge-SNAPSHOT' // LegacyLauncher service launchwrapperCompile configurations.compile + launchwrapperImplementation configurations.implementation launchwrapperCompile ('net.minecraft:launchwrapper:1.11') { exclude module: 'lwjgl' } modlauncherCompile configurations.compile + modlauncherImplementation configurations.implementation modlauncherCompile 'net.sf.jopt-simple:jopt-simple:5.0.4' modlauncherCompile "org.ow2.asm:asm-tree:$modlauncherAsmVersion" modlauncherCompile "org.ow2.asm:asm-commons:$modlauncherAsmVersion" @@ -156,6 +160,7 @@ dependencies { // agent agentCompile configurations.compile + agentImplementation configurations.implementation // asm bridge bridgeCompile log4j2 @@ -298,12 +303,12 @@ build.dependsOn(shadowJar) if (project.doSignJar) { // Define signjar task task signJar() { - inputs.files(jar.outputs) - outputs.files jar.outputs.files.collect { + inputs.files(stagingJar.outputs) + outputs.files stagingJar.outputs.files.collect { new File(it.parent, it.name.replace('-unsigned', '')) } doLast { - jar.outputs.files.each { + stagingJar.outputs.files.each { ant.signjar( alias: project.keyStoreCert, jar: it, @@ -312,7 +317,8 @@ if (project.doSignJar) { storepass: project.keyStoreSecret, keypass: project.keyStoreSecret, tsaurl: project.timestampAuthority, - preservelastmodified: 'true' + preservelastmodified: 'true', + verbose: true ) } } @@ -351,25 +357,15 @@ artifacts { archives javadocJar } -ext.excludePomDeps = [ - 'fernflower', - 'jarjar', - 'hamcrest-library', - 'junit', - 'mockito-core', - 'mixin-asm-debug-all', - 'log4j-core' -] - uploadArchives { repositories { mavenDeployer { configuration = configurations.deployerJars - if (project.hasProperty("chRepo")) { - repository(url: project.chRepo) { - authentication(userName: project.chUsername, password: project.chPassword) + if (project.hasProperty("spongeRepo")) { + repository(url: project.spongeRepo) { + authentication(userName: project.spongeUsername, password: project.spongePassword) } } @@ -402,20 +398,7 @@ uploadArchives { } } } - whenConfigured { - dependencies = dependencies.findAll { - !it.artifactId.matches(excludePomDeps.join('|')) - } - } } } } } - -install.repositories.mavenInstaller.pom { - whenConfigured { - dependencies = dependencies.findAll { - !it.artifactId.matches(excludePomDeps.join('|')) - } - } -} From dd89e232154f930939ddebdf7e4d841dcb9e917b Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 2 Nov 2019 15:03:45 +0000 Subject: [PATCH 15/16] Check mixingradle version in AP so we can notify if mixin ver is ahead --- .../tools/obfuscation/AnnotatedMixins.java | 24 ++++++++++++++++++- .../tools/obfuscation/SupportedOptions.java | 1 + 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java index fdbfee26..c831b057 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixins.java @@ -59,6 +59,7 @@ import org.spongepowered.asm.mixin.Overwrite; 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.tools.obfuscation.interfaces.IJavadocProvider; import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor; import org.spongepowered.tools.obfuscation.interfaces.IMixinValidator; @@ -83,6 +84,8 @@ import com.google.common.collect.ImmutableList.Builder; final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider, ITypeHandleProvider, IJavadocProvider { private static final String MAPID_SYSTEM_PROPERTY = "mixin.target.mapid"; + + private static final String RECOMMENDED_MIXINGRADLE_VERSION = "0.7"; /** * Singleton instances for each ProcessingEnvironment @@ -143,6 +146,7 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider this.processingEnv = processingEnv; this.printMessage(Kind.NOTE, "SpongePowered MIXIN Annotation Processor Version=" + MixinBootstrap.VERSION); + this.checkPluginVersion(this.getOption(SupportedOptions.PLUGIN_VERSION)); this.targets = this.initTargetMap(); this.obf = new ObfuscationManager(this); @@ -152,10 +156,28 @@ final class AnnotatedMixins implements IMixinAnnotationProcessor, ITokenProvider new ParentValidator(this), new TargetValidator(this) ); - + this.initTokenCache(this.getOption(SupportedOptions.TOKENS)); } + /** + * If MixinGradle is in use, check the version. This will allow us to notify + * the user if the version of MixinGradle is out of date relative to the + * Mixin library version + */ + private void checkPluginVersion(String version) { + if (version == null) { + return; + } + + VersionNumber pluginVersion = VersionNumber.parse(version); + VersionNumber recommendedVersion = VersionNumber.parse(AnnotatedMixins.RECOMMENDED_MIXINGRADLE_VERSION); + if (pluginVersion.compareTo(recommendedVersion) < 0) { + this.printMessage(Kind.WARNING, String.format("MixinGradle version %s is out of date. Update to the recommended version %s", + pluginVersion, recommendedVersion)); + } + } + protected TargetMap initTargetMap() { TargetMap targets = TargetMap.create(System.getProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY)); System.setProperty(AnnotatedMixins.MAPID_SYSTEM_PROPERTY, targets.getSessionId()); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java index ac296681..e7d1de21 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/SupportedOptions.java @@ -46,6 +46,7 @@ public final class SupportedOptions { public static final String DEFAULT_OBFUSCATION_ENV = "defaultObfuscationEnv"; public static final String DEPENDENCY_TARGETS_FILE = "dependencyTargetsFile"; public static final String MAPPING_TYPES = "mappingTypes"; + public static final String PLUGIN_VERSION = "pluginVersion"; private SupportedOptions() {} From f9e19c32f4af07479c6256e6c3a19d398f838979 Mon Sep 17 00:00:00 2001 From: Mumfrey Date: Sat, 2 Nov 2019 15:29:44 +0000 Subject: [PATCH 16/16] More injector refactoring, allow capture target args in ModifyVariable --- .../asm/mixin/injection/ModifyVariable.java | 8 +- .../asm/mixin/injection/code/Injector.java | 274 +++++++++++++++++- .../injection/invoke/InvokeInjector.java | 274 +----------------- .../modify/LocalVariableDiscriminator.java | 3 +- .../modify/ModifyVariableInjector.java | 18 +- .../org/spongepowered/asm/util/Bytecode.java | 8 +- 6 files changed, 288 insertions(+), 297 deletions(-) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java index 0e055a30..83acc4fe 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/ModifyVariable.java @@ -63,6 +63,10 @@ import org.spongepowered.asm.util.ConstraintParser.Constraint; * type exists in the target LVT, then capture will succeed. However, if more * than one variable of the required type is encountered in the LVT then an * {@link InvalidInjectionException} is thrown.

    + * + *

    Like other injectors, the callback signature can optionally include the + * target method arguments by simply appending them to the handler method + * signature.

    */ @Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @@ -87,9 +91,7 @@ public @interface ModifyVariable { /** * An {@link At} annotation which describes the {@link InjectionPoint} in - * the target method. The specified {@link InjectionPoint} must only - * return {@link org.objectweb.asm.tree.MethodInsnNode} instances - * and an exception will be thrown if this is not the case. + * the target method. * * @return {@link At} which identifies the target method invocation */ diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index dd8f6bd4..197189a6 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.injection.code; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -37,19 +38,15 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.InsnList; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.LdcInsnNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.*; import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.RestrictTargetLevel; +import org.spongepowered.asm.mixin.injection.invoke.RedirectInjector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; +import org.spongepowered.asm.mixin.injection.struct.Target.Extension; import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -57,9 +54,13 @@ import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.transformer.ClassInfo; import org.spongepowered.asm.mixin.transformer.ClassInfo.Traversal; import org.spongepowered.asm.mixin.transformer.ClassInfo.TypeLookup; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.SignaturePrinter; import org.spongepowered.asm.util.Bytecode.DelegateInitialiser; +import com.google.common.collect.ObjectArrays; + /** * Base class for bytecode injectors */ @@ -102,6 +103,66 @@ public abstract class Injector { } + /** + * Redirection data bundle base. No this isn't meant to be pretty, it's a + * way of passing a bunch of state around the injector without having dumb + * method signatures. + */ + public static class InjectorData { + + /** + * Redirect target + */ + public final Target target; + + /** + * Mutable description. The bundle is be passed to different types of + * handler and the handler decorates the bundle with a description of + * the type of injection, purely for use in error messages. + */ + public String description; + + /** + * When passing through {@link RedirectInjector#validateParams} this + * switch determines whether coercion is supported for both the primary + * handler args and captured target args, or for target args only. + */ + public boolean allowCoerceArgs; + + /** + * Number of arguments to capture from the target, determined by the + * number of extra args on the handler method + */ + public int captureTargetArgs = 0; + + /** + * True if the method itself is decorated with {@link Coerce} and the + * return type is coerced. Instructs the injector to add a CHECKCAST + * following the handler. + */ + public boolean coerceReturnType = false; + + public InjectorData(Target target) { + this(target, "handler"); + } + + public InjectorData(Target target, String description) { + this(target, description, true); + } + + public InjectorData(Target target, String description, boolean allowCoerceArgs) { + this.target = target; + this.description = description; + this.allowCoerceArgs = allowCoerceArgs; + } + + @Override + public String toString() { + return this.description; + } + + } + /** * Log more things */ @@ -351,7 +412,204 @@ public abstract class Injector { this.info.addCallbackInvocation(handler); return insn; } + + /** + * @param args handler arguments + * @param insns InsnList to inject insns into + * @param argMap Mapping of args to local variables + * @return injected insn node + */ + protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) { + return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length); + } + /** + * @param args handler arguments + * @param insns InsnList to inject insns into + * @param argMap Mapping of args to local variables + * @param startArg Starting arg to consume + * @param endArg Ending arg to consume + * @return injected insn node + */ + protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) { + if (!this.isStatic) { + insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); + } + this.pushArgs(args, insns, argMap, startArg, endArg); + return this.invokeHandler(insns); + } + + /** + * Store args on the stack starting at the end and working back to position + * specified by start, return the generated argMap + * + * @param target target method + * @param args argument types + * @param insns instruction list to generate insns into + * @param start Starting index + * @return the generated argmap + */ + protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) { + int[] argMap = target.generateArgMap(args, start); + this.storeArgs(args, insns, argMap, start, args.length); + return argMap; + } + + /** + * Store args on the stack to their positions allocated based on argMap + * + * @param args argument types + * @param insns instruction list to generate insns into + * @param argMap generated argmap containing local indices for all args + * @param start Starting index + * @param end Ending index + */ + protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { + for (int arg = end - 1; arg >= start; arg--) { + insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg])); + } + } + + /** + * Load args onto the stack from their positions allocated in argMap + * + * @param args argument types + * @param insns instruction list to generate insns into + * @param argMap generated argmap containing local indices for all args + * @param start Starting index + * @param end Ending index + */ + protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { + this.pushArgs(args, insns, argMap, start, end, null); + } + + /** + * Load args onto the stack from their positions allocated in argMap + * + * @param args argument types + * @param insns instruction list to generate insns into + * @param argMap generated argmap containing local indices for all args + * @param start Starting index + * @param end Ending index + */ + protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end, Extension extension) { + for (int arg = start; arg < end && arg < args.length; arg++) { + insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg])); + if (extension != null) { + extension.add(args[arg].getSize()); + } + } + } + + /** + * Collects all the logic from old validateParams/checkDescriptor so that we + * can consistently apply coercion logic to method params, and also provide + * more detailed errors when something doesn't line up. + * + *

    The supplied return type and argument list will be verified first. Any + * arguments on the handler beyond the base arguments consume arguments from + * the target. The flag allowCoerceArgs on the redirect + * instance determines whether coercion is supported for the base args and + * return type, coercion is always allowed for captured target args.

    + * + *

    Following validation, the captureTargetArgs and + * coerceReturnType values will be set on the bundle and the + * calling injector function should adjust itself accordingly.

    + * + * @param injector Data bundle for the injector + * @param returnType Return type for the handler, must not be null + * @param args Array of handler args, must not be null + */ + protected final void validateParams(InjectorData injector, Type returnType, Type... args) { + String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext()); + int argIndex = 0; + try { + injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs); + + for (Type arg : args) { + if (arg != null) { + this.checkCoerce(argIndex, arg, description, injector.allowCoerceArgs); + argIndex++; + } + } + + if (argIndex == this.methodArgs.length) { + return; + } + + for (int targetArg = 0; targetArg < injector.target.arguments.length && argIndex < this.methodArgs.length; targetArg++, argIndex++) { + this.checkCoerce(argIndex, injector.target.arguments[targetArg], description, true); + injector.captureTargetArgs++; + } + } catch (InvalidInjectionException ex) { + String expected = this.methodArgs.length > args.length + ? Bytecode.generateDescriptor(returnType, ObjectArrays.concat(args, injector.target.arguments, Type.class)) + : Bytecode.generateDescriptor(returnType, args); + throw new InvalidInjectionException(this.info, String.format("%s. Handler signature: %s Expected signature: %s", ex.getMessage(), + this.methodNode.desc, expected)); + } + + if (argIndex < this.methodArgs.length) { + Type[] extraArgs = Arrays.copyOfRange(this.methodArgs, argIndex, this.methodArgs.length); + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Found %d unexpected additional method arguments: %s", + description, this.methodArgs.length - argIndex, new SignaturePrinter(extraArgs).getFormattedArgs())); + } + } + + /** + * Called inside {@link #validateParams} but can also be used directly. This + * method checks whether the supplied type is compatible with the specified + * handler argument, apply coercion logic where necessary. + * + * @param index Handler argument index, pass in a negative value (by + * convention -1) to specify handler return type + * @param toType Desired type based on the injector contract + * @param description human-readable description of the handler method, used + * in raised exception + * @param allowCoercion True if coercion logic can be applied to this + * argument, false to only allow a precise match + * @return false if the argument matched perfectly, true + * if coercion is required for the argument + */ + protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) { + Type fromType = index < 0 ? this.returnType : this.methodArgs[index]; + if (index >= this.methodArgs.length) { + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Not enough arguments: expected argument type %s at index %d", + description, SignaturePrinter.getTypeName(toType), index)); + } + + AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index); + boolean isReturn = index < 0; + String argType = isReturn ? "return" : "argument"; + Object argIndex = isReturn ? "" : " at index " + index; + + if (fromType.equals(toType)) { + if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex, + SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType)); + } + return false; + } + + if (coerce == null || !allowCoercion) { + String coerceWarning = coerce != null ? ". @Coerce not allowed here" : ""; + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Found unexpected %s type %s%s, expected %s%s", description, argType, + SignaturePrinter.getTypeName(fromType), argIndex, SignaturePrinter.getTypeName(toType), coerceWarning)); + } + + boolean canCoerce = Injector.canCoerce(fromType, toType); + if (!canCoerce) { + throw new InvalidInjectionException(this.info, String.format( + "%s has an invalid signature. Cannot @Coerce %s type %s%s to %s", description, argType, + SignaturePrinter.getTypeName(toType), argIndex, SignaturePrinter.getTypeName(fromType))); + } + + return true; + } + /** * Throw an exception. The exception class must have a string which takes a * string argument diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java index a8e77817..203b0f7f 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/InvokeInjector.java @@ -24,95 +24,20 @@ */ package org.spongepowered.asm.mixin.injection.invoke; -import java.util.Arrays; import java.util.List; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.VarInsnNode; -import org.spongepowered.asm.mixin.MixinEnvironment.Option; -import org.spongepowered.asm.mixin.injection.Coerce; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.code.Injector; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; -import org.spongepowered.asm.mixin.injection.struct.Target.Extension; +import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; -import org.spongepowered.asm.util.Annotations; -import org.spongepowered.asm.util.Bytecode; -import org.spongepowered.asm.util.SignaturePrinter; - -import com.google.common.collect.ObjectArrays; /** * Base class for injectors which inject at method invokes */ public abstract class InvokeInjector extends Injector { - - /** - * Redirection data bundle base. No this isn't meant to be pretty, it's a - * way of passing a bunch of state around the injector without having dumb - * method signatures. - */ - static class InjectorData { - - /** - * Redirect target - */ - final Target target; - - /** - * Mutable description. The bundle is be passed to different types of - * handler and the handler decorates the bundle with a description of - * the type of injection, purely for use in error messages. - */ - String description; - - /** - * When passing through {@link RedirectInjector#validateParams} this - * switch determines whether coercion is supported for both the primary - * handler args and captured target args, or for target args only. - */ - boolean allowCoerceArgs; - - /** - * Number of arguments to capture from the target, determined by the - * number of extra args on the handler method - */ - int captureTargetArgs = 0; - - /** - * True if the method itself is decorated with {@link Coerce} and the - * return type is coerced. Instructs the injector to add a CHECKCAST - * following the handler. - */ - boolean coerceReturnType = false; - - InjectorData(Target target) { - this(target, "handler"); - } - - InjectorData(Target target, String description) { - this(target, description, true); - } - - InjectorData(Target target, String description, boolean allowCoerceArgs) { - this.target = target; - this.description = description; - this.allowCoerceArgs = allowCoerceArgs; - } - - @Override - public String toString() { - return this.description; - } - - } /** * @param info Information about this injection @@ -165,201 +90,4 @@ public abstract class InvokeInjector extends Injector { */ protected abstract void injectAtInvoke(Target target, InjectionNode node); - /** - * @param args handler arguments - * @param insns InsnList to inject insns into - * @param argMap Mapping of args to local variables - * @return injected insn node - */ - protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap) { - return this.invokeHandlerWithArgs(args, insns, argMap, 0, args.length); - } - - /** - * @param args handler arguments - * @param insns InsnList to inject insns into - * @param argMap Mapping of args to local variables - * @param startArg Starting arg to consume - * @param endArg Ending arg to consume - * @return injected insn node - */ - protected AbstractInsnNode invokeHandlerWithArgs(Type[] args, InsnList insns, int[] argMap, int startArg, int endArg) { - if (!this.isStatic) { - insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); - } - this.pushArgs(args, insns, argMap, startArg, endArg); - return this.invokeHandler(insns); - } - - /** - * Store args on the stack starting at the end and working back to position - * specified by start, return the generated argMap - * - * @param target target method - * @param args argument types - * @param insns instruction list to generate insns into - * @param start Starting index - * @return the generated argmap - */ - protected int[] storeArgs(Target target, Type[] args, InsnList insns, int start) { - int[] argMap = target.generateArgMap(args, start); - this.storeArgs(args, insns, argMap, start, args.length); - return argMap; - } - - /** - * Store args on the stack to their positions allocated based on argMap - * - * @param args argument types - * @param insns instruction list to generate insns into - * @param argMap generated argmap containing local indices for all args - * @param start Starting index - * @param end Ending index - */ - protected void storeArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { - for (int arg = end - 1; arg >= start; arg--) { - insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ISTORE), argMap[arg])); - } - } - - /** - * Load args onto the stack from their positions allocated in argMap - * - * @param args argument types - * @param insns instruction list to generate insns into - * @param argMap generated argmap containing local indices for all args - * @param start Starting index - * @param end Ending index - */ - protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end) { - this.pushArgs(args, insns, argMap, start, end, null); - } - - /** - * Load args onto the stack from their positions allocated in argMap - * - * @param args argument types - * @param insns instruction list to generate insns into - * @param argMap generated argmap containing local indices for all args - * @param start Starting index - * @param end Ending index - */ - protected void pushArgs(Type[] args, InsnList insns, int[] argMap, int start, int end, Extension extension) { - for (int arg = start; arg < end && arg < args.length; arg++) { - insns.add(new VarInsnNode(args[arg].getOpcode(Opcodes.ILOAD), argMap[arg])); - if (extension != null) { - extension.add(args[arg].getSize()); - } - } - } - - /** - * Collects all the logic from old validateParams/checkDescriptor so that we - * can consistently apply coercion logic to method params, and also provide - * more detailed errors when something doesn't line up. - * - *

    The supplied return type and argument list will be verified first. Any - * arguments on the handler beyond the base arguments consume arguments from - * the target. The flag allowCoerceArgs on the redirect - * instance determines whether coercion is supported for the base args and - * return type, coercion is always allowed for captured target args.

    - * - *

    Following validation, the captureTargetArgs and - * coerceReturnType values will be set on the bundle and the - * calling injector function should adjust itself accordingly.

    - * - * @param injector Data bundle for the injector - * @param returnType Return type for the handler, must not be null - * @param args Array of handler args, must not be null - */ - protected final void validateParams(InjectorData injector, Type returnType, Type... args) { - String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext()); - int argIndex = 0; - try { - injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs); - - for (Type arg : args) { - if (arg != null) { - this.checkCoerce(argIndex, arg, description, injector.allowCoerceArgs); - argIndex++; - } - } - - if (argIndex == this.methodArgs.length) { - return; - } - - for (int targetArg = 0; targetArg < injector.target.arguments.length && argIndex < this.methodArgs.length; targetArg++, argIndex++) { - this.checkCoerce(argIndex, injector.target.arguments[targetArg], description, true); - injector.captureTargetArgs++; - } - } catch (InvalidInjectionException ex) { - String expected = this.methodArgs.length > args.length - ? Bytecode.generateDescriptor(returnType, ObjectArrays.concat(args, injector.target.arguments, Type.class)) - : Bytecode.generateDescriptor(returnType, args); - throw new InvalidInjectionException(this.info, String.format("%s. Handler signature: %s Expected signature: %s", ex.getMessage(), - this.methodNode.desc, expected)); - } - - if (argIndex < this.methodArgs.length) { - Type[] extraArgs = Arrays.copyOfRange(this.methodArgs, argIndex, this.methodArgs.length); - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Found %d unexpected additional method arguments: %s", - description, this.methodArgs.length - argIndex, new SignaturePrinter(extraArgs).getFormattedArgs())); - } - } - - /** - * Called inside {@link #validateParams} but can also be used directly. This - * method checks whether the supplied type is compatible with the specified - * handler argument, apply coercion logic where necessary. - * - * @param index Handler argument index, pass in a negative value (by - * convention -1) to specify handler return type - * @param toType Desired type based on the injector contract - * @param description human-readable description of the handler method, used - * in raised exception - * @param allowCoercion True if coercion logic can be applied to this - * argument, false to only allow a precise match - * @return false if the argument matched perfectly, true - * if coercion is required for the argument - */ - protected final boolean checkCoerce(int index, Type toType, String description, boolean allowCoercion) { - Type fromType = index < 0 ? this.returnType : this.methodArgs[index]; - if (index >= this.methodArgs.length) { - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Not enough arguments: expected argument type %s at index %d", - description, SignaturePrinter.getTypeName(toType), index)); - } - - AnnotationNode coerce = Annotations.getInvisibleParameter(this.methodNode, Coerce.class, index); - boolean isReturn = index < 0; - String argType = isReturn ? "return" : "argument"; - Object argIndex = isReturn ? "" : " at index " + index; - - if (fromType.equals(toType)) { - if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { - Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex, - SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType)); - } - return false; - } - - if (coerce == null || !allowCoercion) { - String coerceWarning = coerce != null ? ". @Coerce not allowed here" : ""; - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Found unexpected %s type %s%s, expected %s%s", description, argType, - SignaturePrinter.getTypeName(fromType), argIndex, SignaturePrinter.getTypeName(toType), coerceWarning)); - } - - boolean canCoerce = Injector.canCoerce(fromType, toType); - if (!canCoerce) { - throw new InvalidInjectionException(this.info, String.format( - "%s has an invalid signature. Cannot @Coerce %s type %s%s to %s", description, argType, - SignaturePrinter.getTypeName(toType), argIndex, SignaturePrinter.getTypeName(fromType))); - } - - return true; - } - } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java index 499589a1..c035a322 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/LocalVariableDiscriminator.java @@ -41,6 +41,7 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Locals; import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable; import org.spongepowered.asm.util.SignaturePrinter; /** @@ -54,7 +55,7 @@ public class LocalVariableDiscriminator { * Discriminator context information, wraps all relevant information about * a target location for use when performing discrimination */ - public static class Context implements org.spongepowered.asm.util.PrettyPrinter.IPrettyPrintable { + public static class Context implements IPrettyPrintable { /** * Information about a local variable in the LVT, used during diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 3cf6a7af..6933654d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -150,18 +150,15 @@ public class ModifyVariableInjector extends Injector { this.printLocals(target, context); } - String handlerDesc = Bytecode.getDescriptor(new Type[] { this.returnType }, this.returnType); - if (!handlerDesc.equals(this.methodNode.desc)) { - throw new InvalidInjectionException(this.info, "Variable modifier " + this + " has an invalid signature, expected " + handlerDesc - + " but found " + this.methodNode.desc); - } - + InjectorData handler = new InjectorData(target, "handler", false); + this.validateParams(handler, this.returnType, this.returnType); + Extension extraStack = target.extendStack(); try { int local = this.discriminator.findLocal(context); if (local > -1) { - this.inject(context, extraStack, local); + this.inject(context, handler, extraStack, local); } } catch (InvalidImplicitDiscriminatorException ex) { if (this.discriminator.printLVT()) { @@ -206,7 +203,7 @@ public class ModifyVariableInjector extends Injector { * @param extraStack stack extension * @param local local variable to capture */ - private void inject(final Context context, Extension extraStack, final int local) { + private void inject(final Context context, InjectorData handler, Extension extraStack, final int local) { if (!this.isStatic) { context.insns.add(new VarInsnNode(Opcodes.ALOAD, 0)); extraStack.add(); @@ -214,6 +211,11 @@ public class ModifyVariableInjector extends Injector { context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ILOAD), local)); extraStack.add(); + + if (handler.captureTargetArgs > 0) { + this.pushArgs(handler.target.arguments, context.insns, handler.target.getArgIndices(), 0, handler.captureTargetArgs, extraStack); + } + this.invokeHandler(context.insns); context.insns.add(new VarInsnNode(this.returnType.getOpcode(Opcodes.ISTORE), local)); } diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index 10c6ed0f..94d1559e 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -717,18 +717,18 @@ public final class Bytecode { * @param args argument types * @return method descriptor without return type */ - public static String getDescriptor(Type[] args) { + public static String getDescriptor(Type... args) { return "(" + Joiner.on("").join(args) + ")"; } /** * Generate a method descriptor with the specified types - * - * @param args argument types * @param returnType return type + * @param args argument types + * * @return generated method descriptor */ - public static String getDescriptor(Type[] args, Type returnType) { + public static String getDescriptor(Type returnType, Type... args) { return Bytecode.getDescriptor(args) + returnType.toString(); }