From 9766c93518ecd76e308ba82596bd6bfb58f0d35a Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Thu, 19 Nov 2026 13:10:15 +0800 Subject: [PATCH] test(elf): protect GCC unique export bindings (#12049) --- .../nativeExportsGnuUnique.test.ts | 134 ++++++++++++++++++ tests/fixtures/elf-gnu-unique/README.md | 26 ++++ tests/fixtures/elf-gnu-unique/inline.cpp | 4 + tests/fixtures/elf-gnu-unique/oracle.json | 66 +++++++++ tests/fixtures/elf-gnu-unique/produce.py | 91 ++++++++++++ 5 files changed, 321 insertions(+) create mode 100644 tests/acceptance/applications/nativeExportsGnuUnique.test.ts create mode 100644 tests/fixtures/elf-gnu-unique/README.md create mode 100644 tests/fixtures/elf-gnu-unique/inline.cpp create mode 100644 tests/fixtures/elf-gnu-unique/oracle.json create mode 100644 tests/fixtures/elf-gnu-unique/produce.py diff --git a/tests/acceptance/applications/nativeExportsGnuUnique.test.ts b/tests/acceptance/applications/nativeExportsGnuUnique.test.ts new file mode 100644 index 0000000000..dd0ba656a2 --- /dev/null +++ b/tests/acceptance/applications/nativeExportsGnuUnique.test.ts @@ -0,0 +1,134 @@ +import { createHash } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; +import { z } from "zod"; + +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { nativeExportsSchema } from "../../../src/domain/native/nativeExports.js"; +import { elfExportImage } from "../../fixtures/binaryDiagnostics/nativeExports.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +const oracle = z + .object({ + variants: z.array( + z.object({ + name: z.string(), + os_abi: z.int().min(0).max(255), + symbols: z.array( + z.object({ + name: z.string(), + value: z.string(), + size: z.string(), + type_code: z.int(), + type: z.enum(["object", "tls"]), + binding_code: z.int(), + binding: z.enum(["weak", "unique"]), + visibility: z.literal("default"), + }), + ), + }), + ), + }) + .parse( + JSON.parse( + await readFile( + new URL("../../fixtures/elf-gnu-unique/oracle.json", import.meta.url), + "utf8", + ), + ), + ); + +// Keep coverage independent of the rows used to construct the ELF carrier. +// Missing producer variants or symbols must fail before tests are registered. +expect( + oracle.variants.map(({ name, symbols }) => ({ + name, + symbols: symbols.map(({ name, type, binding }) => ({ + name, + type, + binding, + })), + })), +).toEqual([ + { + name: "gnu_unique", + symbols: [ + { name: "process_value", type: "object", binding: "unique" }, + { name: "thread_value", type: "tls", binding: "unique" }, + ], + }, + { + name: "weak", + symbols: [ + { name: "process_value", type: "object", binding: "weak" }, + { name: "thread_value", type: "tls", binding: "weak" }, + ], + }, +]); + +for (const variant of oracle.variants) { + cliTest( + `preserves GCC ${variant.name} object and TLS bindings through native export Evidence`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-elf-inline-bindings-"); + const path = join(root, `${variant.name}.so`); + // Reframe independently observed symbol facts in a portable carrier. This + // does not claim to exercise the compiler's complete ELF layout in CI. + const bytes = elfExportImage({ + symbols: variant.symbols.map((symbol) => ({ + name: symbol.name, + type: symbol.type_code, + binding: symbol.binding_code, + value: BigInt(symbol.value), + size: BigInt(symbol.size), + })), + }); + bytes[7] = variant.os_abi; + await writeFile(path, bytes); + const result = await cli.run({ + arguments: ["inspect-native-exports", path, "--json"], + }); + expect(result.exitCode, result.stderr).toBe(0); + const evidence = toolContract( + "inspect_native_exports", + ).outputSchema.parse(result.json); + const report = nativeExportsSchema.parse(evidence.normalized_result); + if (report.format !== "elf") + throw new Error("Expected ELF export Evidence"); + expect(report).toMatchObject({ + format: "elf", + artifact: { + path, + sha256: createHash("sha256").update(bytes).digest("hex"), + }, + coverage: { status: "complete", exports: variant.symbols.length }, + issues: [], + }); + expect( + report.exports.map( + ({ name, value, size, type, binding, visibility }) => ({ + name, + value, + size, + type, + binding, + visibility, + }), + ), + ).toEqual( + variant.symbols.map( + ({ name, value, size, type, binding, visibility }) => ({ + name, + value, + size, + type, + binding, + visibility, + }), + ), + ); + }, + ); +} diff --git a/tests/fixtures/elf-gnu-unique/README.md b/tests/fixtures/elf-gnu-unique/README.md new file mode 100644 index 0000000000..aa4fe5debe --- /dev/null +++ b/tests/fixtures/elf-gnu-unique/README.md @@ -0,0 +1,26 @@ +# GCC inline-variable export facts + +`inline.cpp` declares ordinary and thread-local inline C++17 variables. GCC +14.2 emits `STB_GNU_UNIQUE` for both. Compiling the same source with +`-fno-gnu-unique` emits `STB_WEAK` instead. No library is loaded or executed. + +`produce.py` compiles both variants in a temporary directory. It reads the +numeric binding/type from each actual ELF `st_info` byte, while GNU readelf +independently supplies the named classifications, symbol values and sizes. +The oracle records the tool versions, flags, source digest and observed OS ABI. +The captured toolchain is g++ 14.2.0 (Debian 14.2.0-19), GNU readelf 2.44, +on Linux x86-64 producing little-endian ELF64. + +Regenerate or verify with those tools (Python standard library only): + +```sh +python tests/fixtures/elf-gnu-unique/produce.py +python tests/fixtures/elf-gnu-unique/produce.py --check +``` + +The public CLI regression puts these selected symbol facts in the existing +portable ELF carrier. It tests object/TLS binding preservation, the weak +negative control and source-digest Evidence without needing GCC in CI or +committing a binary. It does **not** qualify the compiler's complete ELF layout +or a native loader in CI. Current production classifies these bindings +correctly; this fixture protects that existing behavior. diff --git a/tests/fixtures/elf-gnu-unique/inline.cpp b/tests/fixtures/elf-gnu-unique/inline.cpp new file mode 100644 index 0000000000..3bd2875774 --- /dev/null +++ b/tests/fixtures/elf-gnu-unique/inline.cpp @@ -0,0 +1,4 @@ +inline int process_value = 7; +inline thread_local int thread_value = 11; +extern "C" int *process_address() { return &process_value; } +extern "C" int *thread_address() { return &thread_value; } diff --git a/tests/fixtures/elf-gnu-unique/oracle.json b/tests/fixtures/elf-gnu-unique/oracle.json new file mode 100644 index 0000000000..eae4f351f0 --- /dev/null +++ b/tests/fixtures/elf-gnu-unique/oracle.json @@ -0,0 +1,66 @@ +{ + "compiler": "g++ (Debian 14.2.0-19) 14.2.0", + "reference": "GNU readelf (GNU Binutils for Debian) 2.44", + "source_sha256": "a275de3d14c91a02f103df4aa6ee0b5416ead3d36efa67fb06fa243edc4c4eec", + "flags": ["-std=c++17", "-shared", "-fPIC", "-Wl,--build-id=none"], + "variants": [ + { + "name": "gnu_unique", + "flags": [], + "os_abi": 3, + "symbols": [ + { + "name": "process_value", + "value": "0x4010", + "size": "4", + "raw_info": "0xa1", + "type_code": 1, + "type": "object", + "binding_code": 10, + "binding": "unique", + "visibility": "default" + }, + { + "name": "thread_value", + "value": "0x0", + "size": "4", + "raw_info": "0xa6", + "type_code": 6, + "type": "tls", + "binding_code": 10, + "binding": "unique", + "visibility": "default" + } + ] + }, + { + "name": "weak", + "flags": ["-fno-gnu-unique"], + "os_abi": 0, + "symbols": [ + { + "name": "process_value", + "value": "0x4010", + "size": "4", + "raw_info": "0x21", + "type_code": 1, + "type": "object", + "binding_code": 2, + "binding": "weak", + "visibility": "default" + }, + { + "name": "thread_value", + "value": "0x0", + "size": "4", + "raw_info": "0x26", + "type_code": 6, + "type": "tls", + "binding_code": 2, + "binding": "weak", + "visibility": "default" + } + ] + } + ] +} diff --git a/tests/fixtures/elf-gnu-unique/produce.py b/tests/fixtures/elf-gnu-unique/produce.py new file mode 100644 index 0000000000..35b1e58c51 --- /dev/null +++ b/tests/fixtures/elf-gnu-unique/produce.py @@ -0,0 +1,91 @@ +"""Capture GCC inline-variable bindings with GNU readelf; never run the DSO.""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import struct +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parent +FLAGS = ["-std=c++17", "-shared", "-fPIC", "-Wl,--build-id=none"] +TYPES = {"OBJECT": "object", "TLS": "tls"} +NAMES = {"process_value", "thread_value"} + + +def command(*args): + return subprocess.check_output(args, text=True, env={**os.environ, "LC_ALL": "C"}) + + +def produce(compiler, readelf): + variants = [] + with tempfile.TemporaryDirectory(prefix="rea-elf-inline-") as temporary: + for name, extra in [("gnu_unique", []), ("weak", ["-fno-gnu-unique"])]: + binary = Path(temporary) / f"{name}.so" + subprocess.run( + [compiler, *FLAGS, *extra, str(ROOT / "inline.cpp"), "-o", str(binary)], + check=True, + ) + contents = binary.read_bytes() + assert contents[:6] == b"\x7fELF\x02\x01", "this witness requires ELF64 little endian" + assert struct.unpack_from("> 4, + "binding": binding.lower(), + "visibility": "default", + }) + assert {item["name"] for item in symbols} == NAMES + variants.append({"name": name, "flags": extra, "os_abi": contents[7], "symbols": symbols}) + return { + "compiler": command(compiler, "--version").splitlines()[0], + "reference": command(readelf, "--version").splitlines()[0], + "source_sha256": hashlib.sha256((ROOT / "inline.cpp").read_bytes()).hexdigest(), + "flags": FLAGS, + "variants": variants, + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--compiler", default="g++") + parser.add_argument("--readelf", default="readelf") + parser.add_argument("--check", action="store_true") + arguments = parser.parse_args() + observed = produce(arguments.compiler, arguments.readelf) + destination = ROOT / "oracle.json" + if arguments.check: + assert observed == json.loads(destination.read_text()), "producer facts changed" + print("GCC/readelf fixture matches the recorded oracle") + else: + destination.write_text(json.dumps(observed, indent=2) + "\n")