feat: add an in-game performance panel #1090

Manually merged
github merged 1 commit from gh-pr/1090/head into gh-pr/1090/base 2026-11-26 09:42:38 +00:00
Owner

@⁠juanfariasdev on GitHub · 2026-10-05 23:43 UTC · original
juanfariasdev:feat/perf-overlay → main · +1788 −34 · 35 files · 1 commits · merged 2026-10-17 12:47 UTC

Summary

Adds an optional in-game performance panel in the top-right corner of the game window, with a compact view and a detailed view for real-time debugging.

Compact view: FPS, average frame time, a graph of the last 120 frame times (green ≤ 17.5 ms, yellow ≤ 34 ms, red above), the worst frame, emulator CPU, GPU utilization, GPU memory against the Vulkan budget, emulator and system RAM, swap and memory pressure.

Detailed view, in three columns:

  • Frames: 1% low FPS, guest and window resolution, present mode, flip requests, full flip queues, late vblanks, swapchain rebuilds and dropped presents.
  • CPU: machine load, host and guest thread counts, the busiest threads by name, context switches, page faults, thermal pressure, emulated instructions and calls into missing HLE functions.
  • GPU: model and cores, renderer and tiler load, driver memory, GPU resets, draws and instances per frame, indirect draws, dispatches, queue submits, time the CPU spends waiting on the GPU, write-tracking faults, and shader and pipeline compilation counts and times.
  • GPU memory: per-heap Vulkan usage, texture and buffer cache size, uploads, downloads and evictions.
  • PS5 memory: direct, pooled, flexible and extended memory, and page-table entries against the pool. The row turns red when the guest sees no entries left.
  • Emulator process and system memory: footprint, resident, compressed, file-backed, address space, wired, compressed, cached files, free, swap and pressure.
  • I/O and audio: disk and guest file throughput, audio underruns.

It is off by default. Enable it with --perf-overlay true or the launcher's Show performance panel checkbox. In game, F2 toggles the panel and Shift+F2 switches to the detailed view. Mac keyboards send brightness for F2 unless fn is held, so Cmd+P and Cmd+Shift+P do the same on macOS.

How it works

  • Drawing (performanceOverlay.cpp): reuses the ImGui context and Vulkan backend of the existing system overlay. The panel is drawn only on presents that already happen, so it does not change frame pacing. While the guest stops flipping (loading screens), it asks for one repaint per second. Tables are sized to their content, so the panel shrinks and grows with the window.
  • Emulator counters (common/debugCounters.h): relaxed atomic counters at the existing hot spots (draw recording, dispatch, queue submit, semaphore waits, shader and pipeline creation, texture and buffer caches, flips, the host exception handler, guest file I/O, audio). The panel reads them once per second and turns them into rates.
  • Guest memory (Memory::GetDebugStats): read once per second under the memory subsystem's bookkeeping locks only, never g_memory_operation_mutex, so it cannot wait on the GPU. Graphics shuts down before memory, so the present thread can call it safely.
  • Host statistics (common/hostStats.cpp): sampled once per second on a background thread, since thread enumeration and the IOAccelerator registry can take a few milliseconds.
  • Thread names: guest threads and the emulator's own threads (main, window, GPU, present) now get OS thread names, so profilers, Activity Monitor and the panel can tell them apart. Before, they were named only while Tracy was running.
Metric macOS Linux Windows
CPU (process / machine) getrusage / host_statistics getrusage / /proc/stat GetProcessTimes / GetSystemTimes
Per-thread CPU task_threads /proc/self/task n/a
Process memory task_vm_info /proc/self/status working set
System memory and swap host_statistics64, vm.swapusage /proc/meminfo GlobalMemoryStatusEx
Memory pressure kern.memorystatus_vm_pressure_level PSI some avg10, else available memory dwMemoryLoad
Disk I/O proc_pid_rusage /proc/self/io GetProcessIoCounters
GPU load, driver memory, resets IOAccelerator PerformanceStatistics n/a n/a
Thermal pressure com.apple.system.thermalpressurelevel n/a n/a
GPU memory VMA heap budgets VMA heap budgets VMA heap budgets

Other changes

  • F2 is now reserved, like F1, F7 and F11. Existing mappings on a reserved key are ignored with a log line instead of exiting, and the launcher's mapping editor rejects F2.
  • Trophy toasts move below the panel while it is visible, since both use the top-right corner.

Testing

Apple M4 Pro, macOS, x86_64 build. Games need #1083 to boot on macOS, so I tested on a local branch with #1083 merged:

  • Dead Cells (PPSA15552): both views visible and updating, the shortcuts work, no MoltenVK errors. Sample: 60 FPS, 1% low 41 FPS, ~170 draws per frame, GPU 53%, 216 MB texture cache, 3.5 GB of direct memory.
  • Host numbers checked against the system tools: CPU per thread (a busy thread reads 99%, a half-busy one 44%), wired and compressed memory (top), swap (vm.swapusage), memory pressure, GPU (ioreg), disk writes.
  • Panel layout checked with a headless ImGui harness at 960×540, 1280×720, 1920×1080 and 3456×2234, growing and shrinking: no empty space, the same size after shrinking back.
  • --keymap Cross=F2 boots with the warning instead of exiting.
  • shader_cfg_tests pass.

I did not build on Linux or Windows locally; that code follows the documented APIs and relies on CI for compilation.

🤖 Generated with Claude Code

**@⁠juanfariasdev** on GitHub · 2026-10-05 23:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090) `juanfariasdev:feat/perf-overlay` → `main` · +1788 −34 · 35 files · 1 commits · merged 2026-10-17 12:47 UTC ## Summary Adds an optional in-game performance panel in the top-right corner of the game window, with a compact view and a detailed view for real-time debugging. **Compact view:** FPS, average frame time, a graph of the last 120 frame times (green ≤ 17.5 ms, yellow ≤ 34 ms, red above), the worst frame, emulator CPU, GPU utilization, GPU memory against the Vulkan budget, emulator and system RAM, swap and memory pressure. **Detailed view**, in three columns: - **Frames:** 1% low FPS, guest and window resolution, present mode, flip requests, full flip queues, late vblanks, swapchain rebuilds and dropped presents. - **CPU:** machine load, host and guest thread counts, the busiest threads by name, context switches, page faults, thermal pressure, emulated instructions and calls into missing HLE functions. - **GPU:** model and cores, renderer and tiler load, driver memory, GPU resets, draws and instances per frame, indirect draws, dispatches, queue submits, time the CPU spends waiting on the GPU, write-tracking faults, and shader and pipeline compilation counts and times. - **GPU memory:** per-heap Vulkan usage, texture and buffer cache size, uploads, downloads and evictions. - **PS5 memory:** direct, pooled, flexible and extended memory, and page-table entries against the pool. The row turns red when the guest sees no entries left. - **Emulator process and system memory:** footprint, resident, compressed, file-backed, address space, wired, compressed, cached files, free, swap and pressure. - **I/O and audio:** disk and guest file throughput, audio underruns. It is off by default. Enable it with `--perf-overlay true` or the launcher's **Show performance panel** checkbox. In game, **F2** toggles the panel and **Shift+F2** switches to the detailed view. Mac keyboards send brightness for F2 unless fn is held, so **Cmd+P** and **Cmd+Shift+P** do the same on macOS. ## How it works - **Drawing** (`performanceOverlay.cpp`): reuses the ImGui context and Vulkan backend of the existing system overlay. The panel is drawn only on presents that already happen, so it does not change frame pacing. While the guest stops flipping (loading screens), it asks for one repaint per second. Tables are sized to their content, so the panel shrinks and grows with the window. - **Emulator counters** (`common/debugCounters.h`): relaxed atomic counters at the existing hot spots (draw recording, dispatch, queue submit, semaphore waits, shader and pipeline creation, texture and buffer caches, flips, the host exception handler, guest file I/O, audio). The panel reads them once per second and turns them into rates. - **Guest memory** (`Memory::GetDebugStats`): read once per second under the memory subsystem's bookkeeping locks only, never `g_memory_operation_mutex`, so it cannot wait on the GPU. Graphics shuts down before memory, so the present thread can call it safely. - **Host statistics** (`common/hostStats.cpp`): sampled once per second on a background thread, since thread enumeration and the IOAccelerator registry can take a few milliseconds. - **Thread names:** guest threads and the emulator's own threads (main, window, GPU, present) now get OS thread names, so profilers, Activity Monitor and the panel can tell them apart. Before, they were named only while Tracy was running. | Metric | macOS | Linux | Windows | | --- | --- | --- | --- | | CPU (process / machine) | `getrusage` / `host_statistics` | `getrusage` / `/proc/stat` | `GetProcessTimes` / `GetSystemTimes` | | Per-thread CPU | `task_threads` | `/proc/self/task` | n/a | | Process memory | `task_vm_info` | `/proc/self/status` | working set | | System memory and swap | `host_statistics64`, `vm.swapusage` | `/proc/meminfo` | `GlobalMemoryStatusEx` | | Memory pressure | `kern.memorystatus_vm_pressure_level` | PSI `some avg10`, else available memory | `dwMemoryLoad` | | Disk I/O | `proc_pid_rusage` | `/proc/self/io` | `GetProcessIoCounters` | | GPU load, driver memory, resets | IOAccelerator `PerformanceStatistics` | n/a | n/a | | Thermal pressure | `com.apple.system.thermalpressurelevel` | n/a | n/a | | GPU memory | VMA heap budgets | VMA heap budgets | VMA heap budgets | ## Other changes - F2 is now reserved, like F1, F7 and F11. Existing mappings on a reserved key are ignored with a log line instead of exiting, and the launcher's mapping editor rejects F2. - Trophy toasts move below the panel while it is visible, since both use the top-right corner. ## Testing Apple M4 Pro, macOS, x86_64 build. Games need #1083 to boot on macOS, so I tested on a local branch with #1083 merged: - Dead Cells (PPSA15552): both views visible and updating, the shortcuts work, no MoltenVK errors. Sample: 60 FPS, 1% low 41 FPS, ~170 draws per frame, GPU 53%, 216 MB texture cache, 3.5 GB of direct memory. - Host numbers checked against the system tools: CPU per thread (a busy thread reads 99%, a half-busy one 44%), wired and compressed memory (`top`), swap (`vm.swapusage`), memory pressure, GPU (`ioreg`), disk writes. - Panel layout checked with a headless ImGui harness at 960×540, 1280×720, 1920×1080 and 3456×2234, growing and shrinking: no empty space, the same size after shrinking back. - `--keymap Cross=F2` boots with the warning instead of exiting. - `shader_cfg_tests` pass. I did not build on Linux or Windows locally; that code follows the documented APIs and relies on CI for compilation. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:42:37 +00:00
github manually merged commit fc0a85eea1 into gh-pr/1090/base 2026-11-26 09:42:38 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 23:52 UTC · original · edited 2026-10-17 12:32 UTC

Review in Change Stack →

📝 Walkthrough

This change adds a configurable performance panel with compact and detailed views. It samples host and guest metrics, records runtime counters, and connects panel rendering to the presentation path. The launcher and command line can set the panel option, and keyboard shortcuts toggle the panel and its detail view.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟡 Moderate · up to fc0a8

Existing F2 key mappings can prevent games from starting, and the detailed panel can report the wrong guest resolution. Fix the startup failure before merging.

Security architecture risk: 🔵 Low · up to 45836

The inspected paths keep diagnostics local and do not grant additional permissions. No concrete security weakness was established, but incomplete lifecycle coverage prevents a minimal-risk assessment.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected diagnostic flow affects the local emulator process and its displayed host-resource information. Guest activity can influence measured counts and frame dimensions, but does not parameterize host sampling or select its resource targets.

Trust Boundaries and Controls

  • observed — Windows sampling uses the current-process handle, and Linux sampling reads fixed process/system procfs locations. The panel renders values as text, with fixed format strings or unformatted text rather than treating sampled names as format strings.

Resilience and Maintainability Implications

  • observed — The inspected graphics shutdown sequence stops guest GPU work, joins the presentation thread, and then releases the window. ShutdownGpu itself does not destroy the graphics allocator, countering the suspected allocator teardown overlap in that sequence.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 6.87% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 131 functions across 35 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: adding an in-game performance panel.
Description check Passed The description is directly related to the changeset and explains the performance panel, configuration options, platform support, implementation, and testing.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 6.87% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 131 functions across 35 files. (2 skipped: 2 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 23:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#issuecomment-6005828351) · edited 2026-10-17 12:32 UTC <!-- 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/1090?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> This change adds a configurable performance panel with compact and detailed views. It samples host and guest metrics, records runtime counters, and connects panel rendering to the presentation path. The launcher and command line can set the panel option, and keyboard shortcuts toggle the panel and its detail view. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🟡 Moderate</strong> · up to <code>fc0a8</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `fc0a8` --> <!-- final_review_risk_coverage:{"sourceCommitId":"fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42","coveredCommitId":"fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42","kind":"reviewed"} --> Existing F2 key mappings can prevent games from starting, and the detailed panel can report the wrong guest resolution. Fix the startup failure before merging. <!-- final_review_risk_end --> </dd> </dl> </details> <details> <summary><strong>Security architecture risk:</strong> <strong>🔵 Low</strong> · up to <code>45836</code></summary> <dl> <dd> <!-- architecture_review_start --> <!-- architecture_review_label ### Security Architecture Review **Security architecture risk:** _🔵 Low_ · up to `45836` --> The inspected paths keep diagnostics local and do not grant additional permissions. No concrete security weakness was established, but incomplete lifecycle coverage prevents a minimal-risk assessment. **Retained concerns** No architecture-level concerns identified. <details> <summary><strong>Security review details</strong></summary> <dl> <dd> **Security Blast Radius** - _inferred_ — The inspected diagnostic flow affects the local emulator process and its displayed host-resource information. Guest activity can influence measured counts and frame dimensions, but does not parameterize host sampling or select its resource targets. **Trust Boundaries and Controls** - _observed_ — Windows sampling uses the current-process handle, and Linux sampling reads fixed process/system procfs locations. The panel renders values as text, with fixed format strings or unformatted text rather than treating sampled names as format strings. **Resilience and Maintainability Implications** - _observed_ — The inspected graphics shutdown sequence stops guest GPU work, joins the presentation thread, and then releases the window. ShutdownGpu itself does not destroy the graphics allocator, countering the suspected allocator teardown overlap in that sequence. </dd> </dl> </details> <!-- architecture_review_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 warning</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 6.87% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 131 functions across 35 files. (2 skipped:… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely describes the main change: adding an in-game performance panel. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description is directly related to the changeset and explains the performance panel, configuration options, platform support, implementation, and testing. | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 6.87% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 131 functions across 35 files. (2 skipped: 2 unsupported.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autopilot</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1090)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 23:52 UTC · original · edited 2026-10-06 00:30 UTC
On src/graphics/presentation/window/hostInput.cpp line 150 (outdated):

@@ -146,7 +146,8 @@ class InputMap {
 			}
 
 			const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 ||
-			                      binding.key == SDLK_F7 || binding.key == SDLK_F11;
+			                      binding.key == SDLK_F2 || binding.key == SDLK_F7 ||
+			                      binding.key == SDLK_F11;

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Find launcher-side handling of reserved keys and keymap capture.
rg -nP -C3 'F11|F7|F1\b|reserved|Escape' src/launcher
rg -nP -C3 'host_input_mapping' src/launcher

Repository: KytyPS5/KytyPS5

Length of output: 6257


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- PR diff: hostInput.cpp ---'
git diff --unified=12 cdb64bfd4fb4d5312b2542a41a0070f25663166a 2f8ccdbba47c9cf74c4bd304c44cafcfa69421c8 -- src/graphics/presentation/window/hostInput.cpp
printf '%s\n' '--- InputMap current source ---'
nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '105,175p'
printf '%s\n' '--- launcher mapping dialog ---'
nl -ba src/launcher/src/inputMappingDialog.cpp | sed -n '70,175p'
printf '%s\n' '--- settings serialization and launch args ---'
nl -ba src/launcher/include/configuration.h | sed -n '210,285p'
nl -ba src/launcher/src/mainDialog.cpp | sed -n '255,290p'

Repository: KytyPS5/KytyPS5

Length of output: 14726


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- InputMap bindings and keymap source ---'
rg -n -F -- 'InputMap' src/graphics/presentation/window
rg -n -F -- 'GetKeymap' src
printf '%s\n' '--- EXIT definition and related usage ---'
rg -n -F -- '#define EXIT' src
rg -n -F -- 'EXIT("Invalid input mapping:' src
printf '%s\n' '--- LOGF local usages ---'
rg -n -F -- 'LOGF(' src/graphics/presentation/window/hostInput.cpp src/graphics/presentation/window | head -40

Repository: KytyPS5/KytyPS5

Length of output: 6681


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- EXIT macro ---'
nl -ba src/common/assert.h | sed -n '28,53p'
printf '%s\n' '--- keymap config implementation ---'
nl -ba src/common/emulatorConfig.cpp | sed -n '145,190p'
printf '%s\n' '--- CLI keymap option binding ---'
rg -n -F -- '--keymap' src
printf '%s\n' '--- InputMap initialization call site ---'
nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '188,202p'
nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '392,414p'

Repository: KytyPS5/KytyPS5

Length of output: 4318


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- keymap argument parser ---'
nl -ba src/main.cpp | sed -n '425,447p'
printf '%s\n' '--- exit handler declaration and implementation ---'
rg -n -F -- 'DbgExitHandler' src/common
printf '%s\n' '--- host input initialization callers ---'
rg -n -F -- 'HostInputInit(' src

Repository: KytyPS5/KytyPS5

Length of output: 2371


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exit handling implementation ---'
nl -ba src/common/assert.cpp | sed -n '1,60p'
rg -n -C 3 -F -- 'DbgExit(' src/common
printf '%s\n' '--- parsed keymap handoff ---'
rg -n -C 3 -F -- 'options.config' src/main.cpp
rg -n -C 3 -F -- 'g_config =' src/common/emulatorConfig.cpp
printf '%s\n' '--- window initialization context ---'
nl -ba src/graphics/presentation/window/window.cpp | sed -n '798,813p'

Repository: KytyPS5/KytyPS5

Length of output: 12079


Handle existing F2 mappings before rejecting them.

InputMap::InputMap() now rejects F2 during HostInputInit(). The launcher still accepts F2 in its mapping editor and passes saved mappings through --keymap. Existing mappings such as Cross=F2 can therefore terminate the emulator before the game starts.

Reject F2 in the editor and ignore existing reserved-key mappings with a warning:

Suggested fix
-			if (binding.control == INVALID_CONTROL || reserved ||
+			if (reserved && binding.control != INVALID_CONTROL) {
+				LOGF("Ignoring input mapping on reserved key: %s\n", value.c_str());
+				continue;
+			}
+			if (binding.control == INVALID_CONTROL ||
 			    (binding.key == SDLK_UNKNOWN && binding.mouse_button == 0)) {
 				EXIT("Invalid input mapping: %s\n", value.c_str());
-			    tr("Press a key or mouse button.\nF1, F7, and F11 are reserved; Esc cancels."), this);
+			    tr("Press a key or mouse button.\nF1, F2, F7, and F11 are reserved; Esc cancels."), this);
...
-		if (event->key() == Qt::Key_F1 || event->key() == Qt::Key_F7 ||
+		if (event->key() == Qt::Key_F1 || event->key() == Qt::Key_F2 ||
+		    event->key() == Qt::Key_F7 ||
 		    event->key() == Qt::Key_F11) {

✅ Confirmed as addressed by @⁠juanfariasdev

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 23:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#discussion_r4190071845) · edited 2026-10-06 00:30 UTC On `src/graphics/presentation/window/hostInput.cpp` line 150 (outdated): ```diff @@ -146,7 +146,8 @@ class InputMap { } const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 || - binding.key == SDLK_F7 || binding.key == SDLK_F11; + binding.key == SDLK_F2 || binding.key == SDLK_F7 || + binding.key == SDLK_F11; ``` **🗄️ Data Integrity & Integration** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash #!/bin/bash # Find launcher-side handling of reserved keys and keymap capture. rg -nP -C3 'F11|F7|F1\b|reserved|Escape' src/launcher rg -nP -C3 'host_input_mapping' src/launcher ``` Repository: KytyPS5/KytyPS5 Length of output: 6257 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- PR diff: hostInput.cpp ---' git diff --unified=12 cdb64bfd4fb4d5312b2542a41a0070f25663166a 2f8ccdbba47c9cf74c4bd304c44cafcfa69421c8 -- src/graphics/presentation/window/hostInput.cpp printf '%s\n' '--- InputMap current source ---' nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '105,175p' printf '%s\n' '--- launcher mapping dialog ---' nl -ba src/launcher/src/inputMappingDialog.cpp | sed -n '70,175p' printf '%s\n' '--- settings serialization and launch args ---' nl -ba src/launcher/include/configuration.h | sed -n '210,285p' nl -ba src/launcher/src/mainDialog.cpp | sed -n '255,290p' ``` Repository: KytyPS5/KytyPS5 Length of output: 14726 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- InputMap bindings and keymap source ---' rg -n -F -- 'InputMap' src/graphics/presentation/window rg -n -F -- 'GetKeymap' src printf '%s\n' '--- EXIT definition and related usage ---' rg -n -F -- '#define EXIT' src rg -n -F -- 'EXIT("Invalid input mapping:' src printf '%s\n' '--- LOGF local usages ---' rg -n -F -- 'LOGF(' src/graphics/presentation/window/hostInput.cpp src/graphics/presentation/window | head -40 ``` Repository: KytyPS5/KytyPS5 Length of output: 6681 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- EXIT macro ---' nl -ba src/common/assert.h | sed -n '28,53p' printf '%s\n' '--- keymap config implementation ---' nl -ba src/common/emulatorConfig.cpp | sed -n '145,190p' printf '%s\n' '--- CLI keymap option binding ---' rg -n -F -- '--keymap' src printf '%s\n' '--- InputMap initialization call site ---' nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '188,202p' nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '392,414p' ``` Repository: KytyPS5/KytyPS5 Length of output: 4318 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- keymap argument parser ---' nl -ba src/main.cpp | sed -n '425,447p' printf '%s\n' '--- exit handler declaration and implementation ---' rg -n -F -- 'DbgExitHandler' src/common printf '%s\n' '--- host input initialization callers ---' rg -n -F -- 'HostInputInit(' src ``` Repository: KytyPS5/KytyPS5 Length of output: 2371 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- exit handling implementation ---' nl -ba src/common/assert.cpp | sed -n '1,60p' rg -n -C 3 -F -- 'DbgExit(' src/common printf '%s\n' '--- parsed keymap handoff ---' rg -n -C 3 -F -- 'options.config' src/main.cpp rg -n -C 3 -F -- 'g_config =' src/common/emulatorConfig.cpp printf '%s\n' '--- window initialization context ---' nl -ba src/graphics/presentation/window/window.cpp | sed -n '798,813p' ``` Repository: KytyPS5/KytyPS5 Length of output: 12079 --- </details> **Handle existing F2 mappings before rejecting them.** `InputMap::InputMap()` now rejects F2 during `HostInputInit()`. The launcher still accepts F2 in its mapping editor and passes saved mappings through `--keymap`. Existing mappings such as `Cross=F2` can therefore terminate the emulator before the game starts. Reject F2 in the editor and ignore existing reserved-key mappings with a warning: <details> <summary>Suggested fix</summary> ```diff - if (binding.control == INVALID_CONTROL || reserved || + if (reserved && binding.control != INVALID_CONTROL) { + LOGF("Ignoring input mapping on reserved key: %s\n", value.c_str()); + continue; + } + if (binding.control == INVALID_CONTROL || (binding.key == SDLK_UNKNOWN && binding.mouse_button == 0)) { EXIT("Invalid input mapping: %s\n", value.c_str()); ``` ```diff - tr("Press a key or mouse button.\nF1, F7, and F11 are reserved; Esc cancels."), this); + tr("Press a key or mouse button.\nF1, F2, F7, and F11 are reserved; Esc cancels."), this); ... - if (event->key() == Qt::Key_F1 || event->key() == Qt::Key_F7 || + if (event->key() == Qt::Key_F1 || event->key() == Qt::Key_F2 || + event->key() == Qt::Key_F7 || event->key() == Qt::Key_F11) { ``` </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4e18954384c0c4974a73130a --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠juanfariasdev <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-05 23:52 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: 2f12db70-4337-4f3b-8a88-9ca53f3d5cf1
📥 Commits

Reviewing files that changed from the base of the PR and between cdb64bfd4f and 2f8ccdbba47c9cf74c4bd304c44cafcfa69421c8.

📒 Files selected for processing (17)
  • src/common/CMakeLists.txt
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/hostStats.cpp
  • src/common/hostStats.h
  • src/graphics/presentation/performanceOverlay.cpp
  • src/graphics/presentation/performanceOverlay.h
  • src/graphics/presentation/systemOverlay.cpp
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/window/hostInput.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/window.cpp
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/main.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-05 23:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#pullrequestreview-5422103185) · **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**: `2f12db70-4337-4f3b-8a88-9ca53f3d5cf1` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cdb64bfd4fb4d5312b2542a41a0070f25663166a and 2f8ccdbba47c9cf74c4bd304c44cafcfa69421c8. </details> <details> <summary>📒 Files selected for processing (17)</summary> * `src/common/CMakeLists.txt` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/common/hostStats.cpp` * `src/common/hostStats.h` * `src/graphics/presentation/performanceOverlay.cpp` * `src/graphics/presentation/performanceOverlay.h` * `src/graphics/presentation/systemOverlay.cpp` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/window/hostInput.cpp` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/window.cpp` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/mainDialog.cpp` * `src/main.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=eca42dc6-0d35-456b-8a6e-94f6c4f4f7c6 attempt=6e91568a-2e31-454c-add7-e0202041f833 batch=1/1 -->
Author
Owner

@⁠juanfariasdev on GitHub · 2026-10-06 00:30 UTC · original
On src/graphics/presentation/window/hostInput.cpp line 150 (outdated):

@@ -146,7 +146,8 @@ class InputMap {
 			}
 
 			const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 ||
-			                      binding.key == SDLK_F7 || binding.key == SDLK_F11;
+			                      binding.key == SDLK_F2 || binding.key == SDLK_F7 ||
+			                      binding.key == SDLK_F11;

Good catch, thanks. Fixed in 90f863c as suggested:

  • InputMap now ignores a mapping on a reserved key with a log line (Ignoring input mapping on reserved key: Cross=F2) instead of exiting. This also covers Esc, F1, F7 and F11, which the editor already rejected, so it only changes behavior for hand-written --keymap values.
  • The launcher's mapping editor rejects F2 and lists it among the reserved keys.

Tested with --keymap Cross=F2: the game boots and the warning is logged; before the fix it exited with Invalid input mapping.

**@⁠juanfariasdev** on GitHub · 2026-10-06 00:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#discussion_r4190292380) On `src/graphics/presentation/window/hostInput.cpp` line 150 (outdated): ```diff @@ -146,7 +146,8 @@ class InputMap { } const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 || - binding.key == SDLK_F7 || binding.key == SDLK_F11; + binding.key == SDLK_F2 || binding.key == SDLK_F7 || + binding.key == SDLK_F11; ``` Good catch, thanks. Fixed in 90f863c as suggested: - `InputMap` now ignores a mapping on a reserved key with a log line (`Ignoring input mapping on reserved key: Cross=F2`) instead of exiting. This also covers Esc, F1, F7 and F11, which the editor already rejected, so it only changes behavior for hand-written `--keymap` values. - The launcher's mapping editor rejects F2 and lists it among the reserved keys. Tested with `--keymap Cross=F2`: the game boots and the warning is logged; before the fix it exited with `Invalid input mapping`.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 00:30 UTC · original
On src/graphics/presentation/window/hostInput.cpp line 150 (outdated):

@@ -146,7 +146,8 @@ class InputMap {
 			}
 
 			const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 ||
-			                      binding.key == SDLK_F7 || binding.key == SDLK_F11;
+			                      binding.key == SDLK_F2 || binding.key == SDLK_F7 ||
+			                      binding.key == SDLK_F11;

@juanfariasdev Thanks for fixing both paths. Ignoring saved reserved-key mappings prevents the startup failure. Rejecting F2 in the launcher prevents new conflicting mappings. Your --keymap Cross=F2 test confirms the reported failure is addressed.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 00:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#discussion_r4190295680) On `src/graphics/presentation/window/hostInput.cpp` line 150 (outdated): ```diff @@ -146,7 +146,8 @@ class InputMap { } const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 || - binding.key == SDLK_F7 || binding.key == SDLK_F11; + binding.key == SDLK_F2 || binding.key == SDLK_F7 || + binding.key == SDLK_F11; ``` `@juanfariasdev` Thanks for fixing both paths. Ignoring saved reserved-key mappings prevents the startup failure. Rejecting F2 in the launcher prevents new conflicting mappings. Your `--keymap Cross=F2` test confirms the reported failure is addressed. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=Cross%3DF2%20could%20crash%20KytyPS5%20before%20launch.%20%40coderabbitai%20caught%20it%3A%20reserved%20mappings%20are%20now%20ignored%20with%20a%20warning%2C%20and%20F2%20is%20blocked%20in%20the%20editor.%20Try%20CodeRabbit%20for%20actionable%20reviews!%20%F0%9F%9B%A0%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1090%23discussion_r4190071845)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠juanfariasdev on GitHub · 2026-10-06 00:40 UTC · original

image image
**@⁠juanfariasdev** on GitHub · 2026-10-06 00:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#issuecomment-6006697033) <img width="482" height="368" alt="image" src="https://github.com/user-attachments/assets/99f652dd-3542-486e-b23d-960836cac9ea" /> <img width="1664" height="794" alt="image" src="https://github.com/user-attachments/assets/3a655fc9-18ca-473e-803b-199d252f267c" />
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 01:00 UTC · original
On src/common/hostStats.cpp line 415 (outdated):

@@ -0,0 +1,569 @@
+#include "common/hostStats.h"
+
+#include "common/config.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstring>
+#include <thread>
+#include <unordered_map>
+
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h> // IWYU pragma: keep
+// clang-format off
+#include <psapi.h>
+// clang-format on
+#elif defined(__APPLE__)
+#include <CoreFoundation/CoreFoundation.h>
+#include <IOKit/IOKitLib.h>
+#include <libproc.h>
+#include <mach/mach.h>
+#include <notify.h>
+#include <sys/resource.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+#else
+#include <sys/resource.h>
+#include <unistd.h>
+
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+#endif
+
+namespace Common {
+
+namespace {
+
+// Cumulative counters; rates come from the difference between two samples.
+struct Counters {
+	std::optional<uint64_t>                process_cpu_ns;
+	std::optional<uint64_t>                system_busy;
+	std::optional<uint64_t>                system_total;
+	std::optional<uint64_t>                context_switches;
+	std::optional<uint64_t>                page_faults;
+	std::optional<uint64_t>                page_ins;
+	std::optional<uint64_t>                disk_read;
+	std::optional<uint64_t>                disk_write;
+	std::unordered_map<uint64_t, uint64_t> thread_cpu_ns;
+	std::unordered_map<uint64_t, std::string> thread_names;
+	uint64_t                               wall_ns = 0;
+};
+
+uint64_t WallNanoseconds() {
+	return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
+	                                 std::chrono::steady_clock::now().time_since_epoch())
+	                                 .count());
+}
+
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+
+uint64_t FileTimeTo100Ns(const FILETIME& time) {
+	return (static_cast<uint64_t>(time.dwHighDateTime) << 32u) | time.dwLowDateTime;
+}
+
+struct PlatformState {};
+
+void SamplePlatform(PlatformState& /*state*/, HostStats& stats, Counters& now) {
+	const auto process = GetCurrentProcess();
+	FILETIME   creation {};
+	FILETIME   exit {};
+	FILETIME   kernel {};
+	FILETIME   user {};
+	if (GetProcessTimes(process, &creation, &exit, &kernel, &user) != 0) {
+		now.process_cpu_ns = (FileTimeTo100Ns(kernel) + FileTimeTo100Ns(user)) * 100u;
+	}
+	FILETIME idle {};
+	if (GetSystemTimes(&idle, &kernel, &user) != 0) {
+		// Kernel time includes idle time.
+		now.system_total = FileTimeTo100Ns(kernel) + FileTimeTo100Ns(user);
+		now.system_busy  = *now.system_total - FileTimeTo100Ns(idle);
+	}
+
+	PROCESS_MEMORY_COUNTERS memory {};
+	if (K32GetProcessMemoryInfo(process, &memory, sizeof(memory)) != 0) {
+		stats.process_memory   = memory.WorkingSetSize;
+		stats.process_resident = memory.WorkingSetSize;
+		now.page_faults        = memory.PageFaultCount;
+	}
+	IO_COUNTERS io {};
+	if (GetProcessIoCounters(process, &io) != 0) {
+		now.disk_read  = io.ReadTransferCount;
+		now.disk_write = io.WriteTransferCount;
+	}
+
+	MEMORYSTATUSEX system {};
+	system.dwLength = sizeof(system);
+	if (GlobalMemoryStatusEx(&system) != 0) {
+		stats.system_memory_total = system.ullTotalPhys;
+		stats.system_memory_used  = system.ullTotalPhys - system.ullAvailPhys;
+		stats.system_free         = system.ullAvailPhys;
+		stats.memory_pressure     = system.dwMemoryLoad >= 90   ? MemoryPressure::Critical
+		                            : system.dwMemoryLoad >= 80 ? MemoryPressure::Warning
+		                                                        : MemoryPressure::Normal;
+	}
+}
+
+#else
+
+void SampleRusage(Counters& now) {
+	rusage usage {};
+	if (getrusage(RUSAGE_SELF, &usage) != 0) {
+		return;
+	}
+	const auto to_ns = [](const timeval& time) {
+		return static_cast<uint64_t>(time.tv_sec) * 1000000000u +
+		       static_cast<uint64_t>(time.tv_usec) * 1000u;
+	};
+	now.process_cpu_ns   = to_ns(usage.ru_utime) + to_ns(usage.ru_stime);
+	now.context_switches = static_cast<uint64_t>(usage.ru_nvcsw + usage.ru_nivcsw);
+	now.page_faults      = static_cast<uint64_t>(usage.ru_minflt + usage.ru_majflt);
+	now.page_ins         = static_cast<uint64_t>(usage.ru_majflt);
+}
+
+#if defined(__APPLE__)
+
+template <typename T>
+std::optional<T> SysctlValue(const char* name) {
+	T      value {};
+	size_t size = sizeof(value);
+	if (sysctlbyname(name, &value, &size, nullptr, 0) != 0 || size != sizeof(value)) {
+		return std::nullopt;
+	}
+	return value;
+}
+
+struct PlatformState {
+	mach_port_t host          = mach_host_self();
+	int         thermal_token = -1;
+	bool        thermal_ready = false;
+	bool        gpu_info_read = false;
+	std::string gpu_model;
+	std::optional<uint32_t> gpu_cores;
+};
+
+std::optional<int64_t> DictionaryNumber(CFDictionaryRef dictionary, CFStringRef key) {
+	const auto* value  = CFDictionaryGetValue(dictionary, key);
+	int64_t     number = 0;
+	if (value == nullptr || CFGetTypeID(value) != CFNumberGetTypeID() ||
+	    !CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberSInt64Type, &number) ||
+	    number < 0) {
+		return std::nullopt;
+	}
+	return number;
+}
+
+std::string RegistryString(io_object_t service, CFStringRef key) {
+	std::string result;
+	auto*       value = IORegistryEntryCreateCFProperty(service, key, kCFAllocatorDefault, 0);
+	if (value == nullptr) {
+		return result;
+	}
+	if (CFGetTypeID(value) == CFStringGetTypeID()) {
+		char buffer[128] {};
+		if (CFStringGetCString(static_cast<CFStringRef>(value), buffer, sizeof(buffer),
+		                       kCFStringEncodingUTF8)) {
+			result = buffer;
+		}
+	} else if (CFGetTypeID(value) == CFDataGetTypeID()) {
+		// Intel Macs store the model as NUL-terminated data.
+		const auto* data   = static_cast<CFDataRef>(value);
+		const auto* bytes  = reinterpret_cast<const char*>(CFDataGetBytePtr(data));
+		const auto  length = static_cast<size_t>(CFDataGetLength(data));
+		result.assign(bytes, strnlen(bytes, length));
+	}
+	CFRelease(value);
+	return result;
+}
+
+// IOAccelerator exposes whole-device statistics; there is no per-process figure.
+void SampleGpu(PlatformState& state, HostStats& stats) {
+	io_iterator_t iterator = 0;
+	if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("IOAccelerator"),
+	                                 &iterator) != KERN_SUCCESS) {
+		return;
+	}
+	const auto take_max = [](std::optional<double>& target, std::optional<int64_t> value) {
+		if (value) {
+			target = std::max(target.value_or(0.0),
+			                  std::min(100.0, static_cast<double>(*value)));
+		}
+	};
+	const auto add = [](std::optional<uint64_t>& target, std::optional<int64_t> value) {
+		if (value) {
+			target = target.value_or(0) + static_cast<uint64_t>(*value);
+		}
+	};
+	for (io_object_t service = IOIteratorNext(iterator); service != 0;
+	     service             = IOIteratorNext(iterator)) {
+		if (!state.gpu_info_read) {
+			state.gpu_model = RegistryString(service, CFSTR("model"));
+			auto* cores = IORegistryEntryCreateCFProperty(service, CFSTR("gpu-core-count"),
+			                                              kCFAllocatorDefault, 0);
+			int64_t count = 0;
+			if (cores != nullptr) {
+				if (CFGetTypeID(cores) == CFNumberGetTypeID() &&
+				    CFNumberGetValue(static_cast<CFNumberRef>(cores), kCFNumberSInt64Type,
+				                     &count) &&
+				    count > 0) {
+					state.gpu_cores = static_cast<uint32_t>(count);
+				}
+				CFRelease(cores);
+			}
+			state.gpu_info_read = !state.gpu_model.empty();
+		}
+		auto* statistics = IORegistryEntryCreateCFProperty(service, CFSTR("PerformanceStatistics"),
+		                                                   kCFAllocatorDefault, 0);
+		if (statistics != nullptr) {
+			if (CFGetTypeID(statistics) == CFDictionaryGetTypeID()) {
+				const auto* values = static_cast<CFDictionaryRef>(statistics);
+				take_max(stats.gpu_percent,
+				         DictionaryNumber(values, CFSTR("Device Utilization %")));
+				take_max(stats.gpu_renderer_percent,
+				         DictionaryNumber(values, CFSTR("Renderer Utilization %")));
+				take_max(stats.gpu_tiler_percent,
+				         DictionaryNumber(values, CFSTR("Tiler Utilization %")));
+				add(stats.gpu_memory_in_use, DictionaryNumber(values, CFSTR("In use system memory")));
+				add(stats.gpu_memory_allocated,
+				    DictionaryNumber(values, CFSTR("Alloc system memory")));
+				add(stats.gpu_recoveries, DictionaryNumber(values, CFSTR("recoveryCount")));
+			}
+			CFRelease(statistics);
+		}
+		IOObjectRelease(service);
+	}
+	IOObjectRelease(iterator);
+	stats.gpu_model = state.gpu_model;
+	stats.gpu_cores = state.gpu_cores;
+}
+
+void SampleThreads(HostStats& stats, Counters& now) {
+	thread_act_array_t     threads = nullptr;
+	mach_msg_type_number_t count   = 0;
+	const auto             task    = mach_task_self();
+	if (task_threads(task, &threads, &count) != KERN_SUCCESS) {
+		return;
+	}
+	stats.thread_count = count;
+	for (mach_msg_type_number_t i = 0; i < count; i++) {
+		thread_identifier_info_data_t identifier {};
+		mach_msg_type_number_t        size = THREAD_IDENTIFIER_INFO_COUNT;
+		thread_basic_info_data_t      basic {};
+		mach_msg_type_number_t        basic_size = THREAD_BASIC_INFO_COUNT;
+		if (thread_info(threads[i], THREAD_IDENTIFIER_INFO,
+		                reinterpret_cast<thread_info_t>(&identifier), &size) == KERN_SUCCESS &&
+		    thread_info(threads[i], THREAD_BASIC_INFO, reinterpret_cast<thread_info_t>(&basic),
+		                &basic_size) == KERN_SUCCESS) {
+			const auto to_ns = [](const time_value_t& time) {
+				return static_cast<uint64_t>(time.seconds) * 1000000000u +
+				       static_cast<uint64_t>(time.microseconds) * 1000u;
+			};
+			now.thread_cpu_ns[identifier.thread_id] =
+			    to_ns(basic.user_time) + to_ns(basic.system_time);
+			thread_extended_info_data_t extended {};
+			mach_msg_type_number_t      extended_size = THREAD_EXTENDED_INFO_COUNT;
+			if (thread_info(threads[i], THREAD_EXTENDED_INFO,
+			                reinterpret_cast<thread_info_t>(&extended),
+			                &extended_size) == KERN_SUCCESS) {
+				now.thread_names[identifier.thread_id] =
+				    std::string(extended.pth_name, strnlen(extended.pth_name, sizeof(extended.pth_name)));
+			}
+		}
+		mach_port_deallocate(task, threads[i]);
+	}
+	vm_deallocate(task, reinterpret_cast<vm_address_t>(threads), count * sizeof(thread_act_t));
+}
+
+void SamplePlatform(PlatformState& state, HostStats& stats, Counters& now) {
+	SampleRusage(now);
+
+	host_cpu_load_info_data_t load {};
+	mach_msg_type_number_t    load_count = HOST_CPU_LOAD_INFO_COUNT;
+	if (host_statistics(state.host, HOST_CPU_LOAD_INFO, reinterpret_cast<host_info_t>(&load),
+	                    &load_count) == KERN_SUCCESS) {
+		const uint64_t busy = static_cast<uint64_t>(load.cpu_ticks[CPU_STATE_USER]) +
+		                      load.cpu_ticks[CPU_STATE_SYSTEM] + load.cpu_ticks[CPU_STATE_NICE];
+		now.system_busy  = busy;
+		now.system_total = busy + load.cpu_ticks[CPU_STATE_IDLE];
+	}
+
+	// Physical footprint is what Activity Monitor shows in its Memory column.
+	task_vm_info_data_t    vm_info {};
+	mach_msg_type_number_t vm_info_count = TASK_VM_INFO_COUNT;
+	if (task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast<task_info_t>(&vm_info),
+	              &vm_info_count) == KERN_SUCCESS) {
+		stats.process_memory      = vm_info.phys_footprint;
+		stats.process_resident    = vm_info.resident_size;
+		stats.process_compressed  = vm_info.compressed;
+		stats.process_file_backed = vm_info.external;
+		stats.process_virtual     = vm_info.virtual_size;
+	}
+	rusage_info_v2 usage {};
+	if (proc_pid_rusage(getpid(), RUSAGE_INFO_V2, reinterpret_cast<rusage_info_t*>(&usage)) == 0) {
+		now.disk_read  = usage.ri_diskio_bytesread;
+		now.disk_write = usage.ri_diskio_byteswritten;
+	}
+
+	stats.system_memory_total = SysctlValue<uint64_t>("hw.memsize");
+	vm_size_t              page = 0;
+	vm_statistics64_data_t vm {};
+	mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
+	if (host_page_size(state.host, &page) == KERN_SUCCESS &&
+	    host_statistics64(state.host, HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&vm),
+	                      &count) == KERN_SUCCESS) {
+		// Activity Monitor's "Memory Used": app memory + wired + compressed.
+		const uint64_t app = vm.internal_page_count > vm.purgeable_count
+		                         ? vm.internal_page_count - vm.purgeable_count
+		                         : 0;
+		stats.system_memory_used = (app + vm.wire_count + vm.compressor_page_count) * page;
+		stats.system_wired       = static_cast<uint64_t>(vm.wire_count) * page;
+		stats.system_compressed  = static_cast<uint64_t>(vm.compressor_page_count) * page;
+		stats.system_cached =
+		    (static_cast<uint64_t>(vm.external_page_count) + vm.purgeable_count) * page;
+		stats.system_free = static_cast<uint64_t>(vm.free_count) * page;
+	}
+
+	if (const auto swap = SysctlValue<xsw_usage>("vm.swapusage")) {
+		stats.swap_used  = swap->xsu_used;
+		stats.swap_total = swap->xsu_total;
+	}
+
+	// 1 = normal, 2 = warning, 4 = critical, as reported to dispatch memory-pressure sources.
+	if (const auto level = SysctlValue<int>("kern.memorystatus_vm_pressure_level")) {
+		stats.memory_pressure = *level >= 4   ? MemoryPressure::Critical
+		                        : *level >= 2 ? MemoryPressure::Warning
+		                                      : MemoryPressure::Normal;
+	}
+
+	// 0 nominal, 1 moderate, 2 heavy, 3 trapping, 4 sleeping.
+	if (!state.thermal_ready) {
+		state.thermal_ready = notify_register_check("com.apple.system.thermalpressurelevel",
+		                                            &state.thermal_token) == NOTIFY_STATUS_OK;
+	}
+	uint64_t thermal = 0;
+	if (state.thermal_ready && notify_get_state(state.thermal_token, &thermal) == NOTIFY_STATUS_OK) {
+		stats.thermal_pressure = thermal >= 3   ? ThermalPressure::Critical
+		                         : thermal == 2 ? ThermalPressure::Heavy
+		                         : thermal == 1 ? ThermalPressure::Moderate
+		                                        : ThermalPressure::Nominal;
+	}
+
+	SampleThreads(stats, now);
+	SampleGpu(state, stats);
+}
+
+#else
+
+using ProcValues = std::unordered_map<std::string, uint64_t>;
+
+// Reads "<key>: <number> [kB]" lines; kB values are returned in bytes.
+ProcValues ReadProcValues(const char* path) {
+	ProcValues    values;
+	std::ifstream file(path);
+	std::string   line;
+	while (std::getline(file, line)) {
+		const auto colon = line.find(':');
+		if (colon == std::string::npos) {
+			continue;
+		}
+		std::istringstream stream(line.substr(colon + 1));
+		uint64_t           number = 0;
+		std::string        unit;
+		if (stream >> number) {
+			stream >> unit;
+			values[line.substr(0, colon)] = unit == "kB" ? number * 1024u : number;
+		}
+	}
+	return values;
+}
+
+std::optional<uint64_t> Find(const ProcValues& values, const char* key) {
+	const auto it = values.find(key);
+	return it != values.end() ? std::optional(it->second) : std::nullopt;
+}
+
+struct PlatformState {};
+
+void SampleThreads(HostStats& stats, Counters& now) {
+	const double ns_per_tick = 1e9 / static_cast<double>(std::max(sysconf(_SC_CLK_TCK), 1L));
+	std::error_code error;
+	uint32_t        count = 0;
+	for (const auto& entry: std::filesystem::directory_iterator("/proc/self/task", error)) {
+		count++;
+		std::ifstream stat_file(entry.path() / "stat");
+		std::string   stat;
+		std::getline(stat_file, stat);
+		const auto close = stat.rfind(')');
+		if (close == std::string::npos) {
+			continue;
+		}
+		// Fields after the command name start at field 3 (state); utime and stime are 14 and 15.
+		std::istringstream fields(stat.substr(close + 2));
+		std::string        field;
+		uint64_t           user = 0;
+		uint64_t           system = 0;
+		for (int index = 3; index <= 15 && fields >> field; index++) {
+			if (index == 14) {
+				user = std::stoull(field);
+			} else if (index == 15) {
+				system = std::stoull(field);
+			}
+		}
+		const auto id = std::stoull(entry.path().filename().string());

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Catch parse failures in the Linux thread sampler.

std::stoull throws std::invalid_argument or std::out_of_range when a /proc/self/task/<tid>/stat field is malformed. A thread can exit after directory_iterator lists it. In that case stat is empty or truncated, and the read can produce a partial field. The sampler runs on a background std::jthread without a try block. An uncaught exception in that thread calls std::terminate and ends the emulator. Use std::from_chars, or wrap the parse in a try block and skip the thread on failure. Apply the same fix to std::stod at Line 477.

Proposed fix
-			if (index == 14) {
-				user = std::stoull(field);
-			} else if (index == 15) {
-				system = std::stoull(field);
-			}
+			if (index == 14 || index == 15) {
+				uint64_t parsed = 0;
+				const auto [ptr, ec] =
+				    std::from_chars(field.data(), field.data() + field.size(), parsed);
+				if (ec != std::errc {}) {
+					break;
+				}
+				(index == 14 ? user : system) = parsed;
+			}
 		}
-		const auto id = std::stoull(entry.path().filename().string());
+		uint64_t id = 0;
+		const auto name = entry.path().filename().string();
+		if (std::from_chars(name.data(), name.data() + name.size(), id).ec != std::errc {}) {
+			continue;
+		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		for (int index = 3; index <= 15 && fields >> field; index++) {
			if (index == 14 || index == 15) {
				uint64_t parsed = 0;
				const auto [ptr, ec] =
				    std::from_chars(field.data(), field.data() + field.size(), parsed);
				if (ec != std::errc {}) {
					break;
				}
				(index == 14 ? user : system) = parsed;
			}
		}
		uint64_t id = 0;
		const auto name = entry.path().filename().string();
		if (std::from_chars(name.data(), name.data() + name.size(), id).ec != std::errc {}) {
			continue;
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 01:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#discussion_r4190482942) On `src/common/hostStats.cpp` line 415 (outdated): ```diff @@ -0,0 +1,569 @@ +#include "common/hostStats.h" + +#include "common/config.h" + +#include <algorithm> +#include <chrono> +#include <cstring> +#include <thread> +#include <unordered_map> + +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> // IWYU pragma: keep +// clang-format off +#include <psapi.h> +// clang-format on +#elif defined(__APPLE__) +#include <CoreFoundation/CoreFoundation.h> +#include <IOKit/IOKitLib.h> +#include <libproc.h> +#include <mach/mach.h> +#include <notify.h> +#include <sys/resource.h> +#include <sys/sysctl.h> +#include <unistd.h> +#else +#include <sys/resource.h> +#include <unistd.h> + +#include <filesystem> +#include <fstream> +#include <sstream> +#endif + +namespace Common { + +namespace { + +// Cumulative counters; rates come from the difference between two samples. +struct Counters { + std::optional<uint64_t> process_cpu_ns; + std::optional<uint64_t> system_busy; + std::optional<uint64_t> system_total; + std::optional<uint64_t> context_switches; + std::optional<uint64_t> page_faults; + std::optional<uint64_t> page_ins; + std::optional<uint64_t> disk_read; + std::optional<uint64_t> disk_write; + std::unordered_map<uint64_t, uint64_t> thread_cpu_ns; + std::unordered_map<uint64_t, std::string> thread_names; + uint64_t wall_ns = 0; +}; + +uint64_t WallNanoseconds() { + return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>( + std::chrono::steady_clock::now().time_since_epoch()) + .count()); +} + +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + +uint64_t FileTimeTo100Ns(const FILETIME& time) { + return (static_cast<uint64_t>(time.dwHighDateTime) << 32u) | time.dwLowDateTime; +} + +struct PlatformState {}; + +void SamplePlatform(PlatformState& /*state*/, HostStats& stats, Counters& now) { + const auto process = GetCurrentProcess(); + FILETIME creation {}; + FILETIME exit {}; + FILETIME kernel {}; + FILETIME user {}; + if (GetProcessTimes(process, &creation, &exit, &kernel, &user) != 0) { + now.process_cpu_ns = (FileTimeTo100Ns(kernel) + FileTimeTo100Ns(user)) * 100u; + } + FILETIME idle {}; + if (GetSystemTimes(&idle, &kernel, &user) != 0) { + // Kernel time includes idle time. + now.system_total = FileTimeTo100Ns(kernel) + FileTimeTo100Ns(user); + now.system_busy = *now.system_total - FileTimeTo100Ns(idle); + } + + PROCESS_MEMORY_COUNTERS memory {}; + if (K32GetProcessMemoryInfo(process, &memory, sizeof(memory)) != 0) { + stats.process_memory = memory.WorkingSetSize; + stats.process_resident = memory.WorkingSetSize; + now.page_faults = memory.PageFaultCount; + } + IO_COUNTERS io {}; + if (GetProcessIoCounters(process, &io) != 0) { + now.disk_read = io.ReadTransferCount; + now.disk_write = io.WriteTransferCount; + } + + MEMORYSTATUSEX system {}; + system.dwLength = sizeof(system); + if (GlobalMemoryStatusEx(&system) != 0) { + stats.system_memory_total = system.ullTotalPhys; + stats.system_memory_used = system.ullTotalPhys - system.ullAvailPhys; + stats.system_free = system.ullAvailPhys; + stats.memory_pressure = system.dwMemoryLoad >= 90 ? MemoryPressure::Critical + : system.dwMemoryLoad >= 80 ? MemoryPressure::Warning + : MemoryPressure::Normal; + } +} + +#else + +void SampleRusage(Counters& now) { + rusage usage {}; + if (getrusage(RUSAGE_SELF, &usage) != 0) { + return; + } + const auto to_ns = [](const timeval& time) { + return static_cast<uint64_t>(time.tv_sec) * 1000000000u + + static_cast<uint64_t>(time.tv_usec) * 1000u; + }; + now.process_cpu_ns = to_ns(usage.ru_utime) + to_ns(usage.ru_stime); + now.context_switches = static_cast<uint64_t>(usage.ru_nvcsw + usage.ru_nivcsw); + now.page_faults = static_cast<uint64_t>(usage.ru_minflt + usage.ru_majflt); + now.page_ins = static_cast<uint64_t>(usage.ru_majflt); +} + +#if defined(__APPLE__) + +template <typename T> +std::optional<T> SysctlValue(const char* name) { + T value {}; + size_t size = sizeof(value); + if (sysctlbyname(name, &value, &size, nullptr, 0) != 0 || size != sizeof(value)) { + return std::nullopt; + } + return value; +} + +struct PlatformState { + mach_port_t host = mach_host_self(); + int thermal_token = -1; + bool thermal_ready = false; + bool gpu_info_read = false; + std::string gpu_model; + std::optional<uint32_t> gpu_cores; +}; + +std::optional<int64_t> DictionaryNumber(CFDictionaryRef dictionary, CFStringRef key) { + const auto* value = CFDictionaryGetValue(dictionary, key); + int64_t number = 0; + if (value == nullptr || CFGetTypeID(value) != CFNumberGetTypeID() || + !CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberSInt64Type, &number) || + number < 0) { + return std::nullopt; + } + return number; +} + +std::string RegistryString(io_object_t service, CFStringRef key) { + std::string result; + auto* value = IORegistryEntryCreateCFProperty(service, key, kCFAllocatorDefault, 0); + if (value == nullptr) { + return result; + } + if (CFGetTypeID(value) == CFStringGetTypeID()) { + char buffer[128] {}; + if (CFStringGetCString(static_cast<CFStringRef>(value), buffer, sizeof(buffer), + kCFStringEncodingUTF8)) { + result = buffer; + } + } else if (CFGetTypeID(value) == CFDataGetTypeID()) { + // Intel Macs store the model as NUL-terminated data. + const auto* data = static_cast<CFDataRef>(value); + const auto* bytes = reinterpret_cast<const char*>(CFDataGetBytePtr(data)); + const auto length = static_cast<size_t>(CFDataGetLength(data)); + result.assign(bytes, strnlen(bytes, length)); + } + CFRelease(value); + return result; +} + +// IOAccelerator exposes whole-device statistics; there is no per-process figure. +void SampleGpu(PlatformState& state, HostStats& stats) { + io_iterator_t iterator = 0; + if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("IOAccelerator"), + &iterator) != KERN_SUCCESS) { + return; + } + const auto take_max = [](std::optional<double>& target, std::optional<int64_t> value) { + if (value) { + target = std::max(target.value_or(0.0), + std::min(100.0, static_cast<double>(*value))); + } + }; + const auto add = [](std::optional<uint64_t>& target, std::optional<int64_t> value) { + if (value) { + target = target.value_or(0) + static_cast<uint64_t>(*value); + } + }; + for (io_object_t service = IOIteratorNext(iterator); service != 0; + service = IOIteratorNext(iterator)) { + if (!state.gpu_info_read) { + state.gpu_model = RegistryString(service, CFSTR("model")); + auto* cores = IORegistryEntryCreateCFProperty(service, CFSTR("gpu-core-count"), + kCFAllocatorDefault, 0); + int64_t count = 0; + if (cores != nullptr) { + if (CFGetTypeID(cores) == CFNumberGetTypeID() && + CFNumberGetValue(static_cast<CFNumberRef>(cores), kCFNumberSInt64Type, + &count) && + count > 0) { + state.gpu_cores = static_cast<uint32_t>(count); + } + CFRelease(cores); + } + state.gpu_info_read = !state.gpu_model.empty(); + } + auto* statistics = IORegistryEntryCreateCFProperty(service, CFSTR("PerformanceStatistics"), + kCFAllocatorDefault, 0); + if (statistics != nullptr) { + if (CFGetTypeID(statistics) == CFDictionaryGetTypeID()) { + const auto* values = static_cast<CFDictionaryRef>(statistics); + take_max(stats.gpu_percent, + DictionaryNumber(values, CFSTR("Device Utilization %"))); + take_max(stats.gpu_renderer_percent, + DictionaryNumber(values, CFSTR("Renderer Utilization %"))); + take_max(stats.gpu_tiler_percent, + DictionaryNumber(values, CFSTR("Tiler Utilization %"))); + add(stats.gpu_memory_in_use, DictionaryNumber(values, CFSTR("In use system memory"))); + add(stats.gpu_memory_allocated, + DictionaryNumber(values, CFSTR("Alloc system memory"))); + add(stats.gpu_recoveries, DictionaryNumber(values, CFSTR("recoveryCount"))); + } + CFRelease(statistics); + } + IOObjectRelease(service); + } + IOObjectRelease(iterator); + stats.gpu_model = state.gpu_model; + stats.gpu_cores = state.gpu_cores; +} + +void SampleThreads(HostStats& stats, Counters& now) { + thread_act_array_t threads = nullptr; + mach_msg_type_number_t count = 0; + const auto task = mach_task_self(); + if (task_threads(task, &threads, &count) != KERN_SUCCESS) { + return; + } + stats.thread_count = count; + for (mach_msg_type_number_t i = 0; i < count; i++) { + thread_identifier_info_data_t identifier {}; + mach_msg_type_number_t size = THREAD_IDENTIFIER_INFO_COUNT; + thread_basic_info_data_t basic {}; + mach_msg_type_number_t basic_size = THREAD_BASIC_INFO_COUNT; + if (thread_info(threads[i], THREAD_IDENTIFIER_INFO, + reinterpret_cast<thread_info_t>(&identifier), &size) == KERN_SUCCESS && + thread_info(threads[i], THREAD_BASIC_INFO, reinterpret_cast<thread_info_t>(&basic), + &basic_size) == KERN_SUCCESS) { + const auto to_ns = [](const time_value_t& time) { + return static_cast<uint64_t>(time.seconds) * 1000000000u + + static_cast<uint64_t>(time.microseconds) * 1000u; + }; + now.thread_cpu_ns[identifier.thread_id] = + to_ns(basic.user_time) + to_ns(basic.system_time); + thread_extended_info_data_t extended {}; + mach_msg_type_number_t extended_size = THREAD_EXTENDED_INFO_COUNT; + if (thread_info(threads[i], THREAD_EXTENDED_INFO, + reinterpret_cast<thread_info_t>(&extended), + &extended_size) == KERN_SUCCESS) { + now.thread_names[identifier.thread_id] = + std::string(extended.pth_name, strnlen(extended.pth_name, sizeof(extended.pth_name))); + } + } + mach_port_deallocate(task, threads[i]); + } + vm_deallocate(task, reinterpret_cast<vm_address_t>(threads), count * sizeof(thread_act_t)); +} + +void SamplePlatform(PlatformState& state, HostStats& stats, Counters& now) { + SampleRusage(now); + + host_cpu_load_info_data_t load {}; + mach_msg_type_number_t load_count = HOST_CPU_LOAD_INFO_COUNT; + if (host_statistics(state.host, HOST_CPU_LOAD_INFO, reinterpret_cast<host_info_t>(&load), + &load_count) == KERN_SUCCESS) { + const uint64_t busy = static_cast<uint64_t>(load.cpu_ticks[CPU_STATE_USER]) + + load.cpu_ticks[CPU_STATE_SYSTEM] + load.cpu_ticks[CPU_STATE_NICE]; + now.system_busy = busy; + now.system_total = busy + load.cpu_ticks[CPU_STATE_IDLE]; + } + + // Physical footprint is what Activity Monitor shows in its Memory column. + task_vm_info_data_t vm_info {}; + mach_msg_type_number_t vm_info_count = TASK_VM_INFO_COUNT; + if (task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast<task_info_t>(&vm_info), + &vm_info_count) == KERN_SUCCESS) { + stats.process_memory = vm_info.phys_footprint; + stats.process_resident = vm_info.resident_size; + stats.process_compressed = vm_info.compressed; + stats.process_file_backed = vm_info.external; + stats.process_virtual = vm_info.virtual_size; + } + rusage_info_v2 usage {}; + if (proc_pid_rusage(getpid(), RUSAGE_INFO_V2, reinterpret_cast<rusage_info_t*>(&usage)) == 0) { + now.disk_read = usage.ri_diskio_bytesread; + now.disk_write = usage.ri_diskio_byteswritten; + } + + stats.system_memory_total = SysctlValue<uint64_t>("hw.memsize"); + vm_size_t page = 0; + vm_statistics64_data_t vm {}; + mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + if (host_page_size(state.host, &page) == KERN_SUCCESS && + host_statistics64(state.host, HOST_VM_INFO64, reinterpret_cast<host_info64_t>(&vm), + &count) == KERN_SUCCESS) { + // Activity Monitor's "Memory Used": app memory + wired + compressed. + const uint64_t app = vm.internal_page_count > vm.purgeable_count + ? vm.internal_page_count - vm.purgeable_count + : 0; + stats.system_memory_used = (app + vm.wire_count + vm.compressor_page_count) * page; + stats.system_wired = static_cast<uint64_t>(vm.wire_count) * page; + stats.system_compressed = static_cast<uint64_t>(vm.compressor_page_count) * page; + stats.system_cached = + (static_cast<uint64_t>(vm.external_page_count) + vm.purgeable_count) * page; + stats.system_free = static_cast<uint64_t>(vm.free_count) * page; + } + + if (const auto swap = SysctlValue<xsw_usage>("vm.swapusage")) { + stats.swap_used = swap->xsu_used; + stats.swap_total = swap->xsu_total; + } + + // 1 = normal, 2 = warning, 4 = critical, as reported to dispatch memory-pressure sources. + if (const auto level = SysctlValue<int>("kern.memorystatus_vm_pressure_level")) { + stats.memory_pressure = *level >= 4 ? MemoryPressure::Critical + : *level >= 2 ? MemoryPressure::Warning + : MemoryPressure::Normal; + } + + // 0 nominal, 1 moderate, 2 heavy, 3 trapping, 4 sleeping. + if (!state.thermal_ready) { + state.thermal_ready = notify_register_check("com.apple.system.thermalpressurelevel", + &state.thermal_token) == NOTIFY_STATUS_OK; + } + uint64_t thermal = 0; + if (state.thermal_ready && notify_get_state(state.thermal_token, &thermal) == NOTIFY_STATUS_OK) { + stats.thermal_pressure = thermal >= 3 ? ThermalPressure::Critical + : thermal == 2 ? ThermalPressure::Heavy + : thermal == 1 ? ThermalPressure::Moderate + : ThermalPressure::Nominal; + } + + SampleThreads(stats, now); + SampleGpu(state, stats); +} + +#else + +using ProcValues = std::unordered_map<std::string, uint64_t>; + +// Reads "<key>: <number> [kB]" lines; kB values are returned in bytes. +ProcValues ReadProcValues(const char* path) { + ProcValues values; + std::ifstream file(path); + std::string line; + while (std::getline(file, line)) { + const auto colon = line.find(':'); + if (colon == std::string::npos) { + continue; + } + std::istringstream stream(line.substr(colon + 1)); + uint64_t number = 0; + std::string unit; + if (stream >> number) { + stream >> unit; + values[line.substr(0, colon)] = unit == "kB" ? number * 1024u : number; + } + } + return values; +} + +std::optional<uint64_t> Find(const ProcValues& values, const char* key) { + const auto it = values.find(key); + return it != values.end() ? std::optional(it->second) : std::nullopt; +} + +struct PlatformState {}; + +void SampleThreads(HostStats& stats, Counters& now) { + const double ns_per_tick = 1e9 / static_cast<double>(std::max(sysconf(_SC_CLK_TCK), 1L)); + std::error_code error; + uint32_t count = 0; + for (const auto& entry: std::filesystem::directory_iterator("/proc/self/task", error)) { + count++; + std::ifstream stat_file(entry.path() / "stat"); + std::string stat; + std::getline(stat_file, stat); + const auto close = stat.rfind(')'); + if (close == std::string::npos) { + continue; + } + // Fields after the command name start at field 3 (state); utime and stime are 14 and 15. + std::istringstream fields(stat.substr(close + 2)); + std::string field; + uint64_t user = 0; + uint64_t system = 0; + for (int index = 3; index <= 15 && fields >> field; index++) { + if (index == 14) { + user = std::stoull(field); + } else if (index == 15) { + system = std::stoull(field); + } + } + const auto id = std::stoull(entry.path().filename().string()); ``` **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Catch parse failures in the Linux thread sampler.** `std::stoull` throws `std::invalid_argument` or `std::out_of_range` when a `/proc/self/task/<tid>/stat` field is malformed. A thread can exit after `directory_iterator` lists it. In that case `stat` is empty or truncated, and the read can produce a partial field. The sampler runs on a background `std::jthread` without a `try` block. An uncaught exception in that thread calls `std::terminate` and ends the emulator. Use `std::from_chars`, or wrap the parse in a `try` block and skip the thread on failure. Apply the same fix to `std::stod` at Line 477. <details> <summary>Proposed fix</summary> ```diff - if (index == 14) { - user = std::stoull(field); - } else if (index == 15) { - system = std::stoull(field); - } + if (index == 14 || index == 15) { + uint64_t parsed = 0; + const auto [ptr, ec] = + std::from_chars(field.data(), field.data() + field.size(), parsed); + if (ec != std::errc {}) { + break; + } + (index == 14 ? user : system) = parsed; + } } - const auto id = std::stoull(entry.path().filename().string()); + uint64_t id = 0; + const auto name = entry.path().filename().string(); + if (std::from_chars(name.data(), name.data() + name.size(), id).ec != std::errc {}) { + continue; + } ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion for (int index = 3; index <= 15 && fields >> field; index++) { if (index == 14 || index == 15) { uint64_t parsed = 0; const auto [ptr, ec] = std::from_chars(field.data(), field.data() + field.size(), parsed); if (ec != std::errc {}) { break; } (index == 14 ? user : system) = parsed; } } uint64_t id = 0; const auto name = entry.path().filename().string(); if (std::from_chars(name.data(), name.data() + name.size(), id).ec != std::errc {}) { continue; } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:da09f4a36ac43ac6a4bc8b63 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-06 01:00 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: 0967deb9-3042-4cdb-965a-3f8ae8088f95
📥 Commits

Reviewing files that changed from the base of the PR and between 2f8ccdbba47c9cf74c4bd304c44cafcfa69421c8 and 4583663d5c007b71bf8b258342ad1524f85b4469.

📒 Files selected for processing (29)
  • src/common/debugCounters.h
  • src/common/hostStats.cpp
  • src/common/hostStats.h
  • src/common/profiler.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/masterSemaphore.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/vma.cpp
  • src/graphics/presentation/performanceOverlay.cpp
  • src/graphics/presentation/performanceOverlay.h
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/window/hostInput.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/window.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/kernel/pthread.cpp
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/inputMappingDialog.cpp
  • src/libs/audio.cpp
  • src/loader/runtimeLinker.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-06 01:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#pullrequestreview-5422599720) · **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**: `0967deb9-3042-4cdb-965a-3f8ae8088f95` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 2f8ccdbba47c9cf74c4bd304c44cafcfa69421c8 and 4583663d5c007b71bf8b258342ad1524f85b4469. </details> <details> <summary>📒 Files selected for processing (29)</summary> * `src/common/debugCounters.h` * `src/common/hostStats.cpp` * `src/common/hostStats.h` * `src/common/profiler.cpp` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/masterSemaphore.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/host_gpu/vma.cpp` * `src/graphics/presentation/performanceOverlay.cpp` * `src/graphics/presentation/performanceOverlay.h` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/window/hostInput.cpp` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/window.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/kernel/pthread.cpp` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/inputMappingDialog.cpp` * `src/libs/audio.cpp` * `src/loader/runtimeLinker.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=f13a7a49-2834-4473-9c2e-e0c72326dec9 attempt=8ca91962-0258-48c8-9e1d-54c7d91d76e0 batch=1/1 -->
@ -1245,1 +1252,4 @@
m_presenter.Present(std::span(layers.data(), count));
if (requests[0].cfg->bus == 0) {
Graphics::PerformanceOverlayRecordFlip(requests[0].cfg->width, requests[0].cfg->height);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-17 12:32 UTC · original

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Report the guest frame size, not the port's configured size.

VideoOutConfig::width and height come from Impl::Init. That function stores the emulator screen size for every port. Guest buffer registration never updates these fields. The detailed panel's "Guest output" row therefore shows the window size, not the guest resolution.

The presented frame already holds the guest surface extent. Presenter::PrepareFrame configures the frame from the texture-cache backing extent. Use that frame's image extent.

Proposed fix
--- "a/src/graphics/presentation/videoOut.cpp"
+++ "b/src/graphics/presentation/videoOut.cpp"
@@ -1250,9 +1250,10 @@
 	}
 	if (due) {
 		m_presenter.Present(std::span(layers.data(), count));
 		if (requests[0].cfg->bus == 0) {
-			Graphics::PerformanceOverlayRecordFlip(requests[0].cfg->width, requests[0].cfg->height);
+			Graphics::PerformanceOverlayRecordFlip(requests[0].frame->image.extent.width,
+			                                       requests[0].frame->image.extent.height);
 		}
 	}
 
 	m_mutex.Lock();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

		if (requests[0].cfg->bus == 0) {
			Graphics::PerformanceOverlayRecordFlip(requests[0].frame->image.extent.width,
			                                       requests[0].frame->image.extent.height);
		}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-17 12:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#discussion_r4302667612) **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** **Report the guest frame size, not the port's configured size.** `VideoOutConfig::width` and `height` come from `Impl::Init`. That function stores the emulator screen size for every port. Guest buffer registration never updates these fields. The detailed panel's "Guest output" row therefore shows the window size, not the guest resolution. The presented frame already holds the guest surface extent. `Presenter::PrepareFrame` configures the frame from the texture-cache backing extent. Use that frame's image extent. <details> <summary>Proposed fix</summary> ```diff --- "a/src/graphics/presentation/videoOut.cpp" +++ "b/src/graphics/presentation/videoOut.cpp" @@ -1250,9 +1250,10 @@ } if (due) { m_presenter.Present(std::span(layers.data(), count)); if (requests[0].cfg->bus == 0) { - Graphics::PerformanceOverlayRecordFlip(requests[0].cfg->width, requests[0].cfg->height); + Graphics::PerformanceOverlayRecordFlip(requests[0].frame->image.extent.width, + requests[0].frame->image.extent.height); } } m_mutex.Lock(); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if (requests[0].cfg->bus == 0) { Graphics::PerformanceOverlayRecordFlip(requests[0].frame->image.extent.width, requests[0].frame->image.extent.height); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a97c4c612928b5bb8d7e25fc --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -257,2 +257,2 @@
binding.key == SDLK_F7 || binding.key == SDLK_F8 ||
binding.key == SDLK_F11;
binding.key == SDLK_F2 || binding.key == SDLK_F7 ||
binding.key == SDLK_F8 || binding.key == SDLK_F11;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-17 12:32 UTC · original

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '225,280p' src/graphics/presentation/window/hostInput.cpp
git log --oneline 415387f00d8ff6cf8040cb2f5bd42a4b5f87235f..fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42 -- src/graphics/presentation/window/hostInput.cpp

Repository: KytyPS5/KytyPS5

Length of output: 2295


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- relevant history ---'
git log --all --oneline --decorate -- src/graphics/presentation/window/hostInput.cpp | head -80
printf '%s\n' '--- candidate commit ---'
git show --stat --oneline 90f863c 2>&1 || true
git show --format=fuller --no-ext-diff --find-renames 90f863c -- src/graphics/presentation/window/hostInput.cpp 2>&1 || true
printf '%s\n' '--- current declarations and callers ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'HostInputInit' -e 'InputMap' src || test "$?" -eq 1
printf '%s\n' '--- current implementation block ---'
nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '185,275p'
printf '%s\n' '--- history of reserved/exit lines ---'
git blame -L 245,265 fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42 -- src/graphics/presentation/window/hostInput.cpp
printf '%s\n' '--- all refs containing candidate commit ---'
git branch -a --contains 90f863c 2>&1 || true
git tag --contains 90f863c 2>&1 || true

Repository: KytyPS5/KytyPS5

Length of output: 10376


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- HostInputInit and InputMap accessor ---'
nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '340,365p;735,755p'
printf '%s\n' '--- base versus head reserved validation ---'
git show 415387f00d8ff6cf8040cb2f5bd42a4b5f87235f:src/graphics/presentation/window/hostInput.cpp | nl -ba | sed -n '245,265p'
printf '%s\n' '--- available warning/skip history ---'
git log --all --oneline --decorate --grep='mapping\|reserved\|warning\|keymap' -i --regexp-ignore-case | head -100
printf '%s\n' '--- all objects matching the cited prefix, if any ---'
git rev-list --all --objects | grep -E '(^|/)90f863c' || true

Repository: KytyPS5/KytyPS5

Length of output: 6139


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- EXIT definition ---'
rg -n -F --glob '*.{h,hpp,cpp,c,inl}' -e '#define EXIT' -e 'void Exit' -e 'Exit(' src include 2>/dev/null | head -80
printf '%s\n' '--- keymap declaration and uses ---'
rg -n -F --glob '*.{h,hpp,cpp,c,inl}' -e 'GetKeymap' -e 'keymap' src/graphics src/core src/launcher 2>/dev/null | head -120

Repository: KytyPS5/KytyPS5

Length of output: 2335


🏁 Script executed:

nl -ba src/common/assert.h | sed -n '20,55p'
nl -ba src/common/assert.cpp | sed -n '35,52p'

Repository: KytyPS5/KytyPS5

Length of output: 3048


Ignore saved mappings on reserved keys instead of exiting.

A saved Cross=F2 mapping reaches InputMap during HostInputInit() and triggers EXIT, which terminates the emulator. Warn and skip valid mappings that use reserved keys.

F8 was already reserved before this PR, so this change does not introduce a new F8 regression.

Suggested fix
--- "a/src/graphics/presentation/window/hostInput.cpp"
+++ "b/src/graphics/presentation/window/hostInput.cpp"
@@ -253,13 +253,17 @@
 				}
 			}
 
 			const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 ||
 			                      binding.key == SDLK_F2 || binding.key == SDLK_F7 ||
 			                      binding.key == SDLK_F8 || binding.key == SDLK_F11;
-			if (binding.control == INVALID_CONTROL || reserved ||
+			if (reserved && binding.control != INVALID_CONTROL) {
+				LOGF("Ignoring input mapping on reserved key: %s\n", value.c_str());
+				continue;
+			}
+			if (binding.control == INVALID_CONTROL ||
 			    (binding.key == SDLK_UNKNOWN && binding.mouse_button == 0)) {
 				EXIT("Invalid input mapping: %s\n", value.c_str());
 			}
 			Add(binding);
 		}
 		if (!m_custom_pad) {
**@⁠coderabbitai[bot]** on GitHub · 2026-10-17 12:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#discussion_r4302667619) **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '225,280p' src/graphics/presentation/window/hostInput.cpp git log --oneline 415387f00d8ff6cf8040cb2f5bd42a4b5f87235f..fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42 -- src/graphics/presentation/window/hostInput.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 2295 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- relevant history ---' git log --all --oneline --decorate -- src/graphics/presentation/window/hostInput.cpp | head -80 printf '%s\n' '--- candidate commit ---' git show --stat --oneline 90f863c 2>&1 || true git show --format=fuller --no-ext-diff --find-renames 90f863c -- src/graphics/presentation/window/hostInput.cpp 2>&1 || true printf '%s\n' '--- current declarations and callers ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'HostInputInit' -e 'InputMap' src || test "$?" -eq 1 printf '%s\n' '--- current implementation block ---' nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '185,275p' printf '%s\n' '--- history of reserved/exit lines ---' git blame -L 245,265 fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42 -- src/graphics/presentation/window/hostInput.cpp printf '%s\n' '--- all refs containing candidate commit ---' git branch -a --contains 90f863c 2>&1 || true git tag --contains 90f863c 2>&1 || true ``` Repository: KytyPS5/KytyPS5 Length of output: 10376 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- HostInputInit and InputMap accessor ---' nl -ba src/graphics/presentation/window/hostInput.cpp | sed -n '340,365p;735,755p' printf '%s\n' '--- base versus head reserved validation ---' git show 415387f00d8ff6cf8040cb2f5bd42a4b5f87235f:src/graphics/presentation/window/hostInput.cpp | nl -ba | sed -n '245,265p' printf '%s\n' '--- available warning/skip history ---' git log --all --oneline --decorate --grep='mapping\|reserved\|warning\|keymap' -i --regexp-ignore-case | head -100 printf '%s\n' '--- all objects matching the cited prefix, if any ---' git rev-list --all --objects | grep -E '(^|/)90f863c' || true ``` Repository: KytyPS5/KytyPS5 Length of output: 6139 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- EXIT definition ---' rg -n -F --glob '*.{h,hpp,cpp,c,inl}' -e '#define EXIT' -e 'void Exit' -e 'Exit(' src include 2>/dev/null | head -80 printf '%s\n' '--- keymap declaration and uses ---' rg -n -F --glob '*.{h,hpp,cpp,c,inl}' -e 'GetKeymap' -e 'keymap' src/graphics src/core src/launcher 2>/dev/null | head -120 ``` Repository: KytyPS5/KytyPS5 Length of output: 2335 --- 🏁 Script executed: ```bash nl -ba src/common/assert.h | sed -n '20,55p' nl -ba src/common/assert.cpp | sed -n '35,52p' ``` Repository: KytyPS5/KytyPS5 Length of output: 3048 --- </details> **Ignore saved mappings on reserved keys instead of exiting.** A saved `Cross=F2` mapping reaches `InputMap` during `HostInputInit()` and triggers `EXIT`, which terminates the emulator. Warn and skip valid mappings that use reserved keys. F8 was already reserved before this PR, so this change does not introduce a new F8 regression. <details> <summary>Suggested fix</summary> ```diff --- "a/src/graphics/presentation/window/hostInput.cpp" +++ "b/src/graphics/presentation/window/hostInput.cpp" @@ -253,13 +253,17 @@ } } const bool reserved = binding.key == SDLK_ESCAPE || binding.key == SDLK_F1 || binding.key == SDLK_F2 || binding.key == SDLK_F7 || binding.key == SDLK_F8 || binding.key == SDLK_F11; - if (binding.control == INVALID_CONTROL || reserved || + if (reserved && binding.control != INVALID_CONTROL) { + LOGF("Ignoring input mapping on reserved key: %s\n", value.c_str()); + continue; + } + if (binding.control == INVALID_CONTROL || (binding.key == SDLK_UNKNOWN && binding.mouse_button == 0)) { EXIT("Invalid input mapping: %s\n", value.c_str()); } Add(binding); } if (!m_custom_pad) { ``` </details> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a275168dd5ac93d9b1612d7a --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-17 12:32 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 550fff19-753d-406a-b7cc-495263498845
📥 Commits

Reviewing files that changed from the base of the PR and between 4583663d5c007b71bf8b258342ad1524f85b4469 and fc0a85eea1.

📒 Files selected for processing: 34
  • src/common/CMakeLists.txt
  • src/common/debugCounters.h
  • src/common/emulatorConfig.cpp
  • src/common/emulatorConfig.h
  • src/common/hostStats.cpp
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/commandScheduler.cpp
  • src/graphics/host_gpu/renderer/masterSemaphore.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/renderCompute.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/host_gpu/vma.cpp
  • src/graphics/presentation/performanceOverlay.cpp
  • src/graphics/presentation/performanceOverlay.h
  • src/graphics/presentation/systemOverlay.cpp
  • src/graphics/presentation/videoOut.cpp
  • src/graphics/presentation/window/hostInput.cpp
  • src/graphics/presentation/window/swapchain.cpp
  • src/graphics/presentation/window/window.cpp
  • src/kernel/fileSystem.cpp
  • src/kernel/memory.cpp
  • src/kernel/memory.h
  • src/launcher/forms/configuration_edit_dialog.ui
  • src/launcher/include/configuration.h
  • src/launcher/src/configuration.cpp
  • src/launcher/src/configurationEditDialog.cpp
  • src/launcher/src/inputMappingDialog.cpp
  • src/launcher/src/mainDialog.cpp
  • src/libs/audio.cpp
  • src/loader/runtimeLinker.cpp
  • src/main.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-17 12:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1090#pullrequestreview-5557768068) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `550fff19-753d-406a-b7cc-495263498845` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 4583663d5c007b71bf8b258342ad1524f85b4469 and fc0a85eea11d1a9b9888ce68d6bd45d56e67ad42. </details> <details> <summary>📒 Files selected for processing: 34</summary> * `src/common/CMakeLists.txt` * `src/common/debugCounters.h` * `src/common/emulatorConfig.cpp` * `src/common/emulatorConfig.h` * `src/common/hostStats.cpp` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/commandScheduler.cpp` * `src/graphics/host_gpu/renderer/masterSemaphore.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/renderCompute.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/host_gpu/vma.cpp` * `src/graphics/presentation/performanceOverlay.cpp` * `src/graphics/presentation/performanceOverlay.h` * `src/graphics/presentation/systemOverlay.cpp` * `src/graphics/presentation/videoOut.cpp` * `src/graphics/presentation/window/hostInput.cpp` * `src/graphics/presentation/window/swapchain.cpp` * `src/graphics/presentation/window/window.cpp` * `src/kernel/fileSystem.cpp` * `src/kernel/memory.cpp` * `src/kernel/memory.h` * `src/launcher/forms/configuration_edit_dialog.ui` * `src/launcher/include/configuration.h` * `src/launcher/src/configuration.cpp` * `src/launcher/src/configurationEditDialog.cpp` * `src/launcher/src/inputMappingDialog.cpp` * `src/launcher/src/mainDialog.cpp` * `src/libs/audio.cpp` * `src/loader/runtimeLinker.cpp` * `src/main.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=cb0f863f-ebd1-4f2e-ac78-aaaf6becabc1 attempt=153cf984-b25c-40fc-a436-71a57a69ee76 batch=1/1 -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.