import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.jar.*; import java.io.*; import org.objectweb.asm.*; import org.objectweb.asm.tree.*; /** Deterministic source-compatibility linking and restoration of original ABI metadata. */ public final class FinalizeClasses { record Key(String owner,String name,String descriptor){} record Metadata(int access,String signature,String extra){} record Prefix(String name,String descriptor,int valueLocal){} static String decode(String value){return value.equals("-")?null:new String(Base64.getDecoder().decode(value),StandardCharsets.UTF_8);} static final Map types=new HashMap<>(); static final Map fields=new HashMap<>(),methods=new HashMap<>(); static final Map aliases=new HashMap<>(); static final Map> prefixes=new HashMap<>(); static final Map nesting=new HashMap<>(); static int count,relinked,helpers,restoredPrefixes; static String nullable(String value){return value.equals("-")?null:value;} static AbstractInsnNode previousCode(AbstractInsnNode node){do{node=node.getPrevious();}while(node!=null&&node.getOpcode()<0);return node;} static void restoreConstructorPrefix(ClassNode owner,MethodNode method) { List expected=prefixes.get(new Key(owner.name,method.name,method.desc));if(expected==null)return; MethodInsnNode parentInit=null; for(AbstractInsnNode i:method.instructions)if(i instanceof MethodInsnNode call&&call.getOpcode()==Opcodes.INVOKESPECIAL&&call.name.equals("")&&call.owner.equals(owner.superName)){parentInit=call;break;} if(parentInit==null)throw new IllegalStateException("Missing direct super constructor: "+owner.name+method.desc); InsnList prefix=new InsnList(); for(Prefix assignment:expected){ FieldInsnNode field=null;for(AbstractInsnNode i:method.instructions)if(i instanceof FieldInsnNode f&&f.getOpcode()==Opcodes.PUTFIELD&&f.owner.equals(owner.name)&&f.name.equals(assignment.name)&&f.desc.equals(assignment.descriptor)){if(field!=null)throw new IllegalStateException("Repeated captured field assignment");field=f;} if(field==null)throw new IllegalStateException("Missing captured field: "+owner.name+"."+assignment.name); AbstractInsnNode value=previousCode(field),receiver=value==null?null:previousCode(value); if(!(receiver instanceof VarInsnNode r)||r.getOpcode()!=Opcodes.ALOAD||r.var!=0||!(value instanceof VarInsnNode v)||v.getOpcode()!=Opcodes.ALOAD||v.var!=assignment.valueLocal)throw new IllegalStateException("Unsupported constructor capture: "+owner.name+method.desc); if(method.instructions.indexOf(field)0)method.instructions.insertBefore(method.instructions.getFirst(),prefix); } static byte[] link(byte[] input,boolean artifact){ ClassNode c=new ClassNode();new ClassReader(input).accept(c,0);Metadata cm=types.get(c.name); if(artifact&&cm!=null){c.access=cm.access;c.signature=cm.signature;c.version=Integer.parseInt(cm.extra);} if(artifact&&nesting.containsKey(c.name)){ String[] n=nesting.get(c.name);c.nestHostClass=nullable(n[1]);c.nestMembers=n[2].equals("-")||n[2].isEmpty()?null:new ArrayList<>(List.of(n[2].split(","))); c.outerClass=nullable(n[3]);c.outerMethod=nullable(n[4]);c.outerMethodDesc=nullable(n[5]);c.innerClasses=new ArrayList<>(); String inner=new String(Base64.getDecoder().decode(n[6]),StandardCharsets.UTF_8); for(String line:inner.split("\n"))if(!line.isEmpty()){String[] p=line.split("\t",-1);c.innerClasses.add(new InnerClassNode(p[0],nullable(p[1]),nullable(p[2]),Integer.parseInt(p[3])));} } for(FieldNode f:c.fields){Metadata m=fields.get(new Key(c.name,f.name,f.desc));if(artifact&&m!=null){f.access=m.access;f.signature=m.signature;}} for(MethodNode method:c.methods){ if(artifact&&method.name.equals(""))restoreConstructorPrefix(c,method); Metadata m=methods.get(new Key(c.name,method.name,method.desc));if(artifact&&m!=null){method.access=m.access;method.signature=m.signature;method.exceptions=m.extra.isEmpty()?new ArrayList<>():new ArrayList<>(List.of(m.extra.split(",")));} else if(m==null){ if(artifact){if(cm!=null)method.access|=Opcodes.ACC_SYNTHETIC;} else if((method.access&Opcodes.ACC_BRIDGE)==0&&!method.name.startsWith("lambda$"))method.access&=~Opcodes.ACC_SYNTHETIC; helpers++; } for(AbstractInsnNode instruction:method.instructions){ if(instruction instanceof MethodInsnNode call){String original=aliases.get(new Key(call.owner,call.name,call.desc));if(original!=null){call.name=original;relinked++;}} else if(instruction instanceof InvokeDynamicInsnNode indy){for(int k=0;k",p[1]),k->new ArrayList<>()).add(new Prefix(p[2],p[3],Integer.parseInt(p[4]))); } for(String line:Files.readAllLines(metadata.resolveSibling("class-nesting-"+suffix),StandardCharsets.UTF_8))if(!line.isBlank()&&!line.startsWith("owner\t")){String[] p=line.split("\t",-1);nesting.put(p[0],p);} Path directory=Path.of(args[2]); if(Files.isRegularFile(directory)){ Path staging=directory.resolveSibling(directory.getFileName()+".linking"); try(JarFile input=new JarFile(directory.toFile());JarOutputStream output=new JarOutputStream(Files.newOutputStream(staging))){ for(JarEntry entry:Collections.list(input.entries())){ JarEntry copy=new JarEntry(entry.getName());copy.setTime(entry.getTime());output.putNextEntry(copy); if(!entry.isDirectory()){byte[] bytes=input.getInputStream(entry).readAllBytes();output.write(entry.getName().endsWith(".class")?link(bytes,true):bytes);}output.closeEntry(); } } Files.move(staging,directory,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE); System.out.println("Artifact linking: classes="+count+", restoredReservedCalls="+relinked+", restoredConstructorPrefixes="+restoredPrefixes+", sourceCompatibilityMethods="+helpers);return; } if(!Files.isDirectory(directory))return; try(var paths=Files.walk(directory)){ for(Path path:paths.filter(p->p.toString().endsWith(".class")).sorted().toList()){ byte[] input=Files.readAllBytes(path),output=link(input,false); if(!Arrays.equals(input,output)){Path staging=path.resolveSibling(path.getFileName()+".linking");Files.write(staging,output);Files.move(staging,path,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.ATOMIC_MOVE);} } } System.out.println("Source linking: classes="+count+", restoredReservedCalls="+relinked+", sourceCompatibilityMethods="+helpers); } }