#!/usr/bin/env python3 """Regenerate clang-offload-bundler-magic-collision.co. This input reproduces a magic-byte collision in the compressed offload bundle (CCOB) reader. The reader used to find the boundary between concatenated bundles by scanning for the literal 4-byte magic "CCOB"; because that magic can appear by chance inside a compressed payload, the reader could truncate a valid single bundle and then fail to decompress it. To make the collision deterministic we take a real compressed bundle produced by clang-offload-bundler and splice a zstd *skippable frame* whose body is the bytes "CCOB" into the compressed region. A zstd skippable frame is ignored by the decompressor, so the bundle still decompresses correctly, but a naive find("CCOB", 4) scan stops at the planted bytes. The bundle's header FileSize is updated so it remains authoritative. A reader that advances by FileSize handles this file correctly; a reader that scans for "CCOB" truncates and fails. Usage: clang-offload-bundler-magic-collision.py [output.co] """ import os import struct import subprocess import sys import tempfile # zstd skippable frame magic numbers are 0x184D2A50..0x184D2A5F. ZSTD_SKIPPABLE_MAGIC = 0x184D2A50 PLANTED_MAGIC = b"CCOB" def main(): if len(sys.argv) < 2: sys.exit("usage: %s [output.co]" % sys.argv[0]) bundler = sys.argv[1] out = ( sys.argv[2] if len(sys.argv) > 2 else os.path.join( os.path.dirname(os.path.abspath(__file__)), "clang-offload-bundler-magic-collision.co", ) ) with tempfile.TemporaryDirectory() as d: dev1 = os.path.join(d, "dev1") dev2 = os.path.join(d, "dev2") with open(dev1, "wb") as f: f.write(b"Content of device file 1\n") with open(dev2, "wb") as f: f.write(b"Content of device file 2\n") base = os.path.join(d, "base.co") subprocess.run( [ bundler, "-compress", "-type=bc", "-targets=hip-amdgcn-amd-amdhsa--gfx906," "hip-amdgcn-amd-amdhsa--gfx908", "-input=" + dev1, "-input=" + dev2, "-output=" + base, ], check=True, ) data = bytearray(open(base, "rb").read()) if data[:4] != b"CCOB": sys.exit("unexpected magic in compressed bundle") version = struct.unpack_from("