kernel: allow munmap across released reservation holes #827

Open
github-bot wants to merge 2 commits from github-bot/gh-827 into main AGit
Owner

@⁠Pcniado on GitHub · 2026-09-25 15:20 UTC · original
Pcniado:fix/munmap-reserved-holes → main · +56 −4 · 2 files · 2 commits · open

SUMMARY
A game can reserve a span of memory, unmap one page, and later unmap the original span. Kyty rejected the final sceKernelMunmap call because its tracked ranges no longer covered every page, even though the missing page had already been released.
CHANGE
KernelMunmap now walks the span, validates released holes against the guest address space, and unmaps the remaining tracked regions.
TESTING
Astro’s Playroom boots fine with this change.

AI assisted with investigating this issue.

**@⁠Pcniado** on GitHub · 2026-09-25 15:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/827) `Pcniado:fix/munmap-reserved-holes` → `main` · +56 −4 · 2 files · 2 commits · open **SUMMARY** A game can reserve a span of memory, unmap one page, and later unmap the original span. Kyty rejected the final sceKernelMunmap call because its tracked ranges no longer covered every page, even though the missing page had already been released. **CHANGE** KernelMunmap now walks the span, validates released holes against the guest address space, and unmaps the remaining tracked regions. **TESTING** Astro’s Playroom boots fine with this change. AI assisted with investigating this issue.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:34:04 +00:00
@ -2558,0 +2565,4 @@
if (!g_guest_address_space->ReleaseFree(current, end - current)) {
return KERNEL_ERROR_EACCES;
}
break;
Author
Owner

@⁠Copilot on GitHub · 2026-09-25 15:30 UTC · original

ReleaseFree only checks that the host address-space placeholder is free and does not require a VirtualRanges entry. Therefore, when munmap is called on an entirely untracked address that falls inside the guest placeholder, this branch accepts the span and the function returns OK even though there is no mapping to remove. Reject the operation when no tracked chunk has been found, preserving the previous QuerySpan behavior for arbitrary unmapped addresses.

**@⁠Copilot** on GitHub · 2026-09-25 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/827#discussion_r4106050333) `ReleaseFree` only checks that the host address-space placeholder is free and does not require a `VirtualRanges` entry. Therefore, when `munmap` is called on an entirely untracked address that falls inside the guest placeholder, this branch accepts the span and the function returns `OK` even though there is no mapping to remove. Reject the operation when no tracked chunk has been found, preserving the previous `QuerySpan` behavior for arbitrary unmapped addresses.
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-09-25 15:30 UTC · original · reviewed

Copilot review overview

A critical issue allows successful unmapping of an entirely untracked address range.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity

Open (1)
What changed in this PR

Updates KernelMunmap to support reserved spans containing previously released holes.

Changes:

  • Validates released gaps against the guest address space.
  • Unmaps remaining tracked regions individually.
  • Adds regression coverage.

Review finding: entirely untracked addresses inside the guest placeholder must still be rejected.

File Summary
tests/​VirtualMemoryAllocationTests.cpp Adds released-hole regression coverage.
src/​kernel/​memory.cpp Implements hole-aware unmapping; requires rejection of wholly untracked spans.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-09-25 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/827#pullrequestreview-5319519756) · **reviewed** <!-- ccr-overview-v2 --> ## Copilot review overview ### 🟡 Changes recommended A critical issue allows successful unmapping of an entirely untracked address range. *Get a fresh assessment by requesting another Copilot review.* **Review effort:** Lite **Findings:** 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> <details open> <summary><strong>Open (1)</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Reject munmap for untracked addresses inside guest placeholder](#discussion_r4106050333) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> Updates `KernelMunmap` to support reserved spans containing previously released holes. **Changes:** - Validates released gaps against the guest address space. - Unmaps remaining tracked regions individually. - Adds regression coverage. Review finding: entirely untracked addresses inside the guest placeholder must still be rejected. | File | Summary | |---|---| | `tests/​VirtualMemoryAllocationTests.cpp` | Adds released-hole regression coverage. | | `src/​kernel/​memory.cpp` | Implements hole-aware unmapping; requires rejection of wholly untracked spans. | </details> --- 💡 <a href="/KytyPS5/KytyPS5/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a `code-review` agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 15:45 UTC · original

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

KernelMunmap now walks the requested span, releases untracked gaps that GuestAddressSpace::ReleaseFree accepts, and unmaps tracked chunks. It returns KERNEL_ERROR_EACCES if it finds no tracked chunks. A new test checks unmapping a reserved span after its middle page has already been released, then checks that repeating the full-span unmap returns ErrorAccess.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🔵 Low · up to aeb2a

A munmap spanning separately released adjacent holes can fail on Windows even when the entire gap is free. This is a bounded edge case that should be fixed or accepted before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to aeb2a

Unmapping can now cross released pages, and the gap check does not distinguish a previously released page from other free guest memory. The reviewed path remains limited to guest-owned address space and tracked mappings; no host-memory boundary bypass was established.

Retained concerns

  • Low · architecture · inferred: Gap validation proves that an interval is free within the host-owned guest address space, but not that it was released from the requested reservation. A mixed request can now cross an unrelated free interval and unmap tracked memory beyond it, where the previous full-span check returned an error. This is a guest-memory ownership distinction, not an established host-memory or privilege-boundary bypass.
Security review details

Security Blast Radius

  • inferred — A caller controls the requested address and length. Cleanup is confined to tracked chunks in that non-overflowing span, while each untracked gap must pass guest-address-space free-range containment; no fixed per-reservation span limit is established.

Trust Boundaries and Controls

  • inferred — The host free-range check prevents an unowned gap from qualifying, but it does not attest that an accepted gap was previously released by the guest. Existing tracked-range checks still govern the chunks actually unmapped.

Hardening Proposals

  • proposed — If acceptance must be limited to holes from a particular guest reservation, retain reservation provenance and validate gaps against it rather than against host-free containment alone.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly explains the munmap change, the released-hole behavior, and the reported testing result.
Title check ✅ Passed The title clearly and concisely describes the main change: allowing munmap across released reservation holes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 15:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/827#issuecomment-5835217676) <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/827"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough `KernelMunmap` now walks the requested span, releases untracked gaps that `GuestAddressSpace::ReleaseFree` accepts, and unmaps tracked chunks. It returns `KERNEL_ERROR_EACCES` if it finds no tracked chunks. A new test checks unmapping a reserved span after its middle page has already been released, then checks that repeating the full-span unmap returns `ErrorAccess`. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"aeb2a7394ee98ebc8a1103b006b31b2b1494a548" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🔵 Low_ · up to `aeb2a` <!-- final_review_risk_coverage:{"sourceCommitId":"aeb2a7394ee98ebc8a1103b006b31b2b1494a548","coveredCommitId":"aeb2a7394ee98ebc8a1103b006b31b2b1494a548","kind":"reviewed"} --> A munmap spanning separately released adjacent holes can fail on Windows even when the entire gap is free. This is a bounded edge case that should be fixed or accepted before merging. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `aeb2a` Unmapping can now cross released pages, and the gap check does not distinguish a previously released page from other free guest memory. The reviewed path remains limited to guest-owned address space and tracked mappings; no host-memory boundary bypass was established. **Retained concerns** - **Low · architecture · inferred:** Gap validation proves that an interval is free within the host-owned guest address space, but not that it was released from the requested reservation. A mixed request can now cross an unrelated free interval and unmap tracked memory beyond it, where the previous full-span check returned an error. This is a guest-memory ownership distinction, not an established host-memory or privilege-boundary bypass. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — A caller controls the requested address and length. Cleanup is confined to tracked chunks in that non-overflowing span, while each untracked gap must pass guest-address-space free-range containment; no fixed per-reservation span limit is established. **Trust Boundaries and Controls** - _inferred_ — The host free-range check prevents an unowned gap from qualifying, but it does not attest that an accepted gap was previously released by the guest. Existing tracked-range checks still govern the chunks actually unmapped. **Hardening Proposals** - _proposed_ — If acceptance must be limited to holes from a particular guest reservation, retain reservation provenance and validate gaps against it rather than against host-free containment alone. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :--------------------------------------------------------------------------------------------------------------- | | Description check | ✅ Passed | The description clearly explains the munmap change, the released-hole behavior, and the reported testing result. | | Title check | ✅ Passed | The title clearly and concisely describes the main change: allowing munmap across released reservation holes. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 15:45 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: fc453323-bff2-450b-a48e-66afc3239e09

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce4f08364 and aeb2a7394e.

📒 Files selected for processing (2)
  • src/kernel/memory.cpp
  • tests/VirtualMemoryAllocationTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 15:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/827#pullrequestreview-5319677044) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `fc453323-bff2-450b-a48e-66afc3239e09` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 5ce4f08364f8875f6554dcbfffd8619c7afc6433 and aeb2a7394ee98ebc8a1103b006b31b2b1494a548. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/kernel/memory.cpp` * `tests/VirtualMemoryAllocationTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
@ -2562,0 +2589,4 @@
return result;
}
}
return OK;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-25 15:45 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

git diff 5ce4f08364f8875f6554dcbfffd8619c7afc6433 aeb2a7394ee98ebc8a1103b006b31b2b1494a548 -- src/kernel/memory.cpp tests/VirtualMemoryAllocationTests.cpp
sed -n '2535,2610p' src/kernel/memory.cpp
sed -n '790,855p' src/kernel/memoryAddressSpace.inc
rg -n 'FindContaining|ReleaseFree|QuerySpan' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 11121


🏁 Script executed:

sed -n '240,315p' src/kernel/memoryAddressSpace.inc
sed -n '440,525p' src/kernel/memoryAddressSpace.inc
sed -n '960,1010p' src/kernel/memoryAddressSpace.inc
sed -n '1200,1265p' src/kernel/memoryAddressSpace.inc
sed -n '2460,2495p' src/kernel/memory.cpp
sed -n '3275,3370p' src/kernel/memory.cpp
rg -n -C 5 'AddFree|RemoveMappedUnlocked|ConsumeUnlocked|ReleaseFree|ReserveFixed|ReserveAligned|TestContainsFree' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp tests

Repository: KytyPS5/KytyPS5

Length of output: 38613


🏁 Script executed:

sed -n '1280,1335p' src/kernel/memoryAddressSpace.inc
sed -n '350,430p' src/kernel/memory.cpp
rg -n -C 8 'bool Add\\(|Add\\(uint64_t|Query\\(uint64_t|QuerySpan|Remove\\(uint64_t' src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 3893


🏁 Script executed:

rg -n -C 12 'CoalescePlaceholders|KernelReserveVirtualRange|ReserveVirtualRange|VirtualRangeType::Reserved' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 24359


🏁 Script executed:

sed -n '207,355p' src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4692


🏁 Script executed:

rg -n -A75 -B8 'RemoveUnlocked|MergeAroundUnlocked' src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10405


Accept gaps spanning adjacent free ranges.

On Windows, AddFreeUnlocked can leave adjacent entries in m_free when CoalescePlaceholders fails. After adjacent reserved holes are unmapped separately, KernelMunmap can pass their combined gap to ReleaseFree. FindContaining checks only the first entry, so KernelMunmap can return KERNEL_ERROR_EACCES even though every page in the gap is free.

Make ReleaseFree walk contiguous free entries and reject only a real gap.

Suggested fix
 bool ReleaseFree(uint64_t vaddr, uint64_t size) {
 	std::lock_guard lock(m_mutex);
-	return FindContaining(vaddr, size) != m_free.end();
+	if (size == 0 || UINT64_MAX - vaddr < size) {
+		return false;
+	}
+	const auto end = vaddr + size;
+	auto       current = vaddr;
+	while (current < end) {
+		auto it = FindContaining(current, 1);
+		if (it == m_free.end()) {
+			return false;
+		}
+		const auto range_end = it->first + it->second;
+		if (range_end <= current) {
+			return false;
+		}
+		current = std::min(end, range_end);
+	}
+	return true;
 }
**@⁠coderabbitai[bot]** on GitHub · 2026-09-25 15:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/827#discussion_r4106186493) _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash git diff 5ce4f08364f8875f6554dcbfffd8619c7afc6433 aeb2a7394ee98ebc8a1103b006b31b2b1494a548 -- src/kernel/memory.cpp tests/VirtualMemoryAllocationTests.cpp sed -n '2535,2610p' src/kernel/memory.cpp sed -n '790,855p' src/kernel/memoryAddressSpace.inc rg -n 'FindContaining|ReleaseFree|QuerySpan' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 11121 --- 🏁 Script executed: ```bash sed -n '240,315p' src/kernel/memoryAddressSpace.inc sed -n '440,525p' src/kernel/memoryAddressSpace.inc sed -n '960,1010p' src/kernel/memoryAddressSpace.inc sed -n '1200,1265p' src/kernel/memoryAddressSpace.inc sed -n '2460,2495p' src/kernel/memory.cpp sed -n '3275,3370p' src/kernel/memory.cpp rg -n -C 5 'AddFree|RemoveMappedUnlocked|ConsumeUnlocked|ReleaseFree|ReserveFixed|ReserveAligned|TestContainsFree' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp tests ``` Repository: KytyPS5/KytyPS5 Length of output: 38613 --- 🏁 Script executed: ```bash sed -n '1280,1335p' src/kernel/memoryAddressSpace.inc sed -n '350,430p' src/kernel/memory.cpp rg -n -C 8 'bool Add\\(|Add\\(uint64_t|Query\\(uint64_t|QuerySpan|Remove\\(uint64_t' src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 3893 --- 🏁 Script executed: ```bash rg -n -C 12 'CoalescePlaceholders|KernelReserveVirtualRange|ReserveVirtualRange|VirtualRangeType::Reserved' src/kernel/memoryAddressSpace.inc src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 24359 --- 🏁 Script executed: ```bash sed -n '207,355p' src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4692 --- 🏁 Script executed: ```bash rg -n -A75 -B8 'RemoveUnlocked|MergeAroundUnlocked' src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10405 --- </details> **Accept gaps spanning adjacent free ranges.** On Windows, `AddFreeUnlocked` can leave adjacent entries in `m_free` when `CoalescePlaceholders` fails. After adjacent reserved holes are unmapped separately, `KernelMunmap` can pass their combined gap to `ReleaseFree`. `FindContaining` checks only the first entry, so `KernelMunmap` can return `KERNEL_ERROR_EACCES` even though every page in the gap is free. Make `ReleaseFree` walk contiguous free entries and reject only a real gap. <details> <summary>Suggested fix</summary> ```diff bool ReleaseFree(uint64_t vaddr, uint64_t size) { std::lock_guard lock(m_mutex); - return FindContaining(vaddr, size) != m_free.end(); + if (size == 0 || UINT64_MAX - vaddr < size) { + return false; + } + const auto end = vaddr + size; + auto current = vaddr; + while (current < end) { + auto it = FindContaining(current, 1); + if (it == m_free.end()) { + return false; + } + const auto range_end = it->first + it->second; + if (range_end <= current) { + return false; + } + current = std::min(end, range_end); + } + return true; } ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:aebb97c0b28e3876e6188ec8 --> <!-- This is an auto-generated comment by CodeRabbit -->
This pull request has changes conflicting with the target branch.
  • src/kernel/memory.cpp
  • tests/VirtualMemoryAllocationTests.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/827/head:github-bot/gh-827'
git switch 'github-bot/gh-827'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-827'
git switch 'github-bot/gh-827'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-827'
git switch 'github-bot/gh-827'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-827'
git switch 'main'
git merge --squash 'github-bot/gh-827'
git switch 'main'
git merge --ff-only 'github-bot/gh-827'
git switch 'main'
git merge 'github-bot/gh-827'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.