Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/lib/machinecode.py8# Module : Security9# Repository : https://git.spboucher.ai/qyvora10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Counts conditional branches in the compiled machine code of engine functions (arm64).4243The source of the engine avoids secret-dependent branches, but only the machine code decides: the44Swift optimiser is free to turn a branch-free expression into a conditional branch (it did for the45carry chain of the secp256k1 field arithmetic, finding QYV-AUD-002). This module disassembles the46release objects with `otool` and counts, per function, the conditional branch instructions47(b.cond, cbz, cbnz, tbz, tbnz). It cannot tell whether a branch depends on a secret: the policy48file lists the functions that must have none, and the reviewed maximum for the others.49"""5051from __future__ import annotations5253import re54import subprocess55from pathlib import Path5657COND = re.compile(r"^(b\.[a-z]{2}|cbz|cbnz|tbz|tbnz)$")58INS = re.compile(r"^([0-9a-f]{8,16})\s+(\S+)")596061def object_files(scratch: Path, module: str) -> list[Path]:62 """Release object files of an engine module, for both SwiftPM build layouts."""63 found = [p for p in scratch.rglob(f"{module}.o") if "Release" in str(p) or "release" in str(p)]64 if found:65 return found[:1]66 out = []67 for d in scratch.rglob(f"{module}.build"):68 if "release" in str(d).lower():69 out += [p for p in d.rglob("*.o")]70 return out717273def functions(obj: Path, symbols: Path | None = None) -> dict[str, dict]:74 """{demangled name: {instructions, conditional_branches}} for every text symbol of an object file or executable.75 `symbols`: file to read the symbol table from when the code file is stripped (the DWARF file of a dSYM)."""76 nm = subprocess.run(["nm", "-n", str(symbols or obj)], capture_output=True, text=True).stdout.splitlines()77 syms = []78 for line in nm:79 parts = line.split(" ", 2)80 if len(parts) == 3 and parts[0] and parts[1] in "tT":81 syms.append((int(parts[0], 16), parts[2]))82 if not syms:83 return {}84 demangled = subprocess.run(["xcrun", "swift-demangle"], input="\n".join(s for _, s in syms),85 capture_output=True, text=True).stdout.splitlines()86 dis = subprocess.run(["xcrun", "otool", "-tV", str(obj)], capture_output=True, text=True).stdout.splitlines()87 ins = []88 for line in dis:89 m = INS.match(line)90 if m:91 ins.append((int(m.group(1), 16), m.group(2)))92 ins.sort()93 out: dict[str, dict] = {}94 addresses = [a for a, _ in ins]95 import bisect96 for i, ((addr, _), name) in enumerate(zip(syms, demangled)):97 end = syms[i + 1][0] if i + 1 < len(syms) else addr + (1 << 30)98 lo, hi = bisect.bisect_left(addresses, addr), bisect.bisect_left(addresses, end)99 body = ins[lo:hi]100 if not body:101 continue102 entry = out.setdefault(name, {"instructions": 0, "conditional_branches": 0})103 entry["instructions"] += len(body)104 entry["conditional_branches"] += sum(1 for _, mnemonic in body if COND.match(mnemonic))105 return out106