diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3d878ea47b..dfb3dbbd32 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -208,6 +208,7 @@ jobs: tests/startup_gfx2hlsl_capture_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_archive_requests_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 0dd5a5ecd4..8dce302fa0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -157,6 +157,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py +./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 97ae83c778..3f0b6e11f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2202,6 +2202,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_capture COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_capture_check.py") set_tests_properties(startup_gfx2hlsl_capture PROPERTIES TIMEOUT 120) + # archive_requests.py writes runtime-keyed shader requests from a synthetic archive. + add_test(NAME startup_archive_requests COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_archive_requests_check.py") + set_tests_properties(startup_archive_requests PROPERTIES TIMEOUT 120) # Two integer operations whose refusal was never reached: v_cvt_i32_f32 with an output # modifier, and v_readfirstlane_b32 without a proven uniform source. add_test(NAME startup_gfx2hlsl_op_refusals COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f2785aa286..774c081b28 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -448,6 +448,67 @@ It writes: | `/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) | | `/files.txt` | every file the process opened | +### Shader requests from the archive, before a run + +`tools/startup/archive_requests.py [--roots ...]` writes +requests without starting the title, then `gfx2hlsl.py --pending ` translates them: + +```powershell +python -B tools/startup/archive_requests.py out/startup/shader_cache +python -B tools/startup/gfx2hlsl.py --pending out/startup/shader_cache +``` + +A startup run that traced every DirectStorage read showed where the native programs come from: +zlib streams in the shader archive that start on 64-byte boundaries and inflate to 64 KiB. Inflated +offline, those streams hold the exact bytes the runtime later records. Each program has a 36-byte +header followed by `s_inst_prefetch`, is padded in 64-byte blocks and starts on a 256-byte step, +and in every measured pipeline the vertex program directly follows the pixel program. The tool +carves every program that ends in `s_endpgm` (an all-zero block inside a program would cut it +short), pairs each pixel program with a vertex program that starts on the next 256-byte step +and writes `req_.{a,b,root}` with the runtime's key. + +What it cannot take from the archive: + +- **Root signatures.** None of the recorded root signatures occurs in the archive or the + executable; the title appears to serialize them at run time. The tool reads `req_*.root` files + from earlier runs (by default those in the cache) and writes each pair once per distinct root. + A key is only used when the title binds that pair with that root, so the extra requests cost + translation time and nothing else. +- **Pipelines the title builds from other sources.** Programs embedded in the executable as DXBC + containers are not in the archive. +- **Other pairings.** A program shared by several pipelines, or a pair that is not adjacent, is + only found by a run (`run.ps1 -Translate`). +- **Programs cut off at the end of a stream.** A zlib stream that starts on the 64-byte boundary + right after the previous one continues it, and the two are carved as one, so a program split + between them is kept. A program that reaches the end of such a joined run is skipped. + +A stream that would inflate past 1 MiB is counted as `oversized` and skipped without inflating it in +full, and a joined run stops growing at 64 MiB. A request is written as `.b`, `.root`, then `.a`; +if one part cannot be written, no `.a` and no temporary file are left and the run exits with an +error, as it does when the archive yields no pair at all. + +In one local measurement the tool joined 1,079 zlib streams into 800 runs, carved 4,982 programs +(2,730 pixel, 2,115 vertex, 137 other) and wrote 3,774 requests for 1,258 pairs and three recorded +root signatures in 22 s. Eight of the eleven pipelines that a cold run recorded were among them with +identical keys, and their translations (`.txt`, both `.hlsl` files and both `.cso` files) were +byte-identical to those from the run. The other three were two pipelines whose programs are DXBC +containers in the executable and one pipeline whose programs were not carved. + +Check with `python3 -B tests/startup_archive_requests_check.py` (ctest `startup_archive_requests`). +On a synthetic archive built from documented instruction words, each adjacent pixel/vertex pair +becomes one request per root, and the test computes the expected keys with its own copy of the +runtime's hash. Controls that write nothing: + +- a pixel program followed by a pixel program, or a vertex program without a pixel program before it; +- a vertex program one empty step after its pixel program, or after a pixel program without `s_endpgm`; +- a program without the header tag, or a pair at offsets that are not a multiple of 4; +- a pair that reaches the end of its stream, or a pair in a stream off the 64-byte grid; +- an empty or duplicate root file, an oversized stream, or a run without root signatures. + +A pair split between two consecutive zlib streams is carved whole. A blocked `.root` write leaves no +`.a` and no temporary file and fails the run, as does an archive without pairs. A second run writes +nothing new. + `run.ps1` prints the first five lines of `.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process did. Check with `python3 -B tests/startup_run_ps1_check.py` (ctest `startup_run_ps1`): on Windows it diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py new file mode 100644 index 0000000000..dc0109e7f1 --- /dev/null +++ b/tests/startup_archive_requests_check.py @@ -0,0 +1,206 @@ +"""archive_requests.py on a synthetic archive (pure Python, no Windows, no GPU, no title files). + +Programs follow the measured layout: a 36-byte header, s_inst_prefetch, code, s_code_end padding to +64 bytes, each on a 256-byte step of a zlib stream that starts on a 64-byte boundary. Each pixel +program directly followed by a vertex program must become one request per root, keyed exactly as +the runtime keys it; the expected keys are computed here with an independent FNV-1a, not with the +translator's function. + +Controls that must write nothing: a pixel program followed by another pixel program, a vertex +program with no pixel program before it, a vertex program one empty 256-byte step after a pixel +program, a pixel program without s_endpgm, a program without the header tag, a pair at an offset +that is not a multiple of 4, a program that runs to the end of its stream, a valid pair in a stream +that is not on a 64-byte boundary, an empty or duplicate root file, a stream that inflates past the +limit, and a run with no root signature. A pair split between two consecutive zlib streams must be +carved whole. A request whose .root cannot be written must leave no .a and no temporary file and make +the run fail. An archive without any pair must make the run fail. 65 MiB of consecutive streams +must be split into two joined runs. A second run must write nothing new. +""" +import re +import struct +import subprocess +import sys +import tempfile +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / 'tools' / 'startup' / 'archive_requests.py' + +REVISION = re.search(rb'constexpr char revision\[\] = "([^"]+)";', + (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_bytes()).group(1) +PREFETCH = bytes.fromhex('0300a0bf') # s_inst_prefetch 0x3 +CODE_END = bytes.fromhex('00009fbf') +ENDPGM = struct.pack(' [--roots ...] + +The archive stores native programs in zlib streams that start on 64-byte boundaries. Each program +begins with a 36-byte header followed by s_inst_prefetch and is padded in 64-byte blocks. In the +measured archive a pipeline's vertex program directly follows its pixel program, so each pixel +program followed by a vertex program in the same stream becomes one request (a = pixel, b = vertex, +the order the runtime records). Root signatures were not found in the archive; they are read from +existing req_*.root files (by default those already in the cache), and every pair is written once +per distinct root, so each key matches what the runtime would compute for that combination. +Translate the result with gfx2hlsl.py --pending . +""" +import argparse +import glob +import mmap +import os +import sys +import zlib + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl # noqa: E402 + +HEADER = 0x24 # bytes before s_inst_prefetch +HEADER_TAG = b'\x80\xd5' # bytes 2..3 of the first header word in every measured program +BLOCK = 0x40 +STEP = 0x100 # programs start on 256-byte steps of the stream +WINDOW = 0x20000 # compressed bytes offered to one stream; a 64 KiB stream needs far less +ENDPGM = bytes.fromhex('000081bf') # s_endpgm + + +def complete(program): + """True when the carved bytes hold an s_endpgm; an all-zero block inside a program cuts it short.""" + return any(program[at:at + 4] == ENDPGM for at in range(HEADER, len(program) - 3, 4)) + + +def stage_of(program): + """'vs', 'ps', 'other' or 'undecodable', from the export targets alone (the rule of + gfx2hlsl.classify). It reads the disassembler directly: gfx2hlsl.decode also refuses forms the + translator cannot lower, and whether a program can be translated must not decide its pairing.""" + code, at, exports = gfx2hlsl.strip_header(program), 0, [] + while at + 4 <= len(code): + try: + size, name, asm, _ = gfx2hlsl.D.decode_instruction(code, at) + except Exception: # noqa: BLE001 - any word the disassembler cannot read + return 'undecodable' + if name == 'exp': + exports.append(asm) + if name == 's_endpgm': + break + at += size + text = ' '.join(exports) + return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or not text else 'other' + + +def next_step(at, program): + """Stream offset of the 256-byte step right after the program.""" + return at + -(-len(program) // STEP) * STEP + + +def is_program(data, at): + return (at >= 0 and data[at + 2:at + 4] == HEADER_TAG + and data[at + HEADER:at + HEADER + 4] == gfx2hlsl.PREFETCH) + + +def carve(data): + """Yield (offset, program) in stream order; a program that runs past the stream is skipped.""" + hit = data.find(gfx2hlsl.PREFETCH) + while hit >= 0: + at = hit - HEADER + if at % 4 == 0 and is_program(data, at): + end = at + BLOCK + # 64-byte blocks until an all-zero block or the next program on a 256-byte step + while end + BLOCK <= len(data) and any(data[end:end + BLOCK]) and not ( + (end - at) % STEP == 0 and is_program(data, end)): + end += BLOCK + # a program that reaches the end of the joined stream may be cut off, so it is skipped + if end + BLOCK <= len(data): + yield at, data[at:end] + hit = data.find(gfx2hlsl.PREFETCH, hit + 4) + + +MAX_INFLATE = 0x100000 # one measured stream inflates to 64 KiB; a larger one is refused +MAX_JOINED = 0x4000000 # bound a joined run of consecutive streams (64 MiB) + + +def chunks(view, counts): + """Yield (archive offset, end offset, inflated bytes) for each complete zlib stream on a 64-byte + boundary. A stream that inflates past MAX_INFLATE is counted as oversized and skipped.""" + at = 0 + while at < len(view) - 1: + cmf, flg = view[at], view[at + 1] + if cmf == 0x78 and (cmf << 8 | flg) % 31 == 0: + inflater = zlib.decompressobj() + window = view[at:at + WINDOW] + try: + data = inflater.decompress(window, MAX_INFLATE) + except zlib.error: + data = b'' + if data and not inflater.eof and len(data) == MAX_INFLATE: + counts['oversized'] += 1 + elif inflater.eof and data: + end = at + len(window) - len(inflater.unused_data) + yield at, end, data + at = (end + 63) & ~63 + continue + at += 64 + + +def streams(archive, counts): + """Yield (archive offset, inflated bytes); a zlib stream that starts on the 64-byte boundary right + after the previous one continues it, so a program split between the two is carved whole.""" + with open(archive, 'rb') as file: + if os.fstat(file.fileno()).st_size == 0: + return + with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as view: + start, joined, size, expected = None, [], 0, None + for at, end, data in chunks(view, counts): + if joined and (at != expected or size + len(data) > MAX_JOINED): + yield start, b''.join(joined) + joined, size = [], 0 + if not joined: + start = at + joined.append(data) + size += len(data) + expected = (end + 63) & ~63 + if joined: + yield start, b''.join(joined) + + +def read_roots(paths): + roots = [] + for path in paths: + if not os.path.exists(path): + sys.exit('root signature path not found: %s' % path) + files = sorted(glob.glob(os.path.join(path, 'req_*.root'))) if os.path.isdir(path) else [path] + for name in files: + with open(name, 'rb') as file: + blob = file.read() + if blob and blob not in roots: + roots.append(blob) + return roots + + +def write_request(cache, key, a, b, root): + """Writes .b and .root, then .a last: the scanner treats .a as the ready marker. Returns 'written', + 'existing' or 'failed'; a failed write leaves no temporary file and no .a.""" + name = os.path.join(cache, 'req_%016x' % key) + if os.path.exists(name + '.a'): + return 'existing' + for ext, blob in (('.b', b), ('.root', root), ('.a', a)): + temporary = '%s%s.%d.tmp' % (name, ext, os.getpid()) + try: + with open(temporary, 'wb') as out: + out.write(blob) + os.replace(temporary, name + ext) + except OSError as error: + print('req_%016x%s: %s' % (key, ext, error), file=sys.stderr) + if os.path.exists(temporary): + os.remove(temporary) + return 'failed' + return 'written' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('archive') + parser.add_argument('cache') + parser.add_argument('--roots', nargs='+', help='req_*.root files or directories (default: the cache)') + args = parser.parse_args() + roots = read_roots(args.roots or [args.cache]) + if not roots: + sys.exit('no root signature found: run the title once with a shader cache, or pass --roots') + os.makedirs(args.cache, exist_ok=True) + # streams counts joined runs of consecutive zlib streams + counts = dict(streams=0, oversized=0, programs=0, incomplete=0, ps=0, vs=0, other=0, undecodable=0, + pairs=0, written=0, existing=0, failed=0) + for _, data in streams(args.archive, counts): + counts['streams'] += 1 + previous = None # (stage, offset, program) of the program carved just before + for at, program in carve(data): + counts['programs'] += 1 + if not complete(program): + counts['incomplete'] += 1 + previous = None + continue + stage = stage_of(program) + counts[stage] += 1 + # directly following: the vertex program starts on the 256-byte step after the pixel program + if stage == 'vs' and previous and previous[0] == 'ps' and at == next_step(previous[1], previous[2]): + counts['pairs'] += 1 + for root in roots: + # The runtime hashes its first recorded blob (the pixel program here) first. + # pipeline_key names its parameters vs_code, ps_code; only the order matters. + key = gfx2hlsl.pipeline_key(previous[2], program, root) + counts[write_request(args.cache, key, previous[2], program, root)] += 1 + previous = (stage, at, program) + counts['roots'] = len(roots) + print(' '.join('%s=%d' % item for item in counts.items())) + if counts['failed']: + sys.exit('%d request(s) could not be written' % counts['failed']) + if not counts['pairs']: + sys.exit('no program pair found in %s' % args.archive) + + +if __name__ == '__main__': + main()