"""(Triforce) nx2/cmpflags.py (A64_SUB_V): a subtraction's V written as N xor (a < b, signed), game-free. Python, no compiler: - rewrite() replaces SetFlags' subtraction V at both widths and nothing else; A64_SUB_V=0 leaves translate as it was. C (skipped without a compiler or on a host that is not x86-64), with a64emit built here as tests/test_fpx_sticky.py builds it: - the guest words below go through a64emit.translate twice, as the lift has it now (cmpflags on) and as before (the translate it wraps). The subtraction forms (SUBS and CMP immediate, shifted and extended register, 32 and 64 bits, and CCMP register and immediate) must differ only in V's text; the others (ADDS, CMN, ADCS, SBCS, ANDS, CCMN) must be the same text; - tests/cmpflags_test.c runs both from one Ctx and compares the whole Ctx after (every register, N, Z, C, V): every pair of 40 edge values (0, 1, -1, the signed and unsigned extremes at 32 and 64 bits and their neighbours) in the two source registers, under every NZCV the instruction may read (CCMP), then 2,000,000 random states a word; built at -O1 (the lifted code's level) and -O2 (the hot pieces'). It has teeth: with NEW's compare unsigned, or its sign bit taken from _fa, the C check fails (by hand, 2026-11-20). python -I -B tests/test_cmpflags.py [--cc clang] [--cxx clang++] [--random 2000000] """ import argparse import os import platform import sys import tempfile import time ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tests")) sys.path.insert(0, os.path.join(ROOT, "nx2")) # ((Triforce) the form under test: A64_SUB_V=1 or ovf. install() runs once a process and reads it then, so main() runs this # file again for each form; the lift's default here is off) FORM = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--form=")), None) os.environ.pop("A64_SUB_V", None) if FORM: os.environ["A64_SUB_V"] = FORM import test_fpx_sticky as fs # noqa: E402 (its compiler, target, build and run helpers; its paths on sys.path) SEED = 20261120 # (assembly, word, a subtraction whose V is rewritten) WORDS = ( ("cmp x1, x2", 0xEB02003F, 1), ("cmp w1, w2", 0x6B02003F, 1), ("subs x3, x1, x2", 0xEB020023, 1), ("subs w3, w1, w2, lsl #3", 0x6B020C23, 1), ("cmp x1, #5", 0xF100143F, 1), ("cmp w1, #4095", 0x713FFC3F, 1), ("subs x3, x1, #1, lsl #12", 0xF1400423, 1), ("cmp x1, w2, sxtw", 0xEB22C03F, 1), ("subs w3, w1, w2, uxtb #2", 0x6B220823, 1), ("ccmp x1, x2, #0, lt", 0xFA42B020, 1), ("ccmp w1, #3, #5, ne", 0x7A431825, 1), ("adds x3, x1, x2", 0xAB020023, 0), ("cmn w1, #7", 0x31001C3F, 0), ("adcs x3, x1, x2", 0xBA020023, 0), ("sbcs w3, w1, w2", 0x7A020023, 0), ("ands x3, x1, x2", 0xEA020023, 0), ("ccmn x1, x2, #2, ge", 0xBA42A022, 0), ) def fail(msg): raise SystemExit("cmpflags: FAIL: " + msg) def check_python(): import cmpflags t64 = "{ uint64_t _fa=(_a),_fb=(_b),_fr=(_r); c->z=(_fr==0); c->n=(int)((_fr>>63)&1); c->c=(_fa>=_fb); " + cmpflags.OLD[64] + " }" t32 = t64.replace("uint64_t", "uint32_t").replace("(_a)", "(uint32_t)(_a)").replace(">>63", ">>31").replace(cmpflags.OLD[64], cmpflags.OLD[32]) add = "c->v=(int)((((uint64_t)~(_fa^_fb)&(_fa^_fr))>>63)&1); }" if cmpflags.NEW[64] not in cmpflags.rewrite(t64) or cmpflags.OLD[64] in cmpflags.rewrite(t64): fail("the 64-bit subtraction's V not rewritten") if cmpflags.NEW[32] not in cmpflags.rewrite(t32) or cmpflags.OLD[32] in cmpflags.rewrite(t32): fail("the 32-bit subtraction's V not rewritten") if cmpflags.rewrite(add) != add: fail("an addition's V rewritten") for new in [v for form in cmpflags.FORMS.values() for v in form.values()]: if "c->n" in new.split("=", 1)[1] or ";" in new[:-1]: fail("NEW reads N from the context, or holds a ';' (dead_flags cuts a store at its first one): " + new) print("cmpflags: python checks passed") def lifted_cases(a64emit, cmpflags): words = [(0x1000 + 4 * i, w) for i, (_, w, _) in enumerate(WORDS)] now, fl = a64emit.translate(words) if any(fl): fail("a64emit did not translate the guest words: %s" % fl) old, _ = cmpflags._base[0](words) out = ["/* Generated by tests/test_cmpflags.py: each word as the lift translates it now and as before. */"] for i, ((asm, w, sub), n, o) in enumerate(zip(WORDS, now, old)): if sub: if n == o or any(x in n for x in cmpflags.OLD.values()) or not any(x in n for x in cmpflags.NEW.values()): fail("%s: V not rewritten: %s" % (asm, n[:400])) if n.replace(cmpflags.NEW[64], cmpflags.OLD[64]).replace(cmpflags.NEW[32], cmpflags.OLD[32]) != o: fail("%s: more than V's text changed" % asm) elif n != o: fail("%s: not a subtraction's V, but its text changed:\n before %s\n now %s" % (asm, o[:300], n[:300])) out.append("static void g_now%d(Ctx *__restrict c) { %s }" % (i, n)) out.append("static void g_old%d(Ctx *__restrict c) { %s }" % (i, o)) out.append("static const struct { const char *name; int sub; void (*now)(Ctx *), (*old)(Ctx *); } CASES[] = {%s};" % ", ".join('{"%s", %d, g_now%d, g_old%d}' % (asm, sub, i, i) for i, (asm, _, sub) in enumerate(WORDS))) return "\n".join(out) + "\n" def generate(cxx, tmp, flags): dll = os.path.join(tmp, "a64emit.dll" if os.name == "nt" else "liba64emit.so") fs.build([cxx, "-std=c++20", "-O0", "-shared", "-Wno-everything", "-o", dll, os.path.join(fs.KIT, "lift", "a64emit.cpp")] + flags + ([] if os.name == "nt" else ["-fPIC"]), "a64emit") import build_emit build_emit.build = lambda force=False: dll import a64_rtgen import a64emit # The lift imports these for discovery, not for translating these words. import importlib import types class Stub(types.ModuleType): def __getattr__(self, name): if name.startswith("__"): raise AttributeError(name) return 0 for name in ("capstone", "lz4", "lz4.block", "numpy"): try: importlib.import_module(name) except ImportError: sys.modules[name] = Stub(name) import lift # noqa: F401 (installs the actual lift's translate wrappers) import cmpflags if not cmpflags._base: fail("lift did not install cmpflags") try: # A batch without the old expression must bypass the per-instruction rewrite. words = [(0x1000, 0xEA020023)] # ANDS x3, x1, x2 expected = cmpflags._base[0](words) rewrite = cmpflags.rewrite try: def unexpected_rewrite(text): fail("rewrite called for a batch without subtraction V") cmpflags.rewrite = unexpected_rewrite if a64emit.translate(words) != expected: fail("batch without subtraction V changed") finally: cmpflags.rewrite = rewrite a64_rtgen.write(tmp) lifted = lifted_cases(a64emit, cmpflags) finally: if a64emit._lib is not None: import _ctypes (_ctypes.FreeLibrary if os.name == "nt" else _ctypes.dlclose)(a64emit._lib._handle) a64emit._lib = None with open(os.path.join(tmp, "cmpflags_lifted.h"), "w", newline="\n") as f: f.write(lifted) import a64_lift with open(os.path.join(tmp, "a64_fpx.h"), "w", newline="\n") as f: # (a64.h includes it; no float op here) f.write(a64_lift.fpx_header(set())) def check_off(): """A64_SUB_V=0: install() leaves translate alone (a new interpreter: install runs once a process)""" import subprocess for off in ("0", None): # ((Triforce) unset is off too: the default) code = ("import os, sys; sys.path.insert(0, sys.argv[1]); os.environ.pop('A64_SUB_V', None)\n" + ("os.environ['A64_SUB_V'] = '0'\n" if off else "") + "import kit, a64emit, cmpflags\nt = a64emit.translate\ncmpflags.install()\n" "print('same' if a64emit.translate is t and not cmpflags._base else 'wrapped')\n") r = subprocess.run([sys.executable, "-I", "-B", "-c", code, os.path.join(ROOT, "nx2")], capture_output=True, text=True) if r.stdout.strip() != "same": fail("A64_SUB_V %s still wraps translate: %s %s" % ("=0" if off else "unset", r.stdout, r.stderr[-500:])) print("cmpflags: A64_SUB_V=0 and unset leave translate as it was") def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--cc") p.add_argument("--cxx") p.add_argument("--random", type=int, default=2000000) p.add_argument("--form", help="1 or ovf: the form to check (without it: both, each in a process of its own)") a = p.parse_args() if not a.form: import subprocess check_off() for form in ("1", "ovf"): r = subprocess.run([sys.executable, "-I", "-B", os.path.abspath(__file__), "--form=" + form] + sys.argv[1:]) if r.returncode: fail("A64_SUB_V=%s (exit %d)" % (form, r.returncode)) print("cmpflags: both forms pass") return check_python() if platform.machine().lower() not in ("x86_64", "amd64"): fs.skip("not an x86-64 host: %s" % platform.machine()) cc = fs.compiler(a.cc, "CC", ("clang", "gcc", "cc"), "clang") cxx = fs.compiler(a.cxx, "CXX", ("clang++", "g++", "c++"), "clang++") if not cc or not cxx: fs.skip("no C compiler" if not cc else "no C++ compiler") t0 = time.time() failed = [] with tempfile.TemporaryDirectory(prefix="triforce-cmpflags-") as tmp: generate(cxx, tmp, fs.target_flags(cxx, tmp)) for opt in ("-O1", "-O2"): exe = os.path.join(tmp, "cmpflags_test%s.exe" % opt) fs.build([cc] + fs.target_flags(cc, tmp) + ["-march=x86-64", "-ffp-contract=off", "-fno-strict-aliasing", opt, "-D_CRT_SECURE_NO_WARNINGS", "-I" + os.path.join(fs.KIT, "rt"), "-I" + tmp, os.path.join(ROOT, "tests", "cmpflags_test.c"), os.path.join(tmp, "a64_suyu.c"), "-o", exe], "the driver at " + opt) for args in (["sweep"], ["random", str(a.random), str(SEED)]): r = fs.run([exe] + args, timeout=1800) print("%-4s %s" % (opt, r.stdout.rstrip())) if r.returncode: failed.append("%s %s (exit %d)" % (opt, args[0], r.returncode)) if failed: fail("%s in %.1f s" % (", ".join(failed), time.time() - t0)) print("cmpflags: pass in %.1f s" % (time.time() - t0)) if __name__ == "__main__": main()