From 76c9db3d5275e5257156db5feff479552b807424 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 27 Nov 2026 02:57:39 +0000 Subject: [PATCH 1/3] [HLE] Convert a .pkg straight into a .zar, optionally consuming the package in place SharpEmu.CLI --pkg-to-zar [dest.zar] [--consume-source] converts a fake PS4 or PS5 package into a ZArchive without an extracted folder. - PackageSource (was Ps5Source) carries every package read for both formats; it can record the ranges a parse reads, serve them from a snapshot over a truncated file, and refuses file reads past the consumed frontier. - IPackageContent lists exactly what Extract writes (sce_sys metadata + game files, same name checks, later write wins) and maps any file byte range to the highest package offset decoding it reads (PS5: UBlocks -> outer blocks; PS4: PFS blocks -> PFSC extents -> XTS sectors). - Files are laid out in source order; each 1 MiB offset-record group knows its source end. Direct mode writes groups in order and leaves the package untouched. - Consume mode processes groups in descending source end, in windowed batches: append to .partial, F_FULLFSYNC, journal the placements, then truncate the package. The journal holds a snapshot of the parsed ranges and a plan fingerprint, so an interrupted, cancelled or out-of-space run resumes; mismatches are refused. - ZArchiveWriter shares its block encoder and trailer with the converter; Pack output is byte-identical to before. --- src/SharpEmu.CLI/Program.cs | 82 ++ .../FileSystem/Pkg/GamePackage.cs | 31 + .../FileSystem/Pkg/PackageContent.cs | 34 + .../FileSystem/Pkg/PackageSource.cs | 292 +++++ src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs | 32 + src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs | 135 +- .../FileSystem/Pkg/PkgPfsStream.cs | 14 + .../FileSystem/Pkg/PkgZarConverter.cs | 1094 +++++++++++++++++ src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs | 4 +- .../FileSystem/Pkg/Ps5InnerImage.cs | 23 + .../FileSystem/Pkg/Ps5OuterPfs.cs | 32 +- src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs | 60 +- src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs | 58 - src/SharpEmu.HLE/FileSystem/ZArchiveWriter.cs | 101 +- .../FileSystem/PkgTests.cs | 6 +- .../FileSystem/PkgZarConverterTests.cs | 662 ++++++++++ .../FileSystem/Ps5PkgTests.cs | 25 +- 17 files changed, 2555 insertions(+), 130 deletions(-) create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PackageContent.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PackageSource.cs create mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/PkgZarConverter.cs delete mode 100644 src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs create mode 100644 tests/SharpEmu.Libs.Tests/FileSystem/PkgZarConverterTests.cs diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs index bd4cf9aeb..3844ccdef 100644 --- a/src/SharpEmu.CLI/Program.cs +++ b/src/SharpEmu.CLI/Program.cs @@ -190,6 +190,11 @@ private static int Run(string[] args) return InstallPkg(args); } + if (args.Length > 0 && string.Equals(args[0], "--pkg-to-zar", StringComparison.OrdinalIgnoreCase)) + { + return PkgToZar(args); + } + if (!CheckHostArchitecture()) { return 5; @@ -1104,6 +1109,82 @@ private static int InstallPkg(string[] args) } } + // --pkg-to-zar [dest.zar] [--consume-source]: converts a fake PS4 or PS5 package + // straight into a .zar (by default /.zar) without an extracted folder. + // --consume-source shrinks the package as its data lands in the archive and deletes it at the + // end; an interrupted run resumes when the same command runs again. + private static int PkgToZar(string[] args) + { + const string Usage = "Usage: SharpEmu.CLI --pkg-to-zar [destination.zar] [--consume-source]"; + var consume = args.Skip(1).Any(arg => string.Equals(arg, "--consume-source", StringComparison.OrdinalIgnoreCase)); + var positional = args.Skip(1).Where(arg => !string.Equals(arg, "--consume-source", StringComparison.OrdinalIgnoreCase)).ToList(); + if (positional.Count is < 1 or > 2 || positional.Any(arg => arg.StartsWith("--", StringComparison.Ordinal))) + { + Log.Error(Usage); + return 2; + } + + var pkgPath = Path.GetFullPath(positional[0]); + try + { + string destination; + if (positional.Count == 2) + { + destination = Path.GetFullPath(positional[1]); + } + else if (SharpEmu.HLE.FileSystem.Pkg.PkgZarConverter.FindPendingDestination(pkgPath) is { } pending) + { + // The package may already be cut short; the journal knows where it was going. + destination = pending; + } + else + { + if (!File.Exists(pkgPath)) + { + Log.Error($"Package not found: {pkgPath}"); + return 2; + } + + using var package = SharpEmu.HLE.FileSystem.Pkg.GamePackage.Open(pkgPath); + if (!package.IsGameApplication) + { + Log.Error($"{Path.GetFileName(pkgPath)} is not a base game (category '{package.Category}'). Patches and DLC packages are not supported yet."); + return 2; + } + + destination = Path.Combine( + Path.GetDirectoryName(pkgPath)!, + package.GetFolderName(Path.GetFileNameWithoutExtension(pkgPath)) + ".zar"); + } + + var resuming = File.Exists(SharpEmu.HLE.FileSystem.Pkg.PkgZarConverter.JournalPath(destination)); + Log.Info($"{(resuming ? "Resuming the conversion of" : "Converting")} {Path.GetFileName(pkgPath)} into {destination}{(consume ? " (consuming the package)" : string.Empty)}"); + var lastPercent = -1; + var progress = new SynchronousProgress(report => + { + var percent = report.BytesTotal == 0 ? 100 : (int)(report.BytesDone * 100 / report.BytesTotal); + if (percent != lastPercent) + { + lastPercent = percent; + Log.Info($"{percent,3}% {report.BytesDone / (1024.0 * 1024 * 1024):0.00} / {report.BytesTotal / (1024.0 * 1024 * 1024):0.00} GB"); + } + }); + SharpEmu.HLE.FileSystem.Pkg.PkgZarConverter.Convert(pkgPath, destination, consume, progress); + Log.Info($"Done. Launch it with: SharpEmu.CLI \"{destination}\""); + return 0; + } + catch (SharpEmu.HLE.FileSystem.Pkg.PkgConversionPausedException exception) + { + Log.Error(exception.Message); + return 3; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException or OperationCanceledException) + { + Log.Error($"Converting the package failed: {exception.Message}"); + return 1; + } + } + private sealed class SynchronousProgress(Action handler) : IProgress { public void Report(T value) => handler(value); @@ -1113,6 +1194,7 @@ private static void PrintUsage() { Log.Info("Usage: SharpEmu.CLI [--strict[=on|off]] [--precompile-only] [--shader-prewarm-hold] [--shader-cache=] [--shader-learn=] [--trace-imports[=N]] [--cpu-engine=] [--console=] [--console-language=] [--log-level=] [--log-file[=]] [--no-log-file] [--window-mode=] [--resolution=] [--guest-args=<\"ARGS\">] [--display=] [--refresh-rate=] [--scaling=] [--vsync=] [--hdr=] [--overlay=] [--overlay-mode=] [--overlay-preset=] [--overlay-corner=] [--debug-server[=host:port]] "); Log.Info("Install a fake PS4 or PS5 package: SharpEmu.CLI --install-pkg [destination-folder]"); + Log.Info("Convert a fake PS4 or PS5 package to .zar: SharpEmu.CLI --pkg-to-zar [destination.zar] [--consume-source]"); Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin"""); Log.Info("Debug server: --debug-server starts a live debug listener (default 127.0.0.1:5714); connect with SharpEmu.DebugClient."); } diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs index 7a9a5e4fa..2ceb12b0b 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/GamePackage.cs @@ -34,6 +34,37 @@ public static IGamePackage Open(string path) throw new InvalidDataException("Not a PS4 or PS5 package (unknown magic)."); } + // Opens the package through `source`, which it then owns. Every read, the magic included, goes + // through the source, so a recorded snapshot replays this exact open. + internal static IGamePackage Open(PackageSource source) + { + try + { + Span magic = stackalloc byte[4]; + if (source.ReadAt(magic, 0) != 4) + { + throw new InvalidDataException("This file is too short to be a PKG package."); + } + + if (magic.SequenceEqual(CntMagic)) + { + return PkgPackage.Open(source); + } + + if (magic.SequenceEqual(FihMagic)) + { + return Ps5Package.Open(source); + } + + throw new InvalidDataException("Not a PS4 or PS5 package (unknown magic)."); + } + catch + { + source.Dispose(); + throw; + } + } + // True for a readable .pkg file with either known magic. public static bool IsPackagePath(string path) { diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PackageContent.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PackageContent.cs new file mode 100644 index 000000000..772d1a612 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PackageContent.cs @@ -0,0 +1,34 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// A file a folder install of the package writes. Path is relative to the game folder, with '/' +// separators, and passed the same name checks Extract applies. Bytes holds sce_sys metadata read +// while listing (it touches the package no further); Native is the format's handle for the rest. +internal sealed record PackageContentFile(string Path, long Size, byte[]? Bytes, object? Native); + +// The files of a package as a stream of byte ranges with their physical position in the .pkg, so +// a converter can write them anywhere without an extracted folder. Both package formats implement +// it next to Extract and list exactly what Extract writes. +internal interface IPackageContent +{ + PackageSource Source { get; } + + // In Extract's write order: sce_sys metadata first, then the game files. Later entries win when + // two map to one path, as the later write does on disk. + IReadOnlyList ListContentFiles(); + + // Package offset just past the last byte read to decode [offset, offset+length) of `file`; + // 0 when nothing is read (metadata, empty ranges, sparse data). + long SourceEnd(PackageContentFile file, long offset, long length); + + // A reader with its own decode state, for one thread. + IPackageContentReader CreateContentReader(); +} + +internal interface IPackageContentReader : IDisposable +{ + // Fills destination with the file bytes at offset (the range lies inside the file). + void Read(PackageContentFile file, long offset, Memory destination); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PackageSource.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PackageSource.cs new file mode 100644 index 000000000..0049a9762 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PackageSource.cs @@ -0,0 +1,292 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Microsoft.Win32.SafeHandles; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// Positional reads over the package file; every read is range checked. Both package formats read +// through it, which lets a pkg to zar conversion that consumes its source: +// - record every byte range the parser reads while opening the package (TakeSnapshot), +// - serve those ranges from a snapshot once the file has been truncated below them, +// - keep reporting the original length, so parsing a shrunk package sees the same file, +// - refuse any read of file bytes at or past the frontier (the length the file was cut to). +// Reads may run on several threads; the snapshot is immutable once set. +internal sealed class PackageSource : IDisposable +{ + private readonly SafeFileHandle _handle; + private readonly object _gate = new(); + private List<(long Offset, long End)>? _recorded; + // Sorted, non-overlapping. + private (long Offset, byte[] Bytes)[] _snapshot = []; + private long _frontier; + + public PackageSource(string path) + : this(File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess), null) + { + } + + private PackageSource(SafeFileHandle handle, long? originalLength) + { + _handle = handle; + Length = originalLength ?? RandomAccess.GetLength(handle); + _frontier = Length; + } + + // The original package length: the file's own length, or the length recorded before it was cut. + public long Length { get; } + + // File bytes at or past this offset are gone (or about to be); reading them is a bug. + public long Frontier + { + get => Volatile.Read(ref _frontier); + set => Volatile.Write(ref _frontier, value); + } + + public IReadOnlyList<(long Offset, byte[] Bytes)> Snapshot => _snapshot; + + // Called with (offset, length) of every read that goes to the file, after the frontier check. + public Action? FileReadObserver { get; set; } + + // A package cut by a consuming conversion: `snapshot` serves the ranges the parser reads, the + // file serves the rest below `frontier`, and Length stays `originalLength`. + public static PackageSource OpenTruncated(string path, long originalLength, IReadOnlyList<(long Offset, byte[] Bytes)> snapshot, long frontier) + { + var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess); + var source = new PackageSource(handle, originalLength); + source.SetSnapshot(snapshot); + source.Frontier = Math.Min(frontier, RandomAccess.GetLength(handle)); + return source; + } + + // Starts recording the ranges reads touch. + public void StartRecording() + { + lock (_gate) + { + _recorded = []; + } + } + + // Stops recording and reads every recorded range (merged) from the file: the bytes a parse of + // this package needs. The snapshot then serves those ranges from memory. + public IReadOnlyList<(long Offset, byte[] Bytes)> TakeSnapshot() + { + List<(long Offset, long End)> ranges; + lock (_gate) + { + ranges = _recorded ?? throw new InvalidOperationException("Recording was not started."); + _recorded = null; + } + + ranges.Sort((left, right) => left.Offset.CompareTo(right.Offset)); + var merged = new List<(long Offset, long End)>(); + foreach (var range in ranges) + { + if (merged.Count > 0 && range.Offset <= merged[^1].End) + { + merged[^1] = (merged[^1].Offset, Math.Max(merged[^1].End, range.End)); + } + else + { + merged.Add(range); + } + } + + var snapshot = new List<(long Offset, byte[] Bytes)>(merged.Count); + foreach (var (offset, end) in merged) + { + var bytes = new byte[end - offset]; + ReadFile(bytes, offset); + snapshot.Add((offset, bytes)); + } + + SetSnapshot(snapshot); + return _snapshot; + } + + private void SetSnapshot(IReadOnlyList<(long Offset, byte[] Bytes)> snapshot) + { + var sorted = snapshot.OrderBy(range => range.Offset).ToArray(); + for (var i = 0; i < sorted.Length; i++) + { + if (sorted[i].Offset < 0 || sorted[i].Bytes.Length > Length - sorted[i].Offset || + (i > 0 && sorted[i - 1].Offset + sorted[i - 1].Bytes.Length > sorted[i].Offset)) + { + throw new InvalidDataException("The package snapshot ranges overlap or lie outside the package."); + } + } + + _snapshot = sorted; + } + + // Reads up to buffer.Length bytes at offset; short only at Length. + public int ReadAt(Span buffer, long offset) + { + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset)); + } + + if (offset >= Length || buffer.IsEmpty) + { + return 0; + } + + var count = (int)Math.Min(buffer.Length, Length - offset); + Record(offset, count); + var snapshot = _snapshot; + var position = offset; + var end = offset + count; + while (position < end) + { + var index = LastStartingAtOrBefore(snapshot, position); + if (index >= 0 && position < snapshot[index].Offset + snapshot[index].Bytes.Length) + { + var (rangeOffset, bytes) = snapshot[index]; + var take = (int)(Math.Min(end, rangeOffset + bytes.Length) - position); + bytes.AsSpan((int)(position - rangeOffset), take).CopyTo(buffer[(int)(position - offset)..]); + position += take; + continue; + } + + var next = index + 1 < snapshot.Length ? Math.Min(end, snapshot[index + 1].Offset) : end; + var frontier = Frontier; + if (next > frontier) + { + throw new InvalidDataException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Read of package bytes 0x{position:X}..0x{next:X} reaches past 0x{frontier:X}, where the package was already consumed.")); + } + + FileReadObserver?.Invoke(position, next - position); + ReadFile(buffer.Slice((int)(position - offset), (int)(next - position)), position); + position = next; + } + + return count; + } + + // The last snapshot range starting at or before `position`, or -1. + private static int LastStartingAtOrBefore((long Offset, byte[] Bytes)[] snapshot, long position) + { + int low = 0, high = snapshot.Length; + while (low < high) + { + var mid = low + (high - low) / 2; + if (snapshot[mid].Offset <= position) + { + low = mid + 1; + } + else + { + high = mid; + } + } + + return low - 1; + } + + private void Record(long offset, long count) + { + if (_recorded is null) + { + return; + } + + lock (_gate) + { + _recorded?.Add((offset, offset + count)); + } + } + + private void ReadFile(Span buffer, long offset) + { + var done = 0; + while (done < buffer.Length) + { + var read = RandomAccess.Read(_handle, buffer[done..], offset + done); + if (read == 0) + { + throw new InvalidDataException("The package file ended unexpectedly."); + } + + done += read; + } + } + + public void ReadExactAt(Span buffer, long offset) + { + if (offset < 0 || offset > Length || buffer.Length > Length - offset) + { + throw new InvalidDataException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Read of {buffer.Length:N0} bytes at 0x{offset:X} is past the end of the {Length:N0}-byte package.")); + } + + ReadAt(buffer, offset); + } + + public byte[] ReadBytes(long length, long offset) + { + if (length < 0 || length > int.MaxValue || offset < 0 || offset > Length || length > Length - offset) + { + throw new InvalidDataException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Read of {length:N0} bytes at 0x{offset:X} is past the end of the {Length:N0}-byte package.")); + } + + var bytes = new byte[length]; + ReadExactAt(bytes, offset); + return bytes; + } + + public void Dispose() => _handle.Dispose(); +} + +// A read-only, seekable Stream over a PackageSource for readers written against Stream (the PS4 +// package). Each instance keeps its own position, so one per thread may share the source. +internal sealed class PackageSourceStream(PackageSource source) : Stream +{ + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => source.Length; + + public override long Position + { + get => _position; + set => _position = value < 0 ? throw new ArgumentOutOfRangeException(nameof(value)) : value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var read = source.ReadAt(buffer, _position); + _position += read; + return read; + } + + public override long Seek(long offset, SeekOrigin origin) + { + Position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => source.Length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + return _position; + } + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs index 59d655f9b..f6fe41644 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PfsImage.cs @@ -146,10 +146,42 @@ public PfscImage(Stream source, long pfscOffset) } } + // A view of `shared` that reads through `source` (another view of the same image), sharing the + // block table, so each thread can decode with its own stream. + internal PfscImage(PfscImage shared, Stream source) + { + _source = source; + _offset = shared._offset; + _blockOffsets = shared._blockOffsets; + DataLength = shared.DataLength; + BlockCount = shared.BlockCount; + } + public long DataLength { get; } public int BlockCount { get; } + // Where the PFSC starts in the image. + internal long Offset => _offset; + + // The stored bytes of block `index`, relative to the PFSC start: what ReadBlock reads. + internal (long Start, long Size) BlockExtent(long index) + { + if (index < 0 || index >= BlockCount) + { + throw new InvalidDataException($"PFSC block {index} is out of range."); + } + + var start = _blockOffsets[index]; + var size = _blockOffsets[index + 1] - start; + if (size < 0 || size > BlockSize) + { + throw new InvalidDataException($"PFSC block {index} has an invalid size {size}."); + } + + return (start, size); + } + // Finds the PFSC inside a decrypted PFS image: it starts on a 64 KiB boundary after the // image's own header blocks. public static long FindOffset(Stream image, int maxCandidates = 4096) diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs index 15e01b215..01317f085 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPackage.cs @@ -7,19 +7,25 @@ namespace SharpEmu.HLE.FileSystem.Pkg; // A fake (fpkg) PS4 package opened for reading. Extraction streams every file block by block, // so a package of any size needs only a few hundred KiB of memory. -public sealed class PkgPackage : IGamePackage +public sealed class PkgPackage : IGamePackage, IPackageContent { private const int EntryKeysTableOffset = 32 + 7 * 32; // seed digest + 7 digests, then 7 RSA keys private const int EntryKeySize = 256; private const long PfsSeedOffset = 0x370; - private readonly FileStream _file; + private readonly PackageSource _source; + private readonly Stream _file; private readonly byte[] _entryTable; + private (byte[]? Data, byte[]? Tweak)? _pfsKeys; + // The image the content listing walked; SourceEnd maps file blocks through it. + private PkgPfsStream? _contentImage; + private PfscImage? _contentPfsc; private string? _category; private bool _categoryRead; - private PkgPackage(FileStream file, PkgHeader header, byte[] entryTable, PkgEntry[] entries) + private PkgPackage(PackageSource source, Stream file, PkgHeader header, byte[] entryTable, PkgEntry[] entries) { + _source = source; _file = file; Header = header; _entryTable = entryTable; @@ -105,9 +111,12 @@ public static bool IsPkgPath(string path) } } - public static PkgPackage Open(string path) + public static PkgPackage Open(string path) => Open(new PackageSource(path)); + + // Takes ownership of `source`. + internal static PkgPackage Open(PackageSource source) { - var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.RandomAccess); + var file = new PackageSourceStream(source); try { var headerBytes = new byte[PkgHeader.Size]; @@ -132,11 +141,11 @@ public static PkgPackage Open(string path) var table = new byte[checked((int)header.TableEntryCount * PkgEntry.Size_)]; file.Position = header.TableEntryOffset; file.ReadExactly(table); - return new PkgPackage(file, header, table, PkgEntry.ParseTable(table, (int)header.TableEntryCount)); + return new PkgPackage(source, file, header, table, PkgEntry.ParseTable(table, (int)header.TableEntryCount)); } catch { - file.Dispose(); + source.Dispose(); throw; } } @@ -277,14 +286,23 @@ internal void Extract( progress?.Report(new PkgExtractProgress(total, total, string.Empty)); } - private PkgPfsStream OpenPfsImageStream() + private PkgPfsStream OpenPfsImageStream() => OpenPfsImageStream(_file); + + // The decrypted PFS image over `file` (the package itself, or a per-thread view of it). + private PkgPfsStream OpenPfsImageStream(Stream file) + { + var (dataKey, tweakKey) = _pfsKeys ??= DerivePfsKeys(); + return new PkgPfsStream(file, (long)Header.PfsImageOffset, (long)Header.PfsImageSize, dataKey, tweakKey); + } + + private (byte[]? Data, byte[]? Tweak) DerivePfsKeys() { var imageKeyEntry = FindEntry(PkgEntry.ImageKeyId, out var imageKeyRow); var keysEntry = FindEntry(PkgEntry.EntryKeysId, out _); if (imageKeyEntry is null || keysEntry is null) { // No key material means the PFS image is stored in the clear. - return new PkgPfsStream(_file, (long)Header.PfsImageOffset, (long)Header.PfsImageSize, null, null); + return (null, null); } var keys = ReadEntry(keysEntry.Value); @@ -306,8 +324,96 @@ private PkgPfsStream OpenPfsImageStream() var seed = new byte[16]; _file.Position = (long)Header.PfsImageOffset + PfsSeedOffset; _file.ReadExactly(seed); - var (dataKey, tweakKey) = PkgCrypto.DerivePfsKeys(ekpfs, seed); - return new PkgPfsStream(_file, (long)Header.PfsImageOffset, (long)Header.PfsImageSize, dataKey, tweakKey); + return PkgCrypto.DerivePfsKeys(ekpfs, seed); + } + + PackageSource IPackageContent.Source => _source; + + IReadOnlyList IPackageContent.ListContentFiles() + { + var content = new List(); + foreach (var entry in Entries) + { + if (entry.Name is { } name) + { + ResolveSafe(string.Empty, ["sce_sys", .. name.Split('/')]); + var bytes = ReadEntry(entry); + content.Add(new PackageContentFile("sce_sys/" + name, bytes.Length, bytes, null)); + } + } + + _contentImage?.Dispose(); + _contentImage = OpenPfsImageStream(); + _contentPfsc = new PfscImage(_contentImage, PfscImage.FindOffset(_contentImage)); + var pfs = new PfsImage(_contentPfsc); + var files = new List<(string Path, PfsInode Inode)>(); + long total = 0; + CollectTree(pfs, pfs.GetUserRoot(), string.Empty, files, ref total, new HashSet(), 0); + foreach (var (path, inode) in files) + { + if (inode.Size < 0 || inode.Blocks * (long)PfscImage.BlockSize < inode.Size) + { + throw new InvalidDataException("PFS file claims more data than its blocks hold."); + } + + content.Add(new PackageContentFile(string.Join('/', path.Split(Path.DirectorySeparatorChar)), inode.Size, null, inode)); + } + + return content; + } + + long IPackageContent.SourceEnd(PackageContentFile file, long offset, long length) + { + if (file.Native is not PfsInode inode || length <= 0) + { + return 0; + } + + var pfsc = _contentPfsc ?? throw new InvalidOperationException("List the package content first."); + long end = 0; + var last = (offset + length - 1) / PfscImage.BlockSize; + for (var block = offset / PfscImage.BlockSize; block <= last; block++) + { + var (start, size) = pfsc.BlockExtent((long)inode.Location + block); + if (size > 0) + { + end = Math.Max(end, _contentImage!.SourceEnd(pfsc.Offset + start, size)); + } + } + + return end; + } + + IPackageContentReader IPackageContent.CreateContentReader() + { + var pfsc = _contentPfsc ?? throw new InvalidOperationException("List the package content first."); + var image = OpenPfsImageStream(new PackageSourceStream(_source)); + return new ContentReader(image, new PfscImage(pfsc, image)); + } + + // Reads file ranges block by block, as PfsImage.CopyFile does, through its own image view. + private sealed class ContentReader(PkgPfsStream image, PfscImage pfsc) : IPackageContentReader + { + private readonly byte[] _block = new byte[PfscImage.BlockSize]; + + public void Read(PackageContentFile file, long offset, Memory destination) + { + var inode = (PfsInode)file.Native!; + var span = destination.Span; + var done = 0; + while (done < span.Length) + { + var position = offset + done; + var block = position / PfscImage.BlockSize; + var within = (int)(position % PfscImage.BlockSize); + pfsc.ReadBlock((long)inode.Location + block, _block); + var count = Math.Min(span.Length - done, PfscImage.BlockSize - within); + _block.AsSpan(within, count).CopyTo(span[done..]); + done += count; + } + } + + public void Dispose() => image.Dispose(); } private PkgEntry? FindEntry(uint id, out byte[] row) @@ -384,5 +490,10 @@ internal static string ResolveSafe(string root, string[] components) return path; } - public void Dispose() => _file.Dispose(); + public void Dispose() + { + _contentImage?.Dispose(); + _file.Dispose(); + _source.Dispose(); + } } diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs index 5766500c2..7f68cf82c 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgPfsStream.cs @@ -44,6 +44,20 @@ public override long Position set => _position = value < 0 ? throw new ArgumentOutOfRangeException(nameof(value)) : value; } + // Package offset just past the last byte a read of [position, position+count) of the image + // touches: reads cover whole sectors, clipped to the image and to the package file. + internal long SourceEnd(long position, long count) + { + if (count <= 0 || position >= _length) + { + return 0; + } + + var end = position + Math.Min(count, _length - position); + var alignedEnd = (end + PkgCrypto.SectorSize - 1) & ~(long)(PkgCrypto.SectorSize - 1); + return Math.Min(_start + alignedEnd, _inner.Length); + } + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); public override int Read(Span destination) diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/PkgZarConverter.cs b/src/SharpEmu.HLE/FileSystem/Pkg/PkgZarConverter.cs new file mode 100644 index 000000000..39d0279b4 --- /dev/null +++ b/src/SharpEmu.HLE/FileSystem/Pkg/PkgZarConverter.cs @@ -0,0 +1,1094 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using System.Runtime.ExceptionServices; +using System.Security.Cryptography; +using System.Text; +using SharpEmu.Logging; +using ZstdSharp; + +namespace SharpEmu.HLE.FileSystem.Pkg; + +// Thrown when a consuming conversion runs out of disk space. Nothing is lost: the journal, the +// partial archive and what is left of the package resume the conversion when it runs again. +public sealed class PkgConversionPausedException(string message, Exception? inner) : IOException(message, inner); + +// Converts a fake PS4 or PS5 .pkg straight into a .zar, without an extracted folder. +// +// Files go into the archive's data stream in ascending order of where their bytes sit in the +// package, so each 1 MiB offset-record group (16 blocks of 64 KiB) needs a compact stretch of the +// package. For every group the plan knows the highest package byte decoding it reads (its end). +// +// Direct mode writes the groups in logical order and leaves the package alone. +// +// Consume mode shrinks the package as its data lands in the archive, so the package, a folder and +// the archive never need to fit on the drive together. Groups are processed in descending end +// order, in batches covering a window of the package. Each batch: decode and compress in +// parallel, append to .partial, flush it to stable storage, append the batch's placements to +// .journal and flush that, and only then truncate the package to the highest end of the +// groups still to do. The journal starts with a snapshot of every package range the parser read +// while opening the package, so a later run reopens the shrunk package exactly, re-derives the +// same plan, checks it against the journal and continues after the last committed batch. The +// reader resolves every group through its record's base offset, so groups may sit in the data +// section in any order. +public static class PkgZarConverter +{ + public const long DefaultWindowBytes = 256L << 20; + + private static readonly SharpEmuLogger Log = SharpEmuLog.For("PkgZar"); + + public static string PartialPath(string destination) => destination + ".partial"; + + public static string JournalPath(string destination) => destination + ".journal"; + + public static void Convert( + string packagePath, + string destinationPath, + bool consumeSource, + IProgress? progress = null, + CancellationToken cancellation = default) => + Convert(packagePath, destinationPath, new PkgZarOptions { ConsumeSource = consumeSource }, progress, cancellation); + + // The destination of an unfinished consuming conversion of this package: a journal beside it + // that names it. Null when there is none. + public static string? FindPendingDestination(string packagePath) + { + var package = Path.GetFullPath(packagePath); + var directory = Path.GetDirectoryName(package)!; + if (!Directory.Exists(directory)) + { + return null; + } + + foreach (var journal in Directory.EnumerateFiles(directory, "*.zar.journal")) + { + try + { + if (string.Equals(Journal.ReadPackagePath(journal), package, StringComparison.Ordinal)) + { + return journal[..^".journal".Length]; + } + } + catch (Exception exception) when (exception is IOException or InvalidDataException or UnauthorizedAccessException) + { + Log.Warn($"Skipping unreadable journal {journal}: {exception.Message}"); + } + } + + return null; + } + + internal static void Convert( + string packagePath, + string destinationPath, + PkgZarOptions options, + IProgress? progress, + CancellationToken cancellation) + { + ArgumentOutOfRangeException.ThrowIfLessThan(options.WindowBytes, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(options.MaxParallelism, 1); + var package = Path.GetFullPath(packagePath); + var destination = Path.GetFullPath(destinationPath); + if (options.ConsumeSource) + { + ConvertConsuming(package, destination, options, progress, cancellation); + } + else + { + ConvertDirect(package, destination, options, progress, cancellation); + } + } + + // ---- plan ---------------------------------------------------------------------------------- + + internal sealed record PlannedFile(PackageContentFile File, string[] Parts, long DataOffset, long SourceKey); + + internal sealed class Plan + { + public required List Files { get; init; } + + public required long DataSize { get; init; } + + // Per group: the package offset just past the last byte decoding it reads. + public required long[] GroupEnds { get; init; } + + public required byte[] Fingerprint { get; init; } + + public int GroupCount => GroupEnds.Length; + } + + private static IPackageContent OpenContent(PackageSource source) + { + var package = GamePackage.Open(source); + if (!package.IsGameApplication) + { + var category = package.Category; + package.Dispose(); + throw new InvalidDataException($"The package is not a base game (category '{category}'). Patches and DLC packages are not supported yet."); + } + + return (IPackageContent)package; + } + + internal static Plan BuildPlan(IPackageContent content, long windowBytes) + { + var listed = content.ListContentFiles(); + // The archive looks names up without case, so of two files mapping to one path the later + // one wins, as the later write wins on a case-insensitive drive. + var last = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (var index = 0; index < listed.Count; index++) + { + last[listed[index].Path] = index; + } + + var kept = new List<(PackageContentFile File, long Key, int Index)>(); + for (var index = 0; index < listed.Count; index++) + { + if (last[listed[index].Path] == index) + { + var file = listed[index]; + kept.Add((file, content.SourceEnd(file, 0, file.Size), index)); + } + } + + kept.Sort((left, right) => left.Key != right.Key ? left.Key.CompareTo(right.Key) : left.Index.CompareTo(right.Index)); + var files = new List(kept.Count); + long dataSize = 0; + foreach (var (file, key, _) in kept) + { + files.Add(new PlannedFile(file, file.Path.Split('/'), dataSize, key)); + dataSize += file.Size; + } + + var groupCount = (int)((dataSize + ZArchiveWriter.RecordSpan - 1) / ZArchiveWriter.RecordSpan); + var ends = new long[groupCount]; + var at = 0; + for (var group = 0; group < groupCount; group++) + { + var start = (long)group * ZArchiveWriter.RecordSpan; + var stop = Math.Min(dataSize, start + ZArchiveWriter.RecordSpan); + while (files[at].DataOffset + files[at].File.Size <= start) + { + at++; + } + + long end = 0; + for (var index = at; index < files.Count && files[index].DataOffset < stop; index++) + { + var file = files[index]; + var from = Math.Max(start, file.DataOffset); + var to = Math.Min(stop, file.DataOffset + file.File.Size); + if (to > from) + { + end = Math.Max(end, content.SourceEnd(file.File, from - file.DataOffset, to - from)); + } + } + + ends[group] = end; + } + + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + void Add(long value) => hash.AppendData(BitConverter.GetBytes(value)); + Add(files.Count); + foreach (var file in files) + { + hash.AppendData(Encoding.UTF8.GetBytes(file.File.Path)); + Add(file.File.Size); + Add(file.DataOffset); + Add(file.SourceKey); + } + + Add(dataSize); + Add(windowBytes); + foreach (var end in ends) + { + Add(end); + } + + return new Plan { Files = files, DataSize = dataSize, GroupEnds = ends, Fingerprint = hash.GetHashAndReset() }; + } + + // Groups in descending end order, cut into batches that each span at most `windowBytes` of the + // package and at most `windowBytes` of archive data. + internal static List BuildBatches(Plan plan, long windowBytes) + { + var order = Enumerable.Range(0, plan.GroupCount) + .OrderByDescending(group => plan.GroupEnds[group]) + .ThenByDescending(group => group) + .ToList(); + var batches = new List(); + var current = new List(); + long top = 0; + foreach (var group in order) + { + if (current.Count > 0 && + (top - plan.GroupEnds[group] >= windowBytes || (long)(current.Count + 1) * ZArchiveWriter.RecordSpan > windowBytes)) + { + batches.Add([.. current]); + current.Clear(); + } + + if (current.Count == 0) + { + top = plan.GroupEnds[group]; + } + + current.Add(group); + } + + if (current.Count > 0) + { + batches.Add([.. current]); + } + + return batches; + } + + // ---- encoding ------------------------------------------------------------------------------ + + internal readonly record struct EncodedGroup(byte[] Data, int Length, ushort[] Sizes); + + // Decode and compress state for one thread. + private sealed class GroupEncoder(IPackageContent content) : IDisposable + { + private readonly IPackageContentReader _reader = content.CreateContentReader(); + private readonly Compressor _compressor = new(ZArchiveWriter.CompressionLevel); + private readonly byte[] _logical = new byte[ZArchiveWriter.RecordSpan]; + private readonly byte[] _encoded = new byte[ZArchiveWriter.EncodeBufferSize]; + + public EncodedGroup Encode(Plan plan, int group) + { + var start = (long)group * ZArchiveWriter.RecordSpan; + var length = (int)Math.Min(ZArchiveWriter.RecordSpan, plan.DataSize - start); + Fill(plan, start, length); + var blocks = (length + ZArchive.BlockSize - 1) / ZArchive.BlockSize; + Array.Clear(_logical, length, blocks * ZArchive.BlockSize - length); + var data = new byte[blocks * ZArchive.BlockSize]; + var sizes = new ushort[ZArchiveWriter.BlocksPerRecord]; + var written = 0; + for (var block = 0; block < blocks; block++) + { + var size = ZArchiveWriter.EncodeBlock(_compressor, _logical.AsSpan(block * ZArchive.BlockSize, ZArchive.BlockSize), _encoded); + _encoded.AsSpan(0, size).CopyTo(data.AsSpan(written)); + written += size; + sizes[block] = (ushort)(size - 1); + } + + return new EncodedGroup(data, written, sizes); + } + + private void Fill(Plan plan, long start, int length) + { + var files = plan.Files; + // The last file starting at or before `start`. + int low = 0, high = files.Count; + while (low < high) + { + var mid = low + (high - low) / 2; + if (files[mid].DataOffset <= start) + { + low = mid + 1; + } + else + { + high = mid; + } + } + + var position = start; + var stop = start + length; + for (var index = Math.Max(0, low - 1); position < stop && index < files.Count; index++) + { + var file = files[index]; + var fileEnd = file.DataOffset + file.File.Size; + if (fileEnd <= position) + { + continue; + } + + var count = (int)(Math.Min(stop, fileEnd) - position); + var target = _logical.AsMemory((int)(position - start), count); + var offset = position - file.DataOffset; + if (file.File.Bytes is { } bytes) + { + bytes.AsSpan((int)offset, count).CopyTo(target.Span); + } + else + { + _reader.Read(file.File, offset, target); + } + + position += count; + } + + if (position != stop) + { + throw new InvalidDataException("The archive plan does not cover its data."); + } + } + + public void Dispose() + { + _reader.Dispose(); + _compressor.Dispose(); + } + } + + // Encodes `groups` on several threads and hands each result to `write` in list order. At most + // a few groups per worker are held in memory at once. + private sealed class GroupPipeline(IPackageContent content, int parallelism) : IDisposable + { + private readonly ConcurrentBag _encoders = []; + + public void Run(Plan plan, IReadOnlyList groups, Action write, CancellationToken cancellation) + { + var window = parallelism * 2; + var results = new EncodedGroup[window]; + for (var first = 0; first < groups.Count; first += window) + { + cancellation.ThrowIfCancellationRequested(); + var count = Math.Min(window, groups.Count - first); + try + { + Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = parallelism, CancellationToken = cancellation }, index => + { + if (!_encoders.TryTake(out var encoder)) + { + encoder = new GroupEncoder(content); + } + + try + { + results[index] = encoder.Encode(plan, groups[first + index]); + } + finally + { + _encoders.Add(encoder); + } + }); + } + catch (AggregateException aggregate) + { + cancellation.ThrowIfCancellationRequested(); + var inner = aggregate.Flatten().InnerExceptions; + ExceptionDispatchInfo.Capture(inner.FirstOrDefault(e => e is not OperationCanceledException) ?? inner[0]).Throw(); + } + + for (var index = 0; index < count; index++) + { + write(groups[first + index], results[index]); + results[index] = default; + } + } + } + + public void Dispose() + { + while (_encoders.TryTake(out var encoder)) + { + encoder.Dispose(); + } + } + } + + private static IEnumerable<(string[] Parts, ulong Offset, ulong Size)> TreeEntries(Plan plan) => + plan.Files.Select(file => (file.Parts, (ulong)file.DataOffset, (ulong)file.File.Size)); + + private static long GroupBytes(Plan plan, int group) => + Math.Min(ZArchiveWriter.RecordSpan, plan.DataSize - (long)group * ZArchiveWriter.RecordSpan); + + // ---- direct mode --------------------------------------------------------------------------- + + private static void ConvertDirect(string package, string destination, PkgZarOptions options, IProgress? progress, CancellationToken cancellation) + { + if (File.Exists(JournalPath(destination))) + { + throw new IOException($"{JournalPath(destination)} records an unfinished consuming conversion; run it again with the source consumed to resume it."); + } + + var source = new PackageSource(package); + using var content = (IDisposable)OpenContent(source); + var packageContent = (IPackageContent)content; + var plan = BuildPlan(packageContent, options.WindowBytes); + // Both are compressed, so the archive comes out near the package's size, never far above + // the files it holds. + var estimate = Math.Min(plan.DataSize, source.Length); + if (options.AvailableSpace(destination) is { } available && available < estimate) + { + throw new IOException(NotEnoughSpace(estimate, available)); + } + + var partial = PartialPath(destination); + try + { + using (var output = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 20)) + using (var pipeline = new GroupPipeline(packageContent, options.MaxParallelism)) + { + var records = new (ulong BaseOffset, ushort[] Sizes)[plan.GroupCount]; + long done = 0; + var tracker = new ProgressStep(progress, plan.DataSize); + tracker.Report(0); + pipeline.Run(plan, Enumerable.Range(0, plan.GroupCount).ToArray(), (group, encoded) => + { + records[group] = ((ulong)output.Position, encoded.Sizes); + output.Write(encoded.Data, 0, encoded.Length); + done += GroupBytes(plan, group); + tracker.Report(done); + }, cancellation); + ZArchiveWriter.WriteTrailer(output, (ulong)output.Position, records, TreeEntries(plan)); + output.Flush(flushToDisk: true); + tracker.Report(plan.DataSize, force: true); + } + + File.Move(partial, destination, overwrite: true); + } + catch (Exception exception) + { + try + { + File.Delete(partial); + } + catch (IOException) + { + } + + if (exception is IOException io && IsOutOfSpace(io)) + { + throw new IOException("Out of disk space while writing the archive; the partial archive was removed and the package is untouched.", exception); + } + + throw; + } + } + + // ---- consume mode -------------------------------------------------------------------------- + + private static void ConvertConsuming(string package, string destination, PkgZarOptions options, IProgress? progress, CancellationToken cancellation) + { + try + { + RunConsuming(package, destination, options, progress, cancellation); + } + catch (IOException exception) when (IsOutOfSpace(exception) && exception is not PkgConversionPausedException) + { + throw new PkgConversionPausedException( + "Out of disk space: the conversion is paused and nothing is lost. Free some space and run the same conversion again to resume.", + exception); + } + } + + private static void RunConsuming(string package, string destination, PkgZarOptions options, IProgress? progress, CancellationToken cancellation) + { + var journalPath = JournalPath(destination); + var partialPath = PartialPath(destination); + PackageSource source; + Journal journal; + var committed = new List(); + if (File.Exists(journalPath)) + { + var state = Journal.Read(journalPath); + // Released again below unless the conversion takes it over. + using var pending = new JournalLease(state.Journal); + if (!string.Equals(state.Header.PackagePath, package, StringComparison.Ordinal)) + { + throw new InvalidDataException( + $"{journalPath} belongs to a conversion of {state.Header.PackagePath}, not {package}. Finish that conversion or remove the journal."); + } + + if (state.FinishedLength is { } recordedLength) + { + pending.Dispose(); + FinishCommitted(package, destination, journalPath, partialPath, recordedLength); + return; + } + + if (!File.Exists(package)) + { + throw new InvalidDataException($"{journalPath} records an unfinished conversion, but the package {package} is gone."); + } + + var length = new FileInfo(package).Length; + var frontier = state.Batches.Count > 0 ? state.Batches[^1].Frontier : state.Header.OriginalLength; + if (length > state.Header.OriginalLength || length < frontier) + { + throw new InvalidDataException( + $"The package is {length:N0} bytes, but the journal recorded {state.Header.OriginalLength:N0} bytes cut to {frontier:N0}: it is not the package this conversion started from."); + } + + if (!SnapshotMatchesFile(package, state.Header.Snapshot, length)) + { + throw new InvalidDataException($"The package bytes differ from those recorded in {journalPath}: it is not the package this conversion started from."); + } + + source = PackageSource.OpenTruncated(package, state.Header.OriginalLength, state.Header.Snapshot, frontier); + + committed.AddRange(state.Batches); + journal = pending.Take(); + Log.Info($"Resuming the conversion of {package} after {committed.Count} committed batches."); + } + else + { + source = new PackageSource(package); + source.StartRecording(); + journal = null!; + } + + source.FileReadObserver = options.SourceReadObserver is { } observer ? (offset, count) => observer(offset, count, source.Frontier) : null; + using var content = (IDisposable)OpenContent(source); + var packageContent = (IPackageContent)content; + long finishedLength; + Plan plan; + List batches; + try + { + plan = BuildPlan(packageContent, options.WindowBytes); + batches = BuildBatches(plan, options.WindowBytes); + } + catch + { + journal?.Dispose(); + throw; + } + + try + { + if (journal is null) + { + var snapshot = source.TakeSnapshot(); + var snapshotBytes = snapshot.Sum(range => (long)range.Bytes.Length); + var needed = Math.Min(options.WindowBytes, plan.DataSize) + snapshotBytes + (64L << 20); + if (options.AvailableSpace(destination) is { } available && available < needed) + { + throw new IOException(NotEnoughSpace(needed, available)); + } + + journal = Journal.Create(journalPath, new Journal.HeaderData(package, source.Length, options.WindowBytes, plan.GroupCount, plan.Fingerprint, snapshot)); + options.Observer?.Invoke(PkgZarStage.JournalCreated, -1, source.Frontier); + } + else + { + CheckResumable(journal, plan, batches, committed, options.WindowBytes); + } + + finishedLength = ConsumeBatches(package, partialPath, source, packageContent, plan, batches, journal, committed, options, progress, cancellation); + } + finally + { + journal?.Dispose(); + } + + // Every handle on the package and the partial archive is closed before they move. + content.Dispose(); + FinishCommitted(package, destination, journalPath, partialPath, finishedLength); + options.Observer?.Invoke(PkgZarStage.Finished, batches.Count, 0); + } + + // Disposes a journal on an early exit unless Take hands it on. + private sealed class JournalLease(Journal journal) : IDisposable + { + private Journal? _journal = journal; + + public Journal Take() + { + var taken = _journal!; + _journal = null; + return taken; + } + + public void Dispose() => _journal?.Dispose(); + } + + private static void CheckResumable(Journal journal, Plan plan, List batches, List committed, long windowBytes) + { + var header = journal.Header; + if (header.WindowBytes != windowBytes || header.GroupCount != plan.GroupCount || !header.Fingerprint.AsSpan().SequenceEqual(plan.Fingerprint)) + { + throw new InvalidDataException("The package no longer yields the plan recorded in the journal; refusing to resume."); + } + + if (committed.Count > batches.Count) + { + throw new InvalidDataException("The journal records more batches than the plan has."); + } + + long end = 0; + for (var index = 0; index < committed.Count; index++) + { + var batch = committed[index]; + if (batch.Index != index || !batch.Groups.Select(group => group.Group).SequenceEqual(batches[index]) || batch.ZarStart != end) + { + throw new InvalidDataException($"Journal batch {index} does not match the plan; refusing to resume."); + } + + end = batch.ZarEnd; + } + } + + // Returns the finished archive's length. + private static long ConsumeBatches( + string package, + string partialPath, + PackageSource source, + IPackageContent content, + Plan plan, + List batches, + Journal journal, + List committed, + PkgZarOptions options, + IProgress? progress, + CancellationToken cancellation) + { + var records = new (ulong BaseOffset, ushort[] Sizes)[plan.GroupCount]; + long done = 0; + foreach (var batch in committed) + { + foreach (var placement in batch.Groups) + { + records[placement.Group] = ((ulong)placement.ZarOffset, placement.Sizes); + done += GroupBytes(plan, placement.Group); + } + } + + var committedEnd = committed.Count > 0 ? committed[^1].ZarEnd : 0; + using var output = new FileStream(partialPath, committed.Count > 0 ? FileMode.Open : FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 20); + if (output.Length < committedEnd) + { + throw new InvalidDataException($"{partialPath} is {output.Length:N0} bytes, shorter than the {committedEnd:N0} bytes the journal committed."); + } + + // Anything past the last commit belongs to a batch that never finished; it is redone. + output.SetLength(committedEnd); + output.Position = committedEnd; + var tracker = new ProgressStep(progress, plan.DataSize); + tracker.Report(done); + using (var cutter = File.OpenHandle(package, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) + { + var packageLength = RandomAccess.GetLength(cutter); + void Cut(long frontier) + { + source.Frontier = Math.Min(source.Frontier, frontier); + if (frontier < packageLength) + { + RandomAccess.SetLength(cutter, frontier); + packageLength = frontier; + } + } + + // A crash between a commit and its truncation leaves the package longer than committed. + if (committed.Count > 0) + { + Cut(committed[^1].Frontier); + } + + using var pipeline = new GroupPipeline(content, options.MaxParallelism); + for (var index = committed.Count; index < batches.Count; index++) + { + var groups = batches[index]; + var start = output.Position; + var placements = new List(groups.Length); + pipeline.Run(plan, groups, (group, encoded) => + { + placements.Add(new Journal.Placement(group, output.Position, encoded.Sizes)); + output.Write(encoded.Data, 0, encoded.Length); + }, cancellation); + options.Observer?.Invoke(PkgZarStage.BatchWritten, index, packageLength); + output.Flush(flushToDisk: true); + var frontier = index + 1 < batches.Count ? plan.GroupEnds[batches[index + 1][0]] : 0; + journal.Append(new Journal.Batch(index, start, output.Position, frontier, placements)); + foreach (var placement in placements) + { + records[placement.Group] = ((ulong)placement.ZarOffset, placement.Sizes); + done += GroupBytes(plan, placement.Group); + } + + options.Observer?.Invoke(PkgZarStage.BatchCommitted, index, packageLength); + Cut(frontier); + options.Observer?.Invoke(PkgZarStage.BatchTruncated, index, packageLength); + tracker.Report(done); + } + } + + options.Observer?.Invoke(PkgZarStage.DataComplete, batches.Count, source.Frontier); + ZArchiveWriter.WriteTrailer(output, (ulong)output.Position, records, TreeEntries(plan)); + output.Flush(flushToDisk: true); + options.Observer?.Invoke(PkgZarStage.TrailerWritten, batches.Count, source.Frontier); + journal.AppendFinished(output.Length); + options.Observer?.Invoke(PkgZarStage.JournalFinished, batches.Count, source.Frontier); + tracker.Report(plan.DataSize, force: true); + return output.Length; + } + + // The archive is complete on disk and the journal says so: move it into place, then drop the + // package and the journal. Each step can be repeated after a crash. + private static void FinishCommitted(string package, string destination, string journalPath, string partialPath, long finishedLength) + { + if (File.Exists(partialPath)) + { + var length = new FileInfo(partialPath).Length; + if (length != finishedLength) + { + throw new InvalidDataException($"{partialPath} is {length:N0} bytes, but the journal finished it at {finishedLength:N0}."); + } + + File.Move(partialPath, destination, overwrite: true); + } + else if (!File.Exists(destination)) + { + throw new InvalidDataException($"The journal says {destination} was finished, but neither it nor {partialPath} exists."); + } + + File.Delete(package); + File.Delete(journalPath); + } + + private static bool SnapshotMatchesFile(string package, IReadOnlyList<(long Offset, byte[] Bytes)> snapshot, long length) + { + using var handle = File.OpenHandle(package, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + foreach (var (offset, bytes) in snapshot) + { + var count = (int)Math.Clamp(length - offset, 0, bytes.Length); + if (count == 0) + { + continue; + } + + var actual = new byte[count]; + var done = 0; + while (done < count) + { + var read = RandomAccess.Read(handle, actual.AsSpan(done), offset + done); + if (read == 0) + { + return false; + } + + done += read; + } + + if (!actual.AsSpan().SequenceEqual(bytes.AsSpan(0, count))) + { + return false; + } + } + + return true; + } + + // ENOSPC/EDQUOT on Unix (the errno becomes the HResult), ERROR_DISK_FULL/ERROR_HANDLE_DISK_FULL on Windows. + internal static bool IsOutOfSpace(IOException exception) => + exception.HResult is 28 or 69 or 122 or unchecked((int)0x80070070) or unchecked((int)0x80070027); + + private static string NotEnoughSpace(long needed, long available) => string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"Not enough free disk space: need {needed / (1024.0 * 1024 * 1024):0.00} GB, {available / (1024.0 * 1024 * 1024):0.00} GB free."); + + // Reports at most every 16 MiB of archive data, never going backwards. + private sealed class ProgressStep(IProgress? progress, long total) + { + private long _reported = -1; + + public void Report(long done, bool force = false) + { + if (progress is null || (!force && _reported >= 0 && done - _reported < PkgPackage.ProgressStepBytes)) + { + return; + } + + _reported = done; + progress.Report(new PkgExtractProgress(done, total, string.Empty)); + } + } + + // ---- journal ------------------------------------------------------------------------------- + + // .journal: a header written once (through a temporary file, so it is whole or absent), + // then one record per committed batch and a final record once the archive is complete. Every + // part carries a SHA-256; a record cut short by a crash is the uncommitted tail and is dropped. + internal sealed class Journal : IDisposable + { + private const uint Magic = 0x4A5A4553; // "SEZJ" + private const uint Version = 1; + private const uint BatchKind = 1; + private const uint FinishedKind = 2; + private const int HashBytes = 32; + + private readonly FileStream _stream; + + private Journal(FileStream stream, HeaderData header) + { + _stream = stream; + Header = header; + } + + public HeaderData Header { get; } + + public sealed record HeaderData( + string PackagePath, + long OriginalLength, + long WindowBytes, + int GroupCount, + byte[] Fingerprint, + IReadOnlyList<(long Offset, byte[] Bytes)> Snapshot); + + public readonly record struct Placement(int Group, long ZarOffset, ushort[] Sizes); + + public sealed record Batch(int Index, long ZarStart, long ZarEnd, long Frontier, IReadOnlyList Groups); + + public sealed record State(Journal Journal, HeaderData Header, List Batches, long? FinishedLength); + + public static Journal Create(string path, HeaderData header) + { + var body = new MemoryStream(); + using (var writer = new BinaryWriter(body, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(Magic); + writer.Write(Version); + writer.Write(header.PackagePath); + writer.Write(header.OriginalLength); + writer.Write(header.WindowBytes); + writer.Write(header.GroupCount); + writer.Write(header.Fingerprint); + writer.Write(header.Snapshot.Count); + foreach (var (offset, bytes) in header.Snapshot) + { + writer.Write(offset); + writer.Write(bytes.Length); + writer.Write(bytes); + } + } + + body.Write(SHA256.HashData(body.GetBuffer().AsSpan(0, (int)body.Length))); + var temporary = path + ".tmp"; + using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None)) + { + body.Position = 0; + body.CopyTo(file); + file.Flush(flushToDisk: true); + } + + File.Move(temporary, path, overwrite: true); + var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); + stream.Position = stream.Length; + return new Journal(stream, header); + } + + public static string ReadPackagePath(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var reader = new BinaryReader(stream, Encoding.UTF8); + if (reader.ReadUInt32() != Magic || reader.ReadUInt32() != Version) + { + throw new InvalidDataException($"{path} is not a conversion journal this version understands."); + } + + return reader.ReadString(); + } + + public static State Read(string path) + { + var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); + try + { + var bytes = new byte[stream.Length]; + stream.ReadExactly(bytes); + var reader = new BinaryReader(new MemoryStream(bytes), Encoding.UTF8); + HeaderData header; + try + { + if (reader.ReadUInt32() != Magic || reader.ReadUInt32() != Version) + { + throw new InvalidDataException($"{path} is not a conversion journal this version understands."); + } + + var packagePath = reader.ReadString(); + var originalLength = reader.ReadInt64(); + var window = reader.ReadInt64(); + var groupCount = reader.ReadInt32(); + var fingerprint = reader.ReadBytes(HashBytes); + var count = reader.ReadInt32(); + if (count < 0) + { + throw new InvalidDataException($"{path} has a damaged header."); + } + + var snapshot = new List<(long Offset, byte[] Bytes)>(count); + for (var index = 0; index < count; index++) + { + var offset = reader.ReadInt64(); + var length = reader.ReadInt32(); + snapshot.Add((offset, reader.ReadBytes(length))); + } + + header = new HeaderData(packagePath, originalLength, window, groupCount, fingerprint, snapshot); + } + catch (EndOfStreamException) + { + throw new InvalidDataException($"{path} has a truncated header."); + } + + var headerEnd = (int)reader.BaseStream.Position; + if (headerEnd + HashBytes > bytes.Length || + !SHA256.HashData(bytes.AsSpan(0, headerEnd)).AsSpan().SequenceEqual(bytes.AsSpan(headerEnd, HashBytes))) + { + throw new InvalidDataException($"{path} has a damaged header; refusing to guess which bytes of the package are gone."); + } + + var batches = new List(); + long? finished = null; + var position = headerEnd + HashBytes; + while (position < bytes.Length) + { + if (bytes.Length - position < 8) + { + break; + } + + var kind = BitConverter.ToUInt32(bytes, position); + var length = BitConverter.ToUInt32(bytes, position + 4); + if (length > bytes.Length - position - 8 - HashBytes) + { + break; + } + + var end = position + 8 + (int)length; + if (!SHA256.HashData(bytes.AsSpan(position, 8 + (int)length)).AsSpan().SequenceEqual(bytes.AsSpan(end, HashBytes))) + { + if (end + HashBytes == bytes.Length) + { + break; + } + + throw new InvalidDataException($"{path} has a damaged record at 0x{position:X}; refusing to resume."); + } + + if (finished is not null) + { + throw new InvalidDataException($"{path} has records after its finished record."); + } + + var payload = new BinaryReader(new MemoryStream(bytes, position + 8, (int)length)); + if (kind == BatchKind) + { + var index = payload.ReadInt32(); + var start = payload.ReadInt64(); + var stop = payload.ReadInt64(); + var frontier = payload.ReadInt64(); + var count = payload.ReadInt32(); + var placements = new List(count); + for (var group = 0; group < count; group++) + { + var number = payload.ReadInt32(); + var offset = payload.ReadInt64(); + var sizes = new ushort[ZArchiveWriter.BlocksPerRecord]; + for (var block = 0; block < sizes.Length; block++) + { + sizes[block] = payload.ReadUInt16(); + } + + placements.Add(new Placement(number, offset, sizes)); + } + + batches.Add(new Batch(index, start, stop, frontier, placements)); + } + else if (kind == FinishedKind) + { + finished = payload.ReadInt64(); + } + else + { + throw new InvalidDataException($"{path} has an unknown record kind {kind}."); + } + + position = end + HashBytes; + } + + if (position < bytes.Length) + { + Log.Warn($"{path}: dropping {bytes.Length - position} bytes of a record a crash cut short (its batch is redone)."); + stream.SetLength(position); + } + + stream.Position = position; + var journal = new Journal(stream, header); + return new State(journal, header, batches, finished); + } + catch + { + stream.Dispose(); + throw; + } + } + + public void Append(Batch batch) + { + var payload = new MemoryStream(); + using (var writer = new BinaryWriter(payload, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(batch.Index); + writer.Write(batch.ZarStart); + writer.Write(batch.ZarEnd); + writer.Write(batch.Frontier); + writer.Write(batch.Groups.Count); + foreach (var placement in batch.Groups) + { + writer.Write(placement.Group); + writer.Write(placement.ZarOffset); + foreach (var size in placement.Sizes) + { + writer.Write(size); + } + } + } + + AppendRecord(BatchKind, payload.ToArray()); + } + + public void AppendFinished(long zarLength) => AppendRecord(FinishedKind, BitConverter.GetBytes(zarLength)); + + private void AppendRecord(uint kind, byte[] payload) + { + var record = new byte[8 + payload.Length + HashBytes]; + BitConverter.TryWriteBytes(record.AsSpan(0, 4), kind); + BitConverter.TryWriteBytes(record.AsSpan(4, 4), (uint)payload.Length); + payload.CopyTo(record, 8); + SHA256.HashData(record.AsSpan(0, 8 + payload.Length), record.AsSpan(8 + payload.Length)); + _stream.Write(record); + _stream.Flush(flushToDisk: true); + } + + public void Dispose() => _stream.Dispose(); + } +} + +internal enum PkgZarStage +{ + JournalCreated, + BatchWritten, + BatchCommitted, + BatchTruncated, + DataComplete, + TrailerWritten, + JournalFinished, + Finished, +} + +internal sealed class PkgZarOptions +{ + public bool ConsumeSource { get; init; } + + // Package bytes one consume batch spans (and archive bytes it writes) before the package is cut. + public long WindowBytes { get; init; } = PkgZarConverter.DefaultWindowBytes; + + public int MaxParallelism { get; init; } = Math.Clamp(Environment.ProcessorCount / 2, 1, 8); + + // Free bytes for the destination, or null when unknown (no check). + public Func AvailableSpace { get; init; } = PkgPackage.GetAvailableSpace; + + // (stage, batch index, package length) at each step of a consuming conversion; throwing from it + // simulates a crash at that point. + public Action? Observer { get; init; } + + // (offset, length, frontier) of every read that goes to the package file. + public Action? SourceReadObserver { get; init; } +} diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs index b9999acc1..d2ab4ccb0 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Fih.cs @@ -17,7 +17,7 @@ internal sealed record Ps5Fih(ushort FormatVersion, long PfsOffset, long PfsSize private static ReadOnlySpan Magic => [0x7F, 0x46, 0x49, 0x48]; - public static Ps5Fih Read(Ps5Source source) + public static Ps5Fih Read(PackageSource source) { if (source.Length < HeaderSize) { @@ -92,7 +92,7 @@ private Ps5Cnt(string contentId, List files, List skippedEnc public long FilesSize => Files.Sum(file => (long)file.Bytes.Length); - public static Ps5Cnt Read(Ps5Source source, long cntOffset) + public static Ps5Cnt Read(PackageSource source, long cntOffset) { var header = source.ReadBytes(0x80, cntOffset); if (!header.AsSpan(0, 4).SequenceEqual(new byte[] { 0x7F, 0x43, 0x4E, 0x54 })) diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs index 604ac4552..2a386b4eb 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5InnerImage.cs @@ -231,6 +231,29 @@ public void ReadAt(long logical, byte[] buffer) // Streams logical bytes to `sink` one block at a time. public void CopyTo(long logical, long size, SpanAction sink) => _defaultReader.CopyTo(logical, size, sink); + // Package offset just past the last byte that decoding logical [logical, logical+size) reads: + // every block overlapping the range loads its whole stored payload; sparse blocks read nothing. + public long SourceEnd(long logical, long size) + { + if (size <= 0) + { + return 0; + } + + long end = 0; + var stop = logical + size; + for (var index = FindBlock(logical); index < _blocks.Length && _blocks[index].Logical < stop; index++) + { + var block = _blocks[index]; + if (block.Compressed != 0) + { + end = Math.Max(end, _image.SourceEnd(block.OnDisk, block.Compressed)); + } + } + + return end; + } + // A reader with its own decode buffers, for one thread of a parallel extraction. internal BlockReader CreateReader() => new(this); diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs index bcf5aa4ad..9a4166d74 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5OuterPfs.cs @@ -24,13 +24,13 @@ internal sealed class Ps5OuterPfs private static readonly byte[] PlainNoAuthSeed = "PPRPLAIN-NOAUTH!"u8.ToArray(); - private readonly Ps5Source _source; + private readonly PackageSource _source; private readonly long _base; private readonly long _size; private readonly InodeLayout _layout; private readonly Inode[] _inodes; - private Ps5OuterPfs(Ps5Source source, long pfsOffset, long pfsSize, Ps5PfsSuperblock superblock, InodeLayout layout, Inode[] inodes) + private Ps5OuterPfs(PackageSource source, long pfsOffset, long pfsSize, Ps5PfsSuperblock superblock, InodeLayout layout, Inode[] inodes) { _source = source; _base = pfsOffset; @@ -104,7 +104,7 @@ public long Pointer(ReadOnlySpan buf, int index) internal sealed record Inode(long Size, long[] Direct, long[] Indirect); - public static Ps5OuterPfs Open(Ps5Source source, long pfsOffset, long pfsSize, long superblockOffset) + public static Ps5OuterPfs Open(PackageSource source, long pfsOffset, long pfsSize, long superblockOffset) { // Data-first images keep the superblock near the end, where the header points; classic // images keep it at the start of the segment. @@ -288,7 +288,7 @@ internal static long BlockOffset(long baseOffset, long block, long blockSize) } // A file of the outer PFS, read through its block list. -internal sealed class Ps5OuterFile(Ps5Source source, long baseOffset, long blockSize, long[] blocks, long size) +internal sealed class Ps5OuterFile(PackageSource source, long baseOffset, long blockSize, long[] blocks, long size) { public long Size { get; } = size; @@ -320,6 +320,30 @@ public void ReadExactAt(Span buffer, long offset) } } + // Package offset just past the last byte ReadExactAt(offset, count) reads; 0 for an empty range. + public long SourceEnd(long offset, long count) + { + if (count <= 0) + { + return 0; + } + + if (offset < 0 || offset > Size || count > Size - offset) + { + throw new InvalidDataException($"Range of {count:N0} bytes at 0x{offset:X} is past the end of a {Size:N0}-byte outer file."); + } + + long end = 0; + var last = (offset + count - 1) / blockSize; + for (var index = offset / blockSize; index <= last; index++) + { + var within = Math.Min(offset + count, (index + 1) * blockSize) - index * blockSize; + end = Math.Max(end, Ps5OuterPfs.BlockOffset(baseOffset, blocks[index], blockSize) + within); + } + + return end; + } + public byte[] ReadAll() { var bytes = new byte[Size]; diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs index 224dfd967..5c4b32239 100644 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs +++ b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Package.cs @@ -11,7 +11,7 @@ namespace SharpEmu.HLE.FileSystem.Pkg; // PFS is encrypted are refused at Open: their files need console keys. Extraction decodes the files // block by block on several threads (a big file is split into ranges too), so a package of any // size needs only a few hundred KiB of memory per worker. -public sealed class Ps5Package : IGamePackage +public sealed class Ps5Package : IGamePackage, IPackageContent { private const string ImageFileName = "pfs_image.dat"; private const string LayoutFileName = "naps_pkg_layout.dat"; @@ -21,7 +21,7 @@ public sealed class Ps5Package : IGamePackage // few huge files still spread over every worker. private const long DefaultChunkBytes = 64L << 20; - private readonly Ps5Source _source; + private readonly PackageSource _source; private readonly Ps5Fih _fih; private readonly Ps5Cnt _cnt; private readonly Ps5OuterPfs _outer; @@ -32,7 +32,7 @@ public sealed class Ps5Package : IGamePackage private List? _files; private long _filesSize; - private Ps5Package(Ps5Source source, Ps5Fih fih, Ps5Cnt cnt, Ps5OuterPfs outer) + private Ps5Package(PackageSource source, Ps5Fih fih, Ps5Cnt cnt, Ps5OuterPfs outer) { _source = source; _fih = fih; @@ -65,9 +65,11 @@ private Ps5Package(Ps5Source source, Ps5Fih fih, Ps5Cnt cnt, Ps5OuterPfs outer) public string GetFolderName(string fallback) => PkgPackage.ToFolderName(Title) ?? PkgPackage.ToFolderName(TitleId) ?? fallback; - public static Ps5Package Open(string path) + public static Ps5Package Open(string path) => Open(new PackageSource(path)); + + // Takes ownership of `source`. + internal static Ps5Package Open(PackageSource source) { - var source = new Ps5Source(path); try { var fih = Ps5Fih.Read(source); @@ -287,6 +289,54 @@ public void Add(int bytes, string file) } } + PackageSource IPackageContent.Source => _source; + + IReadOnlyList IPackageContent.ListContentFiles() + { + var (_, files) = LoadTree(); + var content = new List(_cnt.Files.Count + files.Count); + foreach (var file in _cnt.Files) + { + PkgPackage.ResolveSafe(string.Empty, ["sce_sys", .. file.Name.Split('/')]); + content.Add(new PackageContentFile("sce_sys/" + file.Name, file.Bytes.Length, file.Bytes, null)); + } + + foreach (var file in files) + { + PkgPackage.ResolveSafe(string.Empty, file.Components); + content.Add(new PackageContentFile(string.Join('/', file.Components), file.Size, null, file)); + } + + return content; + } + + long IPackageContent.SourceEnd(PackageContentFile file, long offset, long length) => + file.Native is Ps5InnerFile inner ? LoadTree().Image.SourceEnd(inner.Logical + offset, length) : 0; + + IPackageContentReader IPackageContent.CreateContentReader() => new ContentReader(LoadTree().Image.CreateReader()); + + private sealed class ContentReader(Ps5InnerImage.BlockReader reader) : IPackageContentReader + { + public void Read(PackageContentFile file, long offset, Memory destination) + { + var inner = (Ps5InnerFile)file.Native!; + var done = 0; + reader.CopyTo(inner.Logical + offset, destination.Length, chunk => + { + chunk.CopyTo(destination.Span[done..]); + done += chunk.Length; + }); + if (done != destination.Length) + { + throw new InvalidDataException("The inner image returned fewer bytes than asked for."); + } + } + + public void Dispose() + { + } + } + // Opens the inner image and lists its files once; both GetInstalledSize and Extract need them. private (Ps5InnerImage Image, List Files) LoadTree() { diff --git a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs b/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs deleted file mode 100644 index 59a8c98c8..000000000 --- a/src/SharpEmu.HLE/FileSystem/Pkg/Ps5Source.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2026 SharpEmu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -using Microsoft.Win32.SafeHandles; - -namespace SharpEmu.HLE.FileSystem.Pkg; - -// Positional reads over the package file; every read is range checked. -internal sealed class Ps5Source : IDisposable -{ - private readonly SafeFileHandle _handle; - - public Ps5Source(string path) - { - _handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, FileOptions.RandomAccess); - Length = RandomAccess.GetLength(_handle); - } - - public long Length { get; } - - public void ReadExactAt(Span buffer, long offset) - { - if (offset < 0 || offset > Length || buffer.Length > Length - offset) - { - throw new InvalidDataException(string.Create( - System.Globalization.CultureInfo.InvariantCulture, - $"Read of {buffer.Length:N0} bytes at 0x{offset:X} is past the end of the {Length:N0}-byte package.")); - } - - var done = 0; - while (done < buffer.Length) - { - var read = RandomAccess.Read(_handle, buffer[done..], offset + done); - if (read == 0) - { - throw new InvalidDataException("The package file ended unexpectedly."); - } - - done += read; - } - } - - public byte[] ReadBytes(long length, long offset) - { - if (length < 0 || length > int.MaxValue || offset < 0 || offset > Length || length > Length - offset) - { - throw new InvalidDataException(string.Create( - System.Globalization.CultureInfo.InvariantCulture, - $"Read of {length:N0} bytes at 0x{offset:X} is past the end of the {Length:N0}-byte package.")); - } - - var bytes = new byte[length]; - ReadExactAt(bytes, offset); - return bytes; - } - - public void Dispose() => _handle.Dispose(); -} diff --git a/src/SharpEmu.HLE/FileSystem/ZArchiveWriter.cs b/src/SharpEmu.HLE/FileSystem/ZArchiveWriter.cs index 148ed8c41..c5d511a9a 100644 --- a/src/SharpEmu.HLE/FileSystem/ZArchiveWriter.cs +++ b/src/SharpEmu.HLE/FileSystem/ZArchiveWriter.cs @@ -14,7 +14,10 @@ namespace SharpEmu.HLE.FileSystem; // through one block at a time, so a large game needs little memory. public static class ZArchiveWriter { - private const int CompressionLevel = 6; + internal const int CompressionLevel = 6; + internal const int BlocksPerRecord = 16; + // Logical bytes behind one offset record: 16 blocks, placed anywhere in the data section. + internal const int RecordSpan = ZArchive.BlockSize * BlocksPerRecord; private const uint Version = 0x61BF3A01; private const uint Magic = 0x169F52D6; @@ -106,37 +109,27 @@ private static void Write( IProgress? progress, CancellationToken cancellationToken) { - var root = new PathNode(string.Empty, isFile: false); var block = new byte[ZArchive.BlockSize]; + var encoded = new byte[EncodeBufferSize]; var filled = 0; var blockIndex = 0; var records = new List<(ulong BaseOffset, ushort[] Sizes)>(); + var entries = new List<(string[] Parts, ulong Offset, ulong Size)>(files.Count); using var compressor = new Compressor(CompressionLevel); ulong dataOffset = 0; var lastReport = 0L; void FlushBlock() { - var compressed = compressor.Wrap(block); var offset = (ulong)output.Position; - int size; - if (compressed.Length >= ZArchive.BlockSize) - { - output.Write(block); - size = ZArchive.BlockSize; - } - else - { - output.Write(compressed); - size = compressed.Length; - } - - if (blockIndex % 16 == 0) + var size = EncodeBlock(compressor, block, encoded); + output.Write(encoded, 0, size); + if (blockIndex % BlocksPerRecord == 0) { - records.Add((offset, new ushort[16])); + records.Add((offset, new ushort[BlocksPerRecord])); } - records[^1].Sizes[blockIndex % 16] = (ushort)(size - 1); + records[^1].Sizes[blockIndex % BlocksPerRecord] = (ushort)(size - 1); blockIndex++; filled = 0; } @@ -144,20 +137,8 @@ void FlushBlock() for (var index = 0; index < files.Count; index++) { var parts = Path.GetRelativePath(source, files[index].FullName).Split(Path.DirectorySeparatorChar); - var directory = root; - foreach (var part in parts[..^1]) - { - var next = directory.Children.Find(child => string.Equals(child.Name, part, StringComparison.OrdinalIgnoreCase)); - if (next is null) - { - next = new PathNode(part, isFile: false); - directory.Children.Add(next); - } - - directory = next; - } - - var file = new PathNode(parts[^1], isFile: true) { FileOffset = dataOffset }; + var fileOffset = dataOffset; + ulong fileSize = 0; using (var input = new FileStream(files[index].FullName, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20)) { int read; @@ -165,7 +146,7 @@ void FlushBlock() { filled += read; dataOffset += (ulong)read; - file.FileSize += (ulong)read; + fileSize += (ulong)read; if (filled == block.Length) { cancellationToken.ThrowIfCancellationRequested(); @@ -179,7 +160,7 @@ void FlushBlock() } } - directory.Children.Add(file); + entries.Add((parts, fileOffset, fileSize)); } if (filled > 0) @@ -188,7 +169,56 @@ void FlushBlock() FlushBlock(); } - var dataSize = (ulong)output.Position; + WriteTrailer(output, (ulong)output.Position, records, entries); + progress?.Report(new Progress(bytesTotal, bytesTotal, files.Count, files.Count)); + } + + // Room EncodeBlock needs in its destination. + internal static int EncodeBufferSize { get; } = Math.Max(Compressor.GetCompressBound(ZArchive.BlockSize), ZArchive.BlockSize); + + // Compresses one 64 KiB block into `destination` (EncodeBufferSize bytes) and returns its stored + // size: the zstd frame, or the raw block when the frame does not shrink it. + internal static int EncodeBlock(Compressor compressor, ReadOnlySpan block, Span destination) + { + var size = compressor.Wrap(block, destination); + if (size >= ZArchive.BlockSize) + { + block.CopyTo(destination); + return ZArchive.BlockSize; + } + + return size; + } + + // Writes everything after the compressed data: padding to 8 bytes, the offset records, names, the + // breadth-first tree (each directory's children sorted without case; directories merge without + // case, the first spelling wins) and the footer. `output` sits at `dataSize`, the end of the data + // section. Files are (path parts, data offset, size), in the order their nodes are created. + internal static void WriteTrailer( + Stream output, + ulong dataSize, + IReadOnlyList<(ulong BaseOffset, ushort[] Sizes)> records, + IEnumerable<(string[] Parts, ulong Offset, ulong Size)> files) + { + var root = new PathNode(string.Empty, isFile: false); + foreach (var (parts, offset, size) in files) + { + var directory = root; + foreach (var part in parts[..^1]) + { + var next = directory.Children.Find(child => string.Equals(child.Name, part, StringComparison.OrdinalIgnoreCase)); + if (next is null) + { + next = new PathNode(part, isFile: false); + directory.Children.Add(next); + } + + directory = next; + } + + directory.Children.Add(new PathNode(parts[^1], isFile: true) { FileOffset = offset, FileSize = size }); + } + while (output.Position % 8 != 0) { output.WriteByte(0); @@ -286,7 +316,6 @@ void FlushBlock() WriteU64(output, (ulong)output.Position + 8 + 4 + 4); WriteU32(output, Version); WriteU32(output, Magic); - progress?.Report(new Progress(bytesTotal, bytesTotal, files.Count, files.Count)); } private static void WriteU16(Stream stream, ushort value) diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs index 14a74dce5..727a51b84 100644 --- a/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs +++ b/tests/SharpEmu.Libs.Tests/FileSystem/PkgTests.cs @@ -559,7 +559,7 @@ private sealed class CollectingProgress(Action handler) : IProgress // A minimal PKG with one unencrypted PFS image and a few sce_sys entries. No key entries: // the reader falls back to reading the image as-is, which keeps this fixture self-contained. - private static byte[] BuildSyntheticPkg(byte[] image, params (uint Id, byte[] Data)[] entries) + internal static byte[] BuildSyntheticPkg(byte[] image, params (uint Id, byte[] Data)[] entries) { const int imageOffset = 0x20000; // FindOffset starts looking for PFSC after the image's own header blocks. @@ -603,7 +603,7 @@ private static void WriteEntry(Span row, uint id, uint nameOffset, uint fl BinaryPrimitives.WriteUInt32BigEndian(row[20..], size); } - private static int WriteDirent(byte[] block, int offset, int inode, PfsDirentType type, string name) + internal static int WriteDirent(byte[] block, int offset, int inode, PfsDirentType type, string name) { var nameBytes = Encoding.UTF8.GetBytes(name); var entrySize = (16 + nameBytes.Length + 7) & ~7; @@ -615,7 +615,7 @@ private static int WriteDirent(byte[] block, int offset, int inode, PfsDirentTyp return offset + entrySize; } - private static void WriteInode(byte[] block, int slot, ushort mode, long size, uint blocks, uint location) + internal static void WriteInode(byte[] block, int slot, ushort mode, long size, uint blocks, uint location) { var span = block.AsSpan(slot * PfsInode.Stride, PfsInode.Stride); BinaryPrimitives.WriteUInt16LittleEndian(span, mode); diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/PkgZarConverterTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/PkgZarConverterTests.cs new file mode 100644 index 000000000..e434f55e2 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/FileSystem/PkgZarConverterTests.cs @@ -0,0 +1,662 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.IO.Compression; +using SharpEmu.HLE.FileSystem; +using SharpEmu.HLE.FileSystem.Pkg; +using Xunit; + +namespace SharpEmu.Libs.Tests.FileSystem; + +// Synthetic packages only. Each test compares the archive against what Extract writes for the +// same package, so the converter must list, name and decode exactly what a folder install does. +public sealed class PkgZarConverterTests : IDisposable +{ + // Window below one group: every consume batch holds one 1 MiB group. + private const long TinyWindow = 1; + + private readonly string _directory = Directory.CreateTempSubdirectory("sharpemu-pkgzar-").FullName; + + public void Dispose() => Directory.Delete(_directory, recursive: true); + + public enum Format + { + Ps4, + Ps5, + Ps5Scrambled, + Ps5Small, + } + + // ---- direct mode --------------------------------------------------------------------------- + + [Theory] + [InlineData(Format.Ps4)] + [InlineData(Format.Ps5)] + [InlineData(Format.Ps5Scrambled)] + [InlineData(Format.Ps5Small)] + public void DirectModeHoldsWhatExtractWritesAndLeavesThePackage(Format format) + { + var bytes = Build(format); + var package = Write("game.pkg", bytes); + var destination = Path.Combine(_directory, "game.zar"); + + PkgZarConverter.Convert(package, destination, Options(consume: false).Build(), null, default); + + Assert.Equal(ExtractTree(bytes), ReadArchive(destination)); + Assert.Equal(bytes, File.ReadAllBytes(package)); + Assert.False(File.Exists(PkgZarConverter.PartialPath(destination))); + Assert.False(File.Exists(PkgZarConverter.JournalPath(destination))); + } + + // ---- consume mode -------------------------------------------------------------------------- + + [Theory] + [InlineData(Format.Ps4)] + [InlineData(Format.Ps5)] + [InlineData(Format.Ps5Scrambled)] + [InlineData(Format.Ps5Small)] + public void ConsumeModeShrinksThePackageAndEndsWithOnlyTheArchive(Format format) + { + var bytes = Build(format); + var package = Write("game.pkg", bytes); + var destination = Path.Combine(_directory, "game.zar"); + var lengths = new List { bytes.Length }; + var reads = 0; + var options = Options(consume: true) with + { + Observer = (stage, _, _) => + { + if (stage == PkgZarStage.BatchTruncated) + { + lengths.Add(new FileInfo(package).Length); + } + }, + // Every byte read from the file must lie below the current cut. + SourceReadObserver = (offset, length, frontier) => + { + Assert.True(offset + length <= frontier, $"read 0x{offset:X}+0x{length:X} past the frontier 0x{frontier:X}"); + Assert.True(offset + length <= new FileInfo(package).Length); + reads++; + }, + }; + + PkgZarConverter.Convert(package, destination, options.Build(), null, default); + + Assert.True(reads > 0); + Assert.Equal(ExtractTree(bytes), ReadArchive(destination)); + Assert.False(File.Exists(package)); + Assert.False(File.Exists(PkgZarConverter.PartialPath(destination))); + Assert.False(File.Exists(PkgZarConverter.JournalPath(destination))); + for (var index = 1; index < lengths.Count; index++) + { + Assert.True(lengths[index] <= lengths[index - 1], $"package grew: {string.Join(", ", lengths)}"); + } + + if (format is Format.Ps4 or Format.Ps5) + { + // Contiguous layouts let most batches give space back, down to the parsed metadata. + Assert.True(lengths.Distinct().Count() >= 4, $"package barely shrank: {string.Join(", ", lengths)}"); + Assert.True(lengths[^1] < bytes.Length / 2, $"package barely shrank: {string.Join(", ", lengths)}"); + } + } + + // ---- interruption and resume --------------------------------------------------------------- + + public static TheoryData Interruptions() + { + var data = new TheoryData(); + foreach (var format in new[] { Format.Ps4, Format.Ps5 }) + { + data.Add(format, nameof(PkgZarStage.JournalCreated), -1); + data.Add(format, nameof(PkgZarStage.BatchWritten), 0); + data.Add(format, nameof(PkgZarStage.BatchCommitted), 0); + data.Add(format, nameof(PkgZarStage.BatchTruncated), 1); + data.Add(format, nameof(PkgZarStage.BatchWritten), 3); + data.Add(format, nameof(PkgZarStage.BatchCommitted), 4); + data.Add(format, nameof(PkgZarStage.DataComplete), -1); + data.Add(format, nameof(PkgZarStage.TrailerWritten), -1); + data.Add(format, nameof(PkgZarStage.JournalFinished), -1); + } + + return data; + } + + [Theory] + [MemberData(nameof(Interruptions))] + public void AnInterruptedConversionResumesToTheSameArchive(Format format, string stageName, int batch) + { + var stage = Enum.Parse(stageName); + var bytes = Build(format); + var expected = ConsumeUninterrupted(bytes); + var package = Write("game.pkg", bytes); + var destination = Path.Combine(_directory, "game.zar"); + var options = Options(consume: true) with + { + Observer = (at, index, _) => + { + if (at == stage && (batch < 0 || index == batch)) + { + throw new SimulatedCrash(); + } + }, + }; + + Assert.Throws(() => PkgZarConverter.Convert(package, destination, options.Build(), null, default)); + Assert.True(File.Exists(PkgZarConverter.JournalPath(destination))); + Assert.False(File.Exists(destination)); + + PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default); + + Assert.Equal(expected, File.ReadAllBytes(destination)); + Assert.False(File.Exists(package)); + Assert.False(File.Exists(PkgZarConverter.JournalPath(destination))); + } + + [Theory] + [InlineData(Format.Ps4)] + [InlineData(Format.Ps5)] + public void CancellationAndRunningOutOfSpacePauseAndResumeRepeatedly(Format format) + { + var bytes = Build(format); + var expected = ConsumeUninterrupted(bytes); + var package = Write("game.pkg", bytes); + var destination = Path.Combine(_directory, "game.zar"); + + using (var cancellation = new CancellationTokenSource()) + { + var cancelling = Options(consume: true) with + { + Observer = (stage, index, _) => + { + if (stage == PkgZarStage.BatchTruncated && index == 1) + { + cancellation.Cancel(); + } + }, + }; + Assert.ThrowsAny(() => PkgZarConverter.Convert(package, destination, cancelling.Build(), null, cancellation.Token)); + } + + var full = Options(consume: true) with + { + Observer = (stage, index, _) => + { + if (stage == PkgZarStage.BatchWritten && index == 3) + { + throw new IOException("No space left on device", 28); + } + }, + }; + var paused = Assert.Throws(() => PkgZarConverter.Convert(package, destination, full.Build(), null, default)); + Assert.Contains("resume", paused.Message); + Assert.Equal(destination, PkgZarConverter.FindPendingDestination(package)); + + PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default); + Assert.Equal(expected, File.ReadAllBytes(destination)); + Assert.False(File.Exists(package)); + } + + [Fact] + public void AJournalForAnotherPackageIsRefused() + { + var first = Build(Format.Ps5); + var second = Build(Format.Ps4); + var package = Write("game.pkg", first); + var other = Write("other.pkg", second); + var destination = Path.Combine(_directory, "game.zar"); + var interrupted = Options(consume: true) with + { + Observer = (stage, index, _) => + { + if (stage == PkgZarStage.BatchTruncated && index == 1) + { + throw new SimulatedCrash(); + } + }, + }; + Assert.Throws(() => PkgZarConverter.Convert(package, destination, interrupted.Build(), null, default)); + var cut = File.ReadAllBytes(package); + Assert.True(cut.Length < first.Length); + + // Another package into the same archive. + var exception = Assert.Throws(() => PkgZarConverter.Convert(other, destination, Options(consume: true).Build(), null, default)); + Assert.Contains("belongs to a conversion of", exception.Message); + + // Another package's bytes at the journal's path, cut to the same length. + File.WriteAllBytes(package, second.AsSpan(0, Math.Min(second.Length, cut.Length)).ToArray()); + Assert.Throws(() => PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default)); + + // A direct conversion does not run over the pending one. + File.WriteAllBytes(package, cut); + Assert.Throws(() => PkgZarConverter.Convert(package, destination, Options(consume: false).Build(), null, default)); + + // The real package still resumes. + PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default); + Assert.Equal(ExtractTree(first), ReadArchive(destination)); + } + + [Fact] + public void ADamagedJournalRecordIsRefusedButACutShortTailIsRedone() + { + var bytes = Build(Format.Ps4); + var expected = ConsumeUninterrupted(bytes); + var package = Write("game.pkg", bytes); + var destination = Path.Combine(_directory, "game.zar"); + var interrupted = Options(consume: true) with + { + Observer = (stage, index, _) => + { + if (stage == PkgZarStage.BatchCommitted && index == 2) + { + throw new SimulatedCrash(); + } + }, + }; + Assert.Throws(() => PkgZarConverter.Convert(package, destination, interrupted.Build(), null, default)); + var journal = PkgZarConverter.JournalPath(destination); + var intact = File.ReadAllBytes(journal); + + // A torn half record after the last commit: dropped, its batch redone. + File.WriteAllBytes(journal, [.. intact, 1, 0, 0, 0, 200, 0]); + // A flipped byte inside a committed record followed by more records: refused. + var damaged = (byte[])intact.Clone(); + damaged[^100] ^= 0xFF; + File.WriteAllBytes(journal, [.. damaged, .. intact[^60..]]); + Assert.Throws(() => PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default)); + + File.WriteAllBytes(journal, [.. intact, 1, 0, 0, 0, 200, 0]); + PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default); + Assert.Equal(expected, File.ReadAllBytes(destination)); + } + + [Fact] + public void BatchesFollowTheWindowAndDescendInSourceOrder() + { + const long MiB = 1 << 20; + var plan = new PkgZarConverter.Plan + { + Files = [], + DataSize = 5L * ZArchiveWriter.RecordSpan, + GroupEnds = [100 * MiB, 500 * MiB, 300 * MiB, 500 * MiB, 0], + Fingerprint = [], + }; + string Batches(long window) => string.Join(";", PkgZarConverter.BuildBatches(plan, window).Select(batch => string.Join(",", batch))); + + // At most one group's worth of archive data per batch: one group each. + Assert.Equal("3;1;2;0;4", Batches(1)); + // The archive-size cap (the package span closes 2 and 0 apart too). + Assert.Equal("3,1;2;0;4", Batches(2 * MiB)); + // The package-span cap. + Assert.Equal("3,1,2;0,4", Batches(250 * MiB)); + Assert.Equal("3,1;2;0,4", Batches(150 * MiB)); + } + + // ---- helpers ------------------------------------------------------------------------------- + + private sealed class SimulatedCrash : Exception; + + private sealed record OptionsBuilder(bool Consume) + { + public Action? Observer { get; init; } + + public Action? SourceReadObserver { get; init; } + + public PkgZarOptions Build() => new() + { + ConsumeSource = Consume, + WindowBytes = TinyWindow, + MaxParallelism = 3, + AvailableSpace = _ => null, + Observer = Observer, + SourceReadObserver = SourceReadObserver, + }; + } + + private static OptionsBuilder Options(bool consume) => new(consume); + + private byte[] ConsumeUninterrupted(byte[] bytes) + { + var directory = Directory.CreateDirectory(Path.Combine(_directory, $"reference-{Guid.NewGuid():N}")).FullName; + var package = Path.Combine(directory, "game.pkg"); + File.WriteAllBytes(package, bytes); + var destination = Path.Combine(directory, "game.zar"); + PkgZarConverter.Convert(package, destination, Options(consume: true).Build(), null, default); + return File.ReadAllBytes(destination); + } + + private string Write(string name, byte[] bytes) + { + var path = Path.Combine(_directory, name); + File.WriteAllBytes(path, bytes); + return path; + } + + private Dictionary ExtractTree(byte[] bytes) + { + var directory = Directory.CreateDirectory(Path.Combine(_directory, $"extract-{Guid.NewGuid():N}")).FullName; + var package = Path.Combine(directory, "game.pkg"); + File.WriteAllBytes(package, bytes); + var folder = Path.Combine(directory, "game"); + using (var opened = GamePackage.Open(package)) + { + opened.Extract(folder); + } + + var tree = new Dictionary(StringComparer.Ordinal); + foreach (var path in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)) + { + tree[Path.GetRelativePath(folder, path).Replace('\\', '/')] = File.ReadAllBytes(path); + } + + Directory.Delete(directory, recursive: true); + return tree; + } + + private static Dictionary ReadArchive(string path) + { + using var archive = ZArchive.Open(path); + Assert.NotNull(archive); + var tree = new Dictionary(StringComparer.Ordinal); + void Walk(string prefix) + { + foreach (var entry in archive.GetEntries(archive.LookUp(prefix))) + { + var child = prefix.Length == 0 ? entry.Name : prefix + "/" + entry.Name; + if (entry.IsDirectory) + { + Walk(child); + continue; + } + + var node = archive.LookUp(child); + var data = new byte[entry.Size]; + Assert.Equal(data.Length, archive.Read(node, 0, data)); + tree[child] = data; + } + } + + Walk(string.Empty); + return tree; + } + + private static byte[] Build(Format format) => format switch + { + Format.Ps4 => BuildPs4(), + Format.Ps5 => BuildPs5(scramble: false), + Format.Ps5Scrambled => BuildPs5(scramble: true), + Format.Ps5Small => Ps5PkgTests.BuildPackage(new Ps5PkgTests.Spec()).Bytes, + _ => throw new ArgumentOutOfRangeException(nameof(format)), + }; + + // Half random (stored raw), half a repeating pattern (compresses). + private static byte[] Content(int seed, int length) + { + var bytes = new byte[length]; + new System.Random(seed).NextBytes(bytes.AsSpan(0, length / 2)); + for (var index = length / 2; index < length; index++) + { + bytes[index] = (byte)(index % 13 + seed); + } + + return bytes; + } + + private static readonly (string Path, int Length)[] GameFiles = + [ + ("eboot.bin", 1_500_000), + ("data/level0.bin", 2_100_000), + ("data/empty.bin", 0), + ("data/small.txt", 777), + ("movie.bin", 1_700_000), + ("sce_module/libc.prx", 0x8000), + ]; + + // A PS4 package with several files in uroot and one level of directories. Logical PFS blocks: + // 0 header, 1 inodes, 2 super root, 3 uroot, then one block per subdirectory, then file data. + private static byte[] BuildPs4() + { + const int BlockSize = PfscImage.BlockSize; + var directories = GameFiles.Select(file => file.Path).Where(path => path.Contains('/')).Select(path => path[..path.IndexOf('/')]).Distinct().ToList(); + var firstData = 4 + directories.Count; + var logical = new List(); + var header = new byte[BlockSize]; + var inodes = new byte[BlockSize]; + var superRoot = new byte[BlockSize]; + var userRoot = new byte[BlockSize]; + var directoryBlocks = directories.Select(_ => new byte[BlockSize]).ToList(); + logical.AddRange([header, inodes, superRoot, userRoot, .. directoryBlocks]); + + // Inodes: 0 super root, 1 uroot, 2.. directories, then files. + PkgTests.WriteInode(inodes, 0, PfsInode.ModeDirectory, BlockSize, 1, 2); + PkgTests.WriteInode(inodes, 1, PfsInode.ModeDirectory, BlockSize, 1, 3); + var offset = PkgTests.WriteDirent(superRoot, 0, 1, PfsDirentType.File, "flat_path_table"); + PkgTests.WriteDirent(superRoot, offset, 1, PfsDirentType.Directory, "uroot"); + var rootAt = PkgTests.WriteDirent(userRoot, 0, 1, PfsDirentType.CurrentDirectory, "."); + rootAt = PkgTests.WriteDirent(userRoot, rootAt, 0x7FFF, PfsDirentType.ParentDirectory, ".."); + var directoryAt = new int[directories.Count]; + for (var index = 0; index < directories.Count; index++) + { + var inode = 2 + index; + PkgTests.WriteInode(inodes, inode, PfsInode.ModeDirectory, BlockSize, 1, (uint)(4 + index)); + rootAt = PkgTests.WriteDirent(userRoot, rootAt, inode, PfsDirentType.Directory, directories[index]); + directoryAt[index] = PkgTests.WriteDirent(directoryBlocks[index], 0, inode, PfsDirentType.CurrentDirectory, "."); + } + + var nextInode = 2 + directories.Count; + var location = firstData; + foreach (var (path, length) in GameFiles) + { + var data = Content(path.Length, length); + var blocks = (length + BlockSize - 1) / BlockSize; + PkgTests.WriteInode(inodes, nextInode, PfsInode.ModeFile, length, (uint)blocks, (uint)location); + var slash = path.IndexOf('/'); + if (slash < 0) + { + rootAt = PkgTests.WriteDirent(userRoot, rootAt, nextInode, PfsDirentType.File, path); + } + else + { + var index = directories.IndexOf(path[..slash]); + directoryAt[index] = PkgTests.WriteDirent(directoryBlocks[index], directoryAt[index], nextInode, PfsDirentType.File, path[(slash + 1)..]); + } + + for (var block = 0; block < blocks; block++) + { + var bytes = new byte[BlockSize]; + Array.Copy(data, block * BlockSize, bytes, 0, Math.Min(BlockSize, length - block * BlockSize)); + logical.Add(bytes); + } + + location += blocks; + nextInode++; + } + + BinaryPrimitives.WriteInt32LittleEndian(header.AsSpan(0x20), BlockSize); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x28), 1); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x38), logical.Count); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x30), nextInode); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x40), 1); + BinaryPrimitives.WriteInt64LittleEndian(header.AsSpan(0x48), 0); + + var stored = new List(); + foreach (var block in logical) + { + using var compressed = new MemoryStream(); + using (var zlib = new ZLibStream(compressed, CompressionLevel.Fastest, leaveOpen: true)) + { + zlib.Write(block); + } + + stored.Add(compressed.Length < BlockSize ? compressed.ToArray() : block); + } + + const int TableOffset = 0x30; + var dataStart = TableOffset + (stored.Count + 1) * 8; + var pfscHeader = new byte[dataStart]; + BinaryPrimitives.WriteUInt32LittleEndian(pfscHeader, PfscImage.Magic); + BinaryPrimitives.WriteInt32LittleEndian(pfscHeader.AsSpan(0x0C), BlockSize); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x10), BlockSize); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x18), TableOffset); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x20), dataStart); + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(0x28), (long)stored.Count * BlockSize); + long position = dataStart; + for (var index = 0; index < stored.Count; index++) + { + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(TableOffset + index * 8), position); + position += stored[index].Length; + } + + BinaryPrimitives.WriteInt64LittleEndian(pfscHeader.AsSpan(TableOffset + stored.Count * 8), position); + var image = new MemoryStream(); + image.Write(pfscHeader); + foreach (var block in stored) + { + image.Write(block); + } + + return PkgTests.BuildSyntheticPkg( + image.ToArray(), + (0x1000, "PARAM"u8.ToArray()), + (0x1200, Content(99, 3000)), + (0x1220, Content(98, 100_000))); + } + + // A PS5 package whose inner image holds GameFiles plus a uroot sce_sys/param.json that + // overrides the CNT copy, as on real packages. Every 256 KiB block is stored raw except a + // 32 KiB one stored Kraken; the outer image is laid out in order unless scrambled. + private static byte[] BuildPs5(bool scramble) + { + const long UblockSize = 0x40000; + var files = GameFiles.Select(file => (file.Path, Data: Content(file.Path.Length + 7, file.Length))).ToList(); + files.Add(("sce_sys/param.json", System.Text.Encoding.UTF8.GetBytes("""{"titleId":"PPSA01234","override":true}"""))); + + // Logical layout: files on 4 KiB boundaries, then the metadata tail on a 64 KiB boundary. + var placed = new List<(string Path, byte[] Data, long Offset)>(); + long cursor = 0; + foreach (var (path, data) in files) + { + placed.Add((path, data, cursor)); + cursor = (cursor + Math.Max(data.Length, 1) + 0xFFF) & ~0xFFFL; + } + + var tailBase = (cursor + 0xFFFF) & ~0xFFFFL; + var directories = files.Select(file => file.Path).Where(path => path.Contains('/')).Select(path => path[..path.IndexOf('/')]).Distinct().ToList(); + // Inodes: 0 root, 1 uroot, 2.. directories, then files. + var inodeCount = 2 + directories.Count + files.Count; + var inodeBlocks = (inodeCount + 23) / 24; + var directoryBlock0 = 1 + inodeBlocks; + var tailLength = (long)(directoryBlock0 + 2 + directories.Count) * 0x1000; + var mount = tailBase + tailLength; + var logical = new byte[mount]; + foreach (var (_, data, offset) in placed) + { + data.CopyTo(logical, offset); + } + + var tail = logical.AsSpan((int)tailBase); + BinaryPrimitives.WriteUInt64LittleEndian(tail, 2); + BinaryPrimitives.WriteUInt64LittleEndian(tail[8..], Ps5OuterPfs.PfsMagic); + BinaryPrimitives.WriteUInt16LittleEndian(tail[0x1C..], 0x10); + BinaryPrimitives.WriteUInt32LittleEndian(tail[0x20..], 0x1000); + BinaryPrimitives.WriteUInt64LittleEndian(tail[0x30..], (ulong)inodeCount); + BinaryPrimitives.WriteUInt64LittleEndian(tail[0x38..], (ulong)(mount / 0x1000)); + void Inode(int index, ushort mode, long size, long where) + { + var at = 0x1000 + index / 24 * 0x1000 + index % 24 * 0xA8; + BinaryPrimitives.WriteUInt16LittleEndian(logical.AsSpan((int)tailBase + at), mode); + BinaryPrimitives.WriteUInt64LittleEndian(logical.AsSpan((int)tailBase + at + 8), (ulong)size); + BinaryPrimitives.WriteUInt64LittleEndian(logical.AsSpan((int)tailBase + at + 0x60), (ulong)where); + } + + long DirectoryAt(int block) => tailBase + (directoryBlock0 + block) * 0x1000L; + const ushort DirMode = 0x41ED; + const ushort FileMode = 0x81A4; + Inode(0, DirMode, 0x1000, DirectoryAt(0)); + Inode(1, DirMode, 0x1000, DirectoryAt(1)); + var rootEntries = new List<(uint, uint, string)> { (1, 4, "."), (0, 5, "..") }; + var childEntries = directories.Select(name => new List<(uint, uint, string)> { (0, 3, "."), (1, 3, "..") }).ToList(); + for (var index = 0; index < directories.Count; index++) + { + Inode(2 + index, DirMode, 0x1000, DirectoryAt(2 + index)); + rootEntries.Add(((uint)(2 + index), 3, directories[index])); + } + + for (var index = 0; index < placed.Count; index++) + { + var (path, data, offset) = placed[index]; + var inode = 2 + directories.Count + index; + Inode(inode, FileMode, data.Length, offset); + var slash = path.IndexOf('/'); + if (slash < 0) + { + rootEntries.Add(((uint)inode, 2, path)); + } + else + { + childEntries[directories.IndexOf(path[..slash])].Add(((uint)inode, 2, path[(slash + 1)..])); + } + } + + Ps5PkgTests.DirectoryBlock(0x1000, (0, 3, "."), (0, 3, ".."), (1, 3, "uroot")).CopyTo(logical, DirectoryAt(0)); + Ps5PkgTests.DirectoryBlock(0x1000, [.. rootEntries]).CopyTo(logical, DirectoryAt(1)); + for (var index = 0; index < directories.Count; index++) + { + Ps5PkgTests.DirectoryBlock(0x1000, [.. childEntries[index]]).CopyTo(logical, DirectoryAt(2 + index)); + } + + // NAPS boundaries: every file start, the tail, and the mount size. + var boundaries = placed.Select(file => file.Offset).Append(tailBase).Distinct().Order().ToList(); + var entries = boundaries.Select(offset => (Offset: offset, Kind: (byte)0)).Append((Offset: mount, Kind: (byte)0x40)).ToList(); + while (entries.Count % 8 != 0) + { + entries.Insert(0, (Offset: 0, Kind: 0)); + } + + // Blocks: up to 256 KiB, cut at every boundary; the 32 KiB module is stored Kraken. + var stored = new MemoryStream(); + var records = new List(); + long at = 0; + var cuts = boundaries.Append(mount).ToList(); + while (at < mount) + { + var next = cuts.First(cut => cut > at); + var length = (int)Math.Min(UblockSize, next - at); + var block = logical.AsSpan((int)at, length).ToArray(); + var kraken = length == 0x8000 && at != tailBase; + records.Add(Ps5PkgTests.CblockRecord((uint)(stored.Length & 0x3FFFF), kraken ? 2UL : 0)); + stored.Write(kraken ? Ps5PkgTests.KrakenLiteralChunk(block) : block); + at += length; + } + + records.Add(Ps5PkgTests.CblockRecord((uint)(stored.Length & 0x3FFFF), 0)); + var image = stored.ToArray(); + var ublocks = records.Count - 1; + var outer = (int)((image.Length + 0xFFFF) / 0x10000); + outer += outer % 2; + var u2c = (ublocks + 8) >> 3; + var fileOffsetsAt = 16 + outer * 8; + var cblocksAt = (fileOffsetsAt + entries.Count * 6 + u2c * 10 + 7) & ~7; + var naps = new byte[cblocksAt + records.Count * 9]; + BinaryPrimitives.WriteUInt64LittleEndian(naps, (ulong)(entries.Count - 1) | (2UL << 24) | ((ulong)ublocks << 32)); + BinaryPrimitives.WriteUInt64LittleEndian(naps.AsSpan(8), (ulong)outer | ((ulong)(records.Count - 2) << 24)); + for (var index = 0; index < entries.Count; index++) + { + var entry = fileOffsetsAt + index * 6; + for (var b = 0; b < 5; b++) + { + naps[entry + b] = (byte)(entries[index].Offset >> (8 * b)); + } + + naps[entry + 5] = entries[index].Kind; + } + + for (var index = 0; index < records.Count; index++) + { + records[index].CopyTo(naps, cblocksAt + index * 9); + } + + var pfs = Ps5PkgTests.BuildOuterPfs(0x10000, "PPRPLAIN-NOAUTH!", [("pfs_image.dat", image), ("naps_pkg_layout.dat", naps)], scramble); + return Ps5PkgTests.AssemblePackage(new Ps5PkgTests.Spec(), pfs, new Dictionary()).Bytes; + } +} diff --git a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs index b422ee602..dd9d9379f 100644 --- a/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs +++ b/tests/SharpEmu.Libs.Tests/FileSystem/Ps5PkgTests.cs @@ -13,7 +13,7 @@ namespace SharpEmu.Libs.Tests.FileSystem; // holding pfs_image.dat and naps_pkg_layout.dat, an inner flat PFS, and an embedded CNT. public sealed class Ps5PkgTests { - private const string DefaultContentId = "UP9000-PPSA01234_00-TESTGAME00000000"; + internal const string DefaultContentId = "UP9000-PPSA01234_00-TESTGAME00000000"; private const string DefaultParamJson = """{"titleId":"PPSA01234","localizedParameters":{"defaultLanguage":"en-US","en-US":{"titleName":"Test: The Game"},"fr-FR":{"titleName":"Le Jeu"}}}"""; @@ -391,7 +391,7 @@ public void OuterPfsFollowsDirectSingleAndDoubleIndirectBlocks() var pfs = BuildOuterPfs(0x1000, "PPRPLAIN-NOAUTH!", [("big.bin", data), ("small.bin", small)], scramble: true); WithFile(pfs, path => { - using var source = new Ps5Source(path); + using var source = new PackageSource(path); var outer = Ps5OuterPfs.Open(source, 0, pfs.Length, 0); var big = outer.OpenFile(outer.Find("big.bin") ?? throw new InvalidOperationException()); Assert.Equal(data.Length, big.Size); @@ -557,7 +557,7 @@ public void KrakenNeverThrowsAnythingButInvalidDataOnCorruptInput() // ---- helpers ------------------------------------------------------------------------------- - private sealed record Spec + internal sealed record Spec { public byte RetailByte { get; init; } @@ -572,9 +572,9 @@ private sealed record Spec public string? ExtraCntName { get; init; } } - private sealed record Built(byte[] Bytes, Dictionary ExpectedFiles, long GameBytes); + internal sealed record Built(byte[] Bytes, Dictionary ExpectedFiles, long GameBytes); - private static byte[] Pattern(int seed, int length) + internal static byte[] Pattern(int seed, int length) { var bytes = new byte[length]; for (var i = 0; i < bytes.Length; i++) @@ -596,7 +596,7 @@ private static byte[] Dirent(uint inode, uint kind, string name, int recordSize) return record; } - private static byte[] DirectoryBlock(int blockSize, params (uint Inode, uint Kind, string Name)[] entries) + internal static byte[] DirectoryBlock(int blockSize, params (uint Inode, uint Kind, string Name)[] entries) { var block = new byte[blockSize]; var at = 0; @@ -613,7 +613,7 @@ private static byte[] DirectoryBlock(int blockSize, params (uint Inode, uint Kin // One LZ chunk (with seed) holding `block` as 8 seed bytes plus literals stored with the memcpy // entropy type and no commands. Every array uses the 3-byte memcpy header: a first byte with the // high bit set would read as the excess framing. - private static byte[] KrakenLiteralChunk(byte[] block) + internal static byte[] KrakenLiteralChunk(byte[] block) { var literals = block[8..]; var payload = new List(); @@ -627,7 +627,7 @@ private static byte[] KrakenLiteralChunk(byte[] block) return [.. payload]; } - private static byte[] CblockRecord(uint coffsetMod, ulong kdePredictor) + internal static byte[] CblockRecord(uint coffsetMod, ulong kdePredictor) { var record = new byte[9]; BinaryPrimitives.WriteUInt64LittleEndian(record, coffsetMod | (kdePredictor << 56)); @@ -636,7 +636,7 @@ private static byte[] CblockRecord(uint coffsetMod, ulong kdePredictor) // Signed 32-bit PFS with the encrypted mode bit set. Block 0 is the superblock, then the inode // table, the root directory, then data (and indirect) blocks, optionally in scrambled order. - private static byte[] BuildOuterPfs(int blockSize, string seed, IReadOnlyList<(string Name, byte[] Data)> files, bool scramble) + internal static byte[] BuildOuterPfs(int blockSize, string seed, IReadOnlyList<(string Name, byte[] Data)> files, bool scramble) { const int InodeSize = 0x2C8; const int Stride = 36; @@ -772,7 +772,7 @@ private static List ResolveBlocks((int[] Direct, int[] Indirect) inode, Lis return blocks.Take(count).ToList(); } - private static Built BuildPackage(Spec spec) + internal static Built BuildPackage(Spec spec) { const int Mount = 0x30000; var logical = new byte[Mount]; @@ -864,7 +864,12 @@ void Inode(int index, ushort mode, long size, long where) CblockRecord((uint)((krakenEnd + 0x10000) & 0x3FFFF), 0).CopyTo(naps, 91); var pfs = BuildOuterPfs(0x10000, spec.Seed, [("pfs_image.dat", image), ("naps_pkg_layout.dat", naps)], scramble: true); + return AssemblePackage(spec, pfs, expected); + } + // CNT and FIH around an outer PFS; adds the sce_sys files the CNT carries to `expected`. + internal static Built AssemblePackage(Spec spec, byte[] pfs, Dictionary expected) + { // CNT: entries, then the names table, then the data they point at. var cntFiles = new List<(uint Id, uint NameAt, uint Flags, byte[] Data)>(); var names = new MemoryStream(); From 4ab3932965ffd8e9c0da1c661d813715114e89ef Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 27 Nov 2026 03:02:48 +0000 Subject: [PATCH 2/3] [GUI] Convert a .pkg straight into a .zar from the install flow, with optional consume mode and resume --- src/SharpEmu.Application/Languages/en.json | 24 +++ src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs | 95 +++++++++- src/SharpEmu.GUI/PkgConfirmDialog.axaml | 42 ++++- src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs | 38 +++- src/SharpEmu.GUI/PkgZarDialog.axaml | 50 +++++ src/SharpEmu.GUI/PkgZarDialog.axaml.cs | 173 ++++++++++++++++++ 6 files changed, 415 insertions(+), 7 deletions(-) create mode 100644 src/SharpEmu.GUI/PkgZarDialog.axaml create mode 100644 src/SharpEmu.GUI/PkgZarDialog.axaml.cs diff --git a/src/SharpEmu.Application/Languages/en.json b/src/SharpEmu.Application/Languages/en.json index 1531efdad..5ebe20dd3 100644 --- a/src/SharpEmu.Application/Languages/en.json +++ b/src/SharpEmu.Application/Languages/en.json @@ -109,6 +109,30 @@ "Library.Pkg.ConfirmMessage": "Found {0} PKG file(s) in this folder. Install them now? This needs {1} GB of free space.", "Library.Pkg.ConfirmInstall": "Install", "Library.Pkg.ConfirmSkip": "Not now", + "Library.Pkg.ConfirmOne": "Install {0}? Choose how SharpEmu stores the game.", + "Library.Pkg.Format": "Install as", + "Library.Pkg.FormatFolder": "Folder", + "Library.Pkg.FormatZar": ".zar archive", + "Library.Pkg.FormatFolderHint": "Unpacks the game into a normal folder. Needs free space for the whole game.", + "Library.Pkg.FormatZarHint": "Converts the game into one compressed .zar file that SharpEmu runs without unpacking. The .pkg stays where it is.", + "Library.Pkg.Consume": "Delete the .pkg as it is converted (needs far less free space)", + "Library.Pkg.ConsumeWarning": "The .pkg cannot be recovered once conversion starts. Cancelling only pauses it: the .pkg stays partly converted until you resume and finish.", + "Library.Pkg.ConsumeBusy": "Not available while a game is running.", + "Library.Pkg.ResumeTitle": "Resume conversion?", + "Library.Pkg.ResumeMessage": "The conversion of {0} was paused before it finished. Resume it into {1}?", + "Library.Pkg.ResumeButton": "Resume", + "Library.PkgZar.Heading": "Converting {0}", + "Library.PkgZar.HeadingResume": "Resuming {0}", + "Library.PkgZar.Explanation": "Converting the .pkg into a .zar archive. The .pkg is not changed.", + "Library.PkgZar.ExplanationConsume": "Converting the .pkg into a .zar archive and deleting it as it goes. Pause stops here and can be resumed; the .pkg cannot be recovered.", + "Library.PkgZar.Pause": "Pause", + "Library.PkgZar.Pausing": "Pausing…", + "Library.PkgZar.Paused": "Paused. Resume now, or install the same .pkg later to continue.", + "Library.PkgZar.OutOfSpace": "Out of space. Free some space, then resume.", + "Library.PkgZar.OutOfSpaceDirect": "Out of space. The partial archive was removed.", + "Library.PkgZar.Failed": "Converting failed: {0}", + "Library.PkgZar.FailedResumable": "The conversion is paused; install the same .pkg again to resume it.", + "Status.ConvertedZar": "Converted game archive: {0}", "Dialog.OpenPkg": "Choose a PKG to install", "Dialog.PkgFiles": "PS4 and PS5 packages", "Dialog.ChoosePkgInstallFolder": "Choose where to install the game", diff --git a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs index 99dae602d..8bca21fcc 100644 --- a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs +++ b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs @@ -115,6 +115,13 @@ private async Task InstallPkgAsync() return; } + // A paused consuming conversion may have cut the package short, so it is not read first. + if (PkgZarConverter.FindPendingDestination(pkgPath) is { } pending) + { + await ResumePendingConversionAsync(pkgPath, pending); + return; + } + if (!TryReadPackageInfo(pkgPath, out var titleId, out var folderName, out var isGame, out var category)) { return; @@ -126,6 +133,15 @@ private async Task InstallPkgAsync() return; } + var format = new PkgConfirmDialog( + loc.Format("Library.Pkg.ConfirmOne", Path.GetFileName(pkgPath)), + offerFormat: true, + canConsume: !_isRunning); + if (await Sheets.ShowAsync(format) is not true) + { + return; + } + var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = loc.Get("Dialog.ChoosePkgInstallFolder"), @@ -137,7 +153,10 @@ private async Task InstallPkgAsync() return; } - if (!await InstallPackageIntoAsync(pkgPath, parent, folderName)) + var succeeded = format.AsZar + ? await ConvertPackageToZarAsync(pkgPath, Path.Combine(parent, folderName + ".zar"), format.ConsumeSource) + : await InstallPackageIntoAsync(pkgPath, parent, folderName); + if (!succeeded) { return; } @@ -145,6 +164,58 @@ private async Task InstallPkgAsync() await RescanLibraryAsync(addingFolder: true); } + // Offers to pick an unfinished consuming conversion up again. The package is partly consumed, + // so starting over is not possible; declining leaves it paused. + private async Task ResumePendingConversionAsync(string pkgPath, string destination) + { + var confirm = PkgConfirmDialog.ForResume( + Localization.Instance.Format("Library.Pkg.ResumeMessage", Path.GetFileName(pkgPath), destination)); + if (await Sheets.ShowAsync(confirm) is true && + await ConvertPackageToZarAsync(pkgPath, destination, consumeSource: true, resuming: true)) + { + await RescanLibraryAsync(addingFolder: true); + } + } + + // Shows the conversion sheet for one package. The caller owns the library rescan. + private async Task ConvertPackageToZarAsync(string pkgPath, string destination, bool consumeSource, bool resuming = false) + { + var loc = Localization.Instance; + if (!resuming && (File.Exists(destination) || File.Exists(PkgZarConverter.JournalPath(destination)))) + { + AppendConsoleLine(loc.Format("Library.Pkg.AlreadyInstalled", Path.GetFileName(pkgPath), destination), DimLineBrush); + return false; + } + + // A running game may hold files of the package open, so it is never consumed then. + consumeSource &= !_isRunning; + var gameName = resuming ? Path.GetFileNameWithoutExtension(destination) : Path.GetFileName(pkgPath); + var dialog = new PkgZarDialog(gameName, pkgPath, destination, consumeSource, resuming); + if (await Sheets.ShowAsync(dialog) is not true) + { + if (dialog.ErrorMessage is { } error) + { + AppendConsoleLine(loc.Format("Library.PkgZar.Failed", error), ErrorLineBrush); + } + + return false; + } + + AppendConsoleLine(loc.Format("Status.ConvertedZar", destination), SuccessLineBrush); + AddInstalledArchiveToLibrary(destination); + return true; + } + + // A .zar is listed through the folder it sits in, so that folder joins the library unless a + // library folder already covers it. + private void AddInstalledArchiveToLibrary(string archive) + { + if (Path.GetDirectoryName(Path.GetFullPath(archive)) is { } folder) + { + AddInstalledGameToLibrary(folder); + } + } + // A folder picked by "Add folder" may hold downloaded .pkg files instead of extracted games. // Walk it recursively with the same depth limit as the library scan, install every package // under the chosen root (named after the game's title) and let the caller's rescan pick them all @@ -173,8 +244,16 @@ private async Task InstallPackagesInFolderAsync(string folder) // Patches and DLC share the base game's title id and the emulator cannot overlay them, so // only base games are installed. var installable = new List<(string Path, string FolderName)>(); + var resumable = new List<(string Path, string Destination)>(); foreach (var pkgPath in packages) { + // A paused consuming conversion may have cut its package short, so it is not read. + if (PkgZarConverter.FindPendingDestination(pkgPath) is { } pending) + { + resumable.Add((pkgPath, pending)); + continue; + } + if (!TryReadPackageInfo(pkgPath, out var titleId, out var folderName, out var isGame, out var category)) { continue; @@ -202,6 +281,11 @@ private async Task InstallPackagesInFolderAsync(string folder) } } + foreach (var (pkgPath, pending) in resumable) + { + await ResumePendingConversionAsync(pkgPath, pending); + } + if (installable.Count == 0) { return; @@ -228,7 +312,9 @@ await Task.Run(() => Localization.Instance.Format( "Library.Pkg.ConfirmMessage", installable.Count, - (neededBytes / (1024.0 * 1024 * 1024)).ToString("0.0", System.Globalization.CultureInfo.CurrentCulture))); + (neededBytes / (1024.0 * 1024 * 1024)).ToString("0.0", System.Globalization.CultureInfo.CurrentCulture)), + offerFormat: true, + canConsume: !_isRunning); if (await Sheets.ShowAsync(confirm) is not true) { return; @@ -237,7 +323,10 @@ await Task.Run(() => foreach (var (pkgPath, folderName) in installable) { // Cancelling one package stops the batch; later packages stay untouched. - if (!await InstallPackageIntoAsync(pkgPath, folder, folderName)) + var installedOne = confirm.AsZar + ? await ConvertPackageToZarAsync(pkgPath, Path.Combine(folder, folderName + ".zar"), confirm.ConsumeSource) + : await InstallPackageIntoAsync(pkgPath, folder, folderName); + if (!installedOne) { return; } diff --git a/src/SharpEmu.GUI/PkgConfirmDialog.axaml b/src/SharpEmu.GUI/PkgConfirmDialog.axaml index 5fcc368c6..d723c3ba7 100644 --- a/src/SharpEmu.GUI/PkgConfirmDialog.axaml +++ b/src/SharpEmu.GUI/PkgConfirmDialog.axaml @@ -9,13 +9,53 @@ SPDX-License-Identifier: GPL-2.0-or-later x:Class="SharpEmu.GUI.PkgConfirmDialog" SheetWidth="520"> - + + + + + + +