libFont: fix writing-line advances and character iteration #2075

Manually merged
github merged 2 commits from gh-pr/2075/head into gh-pr/2075/base 2026-11-26 10:13:25 +00:00
Owner

@⁠gallexme on GitHub · 2026-11-02 18:12 UTC · original
gallexme:fix/scefont-writing-metrics → main · +69 −57 · 1 files · 2 commits · merged 2026-11-03 18:28 UTC

Problem

Text laid out through the sceFontWriting* APIs was not positioned correctly.

fill_writing_metrics() and the writing-step helpers hardcoded an 8 px advance regardless of the font scale, FontWritingRefersRenderStep() never moved to the next character, and FontStringRefersRenderCharacters() counted character ranges exclusive of their last character.

This is visible in the built-in PS1 emulator menu of TEKKEN™ 3 / PPSA31291:

  • save-slot labels, dates and sizes were drawn on top of each other;
  • words lost their final character (EmptySav, PlayTim, FileSiz, Bac);
  • the date/size surfaces were only one character wide.

Fix

Only src/libs/libFont.cpp is changed:

  • derive advances, extents and metrics from the active font instead of the fixed 8 px value;
  • mirror the writing-step semantics: set the pen position, step.x/y, positioning.x/y, and letter_step advances, then accumulate the line metrics;
  • advance to the next character in FontWritingRefersRenderStep() and return the current character from FontWritingRefersRenderStepCharacter();
  • include the last character in FontStringRefersRenderCharacters() ranges.

Testing

Built kyty_emulator and ran the TEKKEN™ 3 / PPSA31291 save menu. Slot labels, dates, play time, file size and button prompts now render as readable text (Slot, EmptySave, PlayTime, FileSize, 5.05M, Back).

There are no existing unit tests for libFont; I did not add one because the behavior is driven by guest font/writing handles. Happy to add a focused test if desired.

before/after

image image

almost forgot a before and after

**@⁠gallexme** on GitHub · 2026-11-02 18:12 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075) `gallexme:fix/scefont-writing-metrics` → `main` · +69 −57 · 1 files · 2 commits · merged 2026-11-03 18:28 UTC ## Problem Text laid out through the `sceFontWriting*` APIs was not positioned correctly. `fill_writing_metrics()` and the writing-step helpers hardcoded an 8 px advance regardless of the font scale, `FontWritingRefersRenderStep()` never moved to the next character, and `FontStringRefersRenderCharacters()` counted character ranges exclusive of their last character. This is visible in the built-in PS1 emulator menu of **TEKKEN™ 3 / PPSA31291**: - save-slot labels, dates and sizes were drawn on top of each other; - words lost their final character (`EmptySav`, `PlayTim`, `FileSiz`, `Bac`); - the date/size surfaces were only one character wide. ## Fix Only `src/libs/libFont.cpp` is changed: - derive advances, extents and metrics from the active font instead of the fixed 8 px value; - mirror the writing-step semantics: set the pen position, `step.x/y`, `positioning.x/y`, and `letter_step` advances, then accumulate the line metrics; - advance to the next character in `FontWritingRefersRenderStep()` and return the current character from `FontWritingRefersRenderStepCharacter()`; - include the last character in `FontStringRefersRenderCharacters()` ranges. ## Testing Built `kyty_emulator` and ran the TEKKEN™ 3 / PPSA31291 save menu. Slot labels, dates, play time, file size and button prompts now render as readable text (`Slot`, `EmptySave`, `PlayTime`, `FileSize`, `5.05M`, `Back`). There are no existing unit tests for `libFont`; I did not add one because the behavior is driven by guest font/writing handles. Happy to add a focused test if desired. ## before/after <img width="1903" height="1101" alt="image" src="https://github.com/user-attachments/assets/caa189bf-b710-4f53-8135-4d3fb5665651" /> <img width="1892" height="1101" alt="image" src="https://github.com/user-attachments/assets/9a1481e5-b4ed-4d24-b759-6db0d27956c4" /> almost forgot a before and after
The writing path hardcoded 8 px glyph advances, never advanced the render step character, and dropped the last character of a referenced range. Games that lay out text through sceFontWriting* rendered glyphs piled on top of each other or clipped the final character.

Derive advances and metrics from the active font, mirror the writing-step semantics (pen position, step and letter-step advances, accumulated metrics), expose step positioning, and make character ranges inclusive of their last character.

Fixes the save menu text in TEKKEN™ 3 / PPSA31291.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:13:24 +00:00
github manually merged commit ac3a83b1fa into gh-pr/2075/base 2026-11-26 10:13:25 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:18 UTC · original · edited 2026-11-03 18:27 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 9ac34c041f067e8aa5a63575c0f4061215b25e44
  • Latest commit, not reviewed: ac3a83b1fa

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

Font writing now uses glyph advances and font metrics when available, with fallback metrics otherwise. The writing state tracks iteration, pen position, and accumulated extents. Render-step retrieval advances through valid characters. Character retrieval returns the current character once. Font operations track active fonts and validate registered font and string handles.

Suggested reviewers: nmzik, mrbigbritches

Change: Bug fix

Merge Risk: Low · previous review 9ac34

Empty text and some returned character metrics may behave incorrectly, while reusing a destroyed handle can cause a failure. These are bounded issues, but the handle deletion guard should be fixed before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… 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 summarizes the main changes: fixing writing-line advances and character iteration in libFont.
Description check Passed The description explains the text-rendering problems, the changes made, and the reported test results. It is directly related to the changeset.
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 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 19 functions across 1 files.

Resolution

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

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 0cd517a54e451d438dab1c264f7c2e59997da06a and 9ac34c041f067e8aa5a63575c0f4061215b25e44.

Files selected for processing: 1
  • src/libs/libFont.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6584789742) · edited 2026-11-03 18:27 UTC <!-- coderabbit-ai-generated:v1 --> <!-- 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/2075?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 --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 9ac34c041f067e8aa5a63575c0f4061215b25e44 > - Latest commit, not reviewed: ac3a83b1fa2d435d74af80081b872c75f543f43e > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> Font writing now uses glyph advances and font metrics when available, with fallback metrics otherwise. The writing state tracks iteration, pen position, and accumulated extents. Render-step retrieval advances through valid characters. Character retrieval returns the current character once. Font operations track active fonts and validate registered font and string handles. **Suggested reviewers:** `nmzik`, `mrbigbritches` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"9ac34c041f067e8aa5a63575c0f4061215b25e44" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · previous review <code>9ac34</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🔵 Low** · up to `9ac34` --> <!-- final_review_risk_coverage:{"sourceCommitId":"9ac34c041f067e8aa5a63575c0f4061215b25e44","coveredCommitId":"9ac34c041f067e8aa5a63575c0f4061215b25e44","kind":"reviewed"} --> Empty text and some returned character metrics may behave incorrectly, while reusing a destroyed handle can cause a failure. These are bounded issues, but the handle deletion guard should be fixed before merging. <!-- final_review_risk_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 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… | 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 summarizes the main changes: fixing writing-line advances and character iteration in libFont. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description explains the text-rendering problems, the changes made, and the reported test results. It is directly related to the changeset. | | 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 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 19 functions across 1 files. **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- announcements_start --> > [!TIP] > <details> > <summary><strong>🎯 Customize your risk assessments</strong></summary> > <dl> > <dd> > > Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using **Merge Risk Instructions** and **Security Risk Instructions** in your review settings. Security architecture risk assessments require the **Advanced plan or above**. > > </dd> > </dl> > </details> > > <details> > <summary><strong>✅ Automatic approvals, with your rules</strong></summary> > <dl> > <dd> > > Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable **Automatic approvals** in review settings, with overrides for teams or file paths. > > </dd> > </dl> > </details> <!-- announcements_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2075)! 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> <!-- tips_end --> <!-- verify_invitation_start --> ### CodeRabbit Verify - [ ] <!-- {"checkboxId":"run-qa-agent"} --> Run CodeRabbit Verify to test the changes in this pull request. <!-- verify_invitation_end --> <!-- recent_review_start --> <h6> <details> <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Recent review info</strong></summary> <dl> <dd> <!-- review_info_content --> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</strong></summary> <dl> <dd> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/4a305a95ebba2318950ec73f3a841ba26729483d/.coderabbit.yaml>) - **Commit**: [4a305a9](<https://github.com/KytyPS5/KytyPS5/commit/4a305a95ebba2318950ec73f3a841ba26729483d>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `502189a5-b205-495b-9ae4-8877ef7bb043` </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 0cd517a54e451d438dab1c264f7c2e59997da06a and 9ac34c041f067e8aa5a63575c0f4061215b25e44. </dd> </dl> </details> <details> <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 1</strong></summary> <dl> <dd> * `src/libs/libFont.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- recent_review_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:18 UTC · original · edited 2026-11-02 18:29 UTC
On src/libs/libFont.cpp line 411 (outdated):

@@ -399,6 +406,10 @@ static std::mutex                g_glyph_mutex;
 static std::unordered_set<void*> g_glyphs;
 static std::mutex                g_writing_mutex;
 static std::unordered_set<void*> g_writing_states;
+// Last font the guest touched. The writing-line API does not carry a font
+// handle, so use it to derive real advances instead of the old fixed 8px.
+static thread_local FontState* g_active_font  = nullptr;

Major · Stability & Availability · Quick win

Fix the dangling g_active_font pointer. It can cause a use-after-free.

g_active_font stores a raw FontState*. FontCloseFont (Lines 1289-1290) deletes the font and does not clear this pointer. The pointer is thread_local, so a close on one thread cannot clear the copy on another thread.

Trigger: the guest touches a font, for example with FontSetScalePixel, FontBindRenderer, or FontCreateString. The guest then calls FontCloseFont. After that, the guest calls FontWritingLineWritesOrder with writing_metrics == nullptr. This reaches fill_writing_metrics(&order_metrics, 1, g_active_font).

That call reads font->scale_h. It also calls fill_metrics_for_code, which calls ensure_stb_font and can write to the freed object through init_font_face.

Before this change, this path used fixed metrics and never dereferenced a font. Guests commonly close a font after use and then keep building writing lines.

Fix: track live fonts in a mutex-protected registry. Validate g_active_font against the registry before each use. Remove the font from the registry in FontCloseFont. Alternatively, store a global atomic pointer and clear it in FontCloseFont when it matches. Then fall back to nullptr metrics.

Sketch of a fix
+static std::mutex                g_font_mutex;
+static std::unordered_set<void*> g_fonts;
+
+static FontState* get_live_active_font() {
+	std::scoped_lock lock(g_font_mutex);
+	return g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr;
+}

Register the font in open_font. Erase it in FontCloseFont before delete. Use get_live_active_font() at Line 2058.

-		fill_writing_metrics(&order_metrics, 1, g_active_font);
+		fill_writing_metrics(&order_metrics, 1, get_live_active_font());

This check must run for the whole use of the font, not only at the lookup. If fonts can close concurrently with use, hold the lock during the fill_writing_metrics call.

Also applies to: 2058-2058

✅ Confirmed as addressed by @⁠gallexme

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446073881) · edited 2026-11-02 18:29 UTC On `src/libs/libFont.cpp` line 411 (outdated): ```diff @@ -399,6 +406,10 @@ static std::mutex g_glyph_mutex; static std::unordered_set<void*> g_glyphs; static std::mutex g_writing_mutex; static std::unordered_set<void*> g_writing_states; +// Last font the guest touched. The writing-line API does not carry a font +// handle, so use it to derive real advances instead of the old fixed 8px. +static thread_local FontState* g_active_font = nullptr; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Stability & Availability** · **Quick win** **Fix the dangling `g_active_font` pointer. It can cause a use-after-free.** `g_active_font` stores a raw `FontState*`. `FontCloseFont` (Lines 1289-1290) deletes the font and does not clear this pointer. The pointer is `thread_local`, so a close on one thread cannot clear the copy on another thread. Trigger: the guest touches a font, for example with `FontSetScalePixel`, `FontBindRenderer`, or `FontCreateString`. The guest then calls `FontCloseFont`. After that, the guest calls `FontWritingLineWritesOrder` with `writing_metrics == nullptr`. This reaches `fill_writing_metrics(&order_metrics, 1, g_active_font)`. That call reads `font->scale_h`. It also calls `fill_metrics_for_code`, which calls `ensure_stb_font` and can write to the freed object through `init_font_face`. Before this change, this path used fixed metrics and never dereferenced a font. Guests commonly close a font after use and then keep building writing lines. Fix: track live fonts in a mutex-protected registry. Validate `g_active_font` against the registry before each use. Remove the font from the registry in `FontCloseFont`. Alternatively, store a global atomic pointer and clear it in `FontCloseFont` when it matches. Then fall back to `nullptr` metrics. <details> <summary>Sketch of a fix</summary> <dl> <dd> ```diff +static std::mutex g_font_mutex; +static std::unordered_set<void*> g_fonts; + +static FontState* get_live_active_font() { + std::scoped_lock lock(g_font_mutex); + return g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr; +} ``` Register the font in `open_font`. Erase it in `FontCloseFont` before `delete`. Use `get_live_active_font()` at Line 2058. ```diff - fill_writing_metrics(&order_metrics, 1, g_active_font); + fill_writing_metrics(&order_metrics, 1, get_live_active_font()); ``` </dd> </dl> </details> This check must run for the whole use of the font, not only at the lookup. If fonts can close concurrently with use, hold the lock during the `fill_writing_metrics` call. Also applies to: 2058-2058 <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d162cfd7a7ae6b6c993bc21f --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠gallexme <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:18 UTC · original · reviewed

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#pullrequestreview-5741247210) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=0d4d7bbf-ba51-43a6-98c2-cba8bcef2d64 attempt=b11137b4-0d3b-4266-8f4f-64b6230acb59 batch=1/1 -->
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 18:21 UTC · original
On src/libs/libFont.cpp line 411 (outdated):

@@ -399,6 +406,10 @@ static std::mutex                g_glyph_mutex;
 static std::unordered_set<void*> g_glyphs;
 static std::mutex                g_writing_mutex;
 static std::unordered_set<void*> g_writing_states;
+// Last font the guest touched. The writing-line API does not carry a font
+// handle, so use it to derive real advances instead of the old fixed 8px.
+static thread_local FontState* g_active_font  = nullptr;

Addressed: opened fonts are now tracked in a mutex-protected registry. FontCloseFont erases the handle before deleting it, and the g_active_font fallback validates the pointer against the registry while holding the same lock, falling back to the fixed metrics if the font was closed.

**@⁠gallexme** on GitHub · 2026-11-02 18:21 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446110921) On `src/libs/libFont.cpp` line 411 (outdated): ```diff @@ -399,6 +406,10 @@ static std::mutex g_glyph_mutex; static std::unordered_set<void*> g_glyphs; static std::mutex g_writing_mutex; static std::unordered_set<void*> g_writing_states; +// Last font the guest touched. The writing-line API does not carry a font +// handle, so use it to derive real advances instead of the old fixed 8px. +static thread_local FontState* g_active_font = nullptr; ``` Addressed: opened fonts are now tracked in a mutex-protected registry. `FontCloseFont` erases the handle before deleting it, and the `g_active_font` fallback validates the pointer against the registry while holding the same lock, falling back to the fixed metrics if the font was closed.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:26 UTC · original · edited 2026-11-02 18:50 UTC
On src/libs/libFont.cpp line 2077 (outdated):

@@ -1944,7 +2068,13 @@ int KYTY_SYSV_ABI FontWritingLineWritesOrder(FontWritingLine           writing_l
 	if (writing_metrics != nullptr) {
 		order_metrics = *writing_metrics;
 	} else {
-		fill_writing_metrics(&order_metrics, 1);
+		// g_active_font is only a hint; the guest may have closed the font
+		// since it was last touched. Keep the lock while filling metrics so
+		// another thread cannot free it underneath us.
+		std::scoped_lock lock(g_font_mutex);
+		const auto*      font =
+		    g_active_font != nullptr && g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr;
+		fill_writing_metrics(&order_metrics, 1, font);

Minor · Functional Correctness · Quick win

Use a nonzero fallback when no font is live.

A zero-advance glyph sets g_last_advance to zero. If the guest then closes the active font, this call uses that zero value for every order without supplied metrics. Those orders overlap at the same position. Use a fixed fallback advance when font is null.

✅ Confirmed as addressed by @⁠gallexme

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446173142) · edited 2026-11-02 18:50 UTC On `src/libs/libFont.cpp` line 2077 (outdated): ```diff @@ -1944,7 +2068,13 @@ int KYTY_SYSV_ABI FontWritingLineWritesOrder(FontWritingLine writing_l if (writing_metrics != nullptr) { order_metrics = *writing_metrics; } else { - fill_writing_metrics(&order_metrics, 1); + // g_active_font is only a hint; the guest may have closed the font + // since it was last touched. Keep the lock while filling metrics so + // another thread cannot free it underneath us. + std::scoped_lock lock(g_font_mutex); + const auto* font = + g_active_font != nullptr && g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr; + fill_writing_metrics(&order_metrics, 1, font); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **Use a nonzero fallback when no font is live.** A zero-advance glyph sets `g_last_advance` to zero. If the guest then closes the active font, this call uses that zero value for every order without supplied metrics. Those orders overlap at the same position. Use a fixed fallback advance when `font` is null. <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:49a03efb03440644cf4e1bc9 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠gallexme <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:27 UTC · original · reviewed

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#pullrequestreview-5741371989) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=72905e9a-a2f9-46ab-8e23-f4b4a07cc531 attempt=dc72b38b-dfe7-43b6-9275-64449b788876 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:29 UTC · original
On src/libs/libFont.cpp line 411 (outdated):

@@ -399,6 +406,10 @@ static std::mutex                g_glyph_mutex;
 static std::unordered_set<void*> g_glyphs;
 static std::mutex                g_writing_mutex;
 static std::unordered_set<void*> g_writing_states;
+// Last font the guest touched. The writing-line API does not carry a font
+// handle, so use it to derive real advances instead of the old fixed 8px.
+static thread_local FontState* g_active_font  = nullptr;

@⁠gallexme The supplied code addresses this finding. FontCloseFont removes the font and deletes it under g_font_mutex. FontWritingLineWritesOrder holds the same mutex through registry validation and fill_writing_metrics, which prevents concurrent deletion during that call. If the font is no longer registered, the call uses nullptr fallback metrics.


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-11-02 18:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446198905) On `src/libs/libFont.cpp` line 411 (outdated): ```diff @@ -399,6 +406,10 @@ static std::mutex g_glyph_mutex; static std::unordered_set<void*> g_glyphs; static std::mutex g_writing_mutex; static std::unordered_set<void*> g_writing_states; +// Last font the guest touched. The writing-line API does not carry a font +// handle, so use it to derive real advances instead of the old fixed 8px. +static thread_local FontState* g_active_font = nullptr; ``` <!-- coderabbit-ai-generated:v1 --> @⁠gallexme The supplied code addresses this finding. `FontCloseFont` removes the font and deletes it under `g_font_mutex`. `FontWritingLineWritesOrder` holds the same mutex through registry validation and `fill_writing_metrics`, which prevents concurrent deletion during that call. If the font is no longer registered, the call uses `nullptr` fallback metrics. --- <!-- 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=A%20dangling%20font%20pointer%20can%20trigger%20use-after-free%20when%20building%20writing%20lines.%20%40coderabbitai%20suggested%20a%20mutex-protected%20live-font%20registry%20to%20safely%20fall%20back%20to%20fixed%20metrics%E2%80%94try%20it%20for%20sharper%20reviews%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2075%23discussion_r4446073881)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 18:43 UTC · original
On src/libs/libFont.cpp line 2077 (outdated):

@@ -1944,7 +2068,13 @@ int KYTY_SYSV_ABI FontWritingLineWritesOrder(FontWritingLine           writing_l
 	if (writing_metrics != nullptr) {
 		order_metrics = *writing_metrics;
 	} else {
-		fill_writing_metrics(&order_metrics, 1);
+		// g_active_font is only a hint; the guest may have closed the font
+		// since it was last touched. Keep the lock while filling metrics so
+		// another thread cannot free it underneath us.
+		std::scoped_lock lock(g_font_mutex);
+		const auto*      font =
+		    g_active_font != nullptr && g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr;
+		fill_writing_metrics(&order_metrics, 1, font);

Good catch. The null-font fallback now uses g_last_advance > 0 ? g_last_advance : 8.0f, so a zero-width glyph (or a font closed right after one) cannot collapse subsequent orders onto the same position. Rebuilt and pushed.

**@⁠gallexme** on GitHub · 2026-11-02 18:43 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446333917) On `src/libs/libFont.cpp` line 2077 (outdated): ```diff @@ -1944,7 +2068,13 @@ int KYTY_SYSV_ABI FontWritingLineWritesOrder(FontWritingLine writing_l if (writing_metrics != nullptr) { order_metrics = *writing_metrics; } else { - fill_writing_metrics(&order_metrics, 1); + // g_active_font is only a hint; the guest may have closed the font + // since it was last touched. Keep the lock while filling metrics so + // another thread cannot free it underneath us. + std::scoped_lock lock(g_font_mutex); + const auto* font = + g_active_font != nullptr && g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr; + fill_writing_metrics(&order_metrics, 1, font); ``` Good catch. The null-font fallback now uses `g_last_advance > 0 ? g_last_advance : 8.0f`, so a zero-width glyph (or a font closed right after one) cannot collapse subsequent orders onto the same position. Rebuilt and pushed.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:49 UTC · original · edited 2026-11-02 19:20 UTC
On src/libs/libFont.cpp line 619 (outdated):

@@ -587,37 +600,34 @@ static void fill_text_codes(FontTextCodes* text_codes, FontCharacterState* chara
 static void fill_metrics(FontGlyphMetrics* metrics, const FontState* font = nullptr);
 static void fill_metrics_for_code(FontGlyphMetrics* metrics, const FontState* font, uint32_t code);
 
-static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count) {
+static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count,
+                                 const FontState* font = nullptr) {
 	if (metrics == nullptr) {
 		return;
 	}
 
-	const float advance    = static_cast<float>(character_count) * 8.0f;
+	// A zero-width glyph must not leave the fallback at zero: orders without
+	// metrics would then overlap at the same position.
+	float advance_per_character = g_last_advance > 0.0f ? g_last_advance : 8.0f;
+	float ascent                = 12.0f;
+	if (font != nullptr) {
+		FontGlyphMetrics glyph_metrics {};
+		fill_metrics_for_code(&glyph_metrics, font, static_cast<uint32_t>('M'));
+		if (glyph_metrics.horizontal.advance > 0.0f) {
+			advance_per_character = glyph_metrics.horizontal.advance;
+		}
+		ascent = font->scale_h > 1.0f ? font->scale_h * 0.75f : 12.0f;

Minor · Functional Correctness · Quick win

Supported by static analysis

Script executed:

set -eu
printf '%s\n' '--- diff ---'
git diff --unified=80 4a305a95ebba2318950ec73f3a841ba26729483d 33a41820a27def183c756cd206352d78d94fbd26 -- src/libs/libFont.cpp
printf '%s\n' '--- target context ---'
nl -ba src/libs/libFont.cpp | sed -n '520,700p'
printf '%s\n' '--- metric symbols and consumers ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'FontWritingRefersRenderLine' -e 'FontWritingRefersRenderStep' -e 'ascent' -e 'descent' -e 'line_height' -e 'FontStringRefersRender' src/libs src || test "$?" -eq 1
printf '%s\n' '--- font metric declarations/usages ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'Get.*Metric' -e 'Get.*Bounds' -e 'bbox' -e 'ascender' -e 'descender' -e 'scale_h' src | head -240

Repository: KytyPS5/KytyPS5

Length of output: 42468


Script executed:

set -eu
printf '%s\n' '--- glyph and layout metric implementations ---'
nl -ba src/libs/libFont.cpp | sed -n '840,985p'
nl -ba src/libs/libFont.cpp | sed -n '1460,1520p'
printf '%s\n' '--- writing-line and writing metric callers ---'
nl -ba src/libs/libFont.cpp | sed -n '1760,2015p'
printf '%s\n' '--- declarations and metric field references ---'
rg -n -F --glob '*.{h,hpp,cpp,c}' -e 'FontWritingMetrics' -e 'FontWritingLineStep' -e 'FontWritingLineWritesOrder' -e 'FontWritingRefersRenderMetrics' -e 'WritingLine' . || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 22061


Script executed:

set -eu
nl -ba src/libs/libFont.cpp | sed -n '2011,2195p'
printf '%s\n' '--- font API and bundled stb bounds declarations ---'
rg -n -F --glob '*.{h,hpp,cpp,c}' -e 'GetFontBoundingBox' -e 'GetCodepointBox' -e 'FontWritingLineWritesOrder' -e 'FontWritingLineGetRenderMetrics' -e 'FontWritingGetRenderMetrics' . || test "$?" -eq 1

Repository: KytyPS5/KytyPS5

Length of output: 10276


Script executed:

set -eu
nl -ba 3rdparty/stb/stb_truetype.h | sed -n '190,212p'
nl -ba 3rdparty/stb/stb_truetype.h | sed -n '775,792p'
nl -ba 3rdparty/stb/stb_truetype.h | sed -n '2640,2670p'

Repository: KytyPS5/KytyPS5

Length of output: 4004


Use conservative font bounds for the null-metrics fallback.

When writing_metrics is null, FontWritingLineWritesOrder uses -0.75 * scale_h and 0.25 * scale_h for the vertical extent. A valid TTF glyph can exceed these limits. A surface sized from these metrics can clip glyphs. Use scaled stbtt_GetFontBoundingBox bounds when per-order glyph bounds are unavailable, while retaining the bitmap fallback for fonts without TTF data.

✅ Confirmed as addressed by @⁠gallexme

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446392967) · edited 2026-11-02 19:20 UTC On `src/libs/libFont.cpp` line 619 (outdated): ```diff @@ -587,37 +600,34 @@ static void fill_text_codes(FontTextCodes* text_codes, FontCharacterState* chara static void fill_metrics(FontGlyphMetrics* metrics, const FontState* font = nullptr); static void fill_metrics_for_code(FontGlyphMetrics* metrics, const FontState* font, uint32_t code); -static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count) { +static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count, + const FontState* font = nullptr) { if (metrics == nullptr) { return; } - const float advance = static_cast<float>(character_count) * 8.0f; + // A zero-width glyph must not leave the fallback at zero: orders without + // metrics would then overlap at the same position. + float advance_per_character = g_last_advance > 0.0f ? g_last_advance : 8.0f; + float ascent = 12.0f; + if (font != nullptr) { + FontGlyphMetrics glyph_metrics {}; + fill_metrics_for_code(&glyph_metrics, font, static_cast<uint32_t>('M')); + if (glyph_metrics.horizontal.advance > 0.0f) { + advance_per_character = glyph_metrics.horizontal.advance; + } + ascent = font->scale_h > 1.0f ? font->scale_h * 0.75f : 12.0f; ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> Script executed: ```bash set -eu printf '%s\n' '--- diff ---' git diff --unified=80 4a305a95ebba2318950ec73f3a841ba26729483d 33a41820a27def183c756cd206352d78d94fbd26 -- src/libs/libFont.cpp printf '%s\n' '--- target context ---' nl -ba src/libs/libFont.cpp | sed -n '520,700p' printf '%s\n' '--- metric symbols and consumers ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'FontWritingRefersRenderLine' -e 'FontWritingRefersRenderStep' -e 'ascent' -e 'descent' -e 'line_height' -e 'FontStringRefersRender' src/libs src || test "$?" -eq 1 printf '%s\n' '--- font metric declarations/usages ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'Get.*Metric' -e 'Get.*Bounds' -e 'bbox' -e 'ascender' -e 'descender' -e 'scale_h' src | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 42468 --- Script executed: ```bash set -eu printf '%s\n' '--- glyph and layout metric implementations ---' nl -ba src/libs/libFont.cpp | sed -n '840,985p' nl -ba src/libs/libFont.cpp | sed -n '1460,1520p' printf '%s\n' '--- writing-line and writing metric callers ---' nl -ba src/libs/libFont.cpp | sed -n '1760,2015p' printf '%s\n' '--- declarations and metric field references ---' rg -n -F --glob '*.{h,hpp,cpp,c}' -e 'FontWritingMetrics' -e 'FontWritingLineStep' -e 'FontWritingLineWritesOrder' -e 'FontWritingRefersRenderMetrics' -e 'WritingLine' . || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 22061 --- Script executed: ```bash set -eu nl -ba src/libs/libFont.cpp | sed -n '2011,2195p' printf '%s\n' '--- font API and bundled stb bounds declarations ---' rg -n -F --glob '*.{h,hpp,cpp,c}' -e 'GetFontBoundingBox' -e 'GetCodepointBox' -e 'FontWritingLineWritesOrder' -e 'FontWritingLineGetRenderMetrics' -e 'FontWritingGetRenderMetrics' . || test "$?" -eq 1 ``` Repository: KytyPS5/KytyPS5 Length of output: 10276 --- Script executed: ```bash set -eu nl -ba 3rdparty/stb/stb_truetype.h | sed -n '190,212p' nl -ba 3rdparty/stb/stb_truetype.h | sed -n '775,792p' nl -ba 3rdparty/stb/stb_truetype.h | sed -n '2640,2670p' ``` Repository: KytyPS5/KytyPS5 Length of output: 4004 --- </dd> </dl> </details> **Use conservative font bounds for the null-metrics fallback.** When `writing_metrics` is null, `FontWritingLineWritesOrder` uses `-0.75 * scale_h` and `0.25 * scale_h` for the vertical extent. A valid TTF glyph can exceed these limits. A surface sized from these metrics can clip glyphs. Use scaled `stbtt_GetFontBoundingBox` bounds when per-order glyph bounds are unavailable, while retaining the bitmap fallback for fonts without TTF data. <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:37cca1ad99afeb96021fb327 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠gallexme <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:49 UTC · original · reviewed

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 18:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#pullrequestreview-5741644324) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=c385a358-2a0b-41c6-aaa1-dea8797439fd attempt=ef95951d-0c96-442a-9350-bd9c2bc2df58 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 18:50 UTC · original
On src/libs/libFont.cpp line 2077 (outdated):

@@ -1944,7 +2068,13 @@ int KYTY_SYSV_ABI FontWritingLineWritesOrder(FontWritingLine           writing_l
 	if (writing_metrics != nullptr) {
 		order_metrics = *writing_metrics;
 	} else {
-		fill_writing_metrics(&order_metrics, 1);
+		// g_active_font is only a hint; the guest may have closed the font
+		// since it was last touched. Keep the lock while filling metrics so
+		// another thread cannot free it underneath us.
+		std::scoped_lock lock(g_font_mutex);
+		const auto*      font =
+		    g_active_font != nullptr && g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr;
+		fill_writing_metrics(&order_metrics, 1, font);

@⁠gallexme Thanks. The supplied fill_writing_metrics() code confirms the positive-value guard. When no font is live and g_last_advance is zero, the fallback uses 8.0f. This addresses the reported overlap case.


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-11-02 18:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446404614) On `src/libs/libFont.cpp` line 2077 (outdated): ```diff @@ -1944,7 +2068,13 @@ int KYTY_SYSV_ABI FontWritingLineWritesOrder(FontWritingLine writing_l if (writing_metrics != nullptr) { order_metrics = *writing_metrics; } else { - fill_writing_metrics(&order_metrics, 1); + // g_active_font is only a hint; the guest may have closed the font + // since it was last touched. Keep the lock while filling metrics so + // another thread cannot free it underneath us. + std::scoped_lock lock(g_font_mutex); + const auto* font = + g_active_font != nullptr && g_fonts.count(g_active_font) != 0 ? g_active_font : nullptr; + fill_writing_metrics(&order_metrics, 1, font); ``` <!-- coderabbit-ai-generated:v1 --> @⁠gallexme Thanks. The supplied `fill_writing_metrics()` code confirms the positive-value guard. When no font is live and `g_last_advance` is zero, the fallback uses `8.0f`. This addresses the reported overlap case. --- <!-- 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=A%20zero-width%20glyph%20followed%20by%20closing%20its%20font%20could%20make%20later%20orders%20overlap.%20%40coderabbitai%20suggested%20a%20nonzero%20fallback%E2%80%94now%20they%20keep%20their%20spacing.%20Try%20CodeRabbit%20for%20sharp%20catches%20like%20this!%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2075%23discussion_r4446173142)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 19:04 UTC · original
On src/libs/libFont.cpp line 619 (outdated):

@@ -587,37 +600,34 @@ static void fill_text_codes(FontTextCodes* text_codes, FontCharacterState* chara
 static void fill_metrics(FontGlyphMetrics* metrics, const FontState* font = nullptr);
 static void fill_metrics_for_code(FontGlyphMetrics* metrics, const FontState* font, uint32_t code);
 
-static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count) {
+static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count,
+                                 const FontState* font = nullptr) {
 	if (metrics == nullptr) {
 		return;
 	}
 
-	const float advance    = static_cast<float>(character_count) * 8.0f;
+	// A zero-width glyph must not leave the fallback at zero: orders without
+	// metrics would then overlap at the same position.
+	float advance_per_character = g_last_advance > 0.0f ? g_last_advance : 8.0f;
+	float ascent                = 12.0f;
+	if (font != nullptr) {
+		FontGlyphMetrics glyph_metrics {};
+		fill_metrics_for_code(&glyph_metrics, font, static_cast<uint32_t>('M'));
+		if (glyph_metrics.horizontal.advance > 0.0f) {
+			advance_per_character = glyph_metrics.horizontal.advance;
+		}
+		ascent = font->scale_h > 1.0f ? font->scale_h * 0.75f : 12.0f;

Updated. When a TTF is available the null-metrics fallback now derives ascent/descent from scaled stbtt_GetFontBoundingBox instead of the fixed 0.75/0.25 scale factors; bitmap-only fonts keep the previous fallback. Rebuilt and pushed.

**@⁠gallexme** on GitHub · 2026-11-02 19:04 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446545266) On `src/libs/libFont.cpp` line 619 (outdated): ```diff @@ -587,37 +600,34 @@ static void fill_text_codes(FontTextCodes* text_codes, FontCharacterState* chara static void fill_metrics(FontGlyphMetrics* metrics, const FontState* font = nullptr); static void fill_metrics_for_code(FontGlyphMetrics* metrics, const FontState* font, uint32_t code); -static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count) { +static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count, + const FontState* font = nullptr) { if (metrics == nullptr) { return; } - const float advance = static_cast<float>(character_count) * 8.0f; + // A zero-width glyph must not leave the fallback at zero: orders without + // metrics would then overlap at the same position. + float advance_per_character = g_last_advance > 0.0f ? g_last_advance : 8.0f; + float ascent = 12.0f; + if (font != nullptr) { + FontGlyphMetrics glyph_metrics {}; + fill_metrics_for_code(&glyph_metrics, font, static_cast<uint32_t>('M')); + if (glyph_metrics.horizontal.advance > 0.0f) { + advance_per_character = glyph_metrics.horizontal.advance; + } + ascent = font->scale_h > 1.0f ? font->scale_h * 0.75f : 12.0f; ``` Updated. When a TTF is available the null-metrics fallback now derives ascent/descent from scaled `stbtt_GetFontBoundingBox` instead of the fixed 0.75/0.25 scale factors; bitmap-only fonts keep the previous fallback. Rebuilt and pushed.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:18 UTC · original · reviewed

Additional comments: 1
src/libs/libFont.cpp-616-618: 1

616-618: Major · Functional Correctness · Heavy lift

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Preserve the order’s measured advance.

When a guest writes a single-character order with null metrics after measuring that character, this replaces its advance with the advance of M. In a proportional font, orders such as i and W then receive the same spacing, so their positions are incorrect. Use metrics associated with the order when available instead of overriding them with M.


Review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 33a41820a27def183c756cd206352d78d94fbd26 and 0cd517a54e451d438dab1c264f7c2e59997da06a.

Files selected for processing: 1
  • src/libs/libFont.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 19:18 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#pullrequestreview-5742022067) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/message-square-off-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/message-square-off.svg" width="16" height="16" align="absmiddle" alt=""></picture> Additional comments: 1</summary><blockquote> <dl> <dd> <details> <summary>src/libs/libFont.cpp-616-618: 1</summary><blockquote> <dl> <dd> `616-618`: **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **Unverified finding** Verification ran but could not confirm this finding. It is shown for review, not as a verified issue. **Preserve the order’s measured advance.** When a guest writes a single-character order with null metrics after measuring that character, this replaces its advance with the advance of `M`. In a proportional font, orders such as `i` and `W` then receive the same spacing, so their positions are incorrect. Use metrics associated with the order when available instead of overriding them with `M`. </dd> </dl> </blockquote></details> </dd> </dl> </blockquote></details> --- <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="16" height="16" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/4a305a95ebba2318950ec73f3a841ba26729483d/.coderabbit.yaml>) - **Commit**: [4a305a9](<https://github.com/KytyPS5/KytyPS5/commit/4a305a95ebba2318950ec73f3a841ba26729483d>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `e87f0604-bcb1-4666-b665-ecc7d7e32c58` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 33a41820a27def183c756cd206352d78d94fbd26 and 0cd517a54e451d438dab1c264f7c2e59997da06a. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 1</summary> <dl> <dd> * `src/libs/libFont.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. </dd> </dl> </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=2e7423b8-5136-4165-8eaa-6a5b78b81665 attempt=4b2dd476-5c94-468b-8adb-96573d9063a2 batch=1/1 -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:20 UTC · original
On src/libs/libFont.cpp line 619 (outdated):

@@ -587,37 +600,34 @@ static void fill_text_codes(FontTextCodes* text_codes, FontCharacterState* chara
 static void fill_metrics(FontGlyphMetrics* metrics, const FontState* font = nullptr);
 static void fill_metrics_for_code(FontGlyphMetrics* metrics, const FontState* font, uint32_t code);
 
-static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count) {
+static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count,
+                                 const FontState* font = nullptr) {
 	if (metrics == nullptr) {
 		return;
 	}
 
-	const float advance    = static_cast<float>(character_count) * 8.0f;
+	// A zero-width glyph must not leave the fallback at zero: orders without
+	// metrics would then overlap at the same position.
+	float advance_per_character = g_last_advance > 0.0f ? g_last_advance : 8.0f;
+	float ascent                = 12.0f;
+	if (font != nullptr) {
+		FontGlyphMetrics glyph_metrics {};
+		fill_metrics_for_code(&glyph_metrics, font, static_cast<uint32_t>('M'));
+		if (glyph_metrics.horizontal.advance > 0.0f) {
+			advance_per_character = glyph_metrics.horizontal.advance;
+		}
+		ascent = font->scale_h > 1.0f ? font->scale_h * 0.75f : 12.0f;

@⁠gallexme Confirmed in the supplied fill_writing_metrics() code: TTF ascent and descent now use scaled stbtt_GetFontBoundingBox bounds. Bitmap-only fonts retain the previous fallback. This addresses the clipping concern.


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-11-02 19:20 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4446702788) On `src/libs/libFont.cpp` line 619 (outdated): ```diff @@ -587,37 +600,34 @@ static void fill_text_codes(FontTextCodes* text_codes, FontCharacterState* chara static void fill_metrics(FontGlyphMetrics* metrics, const FontState* font = nullptr); static void fill_metrics_for_code(FontGlyphMetrics* metrics, const FontState* font, uint32_t code); -static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count) { +static void fill_writing_metrics(FontWritingMetrics* metrics, uint32_t character_count, + const FontState* font = nullptr) { if (metrics == nullptr) { return; } - const float advance = static_cast<float>(character_count) * 8.0f; + // A zero-width glyph must not leave the fallback at zero: orders without + // metrics would then overlap at the same position. + float advance_per_character = g_last_advance > 0.0f ? g_last_advance : 8.0f; + float ascent = 12.0f; + if (font != nullptr) { + FontGlyphMetrics glyph_metrics {}; + fill_metrics_for_code(&glyph_metrics, font, static_cast<uint32_t>('M')); + if (glyph_metrics.horizontal.advance > 0.0f) { + advance_per_character = glyph_metrics.horizontal.advance; + } + ascent = font->scale_h > 1.0f ? font->scale_h * 0.75f : 12.0f; ``` <!-- coderabbit-ai-generated:v1 --> @⁠gallexme Confirmed in the supplied `fill_writing_metrics()` code: TTF ascent and descent now use scaled `stbtt_GetFontBoundingBox` bounds. Bitmap-only fonts retain the previous fallback. This addresses the clipping concern. --- <!-- 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=Null-metrics%20fallbacks%20can%20clip%20tall%20glyphs.%20%40coderabbitai%20recommended%20using%20scaled%20TTF%20font%20bounds%20while%20preserving%20the%20bitmap%20fallback%E2%80%94a%20small%20fix%20for%20more%20reliable%20text%20rendering.%20Try%20%40coderabbitai%20%F0%9F%90%87&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2075%23discussion_r4446392967)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 19:24 UTC · original

Addressed the review note about substituting 'M' for single-character orders: when a null-metrics order covers one character, fill_writing_metrics() now keeps the advance recorded by the preceding writing walk (g_last_advance) instead of using 'M'. Multi-character orders still use the representative advance. Rebuilt and pushed.

**@⁠gallexme** on GitHub · 2026-11-02 19:24 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6586345393) Addressed the review note about substituting 'M' for single-character orders: when a null-metrics order covers one character, `fill_writing_metrics()` now keeps the advance recorded by the preceding writing walk (`g_last_advance`) instead of using 'M'. Multi-character orders still use the representative advance. Rebuilt and pushed.
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 19:51 UTC · original

Self-review pass completed. In addition to the earlier fixes, the branch now:

  • guards writing state against destroyed strings and closed fonts (string registry + font registry validation before dereferencing);
  • returns null/zero instead of walking past an unreachable lastCharacter range;
  • rejects invalid/out-of-range writing start characters and failed initial steps;
  • resets writing-line metrics to zero on clear.

The null-writing_metrics path still uses the last measured advance as a compatibility fallback; this is only reached when the guest omits metrics and avoids collapsing/overlapping orders in the title being tested.

**@⁠gallexme** on GitHub · 2026-11-02 19:51 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6586922918) Self-review pass completed. In addition to the earlier fixes, the branch now: - guards writing state against destroyed strings and closed fonts (string registry + font registry validation before dereferencing); - returns null/zero instead of walking past an unreachable `lastCharacter` range; - rejects invalid/out-of-range writing start characters and failed initial steps; - resets writing-line metrics to zero on clear. The null-`writing_metrics` path still uses the last measured advance as a compatibility fallback; this is only reached when the guest omits metrics and avoids collapsing/overlapping orders in the title being tested.
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 19:51 UTC · original

@⁠coderabbitai review

**@⁠gallexme** on GitHub · 2026-11-02 19:51 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6586923416) @⁠coderabbitai review
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:51 UTC · original · edited 2026-11-02 19:58 UTC

Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 19:51 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6586925532) · edited 2026-11-02 19:58 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated reply by CodeRabbit --> <!-- CodeRabbit review command invocation: v2:a2be588388fa2fd8a41b5d093b9a12108318d2446a00ac1c305135f79700499d --> <details> <summary>Action performed</summary> <dl> <dd> Review finished. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused. </dd> </dl> </details>
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 19:56 UTC · original

Verified on the latest commit (9ac34c04) against the TEKKEN™ 3 / PPSA31291 save menu. Slot names, dates, play time, file size and the button prompts all render correctly: Slot 1, Slot 4, Empty Save, 02/11/2026 17:46, Date, Play Time, File Size, 4.92 MB, Accept, Back, Delete.

**@⁠gallexme** on GitHub · 2026-11-02 19:56 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6587021576) Verified on the latest commit (`9ac34c04`) against the TEKKEN™ 3 / PPSA31291 save menu. Slot names, dates, play time, file size and the button prompts all render correctly: `Slot 1`, `Slot 4`, `Empty Save`, `02/11/2026 17:46`, `Date`, `Play Time`, `File Size`, `4.92 MB`, `Accept`, `Back`, `Delete`.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:58 UTC · original · edited 2026-11-02 20:14 UTC
On src/libs/libFont.cpp line 1725 (outdated):

@@ -1588,7 +1717,12 @@ int KYTY_SYSV_ABI FontDestroyString(FontString* font_string) {
 	LOGF("\t string_ptr = 0x%016" PRIx64 "\n", reinterpret_cast<uint64_t>(font_string));
 
 	if (font_string != nullptr) {
-		delete static_cast<FontStringState*>(*font_string);
+		auto* state = static_cast<FontStringState*>(*font_string);
+		if (state != nullptr) {
+			std::scoped_lock lock(g_string_mutex);
+			g_strings.erase(state);
+			delete state;
+		}

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

sed -n '1315,1355p' src/libs/libFont.cpp
sed -n '1710,1745p' src/libs/libFont.cpp
rg -n 'unregister_glyph|FontDestroyString|FontCloseFont' src/libs/libFont.cpp

Repository: KytyPS5/KytyPS5

Length of output: 2467


Script executed:

sed -n '360,445p' src/libs/libFont.cpp
rg -n -F -e 'g_strings' -e 'g_fonts' -e 'g_string_mutex' -e 'g_font_mutex' -e 'using FontString' -e 'typedef.*FontString' -e 'FontDestroyString' -e 'FontCloseFont' -- src/libs/libFont.cpp src/libs src
sed -n '1,160p' src/libs/libFont.cpp
sed -n '1270,1345p' src/libs/libFont.cpp
sed -n '1640,1735p' src/libs/libFont.cpp
sed -n '2360,2395p' src/libs/libFont.cpp

Repository: KytyPS5/KytyPS5

Length of output: 19105


Guard both deletes with successful registry removal.

FontDestroyString clears only the handle slot passed to it, so a copied handle remains nonnull. FontCloseFont takes its handle by value and clears no caller slot. A second call with either stale handle can delete an unregistered object. Delete only when the corresponding erase succeeds.

Suggested fix
-		g_fonts.erase(font);
+		const bool registered = g_fonts.erase(font) != 0;
 		if (g_active_font == font) {
 			g_active_font = nullptr;
 		}
-		delete font;
+		if (registered) {
+			delete font;
+		}
...
-			g_strings.erase(state);
-			delete state;
+			if (g_strings.erase(state) != 0) {
+				delete state;
+			}
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

		auto* state = static_cast<FontStringState*>(*font_string);
		if (state != nullptr) {
			std::scoped_lock lock(g_string_mutex);
			if (g_strings.erase(state) != 0) {
				delete state;
			}
		}

✅ Confirmed as addressed by @⁠gallexme

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 19:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4447081833) · edited 2026-11-02 20:14 UTC On `src/libs/libFont.cpp` line 1725 (outdated): ```diff @@ -1588,7 +1717,12 @@ int KYTY_SYSV_ABI FontDestroyString(FontString* font_string) { LOGF("\t string_ptr = 0x%016" PRIx64 "\n", reinterpret_cast<uint64_t>(font_string)); if (font_string != nullptr) { - delete static_cast<FontStringState*>(*font_string); + auto* state = static_cast<FontStringState*>(*font_string); + if (state != nullptr) { + std::scoped_lock lock(g_string_mutex); + g_strings.erase(state); + delete state; + } ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Stability & Availability** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> Script executed: ```bash sed -n '1315,1355p' src/libs/libFont.cpp sed -n '1710,1745p' src/libs/libFont.cpp rg -n 'unregister_glyph|FontDestroyString|FontCloseFont' src/libs/libFont.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 2467 --- Script executed: ```bash sed -n '360,445p' src/libs/libFont.cpp rg -n -F -e 'g_strings' -e 'g_fonts' -e 'g_string_mutex' -e 'g_font_mutex' -e 'using FontString' -e 'typedef.*FontString' -e 'FontDestroyString' -e 'FontCloseFont' -- src/libs/libFont.cpp src/libs src sed -n '1,160p' src/libs/libFont.cpp sed -n '1270,1345p' src/libs/libFont.cpp sed -n '1640,1735p' src/libs/libFont.cpp sed -n '2360,2395p' src/libs/libFont.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 19105 --- </dd> </dl> </details> **Guard both deletes with successful registry removal.** `FontDestroyString` clears only the handle slot passed to it, so a copied handle remains nonnull. `FontCloseFont` takes its handle by value and clears no caller slot. A second call with either stale handle can delete an unregistered object. Delete only when the corresponding `erase` succeeds. <details> <summary>Suggested fix</summary> <dl> <dd> ```diff - g_fonts.erase(font); + const bool registered = g_fonts.erase(font) != 0; if (g_active_font == font) { g_active_font = nullptr; } - delete font; + if (registered) { + delete font; + } ... - g_strings.erase(state); - delete state; + if (g_strings.erase(state) != 0) { + delete state; + } ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Review the replacement and indentation, then test before committing. ```suggestion auto* state = static_cast<FontStringState*>(*font_string); if (state != nullptr) { std::scoped_lock lock(g_string_mutex); if (g_strings.erase(state) != 0) { delete state; } } ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:19a395d1e9de4ef63dc554f3 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠gallexme <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:58 UTC · original · edited 2026-11-02 20:13 UTC
On src/libs/libFont.cpp line 1965 (outdated):

@@ -1804,16 +1945,30 @@ int KYTY_SYSV_ABI FontWritingInit(FontWriting* font_writing, FontString font_str
 
 	auto* state           = new FontWritingState {};
 	state->string         = static_cast<FontStringState*>(font_string);
-	state->character      = get_character(font_character);
 	state->invisible_mask = 0;
-	if (state->character == nullptr && state->string != nullptr &&
-	    !state->string->characters.empty()) {
-		state->character = &state->string->characters.front();
+
+	size_t index = 0;
+	if (font_character != nullptr) {
+		auto* requested = get_character(font_character);
+		if (requested == nullptr || requested->string != state->string) {
+			delete state;
+			return -1;
+		}
+		index = requested->index;
 	}
+	state->next_index    = index;
+	state->current_index = index;
 
-	fill_writing_step(&state->step, state->character);
-	fill_writing_letter_step(&state->letter_step, state->character);
-	fill_writing_metrics(&state->metrics, state->step.profile.character_count);
+	if (!populate_writing_step(state, index)) {
+		delete state;
+		return -1;
+	}

Minor · Functional Correctness · Quick win

Supported by static analysis

Script executed:

printf '%s\n' '--- current relevant symbols ---'
rg -n -F -e 'populate_writing_step' -e 'FontWritingInit' -e 'FontWritingRefersRenderStep' -e 'g_strings' src/libs/libFont.cpp | head -100
printf '%s\n' '--- current source around helper and writing APIs ---'
sed -n '1750,2025p' src/libs/libFont.cpp
printf '%s\n' '--- base initializer and render-step implementation ---'
git show 4a305a95ebba2318950ec73f3a841ba26729483d:src/libs/libFont.cpp | rg -n -F -e 'FontWritingInit' -e 'FontWritingRefersRenderStep' -e 'populate_writing_step'
git show 4a305a95ebba2318950ec73f3a841ba26729483d:src/libs/libFont.cpp | sed -n '1770,1995p'

Repository: KytyPS5/KytyPS5

Length of output: 18137


Script executed:

printf '%s\n' '--- helper and related mutex declarations ---'
sed -n '395,435p' src/libs/libFont.cpp
sed -n '650,730p' src/libs/libFont.cpp
printf '%s\n' '--- string constructors and registration ---'
rg -n -F -e 'FontStringCreate' -e 'FontStringCreateWith' -e 'characters.push_back' -e 'g_strings.insert' -e 'g_string_mutex' src/libs/libFont.cpp
sed -n '1650,1740p' src/libs/libFont.cpp
printf '%s\n' '--- public string constructors ---'
rg -n 'FontString.*Create|FontCreate.*String' src/libs/libFont.cpp

Repository: KytyPS5/KytyPS5

Length of output: 8076


Script executed:

printf '%s\n' '--- text parser and character production ---'
sed -n '430,510p' src/libs/libFont.cpp
rg -n -F -e 'parse_text_with_callback' -e 'FontCreateStringDetail' -e 'text_length' -e 'text_size' src/libs/libFont.cpp

Repository: KytyPS5/KytyPS5

Length of output: 3944


Script executed:

sed -n '505,560p' src/libs/libFont.cpp
sed -n '1570,1630p' src/libs/libFont.cpp

Repository: KytyPS5/KytyPS5

Length of output: 4251


Script executed:

printf '%s\n' '--- producer and parser ---'
nl -ba src/libs/libFont.cpp | sed -n '465,535p;1588,1627p;1670,1727p'
printf '%s\n' '--- helper, current initializer, consumer ---'
nl -ba src/libs/libFont.cpp | sed -n '680,722p;1930,2015p'
printf '%s\n' '--- base initializer ---'
git show 4a305a95ebba2318950ec73f3a841ba26729483d:src/libs/libFont.cpp | nl -ba | sed -n '1788,1848p'

Repository: KytyPS5/KytyPS5

Length of output: 15229


Accept registered empty strings in FontWritingInit.

FontTextSourceInit can produce an empty text range, and FontCreateString registers the resulting string. populate_writing_step(state, 0) then fails because the string has no characters, so FontWritingInit returns -1. Keep returning -1 for unregistered strings.

Suggested fix
--- "a/src/libs/libFont.cpp"
+++ "b/src/libs/libFont.cpp"
@@ -1959,10 +1959,18 @@
 	state->next_index    = index;
 	state->current_index = index;
 
 	if (!populate_writing_step(state, index)) {
-		delete state;
-		return -1;
+		bool string_is_empty = false;
+		{
+			std::scoped_lock lock(g_string_mutex);
+			string_is_empty = g_strings.count(state->string) != 0 &&
+			                  state->string->characters.empty();
+		}
+		if (!string_is_empty) {
+			delete state;
+			return -1;
+		}
 	}
 	state->pen_x                 = 0.0f;
 	state->pen_y                 = 0.0f;
 	state->metrics               = {};
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

	if (!populate_writing_step(state, index)) {
		bool string_is_empty = false;
		{
			std::scoped_lock lock(g_string_mutex);
			string_is_empty = g_strings.count(state->string) != 0 &&
			                  state->string->characters.empty();
		}
		if (!string_is_empty) {
			delete state;
			return -1;
		}
	}

✅ Confirmed as addressed by @⁠gallexme

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 19:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4447081862) · edited 2026-11-02 20:13 UTC On `src/libs/libFont.cpp` line 1965 (outdated): ```diff @@ -1804,16 +1945,30 @@ int KYTY_SYSV_ABI FontWritingInit(FontWriting* font_writing, FontString font_str auto* state = new FontWritingState {}; state->string = static_cast<FontStringState*>(font_string); - state->character = get_character(font_character); state->invisible_mask = 0; - if (state->character == nullptr && state->string != nullptr && - !state->string->characters.empty()) { - state->character = &state->string->characters.front(); + + size_t index = 0; + if (font_character != nullptr) { + auto* requested = get_character(font_character); + if (requested == nullptr || requested->string != state->string) { + delete state; + return -1; + } + index = requested->index; } + state->next_index = index; + state->current_index = index; - fill_writing_step(&state->step, state->character); - fill_writing_letter_step(&state->letter_step, state->character); - fill_writing_metrics(&state->metrics, state->step.profile.character_count); + if (!populate_writing_step(state, index)) { + delete state; + return -1; + } ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> Script executed: ```bash printf '%s\n' '--- current relevant symbols ---' rg -n -F -e 'populate_writing_step' -e 'FontWritingInit' -e 'FontWritingRefersRenderStep' -e 'g_strings' src/libs/libFont.cpp | head -100 printf '%s\n' '--- current source around helper and writing APIs ---' sed -n '1750,2025p' src/libs/libFont.cpp printf '%s\n' '--- base initializer and render-step implementation ---' git show 4a305a95ebba2318950ec73f3a841ba26729483d:src/libs/libFont.cpp | rg -n -F -e 'FontWritingInit' -e 'FontWritingRefersRenderStep' -e 'populate_writing_step' git show 4a305a95ebba2318950ec73f3a841ba26729483d:src/libs/libFont.cpp | sed -n '1770,1995p' ``` Repository: KytyPS5/KytyPS5 Length of output: 18137 --- Script executed: ```bash printf '%s\n' '--- helper and related mutex declarations ---' sed -n '395,435p' src/libs/libFont.cpp sed -n '650,730p' src/libs/libFont.cpp printf '%s\n' '--- string constructors and registration ---' rg -n -F -e 'FontStringCreate' -e 'FontStringCreateWith' -e 'characters.push_back' -e 'g_strings.insert' -e 'g_string_mutex' src/libs/libFont.cpp sed -n '1650,1740p' src/libs/libFont.cpp printf '%s\n' '--- public string constructors ---' rg -n 'FontString.*Create|FontCreate.*String' src/libs/libFont.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 8076 --- Script executed: ```bash printf '%s\n' '--- text parser and character production ---' sed -n '430,510p' src/libs/libFont.cpp rg -n -F -e 'parse_text_with_callback' -e 'FontCreateStringDetail' -e 'text_length' -e 'text_size' src/libs/libFont.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 3944 --- Script executed: ```bash sed -n '505,560p' src/libs/libFont.cpp sed -n '1570,1630p' src/libs/libFont.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 4251 --- Script executed: ```bash printf '%s\n' '--- producer and parser ---' nl -ba src/libs/libFont.cpp | sed -n '465,535p;1588,1627p;1670,1727p' printf '%s\n' '--- helper, current initializer, consumer ---' nl -ba src/libs/libFont.cpp | sed -n '680,722p;1930,2015p' printf '%s\n' '--- base initializer ---' git show 4a305a95ebba2318950ec73f3a841ba26729483d:src/libs/libFont.cpp | nl -ba | sed -n '1788,1848p' ``` Repository: KytyPS5/KytyPS5 Length of output: 15229 --- </dd> </dl> </details> **Accept registered empty strings in `FontWritingInit`.** `FontTextSourceInit` can produce an empty text range, and `FontCreateString` registers the resulting string. `populate_writing_step(state, 0)` then fails because the string has no characters, so `FontWritingInit` returns `-1`. Keep returning `-1` for unregistered strings. <details> <summary>Suggested fix</summary> <dl> <dd> ```diff --- "a/src/libs/libFont.cpp" +++ "b/src/libs/libFont.cpp" @@ -1959,10 +1959,18 @@ state->next_index = index; state->current_index = index; if (!populate_writing_step(state, index)) { - delete state; - return -1; + bool string_is_empty = false; + { + std::scoped_lock lock(g_string_mutex); + string_is_empty = g_strings.count(state->string) != 0 && + state->string->characters.empty(); + } + if (!string_is_empty) { + delete state; + return -1; + } } state->pen_x = 0.0f; state->pen_y = 0.0f; state->metrics = {}; ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Review the replacement and indentation, then test before committing. ```suggestion if (!populate_writing_step(state, index)) { bool string_is_empty = false; { std::scoped_lock lock(g_string_mutex); string_is_empty = g_strings.count(state->string) != 0 && state->string->characters.empty(); } if (!string_is_empty) { delete state; return -1; } } ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3ae5704c5984194a1546b5d5 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠gallexme <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:58 UTC · original · edited 2026-11-02 20:13 UTC
On src/libs/libFont.cpp line 2057 (outdated):

@@ -1847,26 +2002,65 @@ const FontWritingStep* KYTY_SYSV_ABI FontWritingRefersRenderStep(FontWriting* fo
 	PRINT_NAME();
 
 	auto* state = get_writing_state(font_writing);
-	auto* step  = state != nullptr ? &state->step : nullptr;
+	if (state == nullptr || !populate_writing_step(state, state->next_index)) {
+		LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n",
+		     reinterpret_cast<uint64_t>(font_writing), uint64_t {0});
+		return nullptr;
+	}
+	state->current_index         = state->next_index;
+	state->has_current_step      = true;
+	state->has_current_character = true;
+	accumulate_writing_metrics(state);
+	++state->next_index;
+
 	LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n",
-	     reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(step));
-	return step;
+	     reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(&state->step));
+	return &state->step;
 }
 
 FontTextCharacter KYTY_SYSV_ABI FontWritingRefersRenderStepCharacter(FontWriting* font_writing,
                                                                      const void** letter_step) {
 	PRINT_NAME();
 
 	auto* state = get_writing_state(font_writing);
-	if (letter_step != nullptr) {
-		*letter_step = state != nullptr ? &state->letter_step : nullptr;
+	if (state == nullptr || !state->has_current_step || !state->has_current_character ||
+	    state->string == nullptr) {
+		if (letter_step != nullptr) {
+			*letter_step = nullptr;
+		}
+		return nullptr;
 	}
+	state->has_current_character = false;
+
+	std::scoped_lock string_lock(g_string_mutex);
+	if (g_strings.count(state->string) == 0 ||
+	    state->current_index >= state->string->characters.size()) {
+		if (letter_step != nullptr) {
+			*letter_step = nullptr;
+		}
+		return nullptr;
+	}
+	auto* character = &state->string->characters[state->current_index];
+	if (letter_step != nullptr) {
+		*letter_step = &state->letter_step;
+	}
+	state->letter_step       = {};
+	state->letter_step.x     = state->step.x;
+	state->letter_step.y     = state->step.y;
+	state->letter_step.advance_x = state->step.advance_x;
+	state->letter_step.advance_y = state->step.advance_y;
+	state->letter_step.components.texts_count          = 1;
+	state->letter_step.components.texts_index          = static_cast<uint32_t>(state->current_index);
+	state->letter_step.components.glyphs_count         = 1;
+	state->letter_step.components.glyphs_index         = static_cast<uint32_t>(state->current_index);
+	state->letter_step.components.character_text_count =
+	    static_cast<uint8_t>(std::max<uint32_t>(state->step.profile.character_count, 1));

Minor · Functional Correctness · Quick win

FontWritingRefersRenderStepCharacter discards the letter-step fields that fill_writing_letter_step sets.

populate_writing_step already fills state->letter_step through fill_writing_letter_step. That function sets base_components_count, base_focus_count, and base_text_count to 1. It also sets glyphs_index to 0.

Line 2047 zeroes the struct. The code then rebuilds only part of it. The three base_* counts are lost, and glyphs_index becomes current_index. The same struct now has two different definitions, depending on whether the guest calls this function.

A guest that reads letter_step->components.base_components_count or base_text_count gets 0 instead of 1. Do not zero the struct. Overwrite only x, y, and the advances, and keep one definition for the index fields.

Proposed fix
--- "a/src/libs/libFont.cpp"
+++ "b/src/libs/libFont.cpp"
@@ -2044,17 +2044,11 @@
 	if (letter_step != nullptr) {
 		*letter_step = &state->letter_step;
 	}
-	state->letter_step       = {};
 	state->letter_step.x     = state->step.x;
 	state->letter_step.y     = state->step.y;
 	state->letter_step.advance_x = state->step.advance_x;
 	state->letter_step.advance_y = state->step.advance_y;
-	state->letter_step.components.texts_count          = 1;
 	state->letter_step.components.texts_index          = static_cast<uint32_t>(state->current_index);
-	state->letter_step.components.glyphs_count         = 1;
-	state->letter_step.components.glyphs_index         = static_cast<uint32_t>(state->current_index);
-	state->letter_step.components.character_text_count =
-	    static_cast<uint8_t>(std::max<uint32_t>(state->step.profile.character_count, 1));
 
 	LOGF("\t writing = 0x%016" PRIx64 ", character = 0x%016" PRIx64 ", letter_step = 0x%016" PRIx64
 	     "\n",
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

	state->letter_step.x     = state->step.x;
	state->letter_step.y     = state->step.y;
	state->letter_step.advance_x = state->step.advance_x;
	state->letter_step.advance_y = state->step.advance_y;
	state->letter_step.components.texts_index          = static_cast<uint32_t>(state->current_index);

✅ Confirmed as addressed by @⁠gallexme

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 19:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4447081877) · edited 2026-11-02 20:13 UTC On `src/libs/libFont.cpp` line 2057 (outdated): ```diff @@ -1847,26 +2002,65 @@ const FontWritingStep* KYTY_SYSV_ABI FontWritingRefersRenderStep(FontWriting* fo PRINT_NAME(); auto* state = get_writing_state(font_writing); - auto* step = state != nullptr ? &state->step : nullptr; + if (state == nullptr || !populate_writing_step(state, state->next_index)) { + LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n", + reinterpret_cast<uint64_t>(font_writing), uint64_t {0}); + return nullptr; + } + state->current_index = state->next_index; + state->has_current_step = true; + state->has_current_character = true; + accumulate_writing_metrics(state); + ++state->next_index; + LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n", - reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(step)); - return step; + reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(&state->step)); + return &state->step; } FontTextCharacter KYTY_SYSV_ABI FontWritingRefersRenderStepCharacter(FontWriting* font_writing, const void** letter_step) { PRINT_NAME(); auto* state = get_writing_state(font_writing); - if (letter_step != nullptr) { - *letter_step = state != nullptr ? &state->letter_step : nullptr; + if (state == nullptr || !state->has_current_step || !state->has_current_character || + state->string == nullptr) { + if (letter_step != nullptr) { + *letter_step = nullptr; + } + return nullptr; } + state->has_current_character = false; + + std::scoped_lock string_lock(g_string_mutex); + if (g_strings.count(state->string) == 0 || + state->current_index >= state->string->characters.size()) { + if (letter_step != nullptr) { + *letter_step = nullptr; + } + return nullptr; + } + auto* character = &state->string->characters[state->current_index]; + if (letter_step != nullptr) { + *letter_step = &state->letter_step; + } + state->letter_step = {}; + state->letter_step.x = state->step.x; + state->letter_step.y = state->step.y; + state->letter_step.advance_x = state->step.advance_x; + state->letter_step.advance_y = state->step.advance_y; + state->letter_step.components.texts_count = 1; + state->letter_step.components.texts_index = static_cast<uint32_t>(state->current_index); + state->letter_step.components.glyphs_count = 1; + state->letter_step.components.glyphs_index = static_cast<uint32_t>(state->current_index); + state->letter_step.components.character_text_count = + static_cast<uint8_t>(std::max<uint32_t>(state->step.profile.character_count, 1)); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **`FontWritingRefersRenderStepCharacter` discards the letter-step fields that `fill_writing_letter_step` sets.** `populate_writing_step` already fills `state->letter_step` through `fill_writing_letter_step`. That function sets `base_components_count`, `base_focus_count`, and `base_text_count` to 1. It also sets `glyphs_index` to 0. Line 2047 zeroes the struct. The code then rebuilds only part of it. The three `base_*` counts are lost, and `glyphs_index` becomes `current_index`. The same struct now has two different definitions, depending on whether the guest calls this function. A guest that reads `letter_step->components.base_components_count` or `base_text_count` gets 0 instead of 1. Do not zero the struct. Overwrite only `x`, `y`, and the advances, and keep one definition for the index fields. <details> <summary>Proposed fix</summary> <dl> <dd> ```diff --- "a/src/libs/libFont.cpp" +++ "b/src/libs/libFont.cpp" @@ -2044,17 +2044,11 @@ if (letter_step != nullptr) { *letter_step = &state->letter_step; } - state->letter_step = {}; state->letter_step.x = state->step.x; state->letter_step.y = state->step.y; state->letter_step.advance_x = state->step.advance_x; state->letter_step.advance_y = state->step.advance_y; - state->letter_step.components.texts_count = 1; state->letter_step.components.texts_index = static_cast<uint32_t>(state->current_index); - state->letter_step.components.glyphs_count = 1; - state->letter_step.components.glyphs_index = static_cast<uint32_t>(state->current_index); - state->letter_step.components.character_text_count = - static_cast<uint8_t>(std::max<uint32_t>(state->step.profile.character_count, 1)); LOGF("\t writing = 0x%016" PRIx64 ", character = 0x%016" PRIx64 ", letter_step = 0x%016" PRIx64 "\n", ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Review the replacement and indentation, then test before committing. ```suggestion state->letter_step.x = state->step.x; state->letter_step.y = state->step.y; state->letter_step.advance_x = state->step.advance_x; state->letter_step.advance_y = state->step.advance_y; state->letter_step.components.texts_index = static_cast<uint32_t>(state->current_index); ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:989eb45ba90130717834f477 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠gallexme <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-02 19:58 UTC · original · reviewed

**@⁠coderabbitai[bot]** on GitHub · 2026-11-02 19:58 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#pullrequestreview-5742529719) · **reviewed** <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=78b6a25e-f302-4de7-ba5f-7a4613501f11 attempt=2c71bce7-3d8b-4926-a76f-c16c4612ba61 batch=1/1 -->
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 20:13 UTC · original
On src/libs/libFont.cpp line 1725 (outdated):

@@ -1588,7 +1717,12 @@ int KYTY_SYSV_ABI FontDestroyString(FontString* font_string) {
 	LOGF("\t string_ptr = 0x%016" PRIx64 "\n", reinterpret_cast<uint64_t>(font_string));
 
 	if (font_string != nullptr) {
-		delete static_cast<FontStringState*>(*font_string);
+		auto* state = static_cast<FontStringState*>(*font_string);
+		if (state != nullptr) {
+			std::scoped_lock lock(g_string_mutex);
+			g_strings.erase(state);
+			delete state;
+		}

Fixed in 3e211335.

**@⁠gallexme** on GitHub · 2026-11-02 20:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4447224778) On `src/libs/libFont.cpp` line 1725 (outdated): ```diff @@ -1588,7 +1717,12 @@ int KYTY_SYSV_ABI FontDestroyString(FontString* font_string) { LOGF("\t string_ptr = 0x%016" PRIx64 "\n", reinterpret_cast<uint64_t>(font_string)); if (font_string != nullptr) { - delete static_cast<FontStringState*>(*font_string); + auto* state = static_cast<FontStringState*>(*font_string); + if (state != nullptr) { + std::scoped_lock lock(g_string_mutex); + g_strings.erase(state); + delete state; + } ``` Fixed in 3e211335.
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 20:13 UTC · original
On src/libs/libFont.cpp line 1965 (outdated):

@@ -1804,16 +1945,30 @@ int KYTY_SYSV_ABI FontWritingInit(FontWriting* font_writing, FontString font_str
 
 	auto* state           = new FontWritingState {};
 	state->string         = static_cast<FontStringState*>(font_string);
-	state->character      = get_character(font_character);
 	state->invisible_mask = 0;
-	if (state->character == nullptr && state->string != nullptr &&
-	    !state->string->characters.empty()) {
-		state->character = &state->string->characters.front();
+
+	size_t index = 0;
+	if (font_character != nullptr) {
+		auto* requested = get_character(font_character);
+		if (requested == nullptr || requested->string != state->string) {
+			delete state;
+			return -1;
+		}
+		index = requested->index;
 	}
+	state->next_index    = index;
+	state->current_index = index;
 
-	fill_writing_step(&state->step, state->character);
-	fill_writing_letter_step(&state->letter_step, state->character);
-	fill_writing_metrics(&state->metrics, state->step.profile.character_count);
+	if (!populate_writing_step(state, index)) {
+		delete state;
+		return -1;
+	}

Fixed in 3e211335.

**@⁠gallexme** on GitHub · 2026-11-02 20:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4447225056) On `src/libs/libFont.cpp` line 1965 (outdated): ```diff @@ -1804,16 +1945,30 @@ int KYTY_SYSV_ABI FontWritingInit(FontWriting* font_writing, FontString font_str auto* state = new FontWritingState {}; state->string = static_cast<FontStringState*>(font_string); - state->character = get_character(font_character); state->invisible_mask = 0; - if (state->character == nullptr && state->string != nullptr && - !state->string->characters.empty()) { - state->character = &state->string->characters.front(); + + size_t index = 0; + if (font_character != nullptr) { + auto* requested = get_character(font_character); + if (requested == nullptr || requested->string != state->string) { + delete state; + return -1; + } + index = requested->index; } + state->next_index = index; + state->current_index = index; - fill_writing_step(&state->step, state->character); - fill_writing_letter_step(&state->letter_step, state->character); - fill_writing_metrics(&state->metrics, state->step.profile.character_count); + if (!populate_writing_step(state, index)) { + delete state; + return -1; + } ``` Fixed in 3e211335.
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 20:13 UTC · original
On src/libs/libFont.cpp line 2057 (outdated):

@@ -1847,26 +2002,65 @@ const FontWritingStep* KYTY_SYSV_ABI FontWritingRefersRenderStep(FontWriting* fo
 	PRINT_NAME();
 
 	auto* state = get_writing_state(font_writing);
-	auto* step  = state != nullptr ? &state->step : nullptr;
+	if (state == nullptr || !populate_writing_step(state, state->next_index)) {
+		LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n",
+		     reinterpret_cast<uint64_t>(font_writing), uint64_t {0});
+		return nullptr;
+	}
+	state->current_index         = state->next_index;
+	state->has_current_step      = true;
+	state->has_current_character = true;
+	accumulate_writing_metrics(state);
+	++state->next_index;
+
 	LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n",
-	     reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(step));
-	return step;
+	     reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(&state->step));
+	return &state->step;
 }
 
 FontTextCharacter KYTY_SYSV_ABI FontWritingRefersRenderStepCharacter(FontWriting* font_writing,
                                                                      const void** letter_step) {
 	PRINT_NAME();
 
 	auto* state = get_writing_state(font_writing);
-	if (letter_step != nullptr) {
-		*letter_step = state != nullptr ? &state->letter_step : nullptr;
+	if (state == nullptr || !state->has_current_step || !state->has_current_character ||
+	    state->string == nullptr) {
+		if (letter_step != nullptr) {
+			*letter_step = nullptr;
+		}
+		return nullptr;
 	}
+	state->has_current_character = false;
+
+	std::scoped_lock string_lock(g_string_mutex);
+	if (g_strings.count(state->string) == 0 ||
+	    state->current_index >= state->string->characters.size()) {
+		if (letter_step != nullptr) {
+			*letter_step = nullptr;
+		}
+		return nullptr;
+	}
+	auto* character = &state->string->characters[state->current_index];
+	if (letter_step != nullptr) {
+		*letter_step = &state->letter_step;
+	}
+	state->letter_step       = {};
+	state->letter_step.x     = state->step.x;
+	state->letter_step.y     = state->step.y;
+	state->letter_step.advance_x = state->step.advance_x;
+	state->letter_step.advance_y = state->step.advance_y;
+	state->letter_step.components.texts_count          = 1;
+	state->letter_step.components.texts_index          = static_cast<uint32_t>(state->current_index);
+	state->letter_step.components.glyphs_count         = 1;
+	state->letter_step.components.glyphs_index         = static_cast<uint32_t>(state->current_index);
+	state->letter_step.components.character_text_count =
+	    static_cast<uint8_t>(std::max<uint32_t>(state->step.profile.character_count, 1));

Fixed in 3e211335.

**@⁠gallexme** on GitHub · 2026-11-02 20:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#discussion_r4447225370) On `src/libs/libFont.cpp` line 2057 (outdated): ```diff @@ -1847,26 +2002,65 @@ const FontWritingStep* KYTY_SYSV_ABI FontWritingRefersRenderStep(FontWriting* fo PRINT_NAME(); auto* state = get_writing_state(font_writing); - auto* step = state != nullptr ? &state->step : nullptr; + if (state == nullptr || !populate_writing_step(state, state->next_index)) { + LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n", + reinterpret_cast<uint64_t>(font_writing), uint64_t {0}); + return nullptr; + } + state->current_index = state->next_index; + state->has_current_step = true; + state->has_current_character = true; + accumulate_writing_metrics(state); + ++state->next_index; + LOGF("\t writing = 0x%016" PRIx64 ", step = 0x%016" PRIx64 "\n", - reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(step)); - return step; + reinterpret_cast<uint64_t>(font_writing), reinterpret_cast<uint64_t>(&state->step)); + return &state->step; } FontTextCharacter KYTY_SYSV_ABI FontWritingRefersRenderStepCharacter(FontWriting* font_writing, const void** letter_step) { PRINT_NAME(); auto* state = get_writing_state(font_writing); - if (letter_step != nullptr) { - *letter_step = state != nullptr ? &state->letter_step : nullptr; + if (state == nullptr || !state->has_current_step || !state->has_current_character || + state->string == nullptr) { + if (letter_step != nullptr) { + *letter_step = nullptr; + } + return nullptr; } + state->has_current_character = false; + + std::scoped_lock string_lock(g_string_mutex); + if (g_strings.count(state->string) == 0 || + state->current_index >= state->string->characters.size()) { + if (letter_step != nullptr) { + *letter_step = nullptr; + } + return nullptr; + } + auto* character = &state->string->characters[state->current_index]; + if (letter_step != nullptr) { + *letter_step = &state->letter_step; + } + state->letter_step = {}; + state->letter_step.x = state->step.x; + state->letter_step.y = state->step.y; + state->letter_step.advance_x = state->step.advance_x; + state->letter_step.advance_y = state->step.advance_y; + state->letter_step.components.texts_count = 1; + state->letter_step.components.texts_index = static_cast<uint32_t>(state->current_index); + state->letter_step.components.glyphs_count = 1; + state->letter_step.components.glyphs_index = static_cast<uint32_t>(state->current_index); + state->letter_step.components.character_text_count = + static_cast<uint8_t>(std::max<uint32_t>(state->step.profile.character_count, 1)); ``` Fixed in 3e211335.
Author
Owner

@⁠gallexme on GitHub · 2026-11-02 20:13 UTC · original

Addressed the latest three review notes in 3e211335:

  • delete fonts/strings only when registry removal succeeds (stale/double handles no longer free);
  • allow registered empty strings to initialize a writing with no steps;
  • stop rebuilding/corrupting the letter-step component fields in FontWritingRefersRenderStepCharacter.

Build passes and the save menu still renders correctly.

**@⁠gallexme** on GitHub · 2026-11-02 20:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2075#issuecomment-6587385694) Addressed the latest three review notes in `3e211335`: - delete fonts/strings only when registry removal succeeds (stale/double handles no longer free); - allow registered empty strings to initialize a writing with no steps; - stop rebuilding/corrupting the letter-step component fields in `FontWritingRefersRenderStepCharacter`. Build passes and the save menu still renders correctly.
This discussion has been locked. Commenting is limited to contributors.
No description provided.