Files
rivencraft/scripts/regression_client118.py
T
2026-11-18 22:55:03 -05:00

196 lines
14 KiB
Python

#!/usr/bin/env python3
"""Isolated 26.3 client-guard checks; no Minecraft client, GPU, server or world starts."""
from pathlib import Path
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
STUBS = {
"net.minecraft.client.Minecraft": "public class Minecraft { public static boolean sameThread=true; private static final Minecraft INSTANCE=new Minecraft(); public static Minecraft getInstance(){return INSTANCE;} public boolean isSameThread(){return sameThread;} }",
"net.minecraft.client.multiplayer.ClientLevel": "public class ClientLevel { public final java.util.List<Integer> acks=new java.util.ArrayList<>(); public void handleBlockChangedAck(int n){acks.add(n);} }",
"net.minecraft.client.multiplayer.ClientPacketListener": "public class ClientPacketListener {}",
"net.minecraft.network.protocol.game.ClientboundBlockChangedAckPacket": "public record ClientboundBlockChangedAckPacket(int sequence) {}",
"net.dnorberg.rivencraft.compat.ImmersiveBookPreviews": "public class ImmersiveBookPreviews { public static boolean reborn,seamless; public static boolean available(){return reborn||seamless;} }",
"qouteall.imm_ptl.core.ClientWorldLoader": "public class ClientWorldLoader { public static boolean initialized; public static int reads; public static final java.util.List<net.minecraft.client.multiplayer.ClientLevel> worlds=new java.util.ArrayList<>(); public static boolean getIsInitialized(){reads++;return initialized;} public static java.util.Collection<net.minecraft.client.multiplayer.ClientLevel> getClientWorlds(){if(!initialized)throw new IllegalArgumentException();return worlds;} }",
"net.minecraft.client.renderer.chunk.SectionRenderDispatcher": "public class SectionRenderDispatcher { public class RenderSection { public boolean dirty=true; } }",
"net.minecraft.client.renderer.ViewArea": "public class ViewArea implements net.dnorberg.rivencraft.mixin.ViewAreaSectionAccessor { public final java.util.Map<Long,net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection> sections=new java.util.HashMap<>(); public boolean fail; public int reads; public net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection rivencraft$getRenderSection(long n){reads++;if(fail)throw new IllegalStateException();return sections.get(n);} }",
"net.minecraft.client.renderer.LevelRenderer": "public class LevelRenderer {}",
"net.minecraft.client.renderer.state.level.CameraRenderState": "public class CameraRenderState {}",
"net.minecraft.client.renderer.state.level.SectionUpdateRenderState": "public record SectionUpdateRenderState(long sectionNode,boolean playerChanged,Object region,java.util.List<Object> additionalRenderers) {}",
"net.minecraft.client.renderer.state.level.LevelRenderState": "public class LevelRenderState { public final java.util.List<SectionUpdateRenderState> sectionUpdateRenderStates=new java.util.ArrayList<>(); }",
}
EXTRACT = r"""
import java.nio.file.*; import java.util.zip.*; import org.objectweb.asm.*;
public class ExtractForkAck {
public static void main(String[] args)throws Exception {
var writer=new ClassWriter(ClassWriter.COMPUTE_FRAMES|ClassWriter.COMPUTE_MAXS);
writer.visit(Opcodes.V25,Opcodes.ACC_PUBLIC,args[1],null,"java/lang/Object",null);
var init=writer.visitMethod(Opcodes.ACC_PUBLIC,"<init>","()V",null,null);
init.visitCode();init.visitVarInsn(Opcodes.ALOAD,0);init.visitMethodInsn(Opcodes.INVOKESPECIAL,"java/lang/Object","<init>","()V",false);init.visitInsn(Opcodes.RETURN);init.visitMaxs(0,0);init.visitEnd();
int[] copied={0};
try(var zip=new ZipFile(args[0])) {
var bytes=zip.getInputStream(zip.getEntry("qouteall/imm_ptl/core/mixin/client/sync/MixinClientPacketListener.class")).readAllBytes();
new ClassReader(bytes).accept(new ClassVisitor(Opcodes.ASM9) {
@Override public MethodVisitor visitMethod(int access,String name,String desc,String sig,String[] exceptions) {
if(!name.equals("redirectHandleBlockChangedAck"))return null;
copied[0]++;
return new MethodVisitor(Opcodes.ASM9,writer.visitMethod(Opcodes.ACC_PUBLIC,"handle",desc,null,null)) {
@Override public AnnotationVisitor visitAnnotation(String desc,boolean visible){return null;}
};
}
},ClassReader.SKIP_FRAMES|ClassReader.SKIP_DEBUG);
}
if(copied[0]!=1)throw new AssertionError("Expected exactly one fork redirect");
writer.visitEnd();Files.write(Path.of(args[2]),writer.toByteArray());
}
}
"""
CHECKS = r"""
import java.util.*;
import java.lang.reflect.*;
import net.minecraft.client.*;
import net.minecraft.client.multiplayer.*;
import net.minecraft.network.protocol.game.*;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.chunk.SectionRenderDispatcher.RenderSection;
import net.minecraft.client.renderer.state.level.*;
import net.dnorberg.rivencraft.mixin.*;
import net.dnorberg.rivencraft.compat.ImmersiveBookPreviews;
import qouteall.imm_ptl.core.ClientWorldLoader;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
public class Client118Checks {
static int checks;
public static class Ack extends ImmersiveBlockAckMixin {}
public static class Rebuild extends ImmersiveSectionRebuildMixin {}
static void check(boolean pass,String message){if(!pass)throw new AssertionError(message);checks++;}
static void field(Object object,Class<?> owner,String name,Object value)throws Exception{
var field=owner.getDeclaredField(name);field.setAccessible(true);field.set(object,value);
}
static void invoke(Object object,Class<?> owner,String name,Class<?>[] types,Object...args)throws Exception{
var method=owner.getDeclaredMethod(name,types);method.setAccessible(true);method.invoke(object,args);
}
static void ack(Ack hook,CallbackInfo callback)throws Exception{
invoke(hook,ImmersiveBlockAckMixin.class,"rivencraft$ackDuringWorldReset",
new Class<?>[]{ClientboundBlockChangedAckPacket.class,CallbackInfo.class},new ClientboundBlockChangedAckPacket(37),callback);
}
static void render(Rebuild hook,CallbackInfo callback)throws Exception{
invoke(hook,ImmersiveSectionRebuildMixin.class,"rivencraft$discardUnavailableSections",
new Class<?>[]{CameraRenderState.class,CallbackInfo.class},new CameraRenderState(),callback);
}
public static void main(String[] args)throws Exception{
for(String engine:List.of("none","reborn","seamless")){
ImmersiveBookPreviews.reborn=engine.equals("reborn");ImmersiveBookPreviews.seamless=engine.equals("seamless");
Object fork=null;Method redirect=null;
if(!engine.equals("none")){
var type=Class.forName(engine.equals("reborn")?"ForkAckReborn":"ForkAckSeamless");
fork=type.getConstructor().newInstance();redirect=type.getMethod("handle",ClientLevel.class,int.class);
ClientWorldLoader.initialized=false;
try{redirect.invoke(fork,new ClientLevel(),37);throw new AssertionError("Original redirect unexpectedly safe");}
catch(InvocationTargetException error){check(error.getCause() instanceof IllegalArgumentException,"Original "+engine+" precondition reproduced");}
}
for(boolean initialized:List.of(false,true)){
ClientWorldLoader.initialized=initialized;ClientWorldLoader.worlds.clear();ClientWorldLoader.reads=0;Minecraft.sameThread=true;
var local=new ClientLevel();var remote=new ClientLevel();ClientWorldLoader.worlds.addAll(List.of(local,remote));
var hook=new Ack();field(hook,ImmersiveBlockAckMixin.class,"level",local);
var callback=new CallbackInfo("ack",true);ack(hook,callback);
boolean fallback=!engine.equals("none")&&!initialized;
check(callback.isCancelled()==fallback,"Cancellation scope "+engine+initialized);
if(!callback.isCancelled()){
if(engine.equals("none"))local.handleBlockChangedAck(37);else redirect.invoke(fork,local,37);
}
check(local.acks.equals(List.of(37)),"Exactly one local ack "+engine+initialized);
check(remote.acks.equals(!engine.equals("none")&&initialized?List.of(37):List.of()),"Warm-map multiworld delivery retained");
local.acks.clear();remote.acks.clear();ClientWorldLoader.reads=0;Minecraft.sameThread=false;
callback=new CallbackInfo("ack",true);ack(hook,callback);
check(!callback.isCancelled()&&local.acks.isEmpty()&&remote.acks.isEmpty()&&ClientWorldLoader.reads==0,"Network-thread scheduling untouched");
}
Minecraft.sameThread=true;ClientWorldLoader.initialized=false;
var hook=new Ack();field(hook,ImmersiveBlockAckMixin.class,"level",null);
var callback=new CallbackInfo("ack",true);ack(hook,callback);
check(callback.isCancelled()!=engine.equals("none"),"Missing packet world handled only for installed fork");
var area=new ViewArea();var first=new net.minecraft.client.renderer.chunk.SectionRenderDispatcher().new RenderSection();var second=new net.minecraft.client.renderer.chunk.SectionRenderDispatcher().new RenderSection();
area.sections.put(1L,first);area.sections.put(2L,second);
var state=new LevelRenderState();Object region=new Object();List<Object> extras=List.of(new Object());
var a=new SectionUpdateRenderState(1,true,region,extras);
var stale=new SectionUpdateRenderState(9,false,new Object(),List.of());
var b=new SectionUpdateRenderState(2,false,new Object(),List.of());
state.sectionUpdateRenderStates.addAll(List.of(a,stale,b,a));
var rebuild=new Rebuild();field(rebuild,ImmersiveSectionRebuildMixin.class,"viewArea",area);
field(rebuild,ImmersiveSectionRebuildMixin.class,"levelRenderState",state);
callback=new CallbackInfo("compile",true);render(rebuild,callback);
boolean active=!engine.equals("none");
check(state.sectionUpdateRenderStates.equals(active?List.of(a,b,a):List.of(a,stale,b,a)),"Only absent sections removed "+engine);
check(state.sectionUpdateRenderStates.getFirst()==a&&a.region()==region&&a.additionalRenderers()==extras,"Valid identity/order/additional geometry preserved");
check(first.dirty&&second.dirty&&!callback.isCancelled(),"Dirty state and render pipeline untouched");
if(!active)check(area.reads==0,"No renderer workaround without optional engine");
state.sectionUpdateRenderStates.clear();state.sectionUpdateRenderStates.add(stale);area.sections.put(9L,new net.minecraft.client.renderer.chunk.SectionRenderDispatcher().new RenderSection());
render(rebuild,new CallbackInfo("compile",true));
check(state.sectionUpdateRenderStates.equals(List.of(stale)),"Newly available section is not blacklisted");
field(rebuild,ImmersiveSectionRebuildMixin.class,"viewArea",null);
render(rebuild,new CallbackInfo("compile",true));
check(state.sectionUpdateRenderStates.equals(List.of(stale)),"Missing view area not mistaken for stale batch");
field(rebuild,ImmersiveSectionRebuildMixin.class,"viewArea",area);
area.fail=true;
if(active){
try{render(rebuild,new CallbackInfo("compile",true));throw new AssertionError("Unrelated exception swallowed");}
catch(InvocationTargetException error){check(error.getCause() instanceof IllegalStateException,"Unrelated renderer exception propagates");}
}
}
System.out.println("CLIENT118_GUARDS_PASS checks="+checks);
}
}
"""
def main():
homes = list((Path.home() / ".gradle/jdks").glob("*25*/bin/javac"))
if not homes:
homes = list((Path.home() / ".gradle/jdks").glob("*25*/*/bin/javac"))
if not homes:
raise SystemExit("JDK 25 not found in Gradle toolchains")
javac = homes[0]
java = javac.with_name("java")
cache = Path.home() / ".gradle/caches/modules-2/files-2.1"
asm = next((cache / "org.ow2.asm/asm/9.11").rglob("asm-*.jar"))
mixin = next((cache / "net.fabricmc/sponge-mixin").rglob("sponge-mixin-*.jar"))
production = ROOT / "ports/mc263/build/classes/java/main"
mods = Path.home() / ".local/share/PrismLauncher/instances/Dev 26.3/minecraft/mods"
forks = {"Reborn": next(mods.glob("immersive-portals-reborn*.jar*")),
"Seamless": next(mods.glob("seamlessportals*.jar"))}
with tempfile.TemporaryDirectory(prefix="rivencraft-client118-") as temporary:
work = Path(temporary)
classes = work / "classes"
classes.mkdir()
for name in ["client/ImmersivePredictionAcks", "client/ImmersiveSectionRebuilds",
"mixin/ImmersiveBlockAckMixin", "mixin/ImmersiveSectionRebuildMixin", "mixin/ViewAreaSectionAccessor"]:
relative = Path("net/dnorberg/rivencraft") / (name + ".class")
dest = classes / relative
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(production / relative, dest)
sources = []
for name, body in STUBS.items():
package, _, simple = name.rpartition(".")
source = work / Path(name.replace(".", "/") + ".java")
source.parent.mkdir(parents=True, exist_ok=True)
source.write_text("package " + package + ";\n" + body + "\n")
sources.append(source)
for name, body in [("ExtractForkAck", EXTRACT), ("Client118Checks", CHECKS)]:
source = work / (name + ".java")
source.write_text(body)
sources.append(source)
classpath = ":".join(map(str, [classes, asm, mixin]))
subprocess.run([str(javac), "-proc:none", "-cp", classpath, "-d", str(classes), *map(str, sources)], check=True)
for name, jar in forks.items():
subprocess.run([str(java), "-cp", classpath, "ExtractForkAck", str(jar),
"ForkAck" + name, str(classes / ("ForkAck" + name + ".class"))], check=True)
result = subprocess.run([str(java), "-cp", classpath, "Client118Checks"], check=True, capture_output=True, text=True)
output = ROOT / "build/verification/issue118/guards.txt"
output.write_text(result.stdout)
print(result.stdout.strip())
print("No client/server/GPU/world started. Minecraft runtime types were isolated stubs; production guard bytecode and fork redirect bytecode were exercised.")
if __name__ == "__main__":
main()