ChronoSheaf-Input-Lag / verification /build_release.py
PureOne's picture
Add CHRONO-SHEAF III input latency research dataset
987b273 verified
Raw History Blame Contribute Delete
5.41 kB
"""Build this x64 release on a Linux research host using GCC, LLVM MC and GNU ld.
End users use the prebuilt add-on. Windows developers can use src/build-windows.cmd.
"""
import argparse
import ctypes as C
import math
import re
import subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
IMPORTS="""GetProcAddress QueryPerformanceFrequency QueryPerformanceCounter
GetCurrentThreadId TryAcquireSRWLockExclusive AcquireSRWLockExclusive ReleaseSRWLockExclusive
CreateWaitableTimerExW SetWaitableTimer WaitForSingleObject CloseHandle""".split()
def llvm_assemble(source, path):
lib=C.CDLL("libLLVM-19.so")
def fn(name,ret,*args):
f=getattr(lib,name);f.restype=ret;f.argtypes=list(args);return f
for item in ("TargetInfo","Target","TargetMC","AsmPrinter","AsmParser"):
fn("LLVMInitializeX86"+item,None)()
P,S,I=C.c_void_p,C.c_char_p,C.c_int
context=fn("LLVMContextCreate",P)()
module=fn("LLVMModuleCreateWithNameInContext",P,S,P)(b"xireun",context)
triple=b"x86_64-pc-windows-msvc"
fn("LLVMSetTarget",None,P,S)(module,triple)
data=source.encode()
fn("LLVMSetModuleInlineAsm2",None,P,S,C.c_size_t)(module,data,len(data))
target=P(); error=S()
if fn("LLVMGetTargetFromTriple",I,S,C.POINTER(P),C.POINTER(S))(triple,C.byref(target),C.byref(error)):
raise RuntimeError(error.value)
machine=fn("LLVMCreateTargetMachine",P,P,S,S,S,I,I,I)(target,triple,b"generic",b"",2,0,0)
if fn("LLVMTargetMachineEmitToFile",I,P,P,S,I,C.POINTER(S))(machine,module,str(path).encode(),1,C.byref(error)):
raise RuntimeError(error.value)
def windows_asm(original):
output=[]; prologue=False; started=finished=0
for line in original.splitlines():
v=line.strip()
if not v or v.startswith((".file",".local",".cfi_")):continue
if v.startswith(".type"):
if v.endswith("@function"):
name=v.split()[1].split(",")[0]
output.append(".seh_proc "+name);prologue=True;started+=1
continue
if v.startswith(".size"):
if ".-" in v:
if prologue:raise ValueError("unrecognized prologue")
output.append(".seh_endproc");finished+=1
continue
if v.startswith(".section"):
if ".note.GNU-stack" in v:continue
if ".rodata" in v:output.append('.section .rdata,"dr"');continue
if ".data.rel.local" in v:output.append('.data');continue
raise ValueError(v)
if v.startswith(".comm"):
name,size,alignment=v.split()[1].split(",")
output.extend([".bss",f".p2align {int(math.log2(int(alignment)))}",name+":",f".zero {size}"])
continue
v=v.replace("@PLT","")
if v.startswith(".string"):v=v.replace(".string",".asciz",1)
if v.startswith(".align"):v=v.replace(".align",".balign",1)
output.append(v)
if v.startswith("pushq"):
if not prologue:raise ValueError("unexpected push in fixed release")
output.append(".seh_pushreg "+v.split()[1])
m=re.fullmatch(r"subq\s+\$(\d+),\s*%rsp",v)
if m:
if not prologue:raise ValueError("variable stack layout")
output.extend([".seh_stackalloc "+m[1],".seh_endprologue"]);prologue=False
if started!=finished or not started:raise ValueError("incomplete unwind table")
return "\n".join(output)+"\n"
def main():
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument("build",type=Path)
args=ap.parse_args();b=args.build.resolve();b.mkdir(parents=True,exist_ok=True)
run=lambda *x:subprocess.run(list(map(str,x)),cwd=b,check=True)
run("gcc","-S","-mabi=ms","-mno-red-zone","-maccumulate-outgoing-args","-fno-stack-protector","-fno-ident",
"-fpie","-fno-shrink-wrap","-fno-shrink-wrap-separate","-fno-optimize-sibling-calls",
"-fno-tree-loop-distribute-patterns","-mgeneral-regs-only","-O2",ROOT/"src/reshade_adapter.c","-o","adapter.s")
asm=windows_asm((b/"adapter.s").read_text())
(b/"win64.s").write_text(asm);llvm_assemble(asm,b/"adapter.obj")
# GNU ld can create a PE import library from a definition file. The disposable
# symbol definitions are link inputs only. The release imports Windows KERNEL32.
(b/"kernel.def").write_text("LIBRARY KERNEL32.dll\nEXPORTS\n"+"\n".join(IMPORTS)+"\n")
llvm_assemble(".text\n"+"".join(f".globl {n}\n{n}:\n ret\n" for n in IMPORTS),b/"imports.obj")
run("ld","-mi386pep","--shared","--no-insert-timestamp","-e","0","--out-implib","kernel.a",
"imports.obj","kernel.def","-o","import-library-intermediate.dll")
(b/"addon.def").write_text("LIBRARY Xireun\nEXPORTS\nAddonInit\nAddonUninit\n\"NAME\" DATA\n\"DESCRIPTION\" DATA\n")
release=ROOT/"drop-in/Xireun.addon64"
run("ld","-mi386pep","--shared","--no-insert-timestamp","--nxcompat","--dynamicbase","-s","-e","0",
"adapter.obj","kernel.a","addon.def","-o",release)
dump=subprocess.check_output(["objdump","-p",str(release)],text=True)
for key in IMPORTS+["DLL Name: KERNEL32.dll","AddonInit","AddonUninit","NAME","DESCRIPTION",
".pdata","Nbr codes","reloc", "DIR64"]:
if key.lower() not in dump.lower():raise RuntimeError("missing PE property "+key)
(b/"pe-inspection.txt").write_text(dump)
print(release)
if __name__=="__main__":main()