Zarchive Loading #724

Manually merged
github merged 3 commits from gh-pr/724/head into gh-pr/724/base 2026-11-26 09:30:49 +00:00
Owner

@⁠Aspenini on GitHub · 2026-09-20 02:48 UTC · original
main → main · +1955 −261 · 29 files · 3 commits · merged 2026-09-28 20:06 UTC

Adds the ability to load Zarchive files, made from folder dumps of PS5 games. This allows games to be stored as a single file with a bit of compression. It is the same format that shadPS4, Cemu, and Xenia use for their consoles' games.

Tested on Dead Cells, which loaded the same as a folder and .zar file.

AI was used to assist development.

**@⁠Aspenini** on GitHub · 2026-09-20 02:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724) `main` → `main` · +1955 −261 · 29 files · 3 commits · merged 2026-09-28 20:06 UTC Adds the ability to load Zarchive files, made from folder dumps of PS5 games. This allows games to be stored as a single file with a bit of compression. It is the same format that shadPS4, Cemu, and Xenia use for their consoles' games. Tested on Dead Cells, which loaded the same as a folder and .zar file. AI was used to assist development.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:30:48 +00:00
github manually merged commit 84eb12a482 into gh-pr/724/base 2026-11-26 09:30:49 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-20 02:59 UTC · original · edited 2026-09-28 19:42 UTC

Review in Change Stack →

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

📝 Walkthrough

Walkthrough

The change adds ZArchive support across the common file API, kernel filesystem, launcher, media streaming, and command-line game loading. Archive files can be opened and read through virtual paths, while archive mounts and launcher content access remain read-only. The launcher discovers supported archives containing eboot.bin and reads bounded metadata, images, and trophy package content. The build adds pinned Zstd and ZArchive dependencies and registers archive-related tests across platforms.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Feature

Merge Risk: 🟡 Moderate · up to 3cd48

Archive directory enumeration can terminate the emulator for a long entry name, and a stalled archive read can block other archive-backed games. Resolve these risks before merging; repeated metadata lookups may also add avoidable loading work.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 3cd48

Archive access is designed to be read-only and confined to mounted paths. However, concurrent file closure may invalidate an active archive read, and a failed read may appear to succeed with fewer bytes. These risks warrant design review before merging.

Retained concerns

  • Medium · security · inferred: A concurrent close can reset and delete an archive-backed descriptor while a read uses its reader and caller-owned queued request. The visible paths do not establish a shared lifetime or close/read synchronization contract.
  • Low · reliability · inferred: A backend read returning zero before the declared end of an archive member is exposed as an EOF-like or short successful read rather than a distinguishable I/O failure.
Security review details

Security Blast Radius

  • inferred — The new input surface is archive content selected for local game loading and read through the emulator's common and kernel file paths. The worker is shared across archive reads in the process; the supplied evidence does not establish a network, tenant, or privileged-service entrypoint.

Security Findings and Attack Paths

  • inferred — If one guest thread closes an archive descriptor while another is reading it, close can release the archive owner without waiting for the read or its queued work. Whether that interleaving is permitted in normal guest execution remains unverified.

Trust Boundaries and Controls

  • observed — Guest paths pass through mount resolution before ordinary opens; archive opens are read-only, and member normalization rejects traversal above the archive root.

Resilience and Maintainability Implications

  • observed — On pthread-backed builds, cancellation is disabled for the duration of an archive read, protecting the caller-owned queued request from cancellation during that operation. This does not establish concurrent-close safety.

Hardening Proposals

  • proposed — Give queued work ownership of the reader and storage it needs, and coordinate descriptor close with active reads; distinguish a backend failure from EOF before the known member size.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 197 functions across 25 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: loading ZArchive files.
Description check ✅ Passed The description directly explains support for loading ZArchive files and includes relevant testing information.
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.

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

❤️ Share

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-20 02:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5747192882) · edited 2026-09-28 19:42 UTC <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/724?cs_source=review_comment"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=2" alt="Review in Change Stack →" width="220" height="32"></a> Navigate logical layers of code changes, visualize relationships, and explore their blast radius. <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change adds ZArchive support across the common file API, kernel filesystem, launcher, media streaming, and command-line game loading. Archive files can be opened and read through virtual paths, while archive mounts and launcher content access remain read-only. The launcher discovers supported archives containing `eboot.bin` and reads bounded metadata, images, and trophy package content. The build adds pinned Zstd and ZArchive dependencies and registers archive-related tests across platforms. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"3cd483ae6a781a5d78612371aebf6e2d86f8de1c" --> **Change:** Feature <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `3cd48` <!-- final_review_risk_coverage:{"sourceCommitId":"3cd483ae6a781a5d78612371aebf6e2d86f8de1c","coveredCommitId":"3cd483ae6a781a5d78612371aebf6e2d86f8de1c","kind":"reviewed"} --> Archive directory enumeration can terminate the emulator for a long entry name, and a stalled archive read can block other archive-backed games. Resolve these risks before merging; repeated metadata lookups may also add avoidable loading work. <!-- final_review_risk_end --> <!-- architecture_review_start --> ### Security Architecture Review **Security architecture risk:** _🟡 Moderate_ · up to `3cd48` Archive access is designed to be read-only and confined to mounted paths. However, concurrent file closure may invalidate an active archive read, and a failed read may appear to succeed with fewer bytes. These risks warrant design review before merging. **Retained concerns** - **Medium · security · inferred:** A concurrent close can reset and delete an archive-backed descriptor while a read uses its reader and caller-owned queued request. The visible paths do not establish a shared lifetime or close/read synchronization contract. - **Low · reliability · inferred:** A backend read returning zero before the declared end of an archive member is exposed as an EOF-like or short successful read rather than a distinguishable I/O failure. <details> <summary>Security review details</summary> **Security Blast Radius** - _inferred_ — The new input surface is archive content selected for local game loading and read through the emulator's common and kernel file paths. The worker is shared across archive reads in the process; the supplied evidence does not establish a network, tenant, or privileged-service entrypoint. **Security Findings and Attack Paths** - _inferred_ — If one guest thread closes an archive descriptor while another is reading it, close can release the archive owner without waiting for the read or its queued work. Whether that interleaving is permitted in normal guest execution remains unverified. **Trust Boundaries and Controls** - _observed_ — Guest paths pass through mount resolution before ordinary opens; archive opens are read-only, and member normalization rejects traversal above the archive root. **Resilience and Maintainability Implications** - _observed_ — On pthread-backed builds, cancellation is disabled for the duration of an archive read, protecting the caller-owned queued request from cancellation during that operation. This does not establish concurrent-close safety. **Hardening Proposals** - _proposed_ — Give queued work ownership of the reader and storage it needs, and coordinate descriptor close with active reads; distinguish a backend failure from EOF before the known member size. </details> <!-- architecture_review_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 3.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 197 functions across 25 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :-------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title clearly identifies the main change: loading ZArchive files. | | Description check | ✅ Passed | The description directly explains support for loading ZArchive files and includes relevant testing information. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=724)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary>❤️ Share</summary> - [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) </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-20 02:59 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 36d5457f-0a29-4442-93bb-7db53c9f9bac

📥 Commits

Reviewing files that changed from the base of the PR and between 8cecaf4e30 and 812de58741e94c3f538abd689679ca4bc8a7c9b8.

📒 Files selected for processing (20)
  • .github/workflows/build.yml
  • 3rdparty/CMakeLists.txt
  • CMakeLists.txt
  • README.md
  • src/common/CMakeLists.txt
  • src/common/file.cpp
  • src/common/zarchive.cpp
  • src/common/zarchive.h
  • src/kernel/fileSystem.cpp
  • src/launcher/CMakeLists.txt
  • src/launcher/include/gameContent.h
  • src/launcher/include/gameListTreeWidget.h
  • src/launcher/src/configurationItem.cpp
  • src/launcher/src/configurationListWidget.cpp
  • src/launcher/src/gameContent.cpp
  • src/launcher/src/mainDialog.cpp
  • src/launcher/src/trophyViewerDialog.cpp
  • src/libs/avPlayer.cpp
  • src/main.cpp
  • tests/ZArchiveFileTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-20 02:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#pullrequestreview-5259189369) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `36d5457f-0a29-4442-93bb-7db53c9f9bac` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 8cecaf4e30bb5fdeeab231864848bbf2d066a6a1 and 812de58741e94c3f538abd689679ca4bc8a7c9b8. </details> <details> <summary>📒 Files selected for processing (20)</summary> * `.github/workflows/build.yml` * `3rdparty/CMakeLists.txt` * `CMakeLists.txt` * `README.md` * `src/common/CMakeLists.txt` * `src/common/file.cpp` * `src/common/zarchive.cpp` * `src/common/zarchive.h` * `src/kernel/fileSystem.cpp` * `src/launcher/CMakeLists.txt` * `src/launcher/include/gameContent.h` * `src/launcher/include/gameListTreeWidget.h` * `src/launcher/src/configurationItem.cpp` * `src/launcher/src/configurationListWidget.cpp` * `src/launcher/src/gameContent.cpp` * `src/launcher/src/mainDialog.cpp` * `src/launcher/src/trophyViewerDialog.cpp` * `src/libs/avPlayer.cpp` * `src/main.cpp` * `tests/ZArchiveFileTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-20 02:59 UTC · original · edited 2026-09-26 22:05 UTC
On src/kernel/fileSystem.cpp line 357 (outdated):

@@ -343,10 +352,12 @@ std::filesystem::path MountPoints::ResolvePath(const std::string& mounted_name)
 		while (rel_path.starts_with('/')) {
 			rel_path = Common::RemoveFirst(rel_path, 1);
 		}
+		if (Common::IsZArchivePath(p.dir)) {
+			return p.dir / std::filesystem::u8path(rel_path);
+		}

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '230,380p' src/kernel/fileSystem.cpp
sed -n '400,500p' src/kernel/fileSystem.cpp
sed -n '1,115p' src/common/zarchive.cpp
rg -n 'ParsePath|ResolvePath\(|CreateDirectories|KernelStat|KernelCheckReachability' src/kernel/fileSystem.cpp src/common

Repository: KytyPS5/KytyPS5

Length of output: 12684


🏁 Script executed:

sed -n '500,545p' src/kernel/fileSystem.cpp
sed -n '880,935p' src/kernel/fileSystem.cpp
sed -n '1035,1130p' src/kernel/fileSystem.cpp
sed -n '1165,1270p' src/kernel/fileSystem.cpp
sed -n '300,370p' src/common/file.cpp
sed -n '70,100p' src/common/file.h
sed -n '160,275p' src/common/zarchive.cpp

Repository: KytyPS5/KytyPS5

Length of output: 13650


Normalize archive-relative paths and reject leading traversal.

MountPoints::ResolvePath joins rel_path without normalization. A path such as /app0/dir/../file.bin becomes <archive>.zar!/dir/../file.bin. Common::IsZArchivePath rejects this path because ParsePath rejects .., so archive lookup fails.

KernelOpen, KernelStat, and KernelCheckReachability then use the exact path as a host path. KernelOpen can bypass the archive EROFS guard and pass the path to Common::File::CreateDirectories and file->f.Create when O_CREAT is set. Mutation operations can likewise act on the host path instead of returning EROFS. With a leading ../ component, the host target can reach the directory that contains the archive.

Normalize the relative path before joining it. Reject normalized paths whose first component is .., and propagate that as an invalid guest path before any host filesystem operation. lexically_normal() alone is not sufficient because it preserves leading ...

✅ Addressed in commit 1bfe1cf

**@⁠coderabbitai[bot]** on GitHub · 2026-09-20 02:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#discussion_r4055882316) · edited 2026-09-26 22:05 UTC On `src/kernel/fileSystem.cpp` line 357 (outdated): ```diff @@ -343,10 +352,12 @@ std::filesystem::path MountPoints::ResolvePath(const std::string& mounted_name) while (rel_path.starts_with('/')) { rel_path = Common::RemoveFirst(rel_path, 1); } + if (Common::IsZArchivePath(p.dir)) { + return p.dir / std::filesystem::u8path(rel_path); + } ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '230,380p' src/kernel/fileSystem.cpp sed -n '400,500p' src/kernel/fileSystem.cpp sed -n '1,115p' src/common/zarchive.cpp rg -n 'ParsePath|ResolvePath\(|CreateDirectories|KernelStat|KernelCheckReachability' src/kernel/fileSystem.cpp src/common ``` Repository: KytyPS5/KytyPS5 Length of output: 12684 --- 🏁 Script executed: ```bash sed -n '500,545p' src/kernel/fileSystem.cpp sed -n '880,935p' src/kernel/fileSystem.cpp sed -n '1035,1130p' src/kernel/fileSystem.cpp sed -n '1165,1270p' src/kernel/fileSystem.cpp sed -n '300,370p' src/common/file.cpp sed -n '70,100p' src/common/file.h sed -n '160,275p' src/common/zarchive.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 13650 --- </details> **Normalize archive-relative paths and reject leading traversal.** `MountPoints::ResolvePath` joins `rel_path` without normalization. A path such as `/app0/dir/../file.bin` becomes `<archive>.zar!/dir/../file.bin`. `Common::IsZArchivePath` rejects this path because `ParsePath` rejects `..`, so archive lookup fails. `KernelOpen`, `KernelStat`, and `KernelCheckReachability` then use the exact path as a host path. `KernelOpen` can bypass the archive `EROFS` guard and pass the path to `Common::File::CreateDirectories` and `file->f.Create` when `O_CREAT` is set. Mutation operations can likewise act on the host path instead of returning `EROFS`. With a leading `../` component, the host target can reach the directory that contains the archive. Normalize the relative path before joining it. Reject normalized paths whose first component is `..`, and propagate that as an invalid guest path before any host filesystem operation. `lexically_normal()` alone is not sufficient because it preserves leading `..`. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:bad5978b699b98168d1b4535 --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1bfe1cf
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-20 02:59 UTC · original · edited 2026-09-26 22:06 UTC
On src/launcher/src/gameContent.cpp line 55 (outdated):

@@ -0,0 +1,69 @@
+#include "gameContent.h"
+
+#include "common/file.h"
+#include "common/stringUtils.h"
+#include "common/zarchive.h"
+
+#include <QFileInfo>
+
+#include <limits>
+
+namespace GameContent {
+
+std::filesystem::path ToPath(const QString& path) {
+#if defined(_WIN32)
+	return std::filesystem::path(path.toStdWString());
+#else
+	return std::filesystem::path(path.toStdString());
+#endif
+}
+
+QString FromPath(const std::filesystem::path& path) {
+#if defined(_WIN32)
+	return QString::fromStdWString(path.wstring());
+#else
+	return QString::fromStdString(Common::PathToString(path));
+#endif
+}
+
+bool IsArchive(const QString& base) {
+	const QFileInfo info(base);
+	return info.isFile() && info.suffix().compare(QStringLiteral("zar"), Qt::CaseInsensitive) == 0;
+}
+
+std::filesystem::path Resolve(const QString& base, const QString& relative) {
+	const auto root = ToPath(base);
+	return IsArchive(base) ? Common::MakeZArchivePath(root, ToPath(relative))
+	                       : root / ToPath(relative);
+}
+
+bool FileExists(const QString& base, const QString& relative) {
+	return Common::File::IsFileExisting(Resolve(base, relative));
+}
+
+QByteArray ReadFile(const QString& base, const QString& relative) {
+	return ReadPath(Resolve(base, relative));
+}
+
+QByteArray ReadPath(const std::filesystem::path& path) {
+	Common::File file(path, Common::File::Mode::Read);
+	if (file.IsInvalid() || file.Size() > static_cast<uint64_t>(std::numeric_limits<int>::max())) {
+		return {};
+	}
+
+	const auto data = file.ReadWholeBuffer();
+	return QByteArray(reinterpret_cast<const char*>(data.data()), static_cast<int>(data.size()));

🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

sed -n '40,75p' src/launcher/src/gameContent.cpp
sed -n '450,690p' src/launcher/src/configurationListWidget.cpp
rg -n 'ReadFile\(|ReadPath\(|ReadWholeBuffer|QByteArray' src/launcher src/common/file.cpp src/common/file.h

Repository: KytyPS5/KytyPS5

Length of output: 13044


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- Common::File definitions and archive size handling ---'
rg -n -C 8 'ReadWholeBuffer|File::Size|Size\(\)|fstat|stat|uncompressed|compressed|inflate|zlib|archive' src/common/file.cpp src/common/file.h src/common/zarchive.cpp src/common/zarchive.h
printf '%s\n' '--- file.cpp around ReadWholeBuffer and nearby constructors/read methods ---'
sed -n '300,455p' src/common/file.cpp
printf '%s\n' '--- launcher asset and trophy callers ---'
sed -n '100,150p' src/launcher/src/configurationListWidget.cpp
sed -n '250,300p' src/launcher/src/configurationItem.cpp
sed -n '70,210p' src/launcher/src/trophyViewerDialog.cpp
sed -n '260,350p' src/launcher/src/trophyViewerDialog.cpp
printf '%s\n' '--- archive implementation files ---'
sed -n '1,260p' src/common/zarchive.cpp

Repository: KytyPS5/KytyPS5

Length of output: 50437


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- zarchive implementation ownership and build references ---'
git ls-files | rg '(^|/)(zarchive|ZArchive)|zarchive' | head -120
rg -n -C 4 'zarchive|ZArchiveReader|BuildTrophySet|ReadUcp|ReadPath\(|ReadFile\(' CMakeLists.txt cmake src tests 2>/dev/null | head -260
printf '%s\n' '--- trophy callers and file discovery ---'
rg -n -C 8 'BuildTrophySet|trophy.*ucp|\\.ucp|ReadUcp|LoadTrophyIcon|UpdateIcon|GetPic0' src/launcher/src src/launcher/include
printf '%s\n' '--- exact archive read wrapper and launcher read paths ---'
sed -n '116,153p' src/common/zarchive.cpp
sed -n '256,282p' src/common/zarchive.cpp
sed -n '420,434p' src/common/file.cpp
sed -n '35,62p' src/launcher/src/gameContent.cpp

Repository: KytyPS5/KytyPS5

Length of output: 35476


🌐 Web query:

"ZArchiveReader" "GetFileSize" "ReadFromFile"

💡 Result:

Inspection citation: inspection_324745f5eee71d4d79dff02b7a5511d3

<search_synthesis>
ZArchiveReader is a C++ class provided by the ZArchive library, which is designed for creating and reading zstd-compressed file archives (.zar) [1]. The library is specifically engineered to support random-access reads within stored files [1]. The methods GetFileSize and ReadFromFile are core components of the ZArchiveReader API: 1. GetFileSize(ZArchiveNodeHandle handle): This method returns the size of a file within the archive, identified by its handle [2][3]. 2. ReadFromFile(ZArchiveNodeHandle handle, uint64_t offset, uint64_t size, void* buffer): This method reads a specified number of bytes from a file within the archive into a provided buffer, starting at a given offset [1]. These methods are commonly used in applications that require efficient, random-access retrieval of data from compressed archives, such as the Cemu emulator, which utilizes ZArchive for handling specific file system formats [2][3].
</search_synthesis>

<source_evidence>

https://github.com/Exzap/ZArchive # Exzap/ZArchive Library for creating and reading zstd-compressed file archives (.zar) - Stars: 159 - Forks: 19 - Watchers: 159 - Open issues: 14 - License: MIT No Attribution - Default branch: master - Created: 2022-04-25T18:40:28Z ## Languages - C - C++ - CMake ## Top Contributors - Exzap (11 contributions) - Tachi107 (3 contributions) - jaimeMF (3 contributions) - Crementif (2 contributions) - AdrianCassar (1 contributions) - SSimco (1 contributions) - SachinVin (1 contributions) - misuzu (1 contributions) --- ## README ## Overview ZArchive is yet another file archive format. Think of zip, tar, 7z, etc. but with the requirement of allowing random-access reads and supporting compression. ## Features / Specifications - Supports random-access reads within stored files - Uses zstd compression (64KiB blocks) - Scales reasonably well up to multiple terabytes with millions of files - The theoretical size limit per-file is 2^48-1 (256 Terabyte) - The encoding for paths within the archive is Windows-1252 (case-insensitive) - Contains a SHA256 hash of the whole archive for integrity checks - Endian-independent. The format always uses big-endian internally - Stateless file and directory iterator handles which don&`#39`;t require memory allocation ## Example - Basic read file ```c++ `#include` "zarchive/zarchivereader.h" int main() { ZArchiveReader* reader = ZArchiveReader::OpenFromFile("archive.zar"); if (!reader) return -1; ZArchiveNodeHandle fileHandle = reader->LookUp("myfolder/example.bin"); if (reader->IsFile(fileHandle)) { uint8_t buffer[1000]; uint64_t n = reader->ReadFromFile(fileHandle, 0, 1000, buffer); // buffer now contains the first n (up to 1000) bytes of example.bin } delete reader; return 0; } ``` For a more detailed example see main.cpp ## Limitations - Not designed for adding, removing or modifying files after the archive has been created ## No-seek creation When creating new archives only byte append operations are used. No file seeking is necessary. This makes it possible to create archives on storage which is write-once. It also simplifies streaming ZArchive creation over network. ## UTF8 paths UTF8 for file and folder paths is theoretically supported as paths are just binary blobs. But the case-insensitive comparison only applies to latin letters (a-z). ## Wii U specifics Originally this format was created to store Wii U games dumps. These use the file extension .wua (Wii U Archive) but are otherwise regular ZArchive files. To allow multiple Wii U titles to be stored inside a single archive, each title must be placed in a subfolder following the naming scheme: 16-digit titleId followed by \_v and then the version as decimal. For example: 0005000e10102000_v32 ## License The ZArchive library is licensed under MIT No Attribution, with the exception of sha_256.c and sha_256.h which are public domain, see: https://github.com/amosnier/sha-2. github.com/cemu-project/Cemu@2913a8ca/src/Cafe/Filesystem/fscDeviceWua.cpp # src/Cafe/Filesystem/fscDeviceWua.cpp - Branch: 2913a8ca - Repository: cemu-project/Cemu --- `#include` "Cafe/Filesystem/fsc.h" `#include` class FSCDeviceWuaFileCtx : public FSCVirtualFile { friend class fscDeviceWUAC; protected: FSCDeviceWuaFileCtx(ZArchiveReader* archive, ZArchiveNodeHandle fstFileHandle, uint32 fscType) { this->m_archive = archive; this->m_fscType = fscType; this->m_nodeHandle = fstFileHandle; this->m_seek = 0; }; public: sint32 fscGetType() override { return m_fscType; } uint32 fscDeviceWuaFile_getFileSize() { return (uint32)m_archive->GetFileSize(m_nodeHandle); } uint64 fscQueryValueU64(uint32 id) override { if (m_fscType == FSC_TYPE_FILE) { if (id == FSC_QUERY_SIZE) return fscDeviceWuaFile_getFileSize(); else if (id == FSC_QUERY_WRITEABLE) return 0; // WUD images are read-only else cemu_assert_error(); } else { cemu_assert_unimplemented(); } return 0; } uint32 fscWriteData(void* buffer, uint32 size) override { cemu_assert_error(); return 0; } uint32 fscReadData(void* buffer, uint32 size) override { if (m_fscType != FSC_TYPE_FILE) return 0; cemu_assert(size < (2ULL * 1024 * 1024 * 1024)); // single read operation larger than 2GiB not supported uint32 bytesLeft = fscDeviceWuaFile_getFileSize() - m_seek; uint32 bytesToRead = (std::min)(bytesLeft, (uint32)size); uint32 bytesSuccessfullyRead = (uint32)m_archive->ReadFromFile(m_nodeHandle, m_seek, bytesToRead, buffer); m_seek += bytesSuccessfullyRead; return bytesSuccessfullyRead; } void fscSetSeek(uint64 seek) override { if (m_fscType != FSC_TYPE_FILE) return; cemu_assert_debug(seek <= 0xFFFFFFFFULL); this->m_seek = (uint32)seek; } uint64 fscGetSeek() override { if (m_fscType != FSC_TYPE_FILE) return 0; return m_seek; } bool fscDirNext(FSCDirEntry* dirEntry) override { if (m_fscType != FSC_TYPE_DIRECTORY) return false; ZArchiveReader::DirEntry zarDirEntry; if (!m_archive->GetDirEntry(m_nodeHandle, m_iteratorIndex, zarDirEntry)) return false; m_iteratorIndex++; if (zarDirEntry.isDirectory) { dirEntry->isDirectory = true; dirEntry->isFile = false; dirEntry->fileSize = 0; } else if(zarDirEntry.isFile) { dirEntry->isDirectory = false; dirEntry->isFile = true; dirEntry->fileSize = (uint32)zarDirEntry.size; } else { cemu_assert_suspicious(); } std::memset(dirEntry->path, 0, sizeof(dirEntry->path)); std::strncpy(dirEntry->path, zarDirEntry.name.data(), std::min(sizeof(dirEntry->path) - 1, zarDirEntry.name.size())); return true; } private: ZArchiveReader* m_archive{nullptr}; sint32 m_fscType; ZArchiveNodeHandle m_nodeHandle; // file uint32 m_seek{0}; // directory uint32 m_iteratorIndex{0}; }; class fscDeviceWUAC : public fscDeviceC { FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override { ZArchiveReader* archive = (ZArchiveReader*)ctx; cemu_assert_debug(!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::WRITE_PERMISSION)); // writing to WUA is not supported ZArchiveNodeHandle fileHandle = archive->LookUp(path, true, true); if (fileHandle == ZARCHIVE_INVALID_NODE) { *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } if (archive->IsFile(fileHandle)) { if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE)) { *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } *fscStatus = FSC_STATUS_OK; return new FSCDeviceWuaFileCtx(archive, fileHandle, FSC_TYPE_FILE); } else if (archive->IsDirectory(fileHandle)) { if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR)) { *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } *fscStatus = FSC_STATUS_OK; return new FSCDeviceWuaFileCtx(archive, fileHandle, FSC_TYPE_DIRECTORY); } else { cemu_assert_suspicious(); } *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } // singleton public: static fscDeviceWUAC& instance() { static fscDeviceWUAC _instance; return _instance; } }; bool FSCDeviceWUA_Mount(std::string_view mountPath, std::string_view destinationBaseDir, ZArc…[truncated] github.com/cemu-project/Cemu@2913a8ca/src/Cafe/OS/libs/nn_olv/nn_olv_OfflineDB.cpp namespace nn { namespace olv { std::mutex g_offlineDBMutex; bool g_offlineDBInitialized = false; ZArchiveReader* g_offlineDBArchive{nullptr}; void OfflineDB_LazyInit() { std::scoped_lock _l(g_offlineDBMutex); if(g_offlineDBInitialized) return; // open archive g_offlineDBArchive = ZArchiveReader::OpenFromFile(ActiveSettings::GetUserDataPath("resources/miiverse/OfflineDB.zar")); if(!g_offlineDBArchive) cemuLog_log(LogType::Force, "Offline miiverse posts are not available"); g_offlineDBInitialized = true; } void OfflineDB_Shutdown() { std::scoped_lock _l(g_offlineDBMutex); if(!g_offlineDBInitialized) return; delete g_offlineDBArchive; g_offlineDBInitialized = false; } bool CheckForOfflineDBFile(const char* filePath, uint32* fileSize) { if(!g_offlineDBArchive) return false; ZArchiveNodeHandle fileHandle = g_offlineDBArchive->LookUp(filePath); if (!g_offlineDBArchive->IsFile(fileHandle)) return false; if(fileSize) *fileSize = g_offlineDBArchive->GetFileSize(fileHandle); return true; } bool LoadOfflineDBFile(const char* filePath, std::vector & fileData) { fileData.clear(); if(!g_offlineDBArchive) return false; ZArchiveNodeHandle fileHandle = g_offlineDBArchive->LookUp(filePath); if (!g_offlineDBArchive->IsFile(fileHandle)) return false; fileData.resize(g_offlineDBArchive->GetFileSize(fileHandle)); g_offlineDBArchive->ReadFromFile(fileHandle, 0, fileData.size(), fileData.data()); return true; } void TryLoadCompressedMemoImage(DownloadedPostData& downloadedPostData) { const unsigned char tgaHeader_320x120_32BPP[] = {0x0,0x0,0x2,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x1,0x78,0x0,0x20,0x8}; std::string memo ... downloadedPostData.downloadedDataBase.postId

Citations:


Denial of Service

Reachability: External
Exploitability: Moderate
CWE: CWE-770 — Allocation of Resources Without Limits or Throttling

Bound archive member reads before whole-buffer allocation.

ReadPath allows any member up to INT_MAX, while Common::File::ReadWholeBuffer allocates the complete reported size. For .zar members, that size comes from ZArchiveReader::GetFileSize; ReadFromFile fills the caller-provided buffer and does not impose a smaller allocation limit. A member below INT_MAX can therefore trigger an allocation near 2 GiB.

ScanGameDirectory reads sce_sys/param.json automatically. Icon, background-image, and trophy-package display paths use the same whole-buffer API. Add a max_size parameter to ReadPath/ReadFile, and apply format-specific limits to JSON and image files. Bound trophy packages or change their parser to use bounded streaming/indexed reads instead of materializing the entire package and its entries.

✅ Addressed in commit 1bfe1cf

**@⁠coderabbitai[bot]** on GitHub · 2026-09-20 02:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#discussion_r4055882318) · edited 2026-09-26 22:06 UTC On `src/launcher/src/gameContent.cpp` line 55 (outdated): ```diff @@ -0,0 +1,69 @@ +#include "gameContent.h" + +#include "common/file.h" +#include "common/stringUtils.h" +#include "common/zarchive.h" + +#include <QFileInfo> + +#include <limits> + +namespace GameContent { + +std::filesystem::path ToPath(const QString& path) { +#if defined(_WIN32) + return std::filesystem::path(path.toStdWString()); +#else + return std::filesystem::path(path.toStdString()); +#endif +} + +QString FromPath(const std::filesystem::path& path) { +#if defined(_WIN32) + return QString::fromStdWString(path.wstring()); +#else + return QString::fromStdString(Common::PathToString(path)); +#endif +} + +bool IsArchive(const QString& base) { + const QFileInfo info(base); + return info.isFile() && info.suffix().compare(QStringLiteral("zar"), Qt::CaseInsensitive) == 0; +} + +std::filesystem::path Resolve(const QString& base, const QString& relative) { + const auto root = ToPath(base); + return IsArchive(base) ? Common::MakeZArchivePath(root, ToPath(relative)) + : root / ToPath(relative); +} + +bool FileExists(const QString& base, const QString& relative) { + return Common::File::IsFileExisting(Resolve(base, relative)); +} + +QByteArray ReadFile(const QString& base, const QString& relative) { + return ReadPath(Resolve(base, relative)); +} + +QByteArray ReadPath(const std::filesystem::path& path) { + Common::File file(path, Common::File::Mode::Read); + if (file.IsInvalid() || file.Size() > static_cast<uint64_t>(std::numeric_limits<int>::max())) { + return {}; + } + + const auto data = file.ReadWholeBuffer(); + return QByteArray(reinterpret_cast<const char*>(data.data()), static_cast<int>(data.size())); ``` _🔒 Security & Privacy_ | _🛡️ Analyzed with Security Review_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```bash sed -n '40,75p' src/launcher/src/gameContent.cpp sed -n '450,690p' src/launcher/src/configurationListWidget.cpp rg -n 'ReadFile\(|ReadPath\(|ReadWholeBuffer|QByteArray' src/launcher src/common/file.cpp src/common/file.h ``` Repository: KytyPS5/KytyPS5 Length of output: 13044 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- Common::File definitions and archive size handling ---' rg -n -C 8 'ReadWholeBuffer|File::Size|Size\(\)|fstat|stat|uncompressed|compressed|inflate|zlib|archive' src/common/file.cpp src/common/file.h src/common/zarchive.cpp src/common/zarchive.h printf '%s\n' '--- file.cpp around ReadWholeBuffer and nearby constructors/read methods ---' sed -n '300,455p' src/common/file.cpp printf '%s\n' '--- launcher asset and trophy callers ---' sed -n '100,150p' src/launcher/src/configurationListWidget.cpp sed -n '250,300p' src/launcher/src/configurationItem.cpp sed -n '70,210p' src/launcher/src/trophyViewerDialog.cpp sed -n '260,350p' src/launcher/src/trophyViewerDialog.cpp printf '%s\n' '--- archive implementation files ---' sed -n '1,260p' src/common/zarchive.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 50437 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- zarchive implementation ownership and build references ---' git ls-files | rg '(^|/)(zarchive|ZArchive)|zarchive' | head -120 rg -n -C 4 'zarchive|ZArchiveReader|BuildTrophySet|ReadUcp|ReadPath\(|ReadFile\(' CMakeLists.txt cmake src tests 2>/dev/null | head -260 printf '%s\n' '--- trophy callers and file discovery ---' rg -n -C 8 'BuildTrophySet|trophy.*ucp|\\.ucp|ReadUcp|LoadTrophyIcon|UpdateIcon|GetPic0' src/launcher/src src/launcher/include printf '%s\n' '--- exact archive read wrapper and launcher read paths ---' sed -n '116,153p' src/common/zarchive.cpp sed -n '256,282p' src/common/zarchive.cpp sed -n '420,434p' src/common/file.cpp sed -n '35,62p' src/launcher/src/gameContent.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 35476 --- 🌐 Web query: `"ZArchiveReader" "GetFileSize" "ReadFromFile"` 💡 Result: Inspection citation: inspection_324745f5eee71d4d79dff02b7a5511d3 <search_synthesis> ZArchiveReader is a C++ class provided by the ZArchive library, which is designed for creating and reading zstd-compressed file archives (.zar) [1]. The library is specifically engineered to support random-access reads within stored files [1]. The methods GetFileSize and ReadFromFile are core components of the ZArchiveReader API: 1. GetFileSize(ZArchiveNodeHandle handle): This method returns the size of a file within the archive, identified by its handle [2][3]. 2. ReadFromFile(ZArchiveNodeHandle handle, uint64_t offset, uint64_t size, void* buffer): This method reads a specified number of bytes from a file within the archive into a provided buffer, starting at a given offset [1]. These methods are commonly used in applications that require efficient, random-access retrieval of data from compressed archives, such as the Cemu emulator, which utilizes ZArchive for handling specific file system formats [2][3]. </search_synthesis> <source_evidence> <source> <title>Exzap/ZArchive</title> <location>https://github.com/Exzap/ZArchive</location> <excerpt># Exzap/ZArchive Library for creating and reading zstd-compressed file archives (.zar) - Stars: 159 - Forks: 19 - Watchers: 159 - Open issues: 14 - License: MIT No Attribution - Default branch: master - Created: 2022-04-25T18:40:28Z ## Languages - C - C++ - CMake ## Top Contributors - Exzap (11 contributions) - Tachi107 (3 contributions) - jaimeMF (3 contributions) - Crementif (2 contributions) - AdrianCassar (1 contributions) - SSimco (1 contributions) - SachinVin (1 contributions) - misuzu (1 contributions) --- ## README ## Overview ZArchive is yet another file archive format. Think of zip, tar, 7z, etc. but with the requirement of allowing random-access reads and supporting compression. ## Features / Specifications - Supports random-access reads within stored files - Uses zstd compression (64KiB blocks) - Scales reasonably well up to multiple terabytes with millions of files - The theoretical size limit per-file is 2^48-1 (256 Terabyte) - The encoding for paths within the archive is Windows-1252 (case-insensitive) - Contains a SHA256 hash of the whole archive for integrity checks - Endian-independent. The format always uses big-endian internally - Stateless file and directory iterator handles which don&`#39`;t require memory allocation ## Example - Basic read file ```c++ `#include` &quot;zarchive/zarchivereader.h&quot; int main() { ZArchiveReader* reader = ZArchiveReader::OpenFromFile(&quot;archive.zar&quot;); if (!reader) return -1; ZArchiveNodeHandle fileHandle = reader-&gt;LookUp(&quot;myfolder/example.bin&quot;); if (reader-&gt;IsFile(fileHandle)) { uint8_t buffer[1000]; uint64_t n = reader-&gt;ReadFromFile(fileHandle, 0, 1000, buffer); // buffer now contains the first n (up to 1000) bytes of example.bin } delete reader; return 0; } ``` For a more detailed example see main.cpp ## Limitations - Not designed for adding, removing or modifying files after the archive has been created ## No-seek creation When creating new archives only byte append operations are used. No file seeking is necessary. This makes it possible to create archives on storage which is write-once. It also simplifies streaming ZArchive creation over network. ## UTF8 paths UTF8 for file and folder paths is theoretically supported as paths are just binary blobs. But the case-insensitive comparison only applies to latin letters (a-z). ## Wii U specifics Originally this format was created to store Wii U games dumps. These use the file extension .wua (Wii U Archive) but are otherwise regular ZArchive files. To allow multiple Wii U titles to be stored inside a single archive, each title must be placed in a subfolder following the naming scheme: 16-digit titleId followed by \_v and then the version as decimal. For example: 0005000e10102000_v32 ## License The ZArchive library is licensed under MIT No Attribution, with the exception of sha_256.c and sha_256.h which are public domain, see: https://github.com/amosnier/sha-2.</excerpt> </source> <source> <title>src/Cafe/Filesystem/fscDeviceWua.cpp</title> <location>https://github.com/cemu-project/Cemu/blob/2913a8ca/src/Cafe/Filesystem/fscDeviceWua.cpp</location> <excerpt># src/Cafe/Filesystem/fscDeviceWua.cpp - Branch: 2913a8ca - Repository: cemu-project/Cemu --- `#include` &quot;Cafe/Filesystem/fsc.h&quot; `#include` class FSCDeviceWuaFileCtx : public FSCVirtualFile { friend class fscDeviceWUAC; protected: FSCDeviceWuaFileCtx(ZArchiveReader* archive, ZArchiveNodeHandle fstFileHandle, uint32 fscType) { this-&gt;m_archive = archive; this-&gt;m_fscType = fscType; this-&gt;m_nodeHandle = fstFileHandle; this-&gt;m_seek = 0; }; public: sint32 fscGetType() override { return m_fscType; } uint32 fscDeviceWuaFile_getFileSize() { return (uint32)m_archive-&gt;GetFileSize(m_nodeHandle); } uint64 fscQueryValueU64(uint32 id) override { if (m_fscType == FSC_TYPE_FILE) { if (id == FSC_QUERY_SIZE) return fscDeviceWuaFile_getFileSize(); else if (id == FSC_QUERY_WRITEABLE) return 0; // WUD images are read-only else cemu_assert_error(); } else { cemu_assert_unimplemented(); } return 0; } uint32 fscWriteData(void* buffer, uint32 size) override { cemu_assert_error(); return 0; } uint32 fscReadData(void* buffer, uint32 size) override { if (m_fscType != FSC_TYPE_FILE) return 0; cemu_assert(size &lt; (2ULL * 1024 * 1024 * 1024)); // single read operation larger than 2GiB not supported uint32 bytesLeft = fscDeviceWuaFile_getFileSize() - m_seek; uint32 bytesToRead = (std::min)(bytesLeft, (uint32)size); uint32 bytesSuccessfullyRead = (uint32)m_archive-&gt;ReadFromFile(m_nodeHandle, m_seek, bytesToRead, buffer); m_seek += bytesSuccessfullyRead; return bytesSuccessfullyRead; } void fscSetSeek(uint64 seek) override { if (m_fscType != FSC_TYPE_FILE) return; cemu_assert_debug(seek &lt;= 0xFFFFFFFFULL); this-&gt;m_seek = (uint32)seek; } uint64 fscGetSeek() override { if (m_fscType != FSC_TYPE_FILE) return 0; return m_seek; } bool fscDirNext(FSCDirEntry* dirEntry) override { if (m_fscType != FSC_TYPE_DIRECTORY) return false; ZArchiveReader::DirEntry zarDirEntry; if (!m_archive-&gt;GetDirEntry(m_nodeHandle, m_iteratorIndex, zarDirEntry)) return false; m_iteratorIndex++; if (zarDirEntry.isDirectory) { dirEntry-&gt;isDirectory = true; dirEntry-&gt;isFile = false; dirEntry-&gt;fileSize = 0; } else if(zarDirEntry.isFile) { dirEntry-&gt;isDirectory = false; dirEntry-&gt;isFile = true; dirEntry-&gt;fileSize = (uint32)zarDirEntry.size; } else { cemu_assert_suspicious(); } std::memset(dirEntry-&gt;path, 0, sizeof(dirEntry-&gt;path)); std::strncpy(dirEntry-&gt;path, zarDirEntry.name.data(), std::min(sizeof(dirEntry-&gt;path) - 1, zarDirEntry.name.size())); return true; } private: ZArchiveReader* m_archive{nullptr}; sint32 m_fscType; ZArchiveNodeHandle m_nodeHandle; // file uint32 m_seek{0}; // directory uint32 m_iteratorIndex{0}; }; class fscDeviceWUAC : public fscDeviceC { FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override { ZArchiveReader* archive = (ZArchiveReader*)ctx; cemu_assert_debug(!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::WRITE_PERMISSION)); // writing to WUA is not supported ZArchiveNodeHandle fileHandle = archive-&gt;LookUp(path, true, true); if (fileHandle == ZARCHIVE_INVALID_NODE) { *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } if (archive-&gt;IsFile(fileHandle)) { if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE)) { *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } *fscStatus = FSC_STATUS_OK; return new FSCDeviceWuaFileCtx(archive, fileHandle, FSC_TYPE_FILE); } else if (archive-&gt;IsDirectory(fileHandle)) { if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR)) { *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } *fscStatus = FSC_STATUS_OK; return new FSCDeviceWuaFileCtx(archive, fileHandle, FSC_TYPE_DIRECTORY); } else { cemu_assert_suspicious(); } *fscStatus = FSC_STATUS_FILE_NOT_FOUND; return nullptr; } // singleton public: static fscDeviceWUAC&amp; instance() { static fscDeviceWUAC _instance; return _instance; } }; bool FSCDeviceWUA_Mount(std::string_view mountPath, std::string_view destinationBaseDir, ZArc…[truncated]</excerpt> </source> <source> <title>src/Cafe/OS/libs/nn_olv/nn_olv_OfflineDB.cpp</title> <location>https://github.com/cemu-project/Cemu/blob/2913a8ca/src/Cafe/OS/libs/nn_olv/nn_olv_OfflineDB.cpp</location> <excerpt>namespace nn { namespace olv { std::mutex g_offlineDBMutex; bool g_offlineDBInitialized = false; ZArchiveReader* g_offlineDBArchive{nullptr}; void OfflineDB_LazyInit() { std::scoped_lock _l(g_offlineDBMutex); if(g_offlineDBInitialized) return; // open archive g_offlineDBArchive = ZArchiveReader::OpenFromFile(ActiveSettings::GetUserDataPath(&quot;resources/miiverse/OfflineDB.zar&quot;)); if(!g_offlineDBArchive) cemuLog_log(LogType::Force, &quot;Offline miiverse posts are not available&quot;); g_offlineDBInitialized = true; } void OfflineDB_Shutdown() { std::scoped_lock _l(g_offlineDBMutex); if(!g_offlineDBInitialized) return; delete g_offlineDBArchive; g_offlineDBInitialized = false; } bool CheckForOfflineDBFile(const char* filePath, uint32* fileSize) { if(!g_offlineDBArchive) return false; ZArchiveNodeHandle fileHandle = g_offlineDBArchive-&gt;LookUp(filePath); if (!g_offlineDBArchive-&gt;IsFile(fileHandle)) return false; if(fileSize) *fileSize = g_offlineDBArchive-&gt;GetFileSize(fileHandle); return true; } bool LoadOfflineDBFile(const char* filePath, std::vector &amp; fileData) { fileData.clear(); if(!g_offlineDBArchive) return false; ZArchiveNodeHandle fileHandle = g_offlineDBArchive-&gt;LookUp(filePath); if (!g_offlineDBArchive-&gt;IsFile(fileHandle)) return false; fileData.resize(g_offlineDBArchive-&gt;GetFileSize(fileHandle)); g_offlineDBArchive-&gt;ReadFromFile(fileHandle, 0, fileData.size(), fileData.data()); return true; } void TryLoadCompressedMemoImage(DownloadedPostData&amp; downloadedPostData) { const unsigned char tgaHeader_320x120_32BPP[] = {0x0,0x0,0x2,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x1,0x78,0x0,0x20,0x8}; std::string memo ... downloadedPostData.downloadedDataBase.postId</excerpt> </source> </source_evidence> Citations: - 1: https://github.com/Exzap/ZArchive - 2: https://github.com/cemu-project/Cemu/blob/2913a8ca/src/Cafe/Filesystem/fscDeviceWua.cpp - 3: https://github.com/cemu-project/Cemu/blob/2913a8ca/src/Cafe/OS/libs/nn_olv/nn_olv_OfflineDB.cpp --- </details> <!-- cr-reachability --> **Denial of Service** **Reachability:** External **Exploitability:** Moderate **CWE:** [CWE-770](https://cwe.mitre.org/data/definitions/770.html) — Allocation of Resources Without Limits or Throttling **Bound archive member reads before whole-buffer allocation.** `ReadPath` allows any member up to `INT_MAX`, while `Common::File::ReadWholeBuffer` allocates the complete reported size. For `.zar` members, that size comes from `ZArchiveReader::GetFileSize`; `ReadFromFile` fills the caller-provided buffer and does not impose a smaller allocation limit. A member below `INT_MAX` can therefore trigger an allocation near 2 GiB. `ScanGameDirectory` reads `sce_sys/param.json` automatically. Icon, background-image, and trophy-package display paths use the same whole-buffer API. Add a `max_size` parameter to `ReadPath`/`ReadFile`, and apply format-specific limits to JSON and image files. Bound trophy packages or change their parser to use bounded streaming/indexed reads instead of materializing the entire package and its entries. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:d1866863a7e6647c92c2184f --> <!-- This is an auto-generated comment by CodeRabbit --> ✅ Addressed in commit 1bfe1cf
Author
Owner

@⁠Heliumrich on GitHub · 2026-09-21 17:32 UTC · original

Amazing, I imagine this will work well with updates/DLCs as other .zar archive files, loaded ontop ?
And what about modding game files, can we load a loose folder ontop ?

**@⁠Heliumrich** on GitHub · 2026-09-21 17:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5764758656) Amazing, I imagine this will work well with updates/DLCs as other .zar archive files, loaded ontop ? And what about modding game files, can we load a loose folder ontop ?
Author
Owner

@⁠fab918 on GitHub · 2026-09-21 21:14 UTC · original

Could you provide the file size and loading time figures before and after compression for a few games?

**@⁠fab918** on GitHub · 2026-09-21 21:14 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5767614899) Could you provide the file size and loading time figures before and after compression for a few games?
Author
Owner

@⁠Crispy81 on GitHub · 2026-09-22 13:16 UTC · original

Be interesting to see how much space is saved and also if there's any overhead ie - longer processing/boot times/CPU usage, etc...

**@⁠Crispy81** on GitHub · 2026-09-22 13:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5777223180) Be interesting to see how much space is saved and also if there's any overhead ie - longer processing/boot times/CPU usage, etc...
Author
Owner

@⁠Heliumrich on GitHub · 2026-09-22 20:27 UTC · original · edited 2026-09-22 20:35 UTC

That's just classic Zstandard (zstd), if there are uncompressed files it can save quite a lot, but usually what takes the most storage space are textures, and they are barely compressible, so it will probably save between 1-10% for 95% of games.

There is a tiny CPU overhead yes, but with modern (multicore) CPUs it's probably not even detectable through benchmark noise.

For me the best thing about this is the rare times I need to copy dumps over to an external SSD or whatever ; +200k files through your SSD controller (and worse, USB controller) slow things down a lot...

**@⁠Heliumrich** on GitHub · 2026-09-22 20:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5783620592) · edited 2026-09-22 20:35 UTC That's just classic Zstandard (zstd), if there are uncompressed files it can save quite a lot, but usually what takes the most storage space are textures, and they are barely compressible, so it will probably save between 1-10% for 95% of games. There is a tiny CPU overhead yes, but with modern (multicore) CPUs it's probably not even detectable through benchmark noise. For me the best thing about this is the rare times I need to copy dumps over to an external SSD or whatever ; +200k files through your SSD controller (and worse, USB controller) slow things down a lot...
Author
Owner

@⁠ew-sudo on GitHub · 2026-09-26 14:26 UTC · original

Tested this PR with Astro Bot (PPSA21564, 01.007) on Windows 11 (Intel Core Ultra 7 155H, RTX 4070 Laptop), merged on top of #780. The archive loads and every file read matches the folder dump, but the game crashed or hung about 16 s in. I tracked it down and have a fix below.

Size and performance (answering the questions above)

  • Folder dump: 148 GiB. .zar (ZArchive v0.1.2 CLI, default settings): 45.2 GiB, about 3.3x smaller. Astro Bot's data is stored uncompressed inside the PS5 package (the console compresses the package itself), so the dump is large and zstd recovers a lot.
  • This gain is specific to games like Astro Bot. Games that ship their data already compressed should gain much less: for example, Sackboy (Unreal Engine) is 56 GB, 54.5 GB of it in .pak files that are already compressed. I have not built a .zar for it.
  • In-game frame rate is the same as from the folder.

The bug

From the .zar the game either hung or stopped with:

Not implemented (*cond == nullptr) in src/kernel/pthread.cpp:2820

From the folder, with the same build, it works.

What I measured:

  • Up to the crash, both runs perform the same 6031 opens and 6030 reads, and every read returns the same number of bytes.
  • The crash happens during one read: hero_umbrella_stick_d.gnfp, 0x20000 bytes into texture memory (0x10c84c0000). The read enters ZArchiveFile::Read, takes the reader lock at once, and never returns.
  • About 1 ms after the read starts, a guest pthread_cond_t at 0x3135478e0 (the game's "Draw Extra Geometry" render thread cond, created at 10.6 s and never destroyed) is overwritten with zero. When the emulator re-initialises it lazily, it is zeroed again within 10 µs. No emulator write path I instrumented touches that address (buffer/texture write-backs through WriteBacking, GPU CopyBuffer, file reads).
  • The read runs on GfxTextureStreamerThread, whose guest stack is only 64 KiB at 0x313550000–0x313560000. The corrupted cond is about 34 KiB below the bottom of that stack. The thread's stack pointer when it enters the read is 0x31355F840, so it has used only about 2 KiB so far.
  • Control test: the folder path with the read forced through a host buffer + memcpy into guest memory (the same copy the archive path does) works. So the copy into GPU-tracked memory is not the problem by itself.

So the corruption happens while the ZArchive/zstd read code runs on that small guest stack. I have not proven the exact mechanism. My guess: the deeper call chain writes into guest stack pages that GPU tracking has write-protected, and on Windows the fault is handled on that same stack, which walks further down into the memory below. Linux uses sigaltstack for this reason (see InitializeThreadSignalStack); Windows has no equivalent here.

Fix

Run the archive read/decompression on one dedicated host thread with a normal stack. The calling guest thread only waits, then copies the result into the destination, like a regular host file read. With this change Astro Bot runs from the .zar past that point and plays normally. I also checked it on Linux with 8 threads on 64 KiB stacks reading random ranges of a test archive in parallel: all data matched the source files.

Patch (src/common/zarchive.cpp)
diff --git a/src/common/zarchive.cpp b/src/common/zarchive.cpp
index 64283ca9..81ec9d66 100644
--- a/src/common/zarchive.cpp
+++ b/src/common/zarchive.cpp
@@ -3,10 +3,16 @@
 #include "common/stringUtils.h"
 
 #include <algorithm>
+#include <condition_variable>
+#include <cstring>
+#include <deque>
+#include <functional>
 #include <mutex>
 #include <string_view>
+#include <thread>
 #include <unordered_map>
 #include <utility>
+#include <vector>
 #include <zarchive/zarchivereader.h>
 
 namespace Common {
@@ -103,6 +109,64 @@ std::shared_ptr<SharedReader> GetReader(const std::filesystem::path& archive) {
 	return shared;
 }
 
+// Guest threads execute emulator code on their own guest stacks, which can be small (Astro Bot
+// streams textures from a thread with a 64 KiB stack). Running the archive read and zstd
+// decompression there corrupted guest memory just below that stack and hung the read, while
+// a plain host file read on the same thread works. Decompress on one host thread with a normal
+// host stack; the calling thread only copies the result, like a regular file read.
+class ArchiveIoThread {
+public:
+	static ArchiveIoThread& Instance() {
+		// Never destroyed: the worker thread runs until the process exits.
+		static auto* instance = new ArchiveIoThread;
+		return *instance;
+	}
+
+	void Run(const std::function<void()>& job) {
+		Job             pending {&job};
+		std::unique_lock lock(m_mutex);
+		m_jobs.push_back(&pending);
+		m_wake.notify_one();
+		m_done.wait(lock, [&pending] { return pending.done; });
+	}
+
+	KYTY_CLASS_NO_COPY(ArchiveIoThread);
+
+private:
+	struct Job {
+		const std::function<void()>* fn   = nullptr;
+		bool                         done = false;
+	};
+
+	ArchiveIoThread() {
+		std::thread([this] { Loop(); }).detach();
+	}
+	~ArchiveIoThread() = default;
+
+	[[noreturn]] void Loop() {
+		for (;;) {
+			Job* job = nullptr;
+			{
+				std::unique_lock lock(m_mutex);
+				m_wake.wait(lock, [this] { return !m_jobs.empty(); });
+				job = m_jobs.front();
+				m_jobs.pop_front();
+			}
+			(*job->fn)();
+			{
+				std::lock_guard lock(m_mutex);
+				job->done = true;
+			}
+			m_done.notify_all();
+		}
+	}
+
+	std::mutex              m_mutex;
+	std::condition_variable m_wake;
+	std::condition_variable m_done;
+	std::deque<Job*>        m_jobs;
+};
+
 ZArchiveNodeHandle Lookup(const std::shared_ptr<SharedReader>& reader, std::string_view member) {
 	if (reader == nullptr || reader->reader == nullptr) {
 		return ZARCHIVE_INVALID_NODE;
@@ -139,12 +203,35 @@ bool ZArchiveFile::Seek(uint64_t offset) {
 }
 
 void ZArchiveFile::Read(void* data, uint32_t size, uint32_t* bytes_read) {
+	// The archive thread decompresses into this host buffer; the copy into the destination,
+	// which is often guest memory tracked for the GPU, stays on the calling thread like a
+	// regular host file read.
+	constexpr uint64_t                chunk_size = uint64_t {1} << 20u;
+	thread_local std::vector<uint8_t> chunk;
+
 	uint64_t read = 0;
 	if (data != nullptr && size != 0 && m_p->position < m_p->size) {
-		const auto      requested = std::min<uint64_t>(size, m_p->size - m_p->position);
-		std::lock_guard lock(m_p->reader->mutex);
-		read = m_p->reader->reader->ReadFromFile(m_p->node, m_p->position, requested, data);
-		m_p->position += read;
+		const auto requested = std::min<uint64_t>(size, m_p->size - m_p->position);
+		if (chunk.size() < chunk_size) {
+			chunk.resize(chunk_size);
+		}
+		auto* dst = static_cast<uint8_t*>(data);
+		while (read < requested) {
+			const auto step = std::min<uint64_t>(chunk_size, requested - read);
+			uint64_t   got    = 0;
+			auto*      buffer = chunk.data(); // thread_local: take this thread's buffer
+			const std::function<void()> job = [this, step, buffer, &got] {
+				std::lock_guard lock(m_p->reader->mutex);
+				got = m_p->reader->reader->ReadFromFile(m_p->node, m_p->position, step, buffer);
+			};
+			ArchiveIoThread::Instance().Run(job);
+			if (got == 0) {
+				break;
+			}
+			std::memcpy(dst + read, chunk.data(), got);
+			read += got;
+			m_p->position += got;
+		}
 	}
 	if (bytes_read != nullptr) {
 		*bytes_read = static_cast<uint32_t>(read);

Happy to open this as a PR against your branch if you prefer.

I used Claude to write this; I built and tested it myself.

**@⁠ew-sudo** on GitHub · 2026-09-26 14:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5847042322) Tested this PR with Astro Bot (PPSA21564, 01.007) on Windows 11 (Intel Core Ultra 7 155H, RTX 4070 Laptop), merged on top of #780. The archive loads and every file read matches the folder dump, but the game crashed or hung about 16 s in. I tracked it down and have a fix below. ### Size and performance (answering the questions above) - Folder dump: **148 GiB**. `.zar` (ZArchive v0.1.2 CLI, default settings): **45.2 GiB**, about 3.3x smaller. Astro Bot's data is stored uncompressed inside the PS5 package (the console compresses the package itself), so the dump is large and zstd recovers a lot. - This gain is specific to games like Astro Bot. Games that ship their data already compressed should gain much less: for example, Sackboy (Unreal Engine) is 56 GB, 54.5 GB of it in `.pak` files that are already compressed. I have not built a `.zar` for it. - In-game frame rate is the same as from the folder. ### The bug From the `.zar` the game either hung or stopped with: ``` Not implemented (*cond == nullptr) in src/kernel/pthread.cpp:2820 ``` From the folder, with the same build, it works. What I measured: - Up to the crash, both runs perform the same 6031 opens and 6030 reads, and every read returns the same number of bytes. - The crash happens during one read: `hero_umbrella_stick_d.gnfp`, 0x20000 bytes into texture memory (`0x10c84c0000`). The read enters `ZArchiveFile::Read`, takes the reader lock at once, and never returns. - About 1 ms after the read starts, a guest `pthread_cond_t` at `0x3135478e0` (the game's "Draw Extra Geometry" render thread cond, created at 10.6 s and never destroyed) is overwritten with zero. When the emulator re-initialises it lazily, it is zeroed again within 10 µs. No emulator write path I instrumented touches that address (buffer/texture write-backs through `WriteBacking`, GPU `CopyBuffer`, file reads). - The read runs on `GfxTextureStreamerThread`, whose guest stack is only **64 KiB** at `0x313550000`–`0x313560000`. The corrupted cond is about 34 KiB below the bottom of that stack. The thread's stack pointer when it enters the read is `0x31355F840`, so it has used only about 2 KiB so far. - Control test: the folder path with the read forced through a host buffer + `memcpy` into guest memory (the same copy the archive path does) works. So the copy into GPU-tracked memory is not the problem by itself. So the corruption happens while the ZArchive/zstd read code runs **on that small guest stack**. I have not proven the exact mechanism. My guess: the deeper call chain writes into guest stack pages that GPU tracking has write-protected, and on Windows the fault is handled on that same stack, which walks further down into the memory below. Linux uses `sigaltstack` for this reason (see `InitializeThreadSignalStack`); Windows has no equivalent here. ### Fix Run the archive read/decompression on one dedicated host thread with a normal stack. The calling guest thread only waits, then copies the result into the destination, like a regular host file read. With this change Astro Bot runs from the `.zar` past that point and plays normally. I also checked it on Linux with 8 threads on 64 KiB stacks reading random ranges of a test archive in parallel: all data matched the source files. <details> <summary>Patch (src/common/zarchive.cpp)</summary> ```diff diff --git a/src/common/zarchive.cpp b/src/common/zarchive.cpp index 64283ca9..81ec9d66 100644 --- a/src/common/zarchive.cpp +++ b/src/common/zarchive.cpp @@ -3,10 +3,16 @@ #include "common/stringUtils.h" #include <algorithm> +#include <condition_variable> +#include <cstring> +#include <deque> +#include <functional> #include <mutex> #include <string_view> +#include <thread> #include <unordered_map> #include <utility> +#include <vector> #include <zarchive/zarchivereader.h> namespace Common { @@ -103,6 +109,64 @@ std::shared_ptr<SharedReader> GetReader(const std::filesystem::path& archive) { return shared; } +// Guest threads execute emulator code on their own guest stacks, which can be small (Astro Bot +// streams textures from a thread with a 64 KiB stack). Running the archive read and zstd +// decompression there corrupted guest memory just below that stack and hung the read, while +// a plain host file read on the same thread works. Decompress on one host thread with a normal +// host stack; the calling thread only copies the result, like a regular file read. +class ArchiveIoThread { +public: + static ArchiveIoThread& Instance() { + // Never destroyed: the worker thread runs until the process exits. + static auto* instance = new ArchiveIoThread; + return *instance; + } + + void Run(const std::function<void()>& job) { + Job pending {&job}; + std::unique_lock lock(m_mutex); + m_jobs.push_back(&pending); + m_wake.notify_one(); + m_done.wait(lock, [&pending] { return pending.done; }); + } + + KYTY_CLASS_NO_COPY(ArchiveIoThread); + +private: + struct Job { + const std::function<void()>* fn = nullptr; + bool done = false; + }; + + ArchiveIoThread() { + std::thread([this] { Loop(); }).detach(); + } + ~ArchiveIoThread() = default; + + [[noreturn]] void Loop() { + for (;;) { + Job* job = nullptr; + { + std::unique_lock lock(m_mutex); + m_wake.wait(lock, [this] { return !m_jobs.empty(); }); + job = m_jobs.front(); + m_jobs.pop_front(); + } + (*job->fn)(); + { + std::lock_guard lock(m_mutex); + job->done = true; + } + m_done.notify_all(); + } + } + + std::mutex m_mutex; + std::condition_variable m_wake; + std::condition_variable m_done; + std::deque<Job*> m_jobs; +}; + ZArchiveNodeHandle Lookup(const std::shared_ptr<SharedReader>& reader, std::string_view member) { if (reader == nullptr || reader->reader == nullptr) { return ZARCHIVE_INVALID_NODE; @@ -139,12 +203,35 @@ bool ZArchiveFile::Seek(uint64_t offset) { } void ZArchiveFile::Read(void* data, uint32_t size, uint32_t* bytes_read) { + // The archive thread decompresses into this host buffer; the copy into the destination, + // which is often guest memory tracked for the GPU, stays on the calling thread like a + // regular host file read. + constexpr uint64_t chunk_size = uint64_t {1} << 20u; + thread_local std::vector<uint8_t> chunk; + uint64_t read = 0; if (data != nullptr && size != 0 && m_p->position < m_p->size) { - const auto requested = std::min<uint64_t>(size, m_p->size - m_p->position); - std::lock_guard lock(m_p->reader->mutex); - read = m_p->reader->reader->ReadFromFile(m_p->node, m_p->position, requested, data); - m_p->position += read; + const auto requested = std::min<uint64_t>(size, m_p->size - m_p->position); + if (chunk.size() < chunk_size) { + chunk.resize(chunk_size); + } + auto* dst = static_cast<uint8_t*>(data); + while (read < requested) { + const auto step = std::min<uint64_t>(chunk_size, requested - read); + uint64_t got = 0; + auto* buffer = chunk.data(); // thread_local: take this thread's buffer + const std::function<void()> job = [this, step, buffer, &got] { + std::lock_guard lock(m_p->reader->mutex); + got = m_p->reader->reader->ReadFromFile(m_p->node, m_p->position, step, buffer); + }; + ArchiveIoThread::Instance().Run(job); + if (got == 0) { + break; + } + std::memcpy(dst + read, chunk.data(), got); + read += got; + m_p->position += got; + } } if (bytes_read != nullptr) { *bytes_read = static_cast<uint32_t>(read); ``` </details> Happy to open this as a PR against your branch if you prefer. I used Claude to write this; I built and tested it myself.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 22:16 UTC · original
On src/common/zarchive.cpp line 41 (outdated):

@@ -0,0 +1,397 @@
+#include "common/zarchive.h"
+
+#include "common/stringUtils.h"
+
+#include <algorithm>
+#include <condition_variable>
+#include <cstring>
+#include <deque>
+#include <functional>
+#include <mutex>
+#include <string_view>
+#include <thread>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+#include <zarchive/zarchivereader.h>
+
+namespace Common {
+
+namespace {
+
+constexpr uint32_t MaxDirectoryEntries = 1u << 20u;
+
+struct ParsedPath {
+	std::filesystem::path archive;
+	std::string           member;
+	bool                  valid = false;
+};
+
+struct SharedReader {
+	explicit SharedReader(ZArchiveReader* value): reader(value) {}
+	~SharedReader() { delete reader; }
+
+	KYTY_CLASS_NO_COPY(SharedReader);
+
+	ZArchiveReader* reader;
+	std::mutex      mutex;
+};
+
+std::mutex                                                   g_readers_mutex;
+std::unordered_map<std::string, std::weak_ptr<SharedReader>> g_readers;

🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- diff ---'
git diff --stat 82b2711cdf47b2b2b1bb34fd54d93c8e813dc120 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6 -- src/common/zarchive.cpp
git diff --unified=80 82b2711cdf47b2b2b1bb34fd54d93c8e813dc120 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6 -- src/common/zarchive.cpp
printf '%s\n' '--- current source around cache/open ---'
nl -ba src/common/zarchive.cpp | sed -n '1,240p'
printf '%s\n' '--- ZArchive references and pins ---'
rg -n --hidden -S 'ZArchive|zarchive|zarchivereader|OpenFromFile|SharedReader' -g '!node_modules' -g '!build' -g '!dist' .

Repository: KytyPS5/KytyPS5

Length of output: 31888


🏁 Script executed:

set -eu
printf '%s\n' '--- repository files ---'
git ls-files | rg -i '(^|/)(zarchive|third.party|third_party|deps?|vendor|submodule|cmake|meson|conan|vcpkg|package|lock)' | head -200
printf '%s\n' '--- changed source ---'
nl -ba src/common/zarchive.cpp | sed -n '1,280p'
printf '%s\n' '--- references ---'
rg -n --hidden -S 'ZArchive|zarchive|zarchivereader|OpenFromFile|SharedReader' -g '!node_modules' -g '!build' -g '!dist' .
printf '%s\n' '--- revision availability ---'
git rev-parse --verify 82b2711cdf47b2b2b1bb34fd54d93c8e813dc120^{commit}
git rev-parse --verify 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6^{commit}

Repository: KytyPS5/KytyPS5

Length of output: 22350


🌐 Web query:

ZArchive GitHub zarchivereader.cpp OpenFromFile reader cache initialization

💡 Result:

`OpenFromFile` does **not** initialize the cache directly. It opens the file and delegates to `OpenFromStream`; after validating the archive and loading its index tables, `OpenFromStream` constructs a `ZArchiveReader` (lines 27–34, 94–99). ([raw.githubusercontent.com](https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp))

Cache initialization happens in the reader’s constructor (lines 101–121): it allocates a 4 MiB data buffer, rounds its size up to a multiple of the compressed-block size, creates one cache descriptor per block, marks each descriptor unused (`blockIndex = UINT64_MAX`), assigns its data slice, and links the descriptors into an LRU list. The first read loads a block on demand; subsequent accesses use the lookup map and update the LRU order. ([raw.githubusercontent.com](https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp))

Citations:

- 1: https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp
- 2: https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp

🏁 Script executed:

set -eu
nl -ba 3rdparty/CMakeLists.txt | sed -n '20,85p'
rg -n --hidden -S 'GIT_TAG|Exzap/ZArchive|ZArchive.git|zarchive_source' 3rdparty CMakeLists.txt .github README.md

Repository: KytyPS5/KytyPS5

Length of output: 3779


🌐 Web query:

https://raw.githubusercontent.com/Exzap/ZArchive/d2c717730092c7bf8cbb033b12fd4001b7c4d932/src/zarchivereader.cpp

💡 Result:

This is the **ZArchive reader implementation**. It opens and validates an archive, reads its file and directory tables, supports path lookup and file reads, and caches decompressed blocks using an LRU cache. [1]

What would you like me to do with it—explain the code, review it for bugs, or summarize a particular function? ([raw.githubusercontent.com](https://raw.githubusercontent.com/Exzap/ZArchive/d2c717730092c7bf8cbb033b12fd4001b7c4d932/src/zarchivereader.cpp))

Citations:

- 1: https://raw.githubusercontent.com/Exzap/ZArchive/d2c717730092c7bf8cbb033b12fd4001b7c4d932/src/zarchivereader.cpp

Retain readers during repeated archive lookups.

g_readers stores weak_ptr values. Metadata helpers release their local shared_ptr when each query returns, so the next query can call OpenFromFile again. The pinned ZArchive revision reads the archive tables and creates a decompressed-block LRU cache during reader initialization. Repeated file and directory queries can therefore reload the tables and recreate the cache.

Keep a bounded strong reader cache with an explicit eviction and invalidation policy.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 22:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#discussion_r4112999076) On `src/common/zarchive.cpp` line 41 (outdated): ```diff @@ -0,0 +1,397 @@ +#include "common/zarchive.h" + +#include "common/stringUtils.h" + +#include <algorithm> +#include <condition_variable> +#include <cstring> +#include <deque> +#include <functional> +#include <mutex> +#include <string_view> +#include <thread> +#include <unordered_map> +#include <utility> +#include <vector> +#include <zarchive/zarchivereader.h> + +namespace Common { + +namespace { + +constexpr uint32_t MaxDirectoryEntries = 1u << 20u; + +struct ParsedPath { + std::filesystem::path archive; + std::string member; + bool valid = false; +}; + +struct SharedReader { + explicit SharedReader(ZArchiveReader* value): reader(value) {} + ~SharedReader() { delete reader; } + + KYTY_CLASS_NO_COPY(SharedReader); + + ZArchiveReader* reader; + std::mutex mutex; +}; + +std::mutex g_readers_mutex; +std::unordered_map<std::string, std::weak_ptr<SharedReader>> g_readers; ``` _🚀 Performance & Scalability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu printf '%s\n' '--- diff ---' git diff --stat 82b2711cdf47b2b2b1bb34fd54d93c8e813dc120 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6 -- src/common/zarchive.cpp git diff --unified=80 82b2711cdf47b2b2b1bb34fd54d93c8e813dc120 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6 -- src/common/zarchive.cpp printf '%s\n' '--- current source around cache/open ---' nl -ba src/common/zarchive.cpp | sed -n '1,240p' printf '%s\n' '--- ZArchive references and pins ---' rg -n --hidden -S 'ZArchive|zarchive|zarchivereader|OpenFromFile|SharedReader' -g '!node_modules' -g '!build' -g '!dist' . ``` Repository: KytyPS5/KytyPS5 Length of output: 31888 --- 🏁 Script executed: ```bash set -eu printf '%s\n' '--- repository files ---' git ls-files | rg -i '(^|/)(zarchive|third.party|third_party|deps?|vendor|submodule|cmake|meson|conan|vcpkg|package|lock)' | head -200 printf '%s\n' '--- changed source ---' nl -ba src/common/zarchive.cpp | sed -n '1,280p' printf '%s\n' '--- references ---' rg -n --hidden -S 'ZArchive|zarchive|zarchivereader|OpenFromFile|SharedReader' -g '!node_modules' -g '!build' -g '!dist' . printf '%s\n' '--- revision availability ---' git rev-parse --verify 82b2711cdf47b2b2b1bb34fd54d93c8e813dc120^{commit} git rev-parse --verify 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6^{commit} ``` Repository: KytyPS5/KytyPS5 Length of output: 22350 --- 🌐 Web query: `ZArchive GitHub zarchivereader.cpp OpenFromFile reader cache initialization` 💡 Result: ``` `OpenFromFile` does **not** initialize the cache directly. It opens the file and delegates to `OpenFromStream`; after validating the archive and loading its index tables, `OpenFromStream` constructs a `ZArchiveReader` (lines 27–34, 94–99). ([raw.githubusercontent.com](https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp)) Cache initialization happens in the reader’s constructor (lines 101–121): it allocates a 4 MiB data buffer, rounds its size up to a multiple of the compressed-block size, creates one cache descriptor per block, marks each descriptor unused (`blockIndex = UINT64_MAX`), assigns its data slice, and links the descriptors into an LRU list. The first read loads a block on demand; subsequent accesses use the lookup map and update the LRU order. ([raw.githubusercontent.com](https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp)) Citations: - 1: https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp - 2: https://raw.githubusercontent.com/Exzap/ZArchive/master/src/zarchivereader.cpp ``` --- 🏁 Script executed: ```bash set -eu nl -ba 3rdparty/CMakeLists.txt | sed -n '20,85p' rg -n --hidden -S 'GIT_TAG|Exzap/ZArchive|ZArchive.git|zarchive_source' 3rdparty CMakeLists.txt .github README.md ``` Repository: KytyPS5/KytyPS5 Length of output: 3779 --- 🌐 Web query: `https://raw.githubusercontent.com/Exzap/ZArchive/d2c717730092c7bf8cbb033b12fd4001b7c4d932/src/zarchivereader.cpp` 💡 Result: ``` This is the **ZArchive reader implementation**. It opens and validates an archive, reads its file and directory tables, supports path lookup and file reads, and caches decompressed blocks using an LRU cache. [1] What would you like me to do with it—explain the code, review it for bugs, or summarize a particular function? ([raw.githubusercontent.com](https://raw.githubusercontent.com/Exzap/ZArchive/d2c717730092c7bf8cbb033b12fd4001b7c4d932/src/zarchivereader.cpp)) Citations: - 1: https://raw.githubusercontent.com/Exzap/ZArchive/d2c717730092c7bf8cbb033b12fd4001b7c4d932/src/zarchivereader.cpp ``` --- </details> **Retain readers during repeated archive lookups.** `g_readers` stores `weak_ptr` values. Metadata helpers release their local `shared_ptr` when each query returns, so the next query can call `OpenFromFile` again. The pinned ZArchive revision reads the archive tables and creates a decompressed-block LRU cache during reader initialization. Repeated file and directory queries can therefore reload the tables and recreate the cache. Keep a bounded strong reader cache with an explicit eviction and invalidation policy. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f2ad2354d7750f03a3ccdda9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 22:16 UTC · original
On src/common/zarchive.cpp line 175 (outdated):

@@ -0,0 +1,397 @@
+#include "common/zarchive.h"
+
+#include "common/stringUtils.h"
+
+#include <algorithm>
+#include <condition_variable>
+#include <cstring>
+#include <deque>
+#include <functional>
+#include <mutex>
+#include <string_view>
+#include <thread>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+#include <zarchive/zarchivereader.h>
+
+namespace Common {
+
+namespace {
+
+constexpr uint32_t MaxDirectoryEntries = 1u << 20u;
+
+struct ParsedPath {
+	std::filesystem::path archive;
+	std::string           member;
+	bool                  valid = false;
+};
+
+struct SharedReader {
+	explicit SharedReader(ZArchiveReader* value): reader(value) {}
+	~SharedReader() { delete reader; }
+
+	KYTY_CLASS_NO_COPY(SharedReader);
+
+	ZArchiveReader* reader;
+	std::mutex      mutex;
+};
+
+std::mutex                                                   g_readers_mutex;
+std::unordered_map<std::string, std::weak_ptr<SharedReader>> g_readers;
+
+bool ParsePath(const std::filesystem::path& path, ParsedPath* parsed) {
+	auto       text      = path.native();
+	const auto slash     = std::filesystem::path("/").native().front();
+	const auto backslash = std::filesystem::path("\\").native().front();
+	std::replace(text.begin(), text.end(), backslash, slash);
+	auto lower = text;
+	for (auto& c: lower) {
+		const auto upper_a = static_cast<std::filesystem::path::value_type>('A');
+		const auto upper_z = static_cast<std::filesystem::path::value_type>('Z');
+		if (c >= upper_a && c <= upper_z) {
+			c += static_cast<std::filesystem::path::value_type>('a' - 'A');
+		}
+	}
+	const auto marker_text = std::filesystem::path(".zar!").native();
+	auto       marker      = lower.find(marker_text);
+	if (marker == std::filesystem::path::string_type::npos) {
+		return false;
+	}
+	auto mark = marker + 4;
+	if ((mark + 1 < text.size() && text[mark + 1] != slash)) {
+		return false;
+	}
+
+	auto member_native =
+	    mark + 1 < text.size() ? text.substr(mark + 1) : std::filesystem::path::string_type {};
+	std::string member = Common::PathToGenericString(std::filesystem::path(member_native));
+	while (member.starts_with('/')) {
+		member.erase(0, 1);
+	}
+
+	std::vector<std::string> components;
+	bool                     valid = true;
+	for (const auto& component: Common::Split(member, "/")) {
+		if (component.empty() || component == ".") {
+			continue;
+		}
+		if (component == "..") {
+			if (components.empty()) {
+				valid = false;
+				continue;
+			}
+			components.pop_back();
+			continue;
+		}
+		components.push_back(component);
+	}
+
+	if (parsed != nullptr) {
+		parsed->archive = std::filesystem::path(text.substr(0, mark));
+		for (const auto& component: components) {
+			if (!parsed->member.empty()) {
+				parsed->member += '/';
+			}
+			parsed->member += component;
+		}
+		parsed->valid = valid;
+	}
+	return true;
+}
+
+std::shared_ptr<SharedReader> GetReader(const std::filesystem::path& archive) {
+	auto key = Common::PathToGenericString(archive);
+#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS
+	key = Common::ToLower(key);
+#endif
+
+	std::lock_guard lock(g_readers_mutex);
+	if (auto it = g_readers.find(key); it != g_readers.end()) {
+		if (auto reader = it->second.lock()) {
+			return reader;
+		}
+		g_readers.erase(it);
+	}
+	std::erase_if(g_readers, [](const auto& entry) { return entry.second.expired(); });
+
+	auto* reader = ZArchiveReader::OpenFromFile(archive);
+	if (reader == nullptr) {
+		return {};
+	}
+
+	auto shared    = std::make_shared<SharedReader>(reader);
+	g_readers[key] = shared;
+	return shared;
+}
+
+// Guest code runs on guest-provided stacks, which can be as small as 64 KiB. Zstd decompression
+// can exhaust those stacks, and Windows has no equivalent of the alternate signal stack used by
+// the Linux fault handler. Keep decompression on one ordinary host thread and copy the result back
+// on the calling thread, matching the regular host-file path.
+class ArchiveIoThread {
+public:
+	static ArchiveIoThread& Instance() {
+		// The detached worker intentionally lives until process termination.
+		static auto* instance = new ArchiveIoThread;
+		return *instance;
+	}
+
+	uint64_t Run(std::function<uint64_t()> function) {
+		auto job      = std::make_shared<Job>();
+		job->function = std::move(function);
+
+		std::unique_lock lock(m_mutex);
+		m_jobs.push_back(job);
+		m_wake.notify_one();
+		m_done.wait(lock, [&job] { return job->done; });
+		return job->result;
+	}
+
+	KYTY_CLASS_NO_COPY(ArchiveIoThread);
+
+private:
+	struct Job {
+		std::function<uint64_t()> function;
+		uint64_t                  result = 0;
+		bool                      done   = false;
+	};
+
+	ArchiveIoThread() {
+		std::thread([this] { Loop(); }).detach();
+	}
+	~ArchiveIoThread() = default;
+
+	[[noreturn]] void Loop() {
+		for (;;) {
+			std::shared_ptr<Job> job;
+			{
+				std::unique_lock lock(m_mutex);
+				m_wake.wait(lock, [this] { return !m_jobs.empty(); });
+				job = std::move(m_jobs.front());
+				m_jobs.pop_front();
+			}
+
+			const auto result = job->function();

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '100,265p' src/common/zarchive.cpp
rg -n 'ReadFromFile|ArchiveFileStreamer|ZArchiveFile::Read|File::Read' src/common/zarchive.cpp src/libs/avPlayer.cpp src/common/file.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5622


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- archive API bindings ---'
rg -n -C 3 'OpenZArchiveFile|ZArchiveFile|ZArchiveFileSize|GetZArchiveDirEntries|IsZArchive(File|Directory|Path)|MakeZArchivePath' --glob '!src/common/zarchive.cpp' .
printf '%s\n' '--- archive streamer caller ---'
sed -n '620,710p' src/libs/avPlayer.cpp
sed -n '740,790p' src/libs/avPlayer.cpp
printf '%s\n' '--- File read contract ---'
sed -n '210,270p' src/common/file.cpp
sed -n '400,440p' src/common/file.cpp
printf '%s\n' '--- archive implementation context ---'
sed -n '1,120p' src/common/zarchive.cpp
sed -n '265,430p' src/common/zarchive.cpp

Repository: KytyPS5/KytyPS5

Length of output: 32230


Isolate stalled archive reads.

If ReadFromFile stalls, ArchiveIoThread cannot process reads for other archives. ArchiveIoThread::Run queues each job and waits for completion, while its single worker executes each job synchronously. Use separate workers per archive or another design that prevents one archive’s I/O from blocking unrelated archives.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 22:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#discussion_r4112999080) On `src/common/zarchive.cpp` line 175 (outdated): ```diff @@ -0,0 +1,397 @@ +#include "common/zarchive.h" + +#include "common/stringUtils.h" + +#include <algorithm> +#include <condition_variable> +#include <cstring> +#include <deque> +#include <functional> +#include <mutex> +#include <string_view> +#include <thread> +#include <unordered_map> +#include <utility> +#include <vector> +#include <zarchive/zarchivereader.h> + +namespace Common { + +namespace { + +constexpr uint32_t MaxDirectoryEntries = 1u << 20u; + +struct ParsedPath { + std::filesystem::path archive; + std::string member; + bool valid = false; +}; + +struct SharedReader { + explicit SharedReader(ZArchiveReader* value): reader(value) {} + ~SharedReader() { delete reader; } + + KYTY_CLASS_NO_COPY(SharedReader); + + ZArchiveReader* reader; + std::mutex mutex; +}; + +std::mutex g_readers_mutex; +std::unordered_map<std::string, std::weak_ptr<SharedReader>> g_readers; + +bool ParsePath(const std::filesystem::path& path, ParsedPath* parsed) { + auto text = path.native(); + const auto slash = std::filesystem::path("/").native().front(); + const auto backslash = std::filesystem::path("\\").native().front(); + std::replace(text.begin(), text.end(), backslash, slash); + auto lower = text; + for (auto& c: lower) { + const auto upper_a = static_cast<std::filesystem::path::value_type>('A'); + const auto upper_z = static_cast<std::filesystem::path::value_type>('Z'); + if (c >= upper_a && c <= upper_z) { + c += static_cast<std::filesystem::path::value_type>('a' - 'A'); + } + } + const auto marker_text = std::filesystem::path(".zar!").native(); + auto marker = lower.find(marker_text); + if (marker == std::filesystem::path::string_type::npos) { + return false; + } + auto mark = marker + 4; + if ((mark + 1 < text.size() && text[mark + 1] != slash)) { + return false; + } + + auto member_native = + mark + 1 < text.size() ? text.substr(mark + 1) : std::filesystem::path::string_type {}; + std::string member = Common::PathToGenericString(std::filesystem::path(member_native)); + while (member.starts_with('/')) { + member.erase(0, 1); + } + + std::vector<std::string> components; + bool valid = true; + for (const auto& component: Common::Split(member, "/")) { + if (component.empty() || component == ".") { + continue; + } + if (component == "..") { + if (components.empty()) { + valid = false; + continue; + } + components.pop_back(); + continue; + } + components.push_back(component); + } + + if (parsed != nullptr) { + parsed->archive = std::filesystem::path(text.substr(0, mark)); + for (const auto& component: components) { + if (!parsed->member.empty()) { + parsed->member += '/'; + } + parsed->member += component; + } + parsed->valid = valid; + } + return true; +} + +std::shared_ptr<SharedReader> GetReader(const std::filesystem::path& archive) { + auto key = Common::PathToGenericString(archive); +#if KYTY_PLATFORM == KYTY_PLATFORM_WINDOWS + key = Common::ToLower(key); +#endif + + std::lock_guard lock(g_readers_mutex); + if (auto it = g_readers.find(key); it != g_readers.end()) { + if (auto reader = it->second.lock()) { + return reader; + } + g_readers.erase(it); + } + std::erase_if(g_readers, [](const auto& entry) { return entry.second.expired(); }); + + auto* reader = ZArchiveReader::OpenFromFile(archive); + if (reader == nullptr) { + return {}; + } + + auto shared = std::make_shared<SharedReader>(reader); + g_readers[key] = shared; + return shared; +} + +// Guest code runs on guest-provided stacks, which can be as small as 64 KiB. Zstd decompression +// can exhaust those stacks, and Windows has no equivalent of the alternate signal stack used by +// the Linux fault handler. Keep decompression on one ordinary host thread and copy the result back +// on the calling thread, matching the regular host-file path. +class ArchiveIoThread { +public: + static ArchiveIoThread& Instance() { + // The detached worker intentionally lives until process termination. + static auto* instance = new ArchiveIoThread; + return *instance; + } + + uint64_t Run(std::function<uint64_t()> function) { + auto job = std::make_shared<Job>(); + job->function = std::move(function); + + std::unique_lock lock(m_mutex); + m_jobs.push_back(job); + m_wake.notify_one(); + m_done.wait(lock, [&job] { return job->done; }); + return job->result; + } + + KYTY_CLASS_NO_COPY(ArchiveIoThread); + +private: + struct Job { + std::function<uint64_t()> function; + uint64_t result = 0; + bool done = false; + }; + + ArchiveIoThread() { + std::thread([this] { Loop(); }).detach(); + } + ~ArchiveIoThread() = default; + + [[noreturn]] void Loop() { + for (;;) { + std::shared_ptr<Job> job; + { + std::unique_lock lock(m_mutex); + m_wake.wait(lock, [this] { return !m_jobs.empty(); }); + job = std::move(m_jobs.front()); + m_jobs.pop_front(); + } + + const auto result = job->function(); ``` _🩺 Stability & Availability_ | _🟠 Major_ | _🏗️ Heavy lift_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '100,265p' src/common/zarchive.cpp rg -n 'ReadFromFile|ArchiveFileStreamer|ZArchiveFile::Read|File::Read' src/common/zarchive.cpp src/libs/avPlayer.cpp src/common/file.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5622 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- archive API bindings ---' rg -n -C 3 'OpenZArchiveFile|ZArchiveFile|ZArchiveFileSize|GetZArchiveDirEntries|IsZArchive(File|Directory|Path)|MakeZArchivePath' --glob '!src/common/zarchive.cpp' . printf '%s\n' '--- archive streamer caller ---' sed -n '620,710p' src/libs/avPlayer.cpp sed -n '740,790p' src/libs/avPlayer.cpp printf '%s\n' '--- File read contract ---' sed -n '210,270p' src/common/file.cpp sed -n '400,440p' src/common/file.cpp printf '%s\n' '--- archive implementation context ---' sed -n '1,120p' src/common/zarchive.cpp sed -n '265,430p' src/common/zarchive.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 32230 --- </details> **Isolate stalled archive reads.** If `ReadFromFile` stalls, `ArchiveIoThread` cannot process reads for other archives. `ArchiveIoThread::Run` queues each job and waits for completion, while its single worker executes each job synchronously. Use separate workers per archive or another design that prevents one archive’s I/O from blocking unrelated archives. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:665b6ab4df04b0baa01b6fe5 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-26 22:16 UTC · original · reviewed

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 7bb0e7bb-dd60-43d6-aca3-f575aec89066

📥 Commits

Reviewing files that changed from the base of the PR and between 812de58741e94c3f538abd689679ca4bc8a7c9b8 and 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6.

📒 Files selected for processing (8)
  • 3rdparty/CMakeLists.txt
  • src/common/zarchive.cpp
  • src/launcher/include/gameContent.h
  • src/launcher/src/configurationItem.cpp
  • src/launcher/src/configurationListWidget.cpp
  • src/launcher/src/gameContent.cpp
  • src/launcher/src/trophyViewerDialog.cpp
  • tests/ZArchiveFileTests.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/launcher/src/configurationListWidget.cpp
  • src/launcher/src/trophyViewerDialog.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-26 22:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#pullrequestreview-5327695815) · **reviewed** **Actionable comments posted: 2** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `7bb0e7bb-dd60-43d6-aca3-f575aec89066` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 812de58741e94c3f538abd689679ca4bc8a7c9b8 and 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6. </details> <details> <summary>📒 Files selected for processing (8)</summary> * `3rdparty/CMakeLists.txt` * `src/common/zarchive.cpp` * `src/launcher/include/gameContent.h` * `src/launcher/src/configurationItem.cpp` * `src/launcher/src/configurationListWidget.cpp` * `src/launcher/src/gameContent.cpp` * `src/launcher/src/trophyViewerDialog.cpp` * `tests/ZArchiveFileTests.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary> * src/launcher/src/configurationListWidget.cpp * src/launcher/src/trophyViewerDialog.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠Nmzik on GitHub · 2026-09-28 19:25 UTC · original

First implementation is in. Simplified and optimized.

**@⁠Nmzik** on GitHub · 2026-09-28 19:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#issuecomment-5876914048) First implementation is in. Simplified and optimized.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 19:28 UTC · original · reviewed

🧹 Nitpick comments (1)
src/common/archive.cpp (1)

272-280: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Large archive reads keep a 1 MiB buffer on every thread that reads

chunk is thread_local and never shrinks. After a thread reads 1 MiB or more, it keeps a 1 MiB buffer until the thread exits. Guest titles can run many threads, so host memory use grows with the thread count. This is acceptable only if the thread count stays small.

Consider one of these fixes:

  • Stage reads in a buffer owned by the worker, then hand off the data.
  • Use a smaller chunk_size, for example 64 KiB. This matches COMPRESSED_BLOCK_SIZE.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 7e2fe729-e8a1-4a3e-93bb-756168d0bb63

📥 Commits

Reviewing files that changed from the base of the PR and between 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6 and 7d3702919f.

📒 Files selected for processing (27)
  • .github/workflows/build.yml
  • 3rdparty/CMakeLists.txt
  • 3rdparty/patches/zarchive-reader.patch
  • CMakeLists.txt
  • README.md
  • src/common/archive.cpp
  • src/common/archive.h
  • src/common/file.cpp
  • src/common/file.h
  • src/common/platform/sysFileIO.h
  • src/common/platform/sysLinuxFileIO.cpp
  • src/common/platform/sysWindowsFileIO.cpp
  • src/kernel/fileSystem.cpp
  • src/launcher/CMakeLists.txt
  • src/launcher/include/configurationItem.h
  • src/launcher/include/gameListTreeWidget.h
  • src/launcher/src/configurationItem.cpp
  • src/launcher/src/configurationListWidget.cpp
  • src/launcher/src/gameContent.cpp
  • src/launcher/src/mainDialog.cpp
  • src/launcher/src/trophyViewerDialog.cpp
  • src/libs/avPlayer.cpp
  • src/main.cpp
  • tests/ArchiveFileTests.cpp
  • tests/ArchiveTestFixture.h
  • tests/AvPlayerFileTests.cpp
  • tests/KernelFileSystemTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 19:28 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#pullrequestreview-5343615928) · **reviewed** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/common/archive.cpp (1)</summary><blockquote> `272-280`: _🚀 Performance & Scalability_ | _🔵 Trivial_ | _💤 Low value_ **Large archive reads keep a 1 MiB buffer on every thread that reads** `chunk` is `thread_local` and never shrinks. After a thread reads 1 MiB or more, it keeps a 1 MiB buffer until the thread exits. Guest titles can run many threads, so host memory use grows with the thread count. This is acceptable only if the thread count stays small. Consider one of these fixes: - Stage reads in a buffer owned by the worker, then hand off the data. - Use a smaller `chunk_size`, for example 64 KiB. This matches `COMPRESSED_BLOCK_SIZE`. <!-- cr-comment:v1:71ef9d66d7f236313f32a7c8 --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `7e2fe729-e8a1-4a3e-93bb-756168d0bb63` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 1bfe1cfef040ae1fa3b76bcf8acdf81f57b254c6 and 7d3702919f9fcd297a806e6f302d9638207a0d1a. </details> <details> <summary>📒 Files selected for processing (27)</summary> * `.github/workflows/build.yml` * `3rdparty/CMakeLists.txt` * `3rdparty/patches/zarchive-reader.patch` * `CMakeLists.txt` * `README.md` * `src/common/archive.cpp` * `src/common/archive.h` * `src/common/file.cpp` * `src/common/file.h` * `src/common/platform/sysFileIO.h` * `src/common/platform/sysLinuxFileIO.cpp` * `src/common/platform/sysWindowsFileIO.cpp` * `src/kernel/fileSystem.cpp` * `src/launcher/CMakeLists.txt` * `src/launcher/include/configurationItem.h` * `src/launcher/include/gameListTreeWidget.h` * `src/launcher/src/configurationItem.cpp` * `src/launcher/src/configurationListWidget.cpp` * `src/launcher/src/gameContent.cpp` * `src/launcher/src/mainDialog.cpp` * `src/launcher/src/trophyViewerDialog.cpp` * `src/libs/avPlayer.cpp` * `src/main.cpp` * `tests/ArchiveFileTests.cpp` * `tests/ArchiveTestFixture.h` * `tests/AvPlayerFileTests.cpp` * `tests/KernelFileSystemTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-28 19:38 UTC · original · reviewed

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Return an error for archive entries longer than 255 bytes. · fileSystem.cpp:132

src/kernel/fileSystem.cpp:132
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Return an error for archive entries longer than 255 bytes.

ZArchiveReader accepts extended name lengths above 255 bytes. Directory enumeration forwards those names to PackDirents, where EXIT_NOT_IMPLEMENTED terminates the process. Make PackDirents report the invalid entry, then return KERNEL_ERROR_ENAMETOOLONG from KernelOpen and KernelStat before using the packed entries.


ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: c78d1b19-51c2-4eac-a3fd-62d816206e45

📥 Commits

Reviewing files that changed from the base of the PR and between 7d3702919f and 3cd483ae6a.

📒 Files selected for processing (4)
  • src/kernel/fileSystem.cpp
  • tests/ArchiveFileTests.cpp
  • tests/ArchiveTestFixture.h
  • tests/KernelFileSystemTests.cpp
💤 Files with no reviewable changes (1)
  • tests/ArchiveFileTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-28 19:38 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/724#pullrequestreview-5343715333) · **reviewed** > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><em>🟡 Minor</em> · Return an error for archive entries longer than 255 bytes. · <code>fileSystem.cpp:132</code></summary><blockquote> > > `src/kernel/fileSystem.cpp:132` > _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ > > **Return an error for archive entries longer than 255 bytes.** > > `ZArchiveReader` accepts extended name lengths above 255 bytes. Directory enumeration forwards those names to `PackDirents`, where `EXIT_NOT_IMPLEMENTED` terminates the process. Make `PackDirents` report the invalid entry, then return `KERNEL_ERROR_ENAMETOOLONG` from `KernelOpen` and `KernelStat` before using the packed entries. > > <!-- cr-comment:v1:d43b8c2228d9569a91fdb197 --> > > </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `c78d1b19-51c2-4eac-a3fd-62d816206e45` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7d3702919f9fcd297a806e6f302d9638207a0d1a and 3cd483ae6a781a5d78612371aebf6e2d86f8de1c. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `src/kernel/fileSystem.cpp` * `tests/ArchiveFileTests.cpp` * `tests/ArchiveTestFixture.h` * `tests/KernelFileSystemTests.cpp` </details> <details> <summary>💤 Files with no reviewable changes (1)</summary> * tests/ArchiveFileTests.cpp </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This discussion has been locked. Commenting is limited to contributors.
No description provided.