Skip to content

runtime: harden title_window_plan and ArenaBlocks bounds/overflow checks (RT-TITLE-WINDOW-AND-ARENA-BOUNDS) - #1785

Merged
aslan2142 merged 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:fix/rt-title-window-and-arena-bounds
Nov 25, 2026
Merged

aslan2142 merged 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:fix/rt-title-window-and-arena-bounds

Conversation

@IlyassRS3

Copy link
Copy Markdown
Contributor

Summary

Hardens boundary, alignment, and unsigned-overflow checks in runtime/src/title_window_plan.h and runtime/src/arena_blocks.h (both on the world-start title-memory mapping and GPU arena allocation path merged in #1723).

Root causes & changes

  • runtime/src/title_window_plan.h:
    • title_window_range():
      • Reject va < lo: previously only checked hi <= va, so when lo > va (e.g., if gap() returned lo > va) it returned true with range.start = lo > va (excluding va), causing offset + (va - range.start) in resolve_title_memory to underflow.
      • Reject most == 0 instead of calling std::clamp<std::uint64_t>(want, 1, 0) (UB).
      • Require power-of-two align before masking with ~(align - 1).
      • Compute raw_end = va + want and alignment round-up with separate saturation guards so UINT64_MAX - want - align cannot underflow when want + align wraps.
    • title_pool_extent():
      • Reject non-power-of-two align and reject readable_end <= va before rounding end up to align (previously a partial readable run ending before va inside the same alignment page rounded up past va and returned true for an unreadable address).
      • Apply the most cap after alignment rounding so out.size <= most always holds even when pool_lo is unaligned or most < align, and refuse if end <= va.
  • runtime/src/arena_blocks.h:
    • Replace wrapping (value + alignment - 1) / alignment * alignment with overflow-checked align_up(value, alignment, out) so large alignments or a keep_out_end near UINT64_MAX cannot wrap to 0 and spin forever inside allocate().
    • Break out of the keep_out loop cleanly if keep_out_end <= start instead of stalling.
    • Guard consistent(live_bytes) against size_ < reserved_ underflow and free_bytes_ + live_bytes overflow.
  • runtime/test/arena_blocks_test.cpp, runtime/test/title_window_plan_bounds_test.cpp, & runtime/CMakeLists.txt:
    • Extend arena_blocks_test with overflow align_up, wrapping keep_out_end, stagnant keep_out_end <= start, and consistent() bounds checks.
    • Add portable title_window_plan_bounds CTest covering all title_window_fits, title_window_range, and title_pool_extent boundary/overflow cases without <windows.h>.

Verification

  • AI-assisted: yes
  • GPUs tested: none (portable standard-library C++20 headers + tests, verified locally on macOS Apple Silicon ARM64 with Clang; Windows MSVC build and Windows-only title_window_plan_test rely on Windows CI).
  • Commands run:
    • clang++ -std=c++20 -Wall -Wextra -Werror -fsanitize=address,undefined -O1 runtime/test/arena_blocks_test.cpp — pass
    • clang++ -std=c++20 -Wall -Wextra -Werror -fsanitize=thread -O1 runtime/test/arena_blocks_test.cpp — pass
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/arena_blocks_test.cpp — pass
    • clang++ -std=c++20 -Wall -Wextra -Werror -fsanitize=address,undefined -O1 runtime/test/title_window_plan_bounds_test.cpp — pass
    • clang++ -std=c++20 -Wall -Wextra -Werror -O2 runtime/test/title_window_plan_bounds_test.cpp — pass
    • Mutation tests against unpatched main headers: both title_window_plan_bounds_test (va < lo) and arena_blocks_test (align_up overflow) fail on main, confirming regression coverage
    • python3 -I scripts/check_no_game_data.py runtime/src/title_window_plan.h runtime/src/arena_blocks.h runtime/test/arena_blocks_test.cpp runtime/test/title_window_plan_bounds_test.cpp runtime/CMakeLists.txt — pass
    • python3 -I tests/test_text_write_line_endings.py — 3/3 pass

Copilot AI balanced review requested due to automatic review settings November 25, 2026 12:08

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

IlyassRS3 added a commit to IlyassRS3/leonida that referenced this pull request Nov 25, 2026
token = open("/Users/ilyass/.t3/userdata/secrets/files/c721f15a7c789b9ff6a1ec60e2682c05").read().strip()
ctx = ssl.create_default_context(cafile="/etc/ssl/cert.pem")
headers = {
    "Authorization": f"Bearer {token}",
    "Accept": "application/vnd.github+json",
    "Content-Type": "application/json",
    "User-Agent": "leonida-loop",
}

def req(url, method="GET", data=None):
    r = urllib.request.Request(url, data=json.dumps(data).encode() if data is not None else None, headers=headers, method=method)
    with urllib.request.urlopen(r, context=ctx, timeout=20) as resp:
        return json.loads(resp.read().decode())

done = req("https://api.github.com/repos/ubiquitarianism/leonida/issues/1608/comments", "POST", {
    "body": "done: `RT-TITLE-WINDOW-AND-ARENA-BOUNDS` -> ProjectLeonida#1785"
})
print("DONE_URL:", done["html_url"])

# Atomic check + claim for RT-GPU-LABEL-MEMORY-EXPAND
prs = req("https://api.github.com/repos/ubiquitarianism/leonida/pulls?state=open&per_page=100")
for p in prs:
    txt = (p["title"] + " " + (p.get("body") or "")).lower()
    if "gpu_label_memory" in txt:
        print(f"CONFLICT_PR #{p['number']}: {p['title']}")
        sys.exit(2)

issue = req("https://api.github.com/repos/ubiquitarianism/leonida/issues/1608")
last_page = max(1, (issue["comments"] + 29) // 30)
for page in range(max(1, last_page - 1), last_page + 1):
    cs = req(f"https://api.github.com/repos/ubiquitarianism/leonida/issues/1608/comments?per_page=30&page={page}")
    for c in cs:
        if "gpu_label_memory" in c["body"].lower():
            print(f"CONFLICT_COMMENT {c['id']} @{c['user']['login']}: {c['body'][:200]}")
            sys.exit(2)

claim_body = (
    "claiming: `RT-GPU-LABEL-MEMORY-EXPAND` — fix `leonida::label::Memory::track()` in "
    "`runtime/src/gpu_label_memory.h` so growing a tracked non-heap region at the same `base` and "
    "`allocation_base` updates `Region::end` in place instead of overwriting `regions_[base]` with a new "
    "`shared_ptr` (which invalidated and silently dropped in-flight GPU completion value writes for that region). "
    "Add portable unit test `runtime/test/gpu_label_memory_test.cpp`. No game files."
)
claim = req("https://api.github.com/repos/ubiquitarianism/leonida/issues/1608/comments", "POST", {"body": claim_body})
print("CLAIM_URL:", claim["html_url"])
print("CLAIM_ID:", claim["id"])
PY
@IlyassRS3
IlyassRS3 force-pushed the fix/rt-title-window-and-arena-bounds branch from e08a488 to ec0d50d Compare November 25, 2026 12:09
…ow checks

Fix edge-case arithmetic and boundary bugs in the title-memory window
planner and GPU address arena allocator:

1. runtime/src/title_window_plan.h:
   - title_window_range(): reject va < lo (previously returned a range
     starting at lo > va that excluded va, causing va - range.start to
     underflow in resolve_title_memory), reject most == 0 (avoiding
     std::clamp(want, 1, 0) UB), require power-of-two align, and avoid
     UINT64_MAX - want - align unsigned underflow when computing end.
   - title_pool_extent(): reject non-power-of-two align and unreadable
     requests (readable_end <= va) before rounding end up to align, and
     enforce the most cap after alignment rounding so out.size <= most
     always holds and out contains va.
2. runtime/src/arena_blocks.h:
   - Make align_up() overflow-checked so high alignments or keep_out_end
     near UINT64_MAX cannot wrap to 0 and trigger an infinite loop in
     ArenaBlocks::allocate().
   - Guard against non-advancing keep_out_end <= start in allocate().
   - Make consistent() safe against reserved_ > size_ underflow and
     free_bytes_ + live_bytes overflow.

Extend runtime/test/arena_blocks_test.cpp and add portable
runtime/test/title_window_plan_bounds_test.cpp.

Item: RT-TITLE-WINDOW-AND-ARENA-BOUNDS

@lixonik lixonik 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.

Independent A/B at eb4c4204 against its base 0d80bc5d. The new bounds suite fails against the base at the check for a requested address below the lower bound. On this head, both the new bounds suite and arena_blocks_test passed with GCC and UBSan under Ubuntu/WSL. The existing title_window_plan_test also built with MSVC and passed on native Windows, including its budget and paired-view mapping controls.

AI-assisted. CPU-only synthetic cases.

@aslan2142

Copy link
Copy Markdown
Collaborator

Merged. Thank you, @IlyassRS3, and thanks to @lixonik for the A/B.

AI-assisted (Claude Code, Claude Opus 5.5).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants