"""Ultra3D memory-cap modification, 2026-11-10. LGPL-2.1-or-later.
Usage: python cap-wasm-memory.py ORIGINAL.wasm NEW-CAPPED.wasm
Output must not exist. Does not modify the input. No vendor code is executed.
"""
import sys,pathlib,hashlib

def read(b,p):
 n=0;s=0
 for _ in range(5):
  c=b[p];p+=1;n|=(c&127)<<s
  if not c&128:return n,p
  s+=7
 raise ValueError('Invalid unsigned LEB128')
def leb(n):
 out=bytearray()
 while True:
  b=n&127;n>>=7;out.append(b|(128 if n else 0))
  if not n:return bytes(out)
def cap(b):
 if len(b)>10*1024*1024 or b[:8]!=b'\0asm\1\0\0\0':raise ValueError('Invalid or excessive WASM input')
 out=bytearray(b[:8]);p=8;patched=False
 while p<len(b):
  tag=b[p];p+=1;size,p=read(b,p)
  if p+size>len(b):raise ValueError('Truncated section')
  body=b[p:p+size];p+=size
  if tag==5:
   count,q=read(body,0);flags,q=read(body,q);minimum,q=read(body,q);maximum,q=read(body,q)
   if patched or count!=1 or flags!=1 or minimum>4096 or maximum!=32768 or q!=len(body):raise ValueError('Unexpected memory declaration')
   body=leb(1)+leb(1)+leb(minimum)+leb(4096);patched=True
  out.append(tag);out.extend(leb(len(body)));out.extend(body)
 if not patched:raise ValueError('Expected memory declaration absent')
 return bytes(out)
if __name__=='__main__':
 if len(sys.argv)!=3:raise SystemExit(__doc__)
 source,target=map(pathlib.Path,sys.argv[1:]);before=source.read_bytes();after=cap(before)
 with target.open('xb') as f:f.write(after)
 print('INPUT_SHA256='+hashlib.sha256(before).hexdigest())
 print('OUTPUT_SHA256='+hashlib.sha256(after).hexdigest())
