strip-wasm-debug.py (1024B)
1 #!/usr/bin/env python3 2 """Drop .debug_* custom sections from a wasm module, keeping `name`.""" 3 import sys 4 5 6 def uleb(buf, i): 7 result = shift = 0 8 while True: 9 byte = buf[i] 10 i += 1 11 result |= (byte & 0x7F) << shift 12 shift += 7 13 if not byte & 0x80: 14 return result, i 15 16 17 def strip(data): 18 assert data[:4] == b"\0asm", "not a wasm module" 19 out, i = bytearray(data[:8]), 8 20 while i < len(data): 21 start = i 22 section_id = data[i] 23 i += 1 24 size, i = uleb(data, i) 25 keep = True 26 if section_id == 0: # custom 27 n, j = uleb(data, i) 28 keep = not data[j:j + n].decode("utf8", "replace").startswith(".debug") 29 if keep: 30 out += data[start:i + size] 31 i += size 32 return bytes(out) 33 34 35 if __name__ == "__main__": 36 src, dst = sys.argv[1], sys.argv[2] 37 data = open(src, "rb").read() 38 out = strip(data) 39 open(dst, "wb").write(out) 40 print(f"{len(data):,} -> {len(out):,} bytes")