Skip to content

fix(relinker): reject out-of-range executable TLS symbols - #11058

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
plexerPK:fix/executable-tls-symbol-bounds
Oct 26, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
plexerPK:fix/executable-tls-symbol-bounds

Conversation

@plexerPK

@plexerPK plexerPK commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What

Reject defined STT_TLS symbols whose value or size falls outside the nonempty PT_TLS segment before folding executable TLS relocations. Previously an out-of-range symbol could convert successfully. The subtraction-safe check accepts an empty symbol at the segment end and preserves the missing/empty-TLS diagnostics introduced by #10730.

Tested

macOS arm64, relinker-only Release build; synthetic fixtures, no title or guest execution. Exact head 5f4c8cb9278af74518872a3453ddf9fbb21db87c on main 35ac3402c80b152983e8aa11196835d3a16370bf. The original baseline regression against main 8864d0e3230ccac2603366474a43f880523a1d4b failed because value 37, size 0 is accepted with exit 0. After this rebase and a Release rebuild, 7/7 focused CTests pass: executable_tls_relocations, guest_own_tls_relocations, guest_tls, tls_diagnostics, executable_export_bounds, linux_executable_exports and macos_executable_exports.

The three affected #8076 suites also pass on this combined tree: control_flow_graph, sce_code_extent and sce_module_code_extent (10/10 focused CTests in total).

Coverage includes three invalid and two valid value/size pairs across Linux, lazy Linux, Windows and macOS conversion (20 cases), plus the unchanged 24 empty-TLS diagnostic cases. No native Linux/Windows guest runtime, GPU or hosted-CI result is claimed.

Conventions and diff checks pass. #8076 merged first at b744c37f4eeb63f7fff9fd7a6928cd4081591283 on 2026-10-26. This branch is rebased onto main containing that merge; the rebase is patch-equivalent, without conflict or changes to the TLS fix. Current #10947 and #11038 compose cleanly in source checks and implement distinct guards. The official overlap checker could not compare #10792 and #10861 because they conflict with the base; their exact authored diffs were reviewed manually and affect syscall routing and tail analysis rather than this TLS guard. No duplicate TLS-bounds implementation was found.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: fix(relinker): mask embedded data tables in inter-FDE gaps #8076 (merged)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

@thepoppfish thepoppfish left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head f76d3bc51c511df4a55430ced1c93b6e44cb6b67 against current main 0119103fa9ed65a894a931da02b6510669991b45. Approve; no actionable findings in this focused review.

The symbol extent is checked against PT_TLS.p_memsz, including zero-fill, before folding local TLS relocations. The short-circuit subtraction avoids unsigned overflow, permits a zero-sized symbol exactly at the segment end, and keeps missing/empty-TLS handling separate. This matches the executable/DSO TLS symbol-offset model in ELF Handling For Thread-Local Storage, section 2. Imported-symbol handling and relocation addends are unchanged.

Independent Windows 11 build 26200 validation, Python 3.14.7, MSYS2 UCRT64 GCC 16.2.0-6, CMake 4.3.1 and Ninja 1.13.2:

  • Built the actual native relinker from both pinned checkouts: Release, ANYPS5_RELINKER_ONLY=ON, BUILD_TESTING=ON, target relinker, 88 Ninja steps each.
  • 10/10 focused CTests pass on both: head 19.21 s, main 32.37 s. These are local run durations, not a performance comparison. Pattern below includes the author's seven groups plus elf_offsets, macos_empty_tls and windows_tls_thread_pointer. The unchanged guest_tls test also exercises the Windows loader and six generated Windows programs returning42 on each version.
  • Running the PR's complete test_executable_tls_relocations.py against the unchanged main binary fails at the new regression: Linux value37, size0 is accepted with exit0. This is the expected assertion failure, not a build/setup error.
  • An additional 176 paired cases / 352 real CLI invocations cover all three TLS relocation types, Linux/lazy Linux/Windows/macOS output, six valid and six invalid value/size pairs (including unsigned extremes), and negative/zero/positive relocation addends. The head reports the new bounds error with no output for all 72 invalid combinations. Main accepts 60 of them; the other12 are DTPMOD64 cases already refused by Windows/macOS, whose diagnostic now occurs earlier. All 92 accepted comparison pairs are byte-identical. The12 valid Windows/macOS DTPMOD64 cases retain their existing unsupported-relocation rejection.
  • Conventions against origin/main and whitespace checks pass; both source worktrees remain clean.

Linux and macOS are output-conversion/inspection targets here. No native Linux/macOS execution, full system-library build, commercial title, GPU, console or hosted-CI validation is claimed. The Windows loader/runtime results above are synthetic fixtures.

Reproduction, using the two pinned checkouts and a compiler/runtime on PATH:

cmake -S <checkout> -B <build> -G Ninja -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++
cmake --build <build> --target relinker --parallel 3
ctest --test-dir <build> -R '^(executable_tls_relocations|guest_own_tls_relocations|guest_tls|tls_diagnostics|executable_export_bounds|linux_executable_exports|macos_executable_exports|elf_offsets|macos_empty_tls|windows_tls_thread_pointer)$' --output-on-failure -j 1
python <head>/core/relinker/relinker/tests/test_executable_tls_relocations.py <main-build>/core/relinker/relinker.exe

The final command should exit1 with AssertionError: ('linux', 37, 0, 0, ''). Use the platform's executable filename.

Complete additional paired CLI probe

Save as probe-executable-tls-bounds.py, then run:

python probe-executable-tls-bounds.py <head-checkout> <head-relinker> <main-relinker> tls-bounds-results.json

The head checkout is asserted by commit ID; build the main binary from the pinned main commit above.

import hashlib
import importlib.util
import json
from pathlib import Path
import struct
import subprocess
import sys
import tempfile


def main():
    repo, head_binary, base_binary, destination = map(Path, sys.argv[1:])
    repo = repo.resolve()
    binaries = {"head": head_binary.resolve(), "base": base_binary.resolve()}
    tests = repo / "core/relinker/relinker/tests"
    sys.path.insert(0, str(tests))
    spec = importlib.util.spec_from_file_location("tls_fixture", tests / "test_executable_tls_relocations.py")
    fixture = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(fixture)
    assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip() == "f76d3bc51c511df4a55430ced1c93b6e44cb6b67"
    maximum = (1 << 64) - 1
    pairs = [(0, 0), (0, 36), (8, 4), (31, 5), (35, 1), (36, 0),
             (0, 37), (35, 2), (36, 1), (37, 0), (maximum, 0), (1, maximum)]
    records = []
    with tempfile.TemporaryDirectory(prefix="anyps5-tls-bounds-review-") as directory:
        work = Path(directory)

        def convert(case, data, flags):
            source = work / (case + ".elf")
            source.write_bytes(data)
            results = {}
            for variant, binary in binaries.items():
                output = work / (case + "-" + variant + ".out")
                process = subprocess.run([str(binary), "--skip-sce-module", *flags, str(source), str(output)],
                                         capture_output=True, text=True, timeout=20)
                artifact = output.read_bytes() if output.exists() else None
                results[variant] = {"returncode": process.returncode, "stderr": process.stderr,
                                    "output_sha256": hashlib.sha256(artifact).hexdigest() if artifact is not None else None}
            return results

        for value, size in pairs:
            valid = value <= 36 and size <= 36 - value
            for kind in (fixture.DTPMOD64, fixture.DTPOFF64, fixture.TPOFF64):
                for flags, target in fixture.TARGETS.items():
                    data = fixture.image([(0x1000, kind, fixture.TLS_SYMBOL, 0)])
                    struct.pack_into("<QQ", data, 0x4900 + fixture.TLS_SYMBOL * 24 + 8, value, size)
                    case = f"bounds-{value}-{size}-{kind}-{target}"
                    result = convert(case, data, flags)
                    if not valid:
                        assert result["head"]["returncode"] == 2 and "TLS symbol exceeds TLS segment" in result["head"]["stderr"], (case, result)
                        assert result["head"]["output_sha256"] is None, (case, result)
                    else:
                        assert result["head"] == result["base"], (case, result)
                    if kind == fixture.DTPMOD64 and target in ("windows", "macos"):
                        assert result["base"]["returncode"] == 2 and "DTPMOD64 relocation is not supported" in result["base"]["stderr"], (case, result)
                        assert result["base"]["output_sha256"] is None, (case, result)
                    else:
                        assert result["base"]["returncode"] == 0 and result["base"]["output_sha256"], (case, result)
                    records.append({"case": case, "group": "bounds", "valid": valid, "kind": kind, "target": target, **result})

        for kind in (fixture.DTPOFF64, fixture.TPOFF64):
            for addend in (-9, -8, 0, 28):
                for flags, target in fixture.TARGETS.items():
                    data = fixture.image([(0x1000, kind, fixture.TLS_SYMBOL, addend)])
                    struct.pack_into("<QQ", data, 0x4900 + fixture.TLS_SYMBOL * 24 + 8, 8, 4)
                    case = f"addend-{kind}-{addend}-{target}"
                    result = convert(case, data, flags)
                    assert result["head"] == result["base"], (case, result)
                    assert result["head"]["returncode"] == 0 and result["head"]["output_sha256"], (case, result)
                    records.append({"case": case, "group": "addend", "kind": kind, "target": target, **result})

    summary = {"paired_cases": len(records), "cli_invocations": 2 * len(records),
               "new_bounds_rejections": sum(r["group"] == "bounds" and not r["valid"] for r in records),
               "previously_accepted_invalid_cases": sum(r["group"] == "bounds" and not r["valid"] and r["base"]["returncode"] == 0 for r in records),
               "byte_identical_accepted_pairs": sum(r["head"]["returncode"] == 0 and r["head"]["output_sha256"] == r["base"]["output_sha256"] for r in records),
               "valid_unsupported_dtpmod_pairs": sum(r["group"] == "bounds" and r["valid"] and r["head"]["returncode"] == 2 for r in records)}
    document = {"head": "f76d3bc51c511df4a55430ced1c93b6e44cb6b67", "base": "0119103fa9ed65a894a931da02b6510669991b45",
                "binary_sha256": {name: hashlib.sha256(binary.read_bytes()).hexdigest() for name, binary in binaries.items()},
                "summary": summary, "cases": records}
    destination.write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(summary))


if __name__ == "__main__":
    main()

AI-assisted review and probe; commands and native outcomes above were run locally.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Manual overlap follow-up: merging the current #11058 and #8076 heads conflicts in RelinkerPipeline.cpp and several relinker files/tests, including the technical-debt entry. There is also a semantic interaction: #8076 changes the TLS relocation requirement from a non-empty PT_TLS to any PT_TLS, while this PR adds a bounds check against the non-empty segment. Please coordinate with #8076’s author on merge order, state any dependency, and verify the combined TLS behavior/tests before merging either branch.

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I manually checked the overlap with #8076. The current heads do not combine cleanly: git merge-tree reports conflicts in RelinkerPipeline.cpp, RelativeJumpTables.cpp, GuestModuleBuilder.cpp, several tests and docs/dev/debt/relinker.md. There is also a TLS-specific behavior interaction: #8076 changes the relocation prerequisite from a non-empty PT_TLS to any PT_TLS, while this PR checks defined TLS symbol bounds against a non-empty segment. Please coordinate with #8076’s author on order and verify the combined TLS cases before merging; record Depends on if the order is required.

@plexerPK
plexerPK force-pushed the fix/executable-tls-symbol-bounds branch from f76d3bc to 5f4c8cb Compare October 26, 2026 07:49
@github-actions

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 10792 core/relinker/relinker/src/pipeline/RelinkerPipeline.cpp
PR 10861 core/relinker/relinker/src/pipeline/RelinkerPipeline.cpp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants