diff --git a/MOHIST.md b/MOHIST.md new file mode 100644 index 00000000..bb94b92b --- /dev/null +++ b/MOHIST.md @@ -0,0 +1,73 @@ +# Mohist + +[Mohist](https://github.com/MohistMC/Mohist) implements the Bukkit API on top of Forge, and forks +ModLauncher and securejarhandler in the process. This branch contains the changes needed to load +Fabric mods through Connector on it, tested with Middle-earth 1.4.2 (2033 classes) on Mohist +1.20.1-ecf8d5ad / Forge 47.4.13. + +## Symptoms + +Without these changes the server dies during `Bootstrap`, naming a vanilla class the mod never +touches: + + java.lang.NoClassDefFoundError: net/minecraft/world/item/DyeableArmorItem + at net.minecraft.world.level.block.ComposterBlock.m_51988_(ComposterBlock.java:70) + at net.minecraft.server.Bootstrap.m_135870_(Bootstrap.java:47) + +The class exists in the runtime jar, and `ComposterBlock` does not reference it. What happens is +that a mixin failed to apply, Mixin aborted the transformation of its target, and +`ModuleClassLoader.loadClass` turned the resulting `MixinTransformerError` into a +`ClassNotFoundException`. `ComposterBlock.bootStrap()` resolves `Items` first, so the failure is +reported at that frame instead of at its cause. + +Look for the earlier `Mixin apply failed` line before chasing the class name. + +## Mixin 0.8.x + +Fabric ships Mixin 0.12, Forge ships 0.8.5. Three things that work on Fabric do not exist there: + +- `Locals.getLocalsAt(ClassNode, MethodNode, AbstractInsnNode, int)`, used by `DynamicLVTPatch`, + was added in 0.12; on 0.8.x the four argument overload takes `Locals$Settings`. The patch is now + applied only when the running Mixin exposes the overload. +- `MixinPreProcessorInterface` rejects private and protected methods in interface mixins + (`Interface mixin contains a non-public method`). `InterfaceMixinAccessWidener` promotes them to + public, turning them into default methods with the same body. +- `MixinApplicatorInterface` rejects every injector declared by an interface mixin, and a class + mixin may not target an interface, so the handler cannot be kept. `InterfaceMixinInjectorStripper` + removes it and logs a warning. + +`JarTransformer.cleanupEnvironment` read `ClassInfo.nonExpandedCache`, which only exists in 0.12. +The lookup threw, which skipped the rest of the cleanup, including restoring `java/lang/Object` in +the class cache. The field is now optional. + +## Mohist specifics + +Mohist rewrites vanilla classes, so injection points that exist on Forge often do not exist there. +Mixin treats a missing injection point as fatal for the whole target class. On Mohist, +`MixinPatchTransformer` writes `injectors.defaultRequire = 0` into the mixin configs of the +transformed mod, which downgrades those failures to warnings. + +`IForgeItemMixin` targets an interface, which hits the second Mixin limitation above, so it is +skipped on Mohist. + +Mohist's forked securejarhandler does not always accept the authlib module move. +`ConnectorLoaderService` now continues without it rather than failing the launch. + +## Limitations + +- Injectors Mixin cannot apply are dropped. The mod loads and the hook stays inert; the log lists + every affected mixin and injection point. +- `@At("STORE")` with `@Inject` is rejected by 0.8.5. Only `@ModifyVariable` may use it. +- Mixins that Mohist itself applies are not part of Connector's transformation, so a Fabric mod that + expects one of Mohist's changes to a vanilla method will not see it. + +## Running + +Put Connector, Fabric API and the mod in `mods/`, then: + + java -Xms2G -Xmx4G -jar mohist-1.20.1-47.4.13.jar nogui + +2G is not enough for Middle-earth: world generation runs out of memory while preparing the nether. + +Delete `mods/.connector` after replacing the Connector jar, otherwise the cached transformation of +the mod is reused. diff --git a/src/main/java/org/sinytra/connector/service/ConnectorLoaderService.java b/src/main/java/org/sinytra/connector/service/ConnectorLoaderService.java index ac9d2ae7..2d4ea410 100644 --- a/src/main/java/org/sinytra/connector/service/ConnectorLoaderService.java +++ b/src/main/java/org/sinytra/connector/service/ConnectorLoaderService.java @@ -87,6 +87,9 @@ public void updateModuleReads(ModuleLayer layer) { @SuppressWarnings("unchecked") @Override public void onLoad(IEnvironment env, Set otherServices) { + if (MohistCompat.isMohistRuntime()) { + LOGGER.info("Mohist compatibility mode active"); + } List injectPlugins = List.of(new ConnectorPreLaunchPlugin()); try { @@ -121,10 +124,19 @@ public List completeScan(IModuleLayerManager layerManager) { else { LOGGER.warn("Broken FML mod files found, not adding Connector locator errors"); } - return List.of(new Resource(IModuleLayerManager.Layer.GAME, List.of( - new FabricASMFixer.FabricASMGeneratedClassesSecureJar(), - ModuleLayerMigrator.moveModule(AUTHLIB_MODULE) - ))); + try { + return List.of(new Resource(IModuleLayerManager.Layer.GAME, List.of( + new FabricASMFixer.FabricASMGeneratedClassesSecureJar(), + ModuleLayerMigrator.moveModule(AUTHLIB_MODULE) + ))); + } catch (Throwable error) { + // Mohist ships a forked securejarhandler; authlib migration may differ there. + // Losing the authlib move only affects Fabric API internals, not server startup. + LOGGER.warn("Could not migrate the '{}' module to the GAME layer (continuing without it): {}", AUTHLIB_MODULE, error.toString()); + return List.of(new Resource(IModuleLayerManager.Layer.GAME, List.of( + new FabricASMFixer.FabricASMGeneratedClassesSecureJar() + ))); + } } @Override diff --git a/src/main/java/org/sinytra/connector/service/MohistCompat.java b/src/main/java/org/sinytra/connector/service/MohistCompat.java new file mode 100644 index 00000000..596eceab --- /dev/null +++ b/src/main/java/org/sinytra/connector/service/MohistCompat.java @@ -0,0 +1,103 @@ +package org.sinytra.connector.service; + +import com.mojang.logging.LogUtils; +import cpw.mods.modlauncher.Launcher; +import org.slf4j.Logger; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; + +/** + * Runtime detection for Mohist, which forks securejarhandler and ModLauncher internals. + */ +public final class MohistCompat { + + private static final Logger LOGGER = LogUtils.getLogger(); + + /** + * Launch plugin service id that only Mohist's ModLauncher fork registers. + */ + private static final String MOHIST_PLUGIN_ID = "mohist_implementer"; + + private static final String[] MOHIST_CLASSES = {"com.mohistmc.MohistMCStart", "com.mohistmc.MohistMC"}; + + private static Boolean mohistRuntime; + + private MohistCompat() { + } + + public static boolean isMohistRuntime() { + if (mohistRuntime == null) { + mohistRuntime = detect(); + LOGGER.debug("Mohist runtime detection: {}", mohistRuntime); + } + return mohistRuntime; + } + + private static boolean detect() { + return hasMohistLaunchPlugin() || hasMohistOnClasspath(); + } + + /** + * Reflective so we do not need ILaunchPluginService, which is not on the compile classpath. + */ + private static boolean hasMohistLaunchPlugin() { + try { + Field launchPluginsField = Launcher.class.getDeclaredField("launchPlugins"); + launchPluginsField.setAccessible(true); + Object raw = launchPluginsField.get(Launcher.INSTANCE); + if (!(raw instanceof List plugins)) { + return false; + } + for (Object plugin : plugins) { + if (plugin == null) { + continue; + } + Method idMethod; + try { + idMethod = plugin.getClass().getMethod("id"); + idMethod.setAccessible(true); + } catch (Throwable ignored) { + continue; + } + Object id; + try { + id = idMethod.invoke(plugin); + } catch (Throwable ignored) { + continue; + } + if (MOHIST_PLUGIN_ID.equals(id)) { + return true; + } + } + } catch (Throwable t) { + LOGGER.debug("Mohist launch-plugin probe failed", t); + } + return false; + } + + private static boolean hasMohistOnClasspath() { + // The Mohist server jar is on the application classpath, not on Connector's module layer, + // so the system classloader has to be probed explicitly. + List loaders = List.of( + MohistCompat.class.getClassLoader(), + ClassLoader.getSystemClassLoader(), + ClassLoader.getPlatformClassLoader() + ); + for (ClassLoader loader : loaders) { + if (loader == null) { + continue; + } + for (String name : MOHIST_CLASSES) { + try { + Class.forName(name, false, loader); + return true; + } catch (Throwable ignored) { + // try the next probe + } + } + } + return false; + } +} diff --git a/src/main/java/org/sinytra/connector/transformer/MixinPatchTransformer.java b/src/main/java/org/sinytra/connector/transformer/MixinPatchTransformer.java index 56d891ad..17b0cd52 100644 --- a/src/main/java/org/sinytra/connector/transformer/MixinPatchTransformer.java +++ b/src/main/java/org/sinytra/connector/transformer/MixinPatchTransformer.java @@ -9,13 +9,18 @@ import com.mojang.logging.LogUtils; import org.sinytra.adapter.patch.transformer.dynamic.DynamicSyntheticInstanceofPatch; import org.sinytra.connector.ConnectorUtil; +import org.sinytra.connector.service.MohistCompat; import org.sinytra.connector.transformer.patch.EnvironmentStripperTransformer; +import org.sinytra.connector.transformer.patch.InterfaceMixinAccessWidener; +import org.sinytra.connector.transformer.patch.InterfaceMixinInjectorStripper; import net.minecraftforge.fart.api.Transformer; import net.minecraftforge.forgespi.locating.IModFile; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; import org.sinytra.adapter.patch.LVTOffsets; import org.sinytra.adapter.patch.api.ClassTransform; import org.sinytra.adapter.patch.api.MixinClassGenerator; @@ -69,6 +74,31 @@ public class MixinPatchTransformer implements Transformer { private final PatchEnvironment environment; private final List patches; + /** + * {@link DynamicLVTPatch} calls {@code Locals.getLocalsAt(ClassNode, MethodNode, AbstractInsnNode, int)}, + * which was added in Mixin 0.12. On 0.8.x the four argument overload takes {@code Locals$Settings} + * instead, so applying the patch throws {@link NoSuchMethodError} and aborts the jar transformation. + */ + private static Patch.Builder dynamicPatches(LVTOffsets lvtOffsets) { + Patch.Builder builder = Patch.builder() + .transform(new DynamicInjectorOrdinalPatch()); + if (hasExtendedLocalsApi()) { + builder.transform(new DynamicLVTPatch(() -> lvtOffsets)); + } + return builder; + } + + private static boolean hasExtendedLocalsApi() { + try { + Class.forName("org.spongepowered.asm.util.Locals", false, MixinPatchTransformer.class.getClassLoader()) + .getMethod("getLocalsAt", ClassNode.class, MethodNode.class, AbstractInsnNode.class, int.class); + return true; + } catch (Throwable t) { + LOGGER.debug("Extended Locals API not available, skipping DynamicLVTPatch"); + return false; + } + } + public MixinPatchTransformer(LVTOffsets lvtOffsets, PatchEnvironment environment, List adapterPatches) { this.environment = environment; this.patches = ImmutableList.builder() @@ -76,9 +106,7 @@ public MixinPatchTransformer(LVTOffsets lvtOffsets, PatchEnvironment environment .addAll(adapterPatches) .addAll(PATCHES) .add( - Patch.builder() - .transform(new DynamicInjectorOrdinalPatch()) - .transform(new DynamicLVTPatch(() -> lvtOffsets)) + dynamicPatches(lvtOffsets) .transform(new DynamicAnonymousShadowFieldTypePatch()) .transform(new DynamicModifyVarAtReturnPatch()) .transform(new DynamicInheritedInjectionPointPatch()) @@ -86,12 +114,17 @@ public MixinPatchTransformer(LVTOffsets lvtOffsets, PatchEnvironment environment .build(), Patch.interfaceBuilder() .transform(new FieldTypePatchTransformer()) + .transform(new InterfaceMixinInjectorStripper()) + .transform(new InterfaceMixinAccessWidener()) .build() ) .build(); } public void finalize(Path zipRoot, Collection configs, Map refmapFiles, Set dirtyRefmaps) throws IOException { + if (MohistCompat.isMohistRuntime()) { + relaxInjectionRequirements(zipRoot, configs); + } Map generatedMixinClasses = this.environment.classGenerator().getGeneratedMixinClasses(); if (!generatedMixinClasses.isEmpty()) { for (String config : configs) { @@ -160,6 +193,43 @@ public void finalize(Path zipRoot, Collection configs, MapMohist rewrites large parts of the vanilla classes a Fabric mod targets, so injection points + * frequently no longer match. Mixin treats that as a critical error and aborts the whole class + * transformation, which the module class loader then reports as a missing class. Requiring 0 turns + * those failures into warnings so the mod still loads, with the affected hook inert. + */ + private static void relaxInjectionRequirements(Path zipRoot, Collection configs) throws IOException { + for (String config : configs) { + Path entry = zipRoot.resolve(config); + if (!Files.exists(entry)) { + continue; + } + JsonObject json; + try (Reader reader = Files.newBufferedReader(entry, StandardCharsets.UTF_8)) { + JsonElement element = JsonParser.parseReader(reader); + if (!element.isJsonObject()) { + continue; + } + json = element.getAsJsonObject(); + } + JsonObject injectors = json.has("injectors") && json.get("injectors").isJsonObject() + ? json.getAsJsonObject("injectors") + : new JsonObject(); + JsonElement current = injectors.get("defaultRequire"); + if (current != null && current.isJsonPrimitive() && current.getAsJsonPrimitive().isNumber() + && current.getAsInt() == 0) { + continue; + } + injectors.addProperty("defaultRequire", 0); + json.add("injectors", injectors); + Files.writeString(entry, new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(json), StandardCharsets.UTF_8); + LOGGER.info("Mohist: relaxed injection requirement in {}", config); + } + } + private Map getMixinsInPackage(String mixinPackage, Map generatedMixinClasses) { Map classes = new HashMap<>(); for (Map.Entry entry : generatedMixinClasses.entrySet()) { diff --git a/src/main/java/org/sinytra/connector/transformer/jar/JarTransformer.java b/src/main/java/org/sinytra/connector/transformer/jar/JarTransformer.java index 303520fc..c92dd360 100644 --- a/src/main/java/org/sinytra/connector/transformer/jar/JarTransformer.java +++ b/src/main/java/org/sinytra/connector/transformer/jar/JarTransformer.java @@ -252,15 +252,25 @@ private static void cleanupEnvironment() { Map cache = (Map) cacheField.get(); cache.clear(); - VarHandle nonExpandedCacheField = lookup.findStaticVarHandle(ClassInfo.class, "nonExpandedCache", Map.class); - Map nonExpandedCache = (Map) nonExpandedCacheField.get(); - nonExpandedCache.clear(); + // nonExpandedCache only exists in Mixin 0.12+; Forge and Mohist ship 0.8.5, where the + // lookup throws and used to abort the rest of the cleanup (including restoring + // java/lang/Object in the main cache). + Map nonExpandedCache = null; + try { + VarHandle nonExpandedCacheField = lookup.findStaticVarHandle(ClassInfo.class, "nonExpandedCache", Map.class); + nonExpandedCache = (Map) nonExpandedCacheField.get(); + nonExpandedCache.clear(); + } catch (NoSuchFieldException ignored) { + // Mixin 0.8.5 + } VarHandle objectField = lookup.findStaticVarHandle(ClassInfo.class, "OBJECT", ClassInfo.class); ClassInfo object = (ClassInfo) objectField.get(); cache.put("java/lang/Object", object); - nonExpandedCache.put("java/lang/Object", object); + if (nonExpandedCache != null) { + nonExpandedCache.put("java/lang/Object", object); + } } catch (Throwable t) { LOGGER.error("Error cleaning up after jar transformation", t); } diff --git a/src/main/java/org/sinytra/connector/transformer/patch/InterfaceMixinAccessWidener.java b/src/main/java/org/sinytra/connector/transformer/patch/InterfaceMixinAccessWidener.java new file mode 100644 index 00000000..840c19c9 --- /dev/null +++ b/src/main/java/org/sinytra/connector/transformer/patch/InterfaceMixinAccessWidener.java @@ -0,0 +1,38 @@ +package org.sinytra.connector.transformer.patch; + +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.sinytra.adapter.patch.api.ClassTransform; +import org.sinytra.adapter.patch.api.Patch; +import org.sinytra.adapter.patch.api.PatchContext; +import org.sinytra.adapter.patch.selector.AnnotationValueHandle; + +/** + * Promotes non-public methods declared by interface mixins to public. + * + *

{@code MixinPreProcessorInterface} rejects private and protected methods with + * "Interface mixin contains a non-public method". Mixin 0.12 accepts Java 9 private interface + * methods and mods use them for injector handlers, so turning such a method into a default method + * keeps the handler body intact while satisfying 0.8.x. Static methods are already allowed and are + * left untouched. + */ +public class InterfaceMixinAccessWidener implements ClassTransform { + @Override + public Patch.Result apply(ClassNode classNode, @Nullable AnnotationValueHandle annotation, PatchContext context) { + if ((classNode.access & Opcodes.ACC_INTERFACE) == 0) { + return Patch.Result.PASS; + } + + boolean applied = false; + for (MethodNode method : classNode.methods) { + if ((method.access & Opcodes.ACC_PUBLIC) != 0 || (method.access & Opcodes.ACC_STATIC) != 0) { + continue; + } + method.access = (method.access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) | Opcodes.ACC_PUBLIC; + applied = true; + } + return applied ? Patch.Result.APPLY : Patch.Result.PASS; + } +} diff --git a/src/main/java/org/sinytra/connector/transformer/patch/InterfaceMixinInjectorStripper.java b/src/main/java/org/sinytra/connector/transformer/patch/InterfaceMixinInjectorStripper.java new file mode 100644 index 00000000..02483cbd --- /dev/null +++ b/src/main/java/org/sinytra/connector/transformer/patch/InterfaceMixinInjectorStripper.java @@ -0,0 +1,82 @@ +package org.sinytra.connector.transformer.patch; + +import com.mojang.logging.LogUtils; +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.sinytra.adapter.patch.api.ClassTransform; +import org.sinytra.adapter.patch.api.Patch; +import org.sinytra.adapter.patch.api.PatchContext; +import org.sinytra.adapter.patch.selector.AnnotationValueHandle; +import org.slf4j.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * Removes injector handlers declared by interface mixins. + * + *

Mixin picks its applicator from the mixin's own access flags. For an interface mixin that is + * {@code MixinApplicatorInterface}, which copies method declarations only and rejects every injector + * with "not supported on interface mixin method". Converting the mixin into a class does not help + * either, since a class mixin may not target an interface. Dropping the handler is therefore the only + * option, matching the relaxed injection requirements used on Mohist: the mod loads and the affected + * hook stays inert. Every removed handler is logged at WARN. + */ +public class InterfaceMixinInjectorStripper implements ClassTransform { + private static final Logger LOGGER = LogUtils.getLogger(); + private static final Set INJECTOR_DESCRIPTORS = Set.of( + "Lorg/spongepowered/asm/mixin/injection/Inject;", + "Lorg/spongepowered/asm/mixin/injection/Redirect;", + "Lorg/spongepowered/asm/mixin/injection/ModifyArg;", + "Lorg/spongepowered/asm/mixin/injection/ModifyArgs;", + "Lorg/spongepowered/asm/mixin/injection/ModifyConstant;", + "Lorg/spongepowered/asm/mixin/injection/ModifyVariable;", + "Lcom/llamalad7/mixinextras/injector/ModifyExpressionValue;", + "Lcom/llamalad7/mixinextras/injector/ModifyReceiver;", + "Lcom/llamalad7/mixinextras/injector/ModifyReturnValue;", + "Lcom/llamalad7/mixinextras/injector/WrapOperation;", + "Lcom/llamalad7/mixinextras/injector/WrapWithCondition;" + ); + + @Override + public Patch.Result apply(ClassNode classNode, @Nullable AnnotationValueHandle annotation, PatchContext context) { + if ((classNode.access & Opcodes.ACC_INTERFACE) == 0) { + return Patch.Result.PASS; + } + + List dropped = new ArrayList<>(); + classNode.methods.removeIf(method -> { + if (!isInjector(method.visibleAnnotations) && !isInjector(method.invisibleAnnotations)) { + return false; + } + dropped.add(method.name + method.desc); + return true; + }); + + if (dropped.isEmpty()) { + return Patch.Result.PASS; + } + LOGGER.warn("Removing {} injector(s) from interface mixin {}: the mixin applicator for interfaces " + + "does not support them", dropped.size(), classNode.name); + for (String method : dropped) { + LOGGER.warn(" - {}", method); + } + return Patch.Result.APPLY; + } + + private static boolean isInjector(@Nullable List annotations) { + if (annotations == null) { + return false; + } + for (AnnotationNode annotation : annotations) { + if (INJECTOR_DESCRIPTORS.contains(annotation.desc)) { + return true; + } + } + return false; + } +} diff --git a/src/mod/java/org/sinytra/connector/mod/ConnectorBootstrap.java b/src/mod/java/org/sinytra/connector/mod/ConnectorBootstrap.java index 3fe94d41..dc3655af 100644 --- a/src/mod/java/org/sinytra/connector/mod/ConnectorBootstrap.java +++ b/src/mod/java/org/sinytra/connector/mod/ConnectorBootstrap.java @@ -1,6 +1,7 @@ package org.sinytra.connector.mod; import org.sinytra.connector.loader.ConnectorEarlyLoader; +import org.sinytra.connector.service.MohistCompat; import net.minecraftforge.coremod.api.ASMAPI; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; @@ -21,8 +22,16 @@ public class ConnectorBootstrap implements IMixinConfigPlugin { CrashReportUpgrade.registerCrashLogInfo(); } + // Mohist's Mixin build rejects injectors on interface targets, which aborts the launch while + // BuiltInRegistries initialises. This mixin only redirects piglin bartering, so skipping it there + // is preferable to failing to start. + private static final String I_FORGE_ITEM_MIXIN = "org.sinytra.connector.mod.mixin.IForgeItemMixin"; + @Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + if (MohistCompat.isMohistRuntime() && I_FORGE_ITEM_MIXIN.equals(mixinClassName)) { + return false; + } return !ConnectorEarlyLoader.hasEncounteredException(); }