Spaces:
Sleeping

foxdec / sefm.py
ejschwartz's picture
Add C source mode, editable config and compiler options for SEFM
31b9410
Raw History Blame Contribute Delete
5.41 kB
import os
import re
import shlex
import shutil
from runner import ROOT, CommandError, read_preview, require_outputs, run_command
TOOL = ROOT / "sefm"
MAX_CONFIG = 1024 * 1024
MAX_SOURCE = 64 * 1024
DEFAULT_CFLAGS = "-O0 -fno-pie -no-pie -fno-stack-protector -fcf-protection=none"
MAX_CFLAGS = 32
# Optimization, code generation, warning and macro options only. Plugins, linker, assembler and
# preprocessor pass-through options, response files and extra include or output paths are refused.
ALLOWED_CFLAG = re.compile(r"-(?:O[0-3sgz]?|g\d?|f[a-z0-9][a-z0-9=,.+-]*|m[a-z0-9][a-z0-9=,.+-]*|std=[a-z0-9+:]+|"
r"W[a-z0-9][a-z0-9=,+-]*|D\w+(?:=\S*)?|U\w+|static|pie|no-pie)")
BLOCKED_CFLAG = re.compile(r"-(?:fplugin|fprofile|fdump|fopt-info|fsave|fcallgraph|fstack-usage|W[lap],|Wrapper)")
DISASSEMBLY = {
"objdump": ["-M", "intel", "-M", "hex", "--no-show-raw-insn", "-d"],
"data": ["-s"],
}
HEADERS = "#include <stdint.h>\n#include <stdbool.h>\n#include <stdlib.h>\n"
CONFIG_TEMPLATE = (
"Text sections:\nmain\n\n"
"Function signatures:\nmain [main_generated] :: EDI => RSI => EAX\n\n"
"Function types:\n\nData:\n\nPreamble:\n" + HEADERS
)
C_EXAMPLE = """\
unsigned sum_to(unsigned n) {
unsigned s = 0;
for (unsigned i = 1; i <= n; i++)
s += i;
return s;
}
int clamp(int x, int lo, int hi) {
if (x < lo) return lo;
if (x > hi) return hi;
return x;
}
int main(void) { return clamp(sum_to(10), 0, 50); }
"""
C_EXAMPLE_CONFIG = (
"Text sections:\nsum_to\nclamp\n\n"
"Function signatures:\nsum_to :: EDI => EAX\nclamp :: EDI => ESI => EDX => EAX\n\n"
"Function types:\n\nData:\n\nPreamble:\n" + HEADERS
)
# The artifact's parser targets binutils 2.26. Newer objdump adds instruction prefixes
# and endbr64, a no-op hint, which it cannot parse.
PREFIXES = re.compile(r"\t(?:(?:cs|data16|notrack|bnd) )+")
ENDBR = re.compile(r"\tendbr64\b")
def example_config():
return (TOOL / "example/wc.config").read_text()
def normalize(disassembly):
disassembly.write_text(ENDBR.sub("\tnop", PREFIXES.sub("\t", disassembly.read_text(errors="replace"))))
def checked(text, limit, what):
if len(text.encode()) > limit:
raise ValueError(f"Enter {what} no larger than {limit // 1024} KiB.")
return text.replace("\r\n", "\n")
def parse_cflags(text):
try:
flags = shlex.split(text or "")
except ValueError:
raise ValueError("The compiler options have unbalanced quotes.") from None
if len(flags) > MAX_CFLAGS:
raise ValueError(f"Enter at most {MAX_CFLAGS} compiler options.")
for flag in flags:
if not ALLOWED_CFLAG.fullmatch(flag) or BLOCKED_CFLAG.match(flag):
raise ValueError(f"The compiler option {flag!r} is not allowed. "
"Use -O, -g, -f, -m, -W, -D, -U, -std, -static, -pie or -no-pie options.")
return flags
def checked_config(text):
config = checked(text or "", MAX_CONFIG, "a configuration").strip("\n")
if not config.startswith("Text sections:"):
raise ValueError("The configuration must start with “Text sections:”. The built-in example shows the format.")
return config + "\n"
def stages(work, log, deadline, *, binary=None, source=None, cflags=DEFAULT_CFLAGS, config="", entries=()):
env = dict(os.environ, LANG="C.UTF-8")
config = checked_config(config)
flags = parse_cflags(cflags) if source is not None else []
for path in (TOOL / "preamble.c", TOOL / "bit_operations.c"):
shutil.copy(path, work)
if source is not None:
(work / "prog.c").write_text(checked(source, MAX_SOURCE, "C source"))
yield "Compiling the C source…", ()
run_command(["gcc", *flags, "-o", "prog", "prog.c"], work, log, deadline, limit_output=True)
binary = work / "prog"
if binary is None:
name = "wc"
for path in (TOOL / "example").iterdir():
shutil.copy(path, work)
else:
name = binary.name
yield "Disassembling the binary…", ()
for suffix, flags in DISASSEMBLY.items():
run_command(["objdump", *flags, name], work, log, deadline,
stdout=work / f"{name}.{suffix}", limit_output=True)
normalize(work / f"{name}.objdump")
(work / f"{name}.config").write_text(config)
yield "Decompiling the disassembly to C…", ()
analysis, generated = work / "decompilation.txt", work / "generated.c"
run_command([TOOL / "bin/main", f"{name}.objdump", f"{name}.data", f"{name}.config", "-c"],
work, log, deadline, env=env, stdout=analysis, limit_output=True)
if not generated.is_file():
with log.open("a") as diagnostics:
print(read_preview(analysis, tail=True)[-2000:], file=diagnostics)
raise RuntimeError("The decompiler produced no C code. Check the configuration and that the program stays within the paper’s subset.")
require_outputs(analysis, generated)
yield "Recompiling the generated C…", ()
files = [generated, analysis, work / f"{name}.config", log]
try:
run_command(["gcc", "-c", "-w", generated.name, "-o", "generated.o"], work, log, deadline, limit_output=True)
except CommandError as error:
yield f"Analysis stopped. The generated C does not recompile ({error}) See run.log.", files
else:
yield "The generated C recompiles.", files