Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions MOHIST.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ public void updateModuleReads(ModuleLayer layer) {
@SuppressWarnings("unchecked")
@Override
public void onLoad(IEnvironment env, Set<String> otherServices) {
if (MohistCompat.isMohistRuntime()) {
LOGGER.info("Mohist compatibility mode active");
}
List<ILaunchPluginService> injectPlugins = List.of(new ConnectorPreLaunchPlugin());

try {
Expand Down Expand Up @@ -121,10 +124,19 @@ public List<Resource> 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
Expand Down
103 changes: 103 additions & 0 deletions src/main/java/org/sinytra/connector/service/MohistCompat.java
Original file line number Diff line number Diff line change
@@ -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<ClassLoader> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -69,29 +74,57 @@ public class MixinPatchTransformer implements Transformer {
private final PatchEnvironment environment;
private final List<? extends Patch> 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<? extends Patch> adapterPatches) {
this.environment = environment;
this.patches = ImmutableList.<Patch>builder()
.addAll(PRIORITY_PATCHES)
.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())
.transform(new DynamicSyntheticInstanceofPatch())
.build(),
Patch.interfaceBuilder()
.transform(new FieldTypePatchTransformer())
.transform(new InterfaceMixinInjectorStripper())
.transform(new InterfaceMixinAccessWidener())
.build()
)
.build();
}

public void finalize(Path zipRoot, Collection<String> configs, Map<String, SrgRemappingReferenceMapper.SimpleRefmap> refmapFiles, Set<String> dirtyRefmaps) throws IOException {
if (MohistCompat.isMohistRuntime()) {
relaxInjectionRequirements(zipRoot, configs);
}
Map<String, MixinClassGenerator.GeneratedClass> generatedMixinClasses = this.environment.classGenerator().getGeneratedMixinClasses();
if (!generatedMixinClasses.isEmpty()) {
for (String config : configs) {
Expand Down Expand Up @@ -160,6 +193,43 @@ public void finalize(Path zipRoot, Collection<String> configs, Map<String, SrgRe
}
}

/**
* Sets {@code injectors.defaultRequire} to 0 for every mixin config of the transformed mod.
*
* <p>Mohist 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<String> 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<String, MixinClassGenerator.GeneratedClass> getMixinsInPackage(String mixinPackage, Map<String, MixinClassGenerator.GeneratedClass> generatedMixinClasses) {
Map<String, MixinClassGenerator.GeneratedClass> classes = new HashMap<>();
for (Map.Entry<String, MixinClassGenerator.GeneratedClass> entry : generatedMixinClasses.entrySet()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,25 @@ private static void cleanupEnvironment() {
Map<String, ClassInfo> cache = (Map<String, ClassInfo>) cacheField.get();
cache.clear();

VarHandle nonExpandedCacheField = lookup.findStaticVarHandle(ClassInfo.class, "nonExpandedCache", Map.class);
Map<String, ClassInfo> nonExpandedCache = (Map<String, ClassInfo>) 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<String, ClassInfo> nonExpandedCache = null;
try {
VarHandle nonExpandedCacheField = lookup.findStaticVarHandle(ClassInfo.class, "nonExpandedCache", Map.class);
nonExpandedCache = (Map<String, ClassInfo>) 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);
}
Expand Down
Loading