Merge pull request #8588 from juanpimg/feat/export-gap-tool

feat(tools): add export_gap, which reports the exports a library lacks
This commit is contained in:
Dean authored and GitHub committed 2026-11-08 08:14:28 +13:00
commit 8f7c957ed0
3 files changed
+993

No files matched your search

+2
View File
@@ -290,6 +290,8 @@ if(BUILD_TESTING)
endif()
endforeach()
endif()
add_test(NAME export_gap COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_export_gap.py)
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py)
add_test(NAME audit_dump COMMAND ${Python3_EXECUTABLE}
+381
View File
@@ -0,0 +1,381 @@
#!/usr/bin/env python3
"""Report the console system library exports an AnyPS5 library does not provide.
Reads the export NIDs of the console library from a genstub style export table
or from a file of NIDs, intersects them with the pinned NID name database and
with what the AnyPS5 library already defines, and writes the missing NIDs in
the format tools/stubgen.py --nids takes.
"""
import argparse
import re
import sys
from pathlib import Path
import nid_names
ROOT = Path(__file__).resolve().parent.parent
PRX = ROOT / "core" / "libs" / "prx"
POSTFIXES = ("_nid_postfix", "_nid_no_patch_cut", "_nid_no_patch")
DISAMBIG = "_nid_disambig"
NID_PATTERN = "[A-Za-z0-9+\\-]{11}"
VABI = re.compile(r"\bAPS5_VABI\s+(\w+)\s*\(")
TABLE_ENTRY = re.compile(r"sprx_dlsym\s*\(\s*__handle\s*,\s*\"(" + NID_PATTERN + r")\"")
DEFINE = re.compile(r"#define\s+(\w+)\s*\(\s*(\w+)\s*\)([^\n]*)")
IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
MODULE_PATTERN = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]*\Z")
def is_mangled(name):
return name.startswith("_Z") and len(name) > 2 and name[2].isdigit()
def helper_reason(name):
if is_mangled(name):
return "is a C++ mangled name"
if IDENTIFIER.match(name) is None:
return "is not a valid C identifier"
return None
def is_safe_module(name):
if not name or name in (".", ".."):
return False
if "/" in name or "\\" in name:
return False
if ".." in name:
return False
return MODULE_PATTERN.match(name) is not None
class GapError(Exception):
pass
def strip_token(raw):
text = raw.lstrip("\ufeff").strip()
if not text:
return ""
if text.startswith("#"):
return ""
if "#" in text:
text = text.split("#", 1)[0].strip()
if not text:
return ""
return text.split()[0]
def parse_nids_file(path):
nids = []
seen = set()
try:
content = Path(path).read_text(encoding="utf-8-sig", errors="replace")
except OSError as error:
raise GapError(f"{path}: cannot read NID file: {error.strerror or error}") from error
for number, line in enumerate(content.split("\n"), 1):
token = strip_token(line)
if not token:
continue
if re.fullmatch(NID_PATTERN, token) is None:
raise GapError(f"{path}:{number}: invalid NID {token!r}")
if token not in seen:
seen.add(token)
nids.append(token)
return nids
def parse_export_table(path):
try:
text = Path(path).read_text(encoding="utf-8-sig", errors="replace")
except OSError as error:
raise GapError(f"{path}: cannot read export table: {error.strerror or error}") from error
nids = []
seen = set()
for match in TABLE_ENTRY.finditer(text):
nid = match.group(1)
if nid not in seen:
seen.add(nid)
nids.append(nid)
return nids
def mask_code(text):
def blank(match):
if match.group("code") is not None:
return match.group()
return re.sub(r"[^\n]", " ", match.group())
return nid_names.CPP_TOKEN.sub(blank, text)
def joined_lines(text):
return text.replace("\\\r\n", "").replace("\\\n", "")
def base_of(name):
for postfix in POSTFIXES:
if name.endswith(postfix) and len(name) > len(postfix):
return name[: -len(postfix)], postfix
return name, None
def strip_disambig(name):
pos = name.rfind(DISAMBIG)
if pos == -1:
return name
tail = name[pos + len(DISAMBIG):]
if tail and all(char in "0123456789" for char in tail):
return name[:pos]
return name
def source_texts(module_dir):
texts = []
for path in sorted(module_dir.rglob("*")):
if not path.is_file():
continue
if path.suffix.lower() not in (".cpp", ".c", ".cc", ".h", ".hpp", ".hh"):
continue
try:
texts.append((path, path.read_text(encoding="utf-8-sig", errors="replace")))
except OSError as error:
raise GapError(f"{path}: cannot read source: {error.strerror or error}") from error
return texts
def same_file(left, right):
left, right = Path(left), Path(right)
return left.resolve() == right.resolve() or (left.exists() and right.exists() and left.samefile(right))
def macro_definitions(texts):
macros = {}
for _, text in texts:
for match in DEFINE.finditer(joined_lines(text)):
macro, param, body = match.group(1), match.group(2), match.group(3)
if re.search(r"\bAPS5_VABI\s+" + re.escape(param) + r"\b", body) is not None:
macros.setdefault(macro, param)
return macros
def record_provided(provided, name, origin=None):
base, postfix = base_of(name)
prefix = f"{origin} " if origin else ""
if postfix == "_nid_no_patch_cut":
provided.setdefault(base, f"{prefix}literally as {base} under {name}")
return
if postfix == "_nid_no_patch":
provided.setdefault(name, f"{prefix}literally as {name}")
return
if postfix is not None and postfix != "_nid_postfix":
return
base = strip_disambig(base)
nid = nid_names.compute_nid(base)
if postfix is None:
provided.setdefault(nid, f"{prefix}under its own name {name}")
else:
provided.setdefault(nid, f"{prefix}under {name} for {base}")
def collect_provided(module_dir):
texts = source_texts(module_dir)
macros = macro_definitions(texts)
provided = {}
for _, text in texts:
for line in mask_code(joined_lines(text)).split("\n"):
if line.lstrip().startswith("#"):
continue
for match in VABI.finditer(line):
record_provided(provided, match.group(1))
for name in nid_names.source_assembly_definitions(text):
record_provided(provided, name, "defined in assembly")
for nid, helper in nid_names.source_aliases(text):
if nid not in provided:
provided[nid] = f"bound with APS5_EXPORT as {helper}"
for macro in sorted(macros):
call = re.compile(r"\b" + re.escape(macro) + r"\s*\(\s*(?:::)?(?:\w+::)*(\w+)\s*\)")
for path, text in texts:
masked = mask_code(text).split("\n")
originals = text.split("\n")
for index in range(len(masked)):
if originals[index].lstrip().startswith("#"):
continue
for match in call.finditer(masked[index]):
symbol = match.group(1)
base, postfix = base_of(symbol)
if postfix == "_nid_no_patch_cut":
if base not in provided:
provided[base] = f"through macro {macro} literally as {base} under {symbol}"
continue
if postfix == "_nid_no_patch":
if symbol not in provided:
provided[symbol] = f"through macro {macro} literally as {symbol}"
continue
if postfix is not None and postfix != "_nid_postfix":
continue
base = strip_disambig(base)
nid = nid_names.compute_nid(base)
if nid not in provided:
provided[nid] = f"through macro {macro} as {symbol}"
return provided
def find_self_calls(module_dir, missing):
if not missing:
return []
names = sorted(set(missing.values()))
alts = "|".join(re.escape(name) for name in names)
call = re.compile(r"(?<![\w:])(::)?\b(" + alts + r")\s*\(")
calls = []
for path, text in source_texts(module_dir):
joined = joined_lines(text)
masked = mask_code(joined)
rows = joined.split("\n")
try:
rel = path.relative_to(ROOT).as_posix()
except ValueError:
rel = path.as_posix()
declared = {}
for match in VABI.finditer(masked):
declared.setdefault(match.start(1), match.group(1))
for match in call.finditer(masked):
qual = match.group(1) or ""
name = match.group(2)
start = match.start(2)
if declared.get(start) == name:
continue
number = masked.count("\n", 0, match.start()) + 1
if rows[number - 1].lstrip().startswith("#"):
continue
nid = next(key for key, value in missing.items() if value == name)
calls.append((name, nid, rel, number, qual))
calls.sort(key=lambda item: (item[0], item[2], item[3], item[4]))
return calls
def load_console_nids(modules, export_table, nids_file):
if export_table is not None:
table_dir = Path(export_table)
if not table_dir.is_dir():
raise GapError(f"{table_dir}: not a directory")
console = {}
for module in modules:
table = table_dir / (module + ".c")
if not table.is_file():
raise GapError(f"{table}: export table not found")
console[module] = parse_export_table(table)
return console
nids = parse_nids_file(nids_file)
return {module: list(nids) for module in modules}
def report_module(module, console_nids, provided, db):
missing = []
already = []
unknown = []
for nid in console_nids:
if nid in provided:
already.append((nid, db.get(nid), provided[nid]))
elif nid not in db:
unknown.append(nid)
else:
missing.append((nid, db[nid]))
lines = [f"{module}: {len(missing)} missing, {len(already)} already provided, {len(unknown)} unknown"]
for nid, name in missing:
reason = helper_reason(name)
if reason is None:
lines.append(f"missing {nid} {name}")
else:
lines.append(f"{module}: {name} ({nid}) {reason} and needs a renamed helper bound with APS5_EXPORT, like libSceAmpr")
for nid, name, how in already:
if name is None:
lines.append(f"already provided {nid} {how}")
else:
lines.append(f"already provided {nid} {name} {how}")
for nid in unknown:
lines.append(f"unknown {nid} not in database, left out")
return missing, already, unknown, lines
def normalize_module(name):
if name.lower().endswith(".prx") and len(name) > 4:
return name[: -len(".prx")]
return name
def main(argv=None):
parser = argparse.ArgumentParser(description="report the console exports an AnyPS5 library does not provide")
parser.add_argument("--module", action="append", default=[], help="AnyPS5 library to report on, e.g. libScePad; repeat for several")
parser.add_argument("--export-table", default=None, help="directory of genstub style export tables, one <module>.c file per library")
parser.add_argument("--nids", default=None, help="file with one export NID per line, an alternative to --export-table")
parser.add_argument("--out", default=None, help="write the missing NIDs to this file; without it they go to standard output")
parser.add_argument("--db", default=None, help="NID name database file; the pinned database is used by default")
args = parser.parse_args(argv)
try:
modules = [normalize_module(name) for name in args.module]
if not modules:
raise GapError("--module is required")
if (args.export_table is None) == (args.nids is None):
raise GapError("exactly one of --export-table and --nids is required")
for module in modules:
if not is_safe_module(module):
raise GapError(f"{module}: invalid module name")
if not (PRX / module).is_dir():
raise GapError(f"{PRX / module}: no such library")
if args.out is not None:
sources = [args.nids, args.db]
if args.export_table is not None:
sources.extend(Path(args.export_table) / (module + ".c") for module in modules)
for source in filter(None, sources):
if same_file(args.out, source):
raise GapError(f"output {args.out!r} would overwrite input {source!r}")
try:
db = nid_names.load_db(Path(args.db) if args.db else nid_names.DEFAULT_CACHE)
except (OSError, UnicodeError) as error:
raise GapError(f"{args.db or nid_names.DEFAULT_CACHE}: cannot read NID database: {error}") from error
console = load_console_nids(modules, args.export_table, args.nids)
report = []
missing_nids = []
seen = set()
for module in modules:
provided = collect_provided(PRX / module)
missing, _, _, lines = report_module(module, console[module], provided, db)
missing_names = {nid: name for nid, name in missing}
calls = find_self_calls(PRX / module, missing_names)
report.extend(lines)
for name, nid, rel, line, qual in calls:
if qual:
report.append(f"{module}: {name} ({nid}) called at {rel}:{line} {qual}{name} needs a renamed helper bound with APS5_EXPORT, like libSceAmpr")
else:
report.append(f"{module}: {name} ({nid}) called at {rel}:{line} needs a renamed helper bound with APS5_EXPORT, like libSceAmpr")
for nid, _ in missing:
if nid not in seen:
seen.add(nid)
missing_nids.append(nid)
if args.out is not None:
destination = Path(args.out)
if destination.exists() and destination.is_dir():
raise GapError(f"{destination}: output is a directory")
try:
with open(destination, "w", encoding="utf-8", newline="\n") as handle:
handle.write("".join(nid + "\n" for nid in missing_nids))
except OSError as error:
raise GapError(f"{destination}: cannot write output: {error.strerror or error}") from error
else:
for nid in missing_nids:
print(nid)
for line in report:
print(line)
except GapError as error:
print(f"FAIL: {error}", file=sys.stderr)
return 2
except OSError as error:
print(f"FAIL: {error.strerror}: {error.filename}" if error.filename else f"FAIL: {error}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(encoding="utf-8", errors="replace")
raise SystemExit(main())
+610
View File
@@ -0,0 +1,610 @@
import contextlib
import io
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import export_gap
import nid_names
import stubgen
MODULE = "libSceExample"
def tree(directory):
root = Path(directory) / "root"
prx = root / "core" / "libs" / "prx"
tables = Path(directory) / "tables"
prx.mkdir(parents=True)
tables.mkdir(parents=True)
return root, prx, tables
def write_module(prx, module, files):
library = prx / module
library.mkdir(parents=True, exist_ok=True)
for name, content in files.items():
path = library / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return library
def write_table(tables, module, nids):
lines = "".join(f'sprx_dlsym(__handle, "{nid}", &__ptr_symbol{i});\n' for i, nid in enumerate(nids))
path = tables / (module + ".c")
path.write_text("void construct(void) {\n" + lines + "}\n", encoding="utf-8")
return path
def write_db(directory, pairs):
path = Path(directory) / "db.csv"
path.write_text("".join(f"{nid} {name}\n" for nid, name in pairs), encoding="utf-8")
return path
def run_tool(root, prx, args):
output = io.StringIO()
with patch.object(export_gap, "ROOT", root), patch.object(export_gap, "PRX", prx):
with contextlib.redirect_stdout(output):
code = export_gap.main(args)
return code, output.getvalue()
def run_tool_with_stderr(root, prx, args):
output = io.StringIO()
error = io.StringIO()
with patch.object(export_gap, "ROOT", root), patch.object(export_gap, "PRX", prx):
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
code = export_gap.main(args)
return code, output.getvalue(), error.getvalue()
def nid_of(name):
return nid_names.compute_nid(name)
def provides_with(source, nid):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": source})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExamplePlaceholder")])
out = Path(directory) / "out.txt"
code, _ = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
if code != 0:
raise AssertionError(f"export_gap failed for {nid}")
return out.read_text(encoding="utf-8") == ""
def provides(name, nid):
return provides_with(f"int APS5_VABI {name}(void) {{ return 0; }}\n", nid)
class ExportGapTests(unittest.TestCase):
def test_all_missing_are_reported(self):
first = nid_names.compute_nid("sceExampleAlpha")
second = nid_names.compute_nid("sceExampleBeta")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [first, second])
db = write_db(directory, [(first, "sceExampleAlpha"), (second, "sceExampleBeta")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [first, second])
self.assertIn(f"missing {first} sceExampleAlpha", report)
self.assertIn(f"missing {second} sceExampleBeta", report)
def test_postfix_name_counts_as_provided(self):
nid = nid_names.compute_nid("sceExamplePostfixBase")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int APS5_VABI sceExamplePostfixBase_nid_postfix(void) { return 0; }\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExamplePostfixBase")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8"), "")
self.assertFalse([line for line in report.splitlines() if line.startswith("missing ")])
self.assertIn("already provided", report)
self.assertIn("sceExamplePostfixBase_nid_postfix", report)
def test_assembly_postfix_name_counts_as_provided(self):
name = "sceExampleAsm_nid_postfix"
source = f'asm(APS5_ASM_FUNCTION("{name}") "ret");\n'
self.assertTrue(provides_with(source, nid_of("sceExampleAsm")))
def test_assembly_no_patch_name_does_not_provide_hashed_nid(self):
name = "sceExampleAsm_nid_no_patch"
source = f'asm(APS5_ASM_FUNCTION("{name}") "ret");\n'
self.assertFalse(provides_with(source, nid_of("sceExampleAsm")))
def test_assembly_no_patch_name_with_export_alias_counts_as_provided(self):
name = "sceExampleAsm_nid_no_patch"
nid = nid_of("sceExampleAsm")
source = f'asm(APS5_ASM_FUNCTION("{name}") "ret");\nAPS5_EXPORT("{nid}", {name});\n'
self.assertTrue(provides_with(source, nid))
def test_no_patch_name_does_not_provide_hashed_nid(self):
self.assertFalse(provides("sceExampleNoPatchBase_nid_no_patch", "T2IWNGg3cnI"))
def test_no_patch_cut_name_does_not_provide_hashed_nid(self):
self.assertFalse(provides("sceExampleNoPatchBase_nid_no_patch_cut", "T2IWNGg3cnI"))
def test_postfix_name_provides_hashed_base_nid(self):
self.assertTrue(provides("sceExampleBase_nid_postfix", nid_of("sceExampleBase")))
def test_disambig_postfix_provides_hashed_base_nid(self):
self.assertTrue(provides("alias_nid_disambig12_nid_postfix", nid_of("alias")))
def test_bare_disambig_provides_hashed_base_nid(self):
self.assertTrue(provides("foo_nid_disambig1", nid_of("foo")))
def test_disambig_non_digit_tail_left_alone(self):
self.assertFalse(provides("foo_nid_disambigX", nid_of("foo")))
self.assertTrue(provides("foo_nid_disambigX", nid_of("foo_nid_disambigX")))
def test_macro_disambig_postfix_counts_as_provided(self):
nid = nid_names.compute_nid("alias")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": (
"int before(void) { return 0; }\n"
"#define EXAMPLE_MACRO(NAME) int APS5_VABI NAME(void) { return 0; }\n"
"EXAMPLE_MACRO(alias_nid_disambig12_nid_postfix)\n")})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "alias")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8"), "")
self.assertIn("already provided", report)
def test_no_patch_cut_base_counts_as_literally_provided(self):
base = "sceCutBase1"
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": f"int APS5_VABI {base}_nid_no_patch_cut(void) {{ return 0; }}\n"})
write_table(tables, MODULE, [base])
db = write_db(directory, [(base, base)])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8"), "")
self.assertFalse([line for line in report.splitlines() if line.startswith("missing ")])
self.assertIn("already provided", report)
self.assertIn(base, report)
def test_no_patch_full_name_counts_as_literally_provided(self):
name = "sceExampleHelper_nid_no_patch"
with tempfile.TemporaryDirectory() as directory:
_, prx, _ = tree(directory)
library = write_module(prx, MODULE, {"Export.cpp": f"int APS5_VABI {name}(void) {{ return 0; }}\n"})
provided = export_gap.collect_provided(library)
self.assertIn(name, provided)
self.assertIn(name, provided[name])
self.assertNotIn(nid_of(name), provided)
self.assertNotIn(nid_of("sceExampleHelper"), provided)
def test_no_patch_cut_literal_provided_while_hashed_base_still_missing(self):
base = "sceCutBase1"
hashed = nid_of(base)
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": f"int APS5_VABI {base}_nid_no_patch_cut(void) {{ return 0; }}\n"})
write_table(tables, MODULE, [base, hashed])
db = write_db(directory, [(base, base), (hashed, "sceCutBaseHashed")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [hashed])
self.assertIn(f"already provided {base}", report)
self.assertIn(f"missing {hashed} sceCutBaseHashed", report)
def test_macro_invocation_counts_as_provided(self):
nid = nid_names.compute_nid("sceExampleMacroProvided")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": (
"int before(void) { return 0; }\n"
"#define EXAMPLE_MACRO(NAME) int APS5_VABI NAME(void) { return 0; }\n"
"EXAMPLE_MACRO(sceExampleMacroProvided)\n")})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleMacroProvided")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8"), "")
self.assertIn("already provided", report)
self.assertIn("EXAMPLE_MACRO", report)
def test_explicit_export_binding_counts_as_provided(self):
nid = nid_names.compute_nid("sceExampleExplicit")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": (
f'APS5_EXPORT("{nid}", myExampleHelper);\n'
"int APS5_VABI myExampleHelper(void) { return 0; }\n")})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleExplicit")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8"), "")
self.assertIn("already provided", report)
self.assertIn("APS5_EXPORT", report)
def test_unknown_nid_is_reported_and_left_out(self):
known = nid_names.compute_nid("sceExampleKnown")
ghost = "AAAAAAAAAAA"
self.assertNotEqual(known, ghost)
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [known, ghost])
db = write_db(directory, [(known, "sceExampleKnown")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [known])
self.assertIn(f"missing {known} sceExampleKnown", report)
self.assertIn(ghost, report)
self.assertIn("not in database", report)
def test_self_call_needs_renamed_helper(self):
nid = nid_names.compute_nid("sceExampleSelfCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleOther(void) { return 0; }\n",
"Caller.cpp": (
"int use(void) {\n"
" return sceExampleSelfCall(1);\n"
"}\n")})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleSelfCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertIn(f"missing {nid} sceExampleSelfCall", report)
self.assertIn("renamed helper", report)
self.assertIn("APS5_EXPORT", report)
self.assertIn("libSceAmpr", report)
self.assertIn("Caller.cpp:2", report)
def test_self_call_with_qualifier_needs_renamed_helper(self):
first = nid_names.compute_nid("sceExampleGlobalCall")
second = nid_names.compute_nid("sceExampleMemberCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleOther(void) { return 0; }\n",
"Caller.cpp": (
"int useGlobal(void) {\n"
" return ::sceExampleGlobalCall(1);\n"
"}\n"
"int useMember(void) {\n"
" return ns::sceExampleMemberCall(1);\n"
"}\n")})
write_table(tables, MODULE, [first, second])
db = write_db(directory, [(first, "sceExampleGlobalCall"), (second, "sceExampleMemberCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertIn(f"missing {first} sceExampleGlobalCall", report)
self.assertIn(f"missing {second} sceExampleMemberCall", report)
self.assertIn("renamed helper", report)
self.assertIn("APS5_EXPORT", report)
self.assertIn("libSceAmpr", report)
self.assertIn("Caller.cpp:2", report)
self.assertIn("::sceExampleGlobalCall", report)
self.assertIn(f"sceExampleGlobalCall ({first}) called at", report)
self.assertNotIn("ns::sceExampleMemberCall", report)
self.assertNotIn(f"sceExampleMemberCall ({second}) called at", report)
def test_nids_input_matches_export_table(self):
first = nid_names.compute_nid("sceExampleAlpha")
second = nid_names.compute_nid("sceExampleBeta")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [first, second])
nids_file = Path(directory) / "nids.txt"
nids_file.write_text(first + "\n" + second + "\n", encoding="utf-8")
db = write_db(directory, [(first, "sceExampleAlpha"), (second, "sceExampleBeta")])
first_out = Path(directory) / "first.txt"
second_out = Path(directory) / "second.txt"
first_code, first_report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(first_out)])
second_code, second_report = run_tool(root, prx, ["--module", MODULE, "--nids", str(nids_file), "--db", str(db), "--out", str(second_out)])
self.assertEqual(first_code, 0)
self.assertEqual(second_code, 0)
self.assertEqual(first_out.read_text(encoding="utf-8"), second_out.read_text(encoding="utf-8"))
self.assertEqual(first_report, second_report)
def test_out_file_uses_stubgen_nids_format(self):
first = nid_names.compute_nid("sceExampleAlpha")
second = nid_names.compute_nid("sceExampleBeta")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [first, second])
db = write_db(directory, [(first, "sceExampleAlpha"), (second, "sceExampleBeta")])
out = Path(directory) / "out.txt"
code, _ = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(stubgen.parse_nids(out), [first, second])
for line in out.read_text(encoding="utf-8").split("\n"):
if line:
self.assertEqual(len(line), 11)
def test_self_call_in_header_is_reported(self):
nid = nid_names.compute_nid("sceExampleHeaderCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleOther(void) { return 0; }\n",
"Include.h": "int useHeader(void) {\n return sceExampleHeaderCall(1);\n}\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleHeaderCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertIn(f"missing {nid} sceExampleHeaderCall", report)
self.assertIn("renamed helper", report)
self.assertIn("Include.h:2", report)
def test_self_call_in_c_file_is_reported(self):
nid = nid_names.compute_nid("sceExampleCCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleOther(void) { return 0; }\n",
"Caller.c": "int use(void) {\n return sceExampleCCall(1);\n}\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleCCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertIn(f"missing {nid} sceExampleCCall", report)
self.assertIn("renamed helper", report)
self.assertIn("Caller.c:2", report)
def test_self_call_split_over_two_lines_is_reported(self):
nid = nid_names.compute_nid("sceExampleSplitCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleOther(void) { return 0; }\n",
"Caller.cpp": "int use(void) {\n return sceExampleSplitCall\n (1);\n}\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleSplitCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertIn(f"missing {nid} sceExampleSplitCall", report)
self.assertIn("renamed helper", report)
self.assertIn("Caller.cpp:2", report)
def test_self_call_in_comment_or_string_is_not_reported(self):
nid = nid_names.compute_nid("sceExampleQuietCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleOther(void) { return 0; }\n",
"Caller.cpp": "// sceExampleQuietCall(1)\nconst char *text = \"sceExampleQuietCall(1)\";\nint use(void) { return 0; }\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleQuietCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertIn(f"missing {nid} sceExampleQuietCall", report)
self.assertNotIn("renamed helper", report)
def test_self_declaration_is_not_a_call(self):
nid = nid_names.compute_nid("sceExampleDeclaredOnly")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {
"Export.cpp": "int APS5_VABI sceExampleDeclaredOnly(void) { return 0; }\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleDeclaredOnly")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertNotIn("renamed helper", report)
def test_missing_module_fails(self):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
db = write_db(directory, [])
code, _, error = run_tool_with_stderr(root, prx, ["--export-table", str(tables), "--db", str(db)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
def test_both_export_table_and_nids_fails(self):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
nids_file = Path(directory) / "nids.txt"
nids_file.write_text("AAAAAAAAAAA\n", encoding="utf-8")
db = write_db(directory, [])
code, _, error = run_tool_with_stderr(root, prx, ["--module", MODULE, "--export-table", str(tables), "--nids", str(nids_file), "--db", str(db)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
def test_invalid_module_name_fails(self):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
db = write_db(directory, [])
code, _, error = run_tool_with_stderr(root, prx, ["--module", "bad-name!", "--export-table", str(tables), "--db", str(db)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
def test_missing_library_directory_fails(self):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
db = write_db(directory, [])
code, _, error = run_tool_with_stderr(root, prx, ["--module", "libSceDoesNotExist", "--export-table", str(tables), "--db", str(db)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
def test_out_refuses_to_overwrite_db(self):
first = nid_names.compute_nid("sceExampleAlpha")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [first])
db = write_db(directory, [(first, "sceExampleAlpha")])
code, _, error = run_tool_with_stderr(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(db)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
self.assertIn("would overwrite input", error)
def test_out_refuses_to_overwrite_export_table(self):
first = nid_names.compute_nid("sceExampleAlpha")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
table = write_table(tables, MODULE, [first])
before = Path(table).read_bytes()
db = write_db(directory, [(first, "sceExampleAlpha")])
code, _, error = run_tool_with_stderr(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(Path(tables) / (MODULE + ".c"))])
self.assertEqual(code, 2)
self.assertIn("would overwrite input", error)
self.assertEqual(Path(table).read_bytes(), before)
def test_out_refuses_hardlink_of_export_table(self):
first = nid_names.compute_nid("sceExampleAlpha")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
table = write_table(tables, MODULE, [first])
before = Path(table).read_bytes()
link = Path(directory) / "alias.c"
try:
os.link(table, link)
except (OSError, NotImplementedError):
self.skipTest("hard links unavailable")
db = write_db(directory, [(first, "sceExampleAlpha")])
code, _, error = run_tool_with_stderr(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(link)])
self.assertEqual(code, 2)
self.assertIn("would overwrite input", error)
self.assertEqual(Path(table).read_bytes(), before)
def test_out_refuses_to_overwrite_nids(self):
first = nid_names.compute_nid("sceExampleAlpha")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
nids_file = Path(directory) / "nids.txt"
nids_file.write_text(first + "\n", encoding="utf-8")
db = write_db(directory, [(first, "sceExampleAlpha")])
code, _, error = run_tool_with_stderr(root, prx, ["--module", MODULE, "--nids", str(nids_file), "--db", str(db), "--out", str(nids_file)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
self.assertIn("would overwrite input", error)
def test_qualified_macro_argument_counts_as_provided(self):
for argument in ("ns::sceExampleQualifiedMacro", "::sceExampleQualifiedMacro"):
nid = nid_names.compute_nid("sceExampleQualifiedMacro")
with self.subTest(argument=argument):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": (
"int before(void) { return 0; }\n"
"#define EXAMPLE_MACRO(NAME) int APS5_VABI NAME(void) { return 0; }\n"
f"EXAMPLE_MACRO({argument})\n")})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, "sceExampleQualifiedMacro")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8"), "")
self.assertIn("already provided", report)
def test_mangled_name_needs_renamed_helper(self):
name = "_Z5dummyv"
nid = nid_names.compute_nid(name)
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, name)])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [nid])
self.assertNotIn(f"missing {nid} {name}", report)
self.assertIn(name, report)
self.assertIn(nid, report)
self.assertIn("mangled", report)
self.assertIn("renamed helper", report)
self.assertIn("APS5_EXPORT", report)
self.assertIn("libSceAmpr", report)
def test_non_identifier_name_needs_renamed_helper(self):
name = "sceExample.dot-name"
nid = nid_names.compute_nid(name)
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, name)])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [nid])
self.assertNotIn(f"missing {nid} {name}", report)
self.assertIn("valid C identifier", report)
self.assertIn("renamed helper", report)
self.assertIn("APS5_EXPORT", report)
self.assertIn("libSceAmpr", report)
def test_native_module_name_is_accepted(self):
native = "libSceExample.native"
nid = nid_names.compute_nid("sceExampleNativeCall")
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, native, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, native, [nid])
db = write_db(directory, [(nid, "sceExampleNativeCall")])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", native, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [nid])
self.assertIn(f"missing {nid} sceExampleNativeCall", report)
def test_underscore_name_is_plain_missing(self):
name = "_sceExampleUnderscore"
nid = nid_names.compute_nid(name)
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
write_module(prx, MODULE, {"Export.cpp": "int helper(void) { return 0; }\n"})
write_table(tables, MODULE, [nid])
db = write_db(directory, [(nid, name)])
out = Path(directory) / "out.txt"
code, report = run_tool(root, prx, ["--module", MODULE, "--export-table", str(tables), "--db", str(db), "--out", str(out)])
self.assertEqual(code, 0)
self.assertEqual(out.read_text(encoding="utf-8").split(), [nid])
self.assertIn(f"missing {nid} {name}", report)
def test_slash_module_name_fails(self):
with tempfile.TemporaryDirectory() as directory:
root, prx, tables = tree(directory)
db = write_db(directory, [])
code, _, error = run_tool_with_stderr(root, prx, ["--module", "libSceExample/bad", "--export-table", str(tables), "--db", str(db)])
self.assertEqual(code, 2)
self.assertIn("FAIL:", error)
if __name__ == "__main__":
unittest.main()