From 4a81aa86a9000969dc28cc35bfd954ad852a3d49 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:00:03 +0300 Subject: [PATCH 1/3] Expose the decoded global stream and extent reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenStream decodes the whole file once into a PlaStream snapshot: every block's payload decoded in block order (raw as they are, zero masks as their full decode, mode 2 as their token-stream output), with false entries of the scan skipped. A directory record's position and count name a byte extent of this stream — the object's data — so PlaStream.ReadExtent returns an object's bytes by record or by position and count. The position/count semantics are confirmed against the object directories of real files and documented on the record. --- CHANGELOG.md | 10 ++++ docs/public-api.md | 11 +++-- src/PlaIO/ObjectDirectory.cs | 8 ++-- src/PlaIO/PlaDocument.cs | 10 ++++ src/PlaIO/PlaStream.cs | 41 ++++++++++++++++ tests/PlaIO.Tests/PlaStreamTests.cs | 73 +++++++++++++++++++++++++++++ tests/PlaIO.Tests/SampleTests.cs | 25 ++++++++++ 7 files changed, 171 insertions(+), 7 deletions(-) create mode 100644 src/PlaIO/PlaStream.cs create mode 100644 tests/PlaIO.Tests/PlaStreamTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 865a60d..9e853cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,16 @@ API between minor releases. - `PlaDocument.ReadPayload` no longer throws `NotSupportedException` for mode 2 blocks: all three storage modes (raw, zero mask, LZ) decode now. +### Added + +- `PlaDocument.OpenStream` and `PlaStream`: the decoded global stream of the document (every block's payload decoded in + block order) and the extents of it. A directory record's position and count name a byte extent of the stream — the + object's data — so `PlaStream.ReadExtent(ObjectDirectoryRecord)` returns an object's bytes; extents can also be read + by position and count. The stream is a snapshot that holds the whole decoded file in memory and the document may be + disposed afterwards. +- The position and count of `ObjectDirectoryRecord` are now documented: a byte extent of the decoded global stream, + confirmed against the object directories of real files. + ## [0.1.0] - 2026-11-12 ### Added diff --git a/docs/public-api.md b/docs/public-api.md index 0fb864f..8dd1c61 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -23,12 +23,16 @@ The `PlaIO` package is the supported surface listed here; every public type is i | `PlaDocument.Blocks` | The block index in file order, found by scanning from offset 32. No on-disk block map is known, so completeness is not claimed. The scan can take a byte run for a block header, so the index may contain false entries. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. | | `PlaDocument.ReadPayload(PlaBlock block)` | The decoded payload of a block of this document. Decodes all three storage modes: raw (mode 0), zero masks (mode 1) and the LZ token stream (mode 2). A mode 2 payload may start with a 9-byte stream header (packed and/or unpacked size). The token stream produces the block's declared unpacked size — some blocks declare a buffer larger than the stream produces, the tail of the buffer stays zero — and may reference the output of any preceding block, so the payload is produced by decoding every preceding block of the file in order into one global window; the cost of the call grows with the size of the file. Preceding blocks that do not decode (false entries of the scan) are skipped and leave the window unchanged. Throws `InvalidDataException` when a back-reference reaches beyond the decoded stream or the file is cut short, and `ArgumentException` when the block is not from this document. | | `PlaDocument.FindDirectories()` | Searches every raw (mode 0) block large enough for 64 records of 30 bytes for an object directory, at most one per block. Recomputed on each call; mode 1 payloads are not searched. | +| `PlaDocument.OpenStream()` | The document's decoded global stream (`PlaStream`): every block's payload decoded in block order. Blocks that do not decode (false entries of the scan) are skipped. The stream is a snapshot — it holds the whole decoded file in memory and the document may be disposed afterwards; decoding it once costs like a full mode-2 read. | | `PlaDocument.Dispose()` | Releases the stream unless the document was opened with `leaveOpen`. | | `FdbHeader` | `Size` (64), `LayoutVersion` (u16 at offset 8), `FormatVersion` (u16 at offset 10), `Field12` (u32 at offset 12; meaning not documented), `Raw` (the first min(64, file length) bytes; bytes 32..63 overlap the first block). | | `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200). | | `PlaBlock` | One indexed block: `Offset`, `Tag` (`BL` or `DY`), `Id` and `Kind` (raw), `Version` (0 or 1), `Flags` (raw), `SizeClass` (`Flags & 0xF`), `Mode`, `Guid` (present when flag 0x20 is set), `PackedSize`, `UnpackedSize`, `Extra` (present when flag 0x400 is set; raw), `PayloadOffset`, `HeaderLength`, `End`. | | `ObjectDirectory` | A run of directory records inside a raw block: `Block`, `RecordOffset` (payload offset of the first record), `Phase` (`RecordOffset % 30`), `Records`, `AbuttingPairs`, `OverlappingPairs`, `DuplicatePositions`. The run is an estimate and can be shorter than the real directory: it stops after more than 8 consecutive records without an abutting neighbour. | -| `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. The units of position and count are not documented, and the class number is not mapped to a class name. | +| `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. The position and count name a byte extent of the decoded global stream — the object's data (see `PlaDocument.OpenStream`). The class number is not mapped to a class name. | +| `PlaStream.Length` | Length of the decoded stream in bytes. | +| `PlaStream.ReadExtent(long position, long count)` | The bytes of one extent of the stream. `ArgumentOutOfRangeException` for negative bounds or an extent past the stream. | +| `PlaStream.ReadExtent(ObjectDirectoryRecord record)` | The bytes of the extent one directory record addresses — the object's data. `InvalidDataException` when the record's extent reaches past the stream. | ## BIMx file (`.bimx`) @@ -45,8 +49,9 @@ The `PlaIO` package is the supported surface listed here; every public type is i ## Resources and threads `PlaDocument` and `BimxDocument` never load the whole file into memory: the block index is built by scanning through the -stream once, at `Open`, and payloads and the cover are read on request. A document is not thread-safe; use one per thread. -After `Dispose`, `ReadPayload`, `FindDirectories` and `ReadCover` throw `ObjectDisposedException`. +stream once, at `Open`, and payloads and the cover are read on request. The exception is `OpenStream`: its decoded global +stream holds the whole decoded file in memory by design. A document is not thread-safe; use one per thread. +After `Dispose`, `ReadPayload`, `FindDirectories`, `OpenStream` and `ReadCover` throw `ObjectDisposedException`. ## Diagnostics diff --git a/src/PlaIO/ObjectDirectory.cs b/src/PlaIO/ObjectDirectory.cs index e00fe85..9ba00b6 100644 --- a/src/PlaIO/ObjectDirectory.cs +++ b/src/PlaIO/ObjectDirectory.cs @@ -1,10 +1,10 @@ namespace PlaIO; -/// One 30-byte directory record: [u16 class][u64 pos][u32 count][GUID16]. The units of -/// and are not documented. +/// One 30-byte directory record: [u16 class][u64 pos][u32 count][GUID16]. The position and count name a +/// byte extent of the decoded global stream (see ), the object's data. /// The class number of the object, raw. It is not mapped to a name. -/// Start of the object's extent, raw. -/// Length of the object's extent, raw. +/// Start of the object's extent in the decoded global stream. +/// Length of the object's extent in bytes. /// The object GUID. public readonly record struct ObjectDirectoryRecord(ushort ClassNumber, ulong Position, uint Count, Guid ObjectId); diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 544efbc..4497ee0 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -158,6 +158,16 @@ internal byte[] ReadPayload(PlaBlock block, out int consumed) } } + /// Decodes the whole file once into the global stream: the raw payloads, the full zero-mask decodes and the + /// mode-2 outputs, in block order. Blocks that do not decode to their declared size (false entries of the scan) are + /// skipped. The stream is a snapshot: it holds the whole decoded file in memory and the document may be disposed + /// afterwards. Object directory records address the stream by position and count. + public PlaStream OpenStream() + { + ObjectDisposedException.ThrowIf(_disposed, this); + return new PlaStream(DecodeGlobalWindow(out _)); + } + /// Appends the decoded payload of one block to the mode-2 global window, or leaves the window unchanged when /// the block does not decode to its declared size (a false entry of the scan is not part of the real stream, so a /// partial decode is rolled back). Returns whether the block was appended. diff --git a/src/PlaIO/PlaStream.cs b/src/PlaIO/PlaStream.cs new file mode 100644 index 0000000..e3df82d --- /dev/null +++ b/src/PlaIO/PlaStream.cs @@ -0,0 +1,41 @@ +namespace PlaIO; + +/// The decoded global stream of a document: every block's payload decoded in block order — raw payloads as +/// they are, zero-mask payloads as their full decode, mode 2 payloads as their token-stream output. The object +/// directories () address this stream: a record's +/// and name a byte extent of the +/// stream, the object's data. The stream is a snapshot: it holds the whole decoded file in memory and never touches the +/// document again, so the document may be disposed. Not thread-safe. +public sealed class PlaStream +{ + private readonly List _bytes; + + internal PlaStream(List bytes) => _bytes = bytes; + + /// Length of the decoded stream in bytes. + public long Length => _bytes.Count; + + /// The bytes of one extent of the stream. + /// The bounds are negative or reach past the stream. + public byte[] ReadExtent(long position, long count) + { + ArgumentOutOfRangeException.ThrowIfNegative(position); + ArgumentOutOfRangeException.ThrowIfNegative(count); + if (position > Length || count > Length - position) + throw new ArgumentOutOfRangeException(nameof(count), $"The extent at {position}+{count} reaches past the decoded stream ({Length} bytes)."); + var extent = new byte[count]; + for (long i = 0; i < count; i++) extent[i] = _bytes[(int)(position + i)]; + return extent; + } + + /// The bytes of the extent one directory record addresses. + /// The record's extent reaches past the decoded stream. + public byte[] ReadExtent(ObjectDirectoryRecord record) + { + long position = (long)record.Position; + long count = record.Count; + if (position > Length || count > Length - position) + throw new InvalidDataException($"The directory record of {record.ObjectId} (class {record.ClassNumber}) addresses {position}+{count}, past the decoded stream ({Length} bytes)."); + return ReadExtent(position, count); + } +} diff --git a/tests/PlaIO.Tests/PlaStreamTests.cs b/tests/PlaIO.Tests/PlaStreamTests.cs new file mode 100644 index 0000000..7821c21 --- /dev/null +++ b/tests/PlaIO.Tests/PlaStreamTests.cs @@ -0,0 +1,73 @@ +using Xunit; + +namespace PlaIO.Tests; + +/// The decoded global stream and the extent reads: the stream is the file decoded in block order, and a +/// directory record's position and count name a byte extent of it — including bytes produced by a mode 2 block. +public class PlaStreamTests +{ + [Fact] + public void ExtentsAddressTheDecodedStreamNotTheRawFile() + { + // Block A: raw "ABCDEFGH". Block B: mode 2 producing "wxyz" (token 0x40 = 4 literals). + var lz = Synthetic.Concat([0x40], "wxyz"u8.ToArray(), [0xFF, 0xFE]); + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "ABCDEFGH"u8.ToArray()), + Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 4)))); + + var stream = document.OpenStream(); + Assert.Equal(12, stream.Length); + Assert.Equal("CDE"u8.ToArray(), stream.ReadExtent(2, 3)); // inside the raw block + Assert.Equal("wxyz"u8.ToArray(), stream.ReadExtent(8, 4)); // inside the mode-2 output + } + + [Fact] + public void RecordExtentReadsTheObjectData() + { + var data = "0123456789"u8.ToArray(); + var record = new ObjectDirectoryRecord(7, 4, 5, Guid.Parse("00112233-4455-6677-8899-aabbccddeeff")); + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, data)))); + + var stream = document.OpenStream(); + Assert.Equal("45678"u8.ToArray(), stream.ReadExtent(record)); + } + + [Fact] + public void AZeroLengthExtentAtTheEndIsEmpty() + { + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray())))); + + var stream = document.OpenStream(); + Assert.Empty(stream.ReadExtent(2, 0)); + Assert.Empty(stream.ReadExtent(new ObjectDirectoryRecord(0, 2, 0, Guid.NewGuid()))); + Assert.Equal("AB"u8.ToArray(), stream.ReadExtent(0, stream.Length)); + } + + [Fact] + public void ExtentBoundsPastTheStreamAreRejected() + { + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray())))); + + var stream = document.OpenStream(); + Assert.Throws(() => stream.ReadExtent(-1, 1)); + Assert.Throws(() => stream.ReadExtent(0, -1)); + Assert.Throws(() => stream.ReadExtent(1, 2)); + Assert.Throws(() => stream.ReadExtent(3, 0)); + } + + [Fact] + public void ARecordExtentPastTheStreamIsRejected() + { + var guid = Guid.NewGuid(); + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray())))); + + var stream = document.OpenStream(); + var e = Assert.Throws(() => + stream.ReadExtent(new ObjectDirectoryRecord(3, 1, 10, guid))); + Assert.Contains(guid.ToString(), e.Message); + } +} diff --git a/tests/PlaIO.Tests/SampleTests.cs b/tests/PlaIO.Tests/SampleTests.cs index 61d7473..a3ea88f 100644 --- a/tests/PlaIO.Tests/SampleTests.cs +++ b/tests/PlaIO.Tests/SampleTests.cs @@ -148,6 +148,31 @@ public void EveryLzBlockDecodesAndOnlyFalseEntriesAreSkipped() } } + [SkippableFact] + public void EveryDirectoryRecordFitsTheGlobalStream() + { + foreach (var sample in corpus.Fdb) + { + var stream = sample.Document.OpenStream(); + foreach (var d in sample.Document.FindDirectories()) + { + string where = $"{sample.Name}: directory in block 0x{d.Block.Offset:x}"; + int checkedReads = 0; + foreach (var r in d.Records) + { + Assert.True(r.Position <= (ulong)stream.Length && r.Count <= (ulong)stream.Length - r.Position, + $"{where}: record {r.ObjectId} (class {r.ClassNumber}) addresses {r.Position}+{r.Count} of a {stream.Length}-byte stream"); + // A few full reads exercise the copy, not every record (the streams are large). + if (r.Count > 0 && checkedReads < 3) + { + Assert.Equal((long)r.Count, stream.ReadExtent(r).Length); + checkedReads++; + } + } + } + } + } + [SkippableFact] public void EveryFdbSampleHasADirectoryOfMostlyAbuttingExtents() { From c2ec387b3d28d7a471c982a355db921bbd04efe1 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:14:42 +0300 Subject: [PATCH 2/3] Report shifted offsets and check record bounds before the long cast Two fixes to the decoded stream: - Blocks of the scan that fail to decode are skipped and contribute no bytes; every stream offset at or past the first skipped block is shifted by the missing bytes. The stream now tracks that boundary and exposes it as PlaStream.UnreliableFrom, and both extent reads report it: a read whose position is at or past the boundary, or that reaches into it, throws InvalidDataException instead of returning bytes of other objects. A zero-length extent at the boundary is shifted too. The record fits test of the sample corpus applies the exact-fit checks only to the records before the boundary and asserts the report for the records past it. - A record position wider than long (ulong.MaxValue) was cast before the bounds check and came out as an ArgumentOutOfRangeException from the extent read; the record read now compares against the stream length as unsigned and reports the documented InvalidDataException. --- src/PlaIO/PlaDocument.cs | 26 ++++++++++++---- src/PlaIO/PlaStream.cs | 27 ++++++++++++++-- tests/PlaIO.Tests/PlaStreamTests.cs | 48 +++++++++++++++++++++++++++++ tests/PlaIO.Tests/SampleTests.cs | 9 +++++- 4 files changed, 100 insertions(+), 10 deletions(-) diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 4497ee0..e379aa8 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -160,12 +160,24 @@ internal byte[] ReadPayload(PlaBlock block, out int consumed) /// Decodes the whole file once into the global stream: the raw payloads, the full zero-mask decodes and the /// mode-2 outputs, in block order. Blocks that do not decode to their declared size (false entries of the scan) are - /// skipped. The stream is a snapshot: it holds the whole decoded file in memory and the document may be disposed + /// skipped: every stream offset at or past the first skipped block is shifted, and the reads of the stream report + /// that. The stream is a snapshot: it holds the whole decoded file in memory and the document may be disposed /// afterwards. Object directory records address the stream by position and count. public PlaStream OpenStream() { ObjectDisposedException.ThrowIf(_disposed, this); - return new PlaStream(DecodeGlobalWindow(out _)); + var window = new List(); + long? unreliableFrom = null; + foreach (var b in _blocks) + { + if (!TryAppendToWindow(b, window)) + { + // The skipped block contributes no bytes: every offset at or past the position it would have held is + // shifted, so reads that reach there are not reliable and report it. + unreliableFrom ??= window.Count; + } + } + return new PlaStream(window, unreliableFrom); } /// Appends the decoded payload of one block to the mode-2 global window, or leaves the window unchanged when @@ -188,15 +200,17 @@ private bool TryAppendToWindow(PlaBlock b, List window) /// Decodes the whole file once into the global window: the raw payloads, the full zero-mask decodes and the /// mode-2 outputs, in block order. Blocks that do not decode to their declared size (false entries of the scan) are - /// skipped and reported in ; the window stays as if they were not there. - internal List DecodeGlobalWindow(out IReadOnlyList skipped) + /// skipped and reported in with the window offset each would have contributed; the window + /// stays as if they were not there. + internal List DecodeGlobalWindow(out IReadOnlyList<(PlaBlock Block, long WindowPosition)> skipped) { ObjectDisposedException.ThrowIf(_disposed, this); var window = new List(); - var failed = new List(); + var failed = new List<(PlaBlock, long)>(); foreach (var b in _blocks) { - if (!TryAppendToWindow(b, window)) failed.Add(b); + int before = window.Count; + if (!TryAppendToWindow(b, window)) failed.Add((b, before)); } skipped = failed.AsReadOnly(); return window; diff --git a/src/PlaIO/PlaStream.cs b/src/PlaIO/PlaStream.cs index e3df82d..80cb48c 100644 --- a/src/PlaIO/PlaStream.cs +++ b/src/PlaIO/PlaStream.cs @@ -6,36 +6,57 @@ namespace PlaIO; /// and name a byte extent of the /// stream, the object's data. The stream is a snapshot: it holds the whole decoded file in memory and never touches the /// document again, so the document may be disposed. Not thread-safe. +/// Blocks of the scan that fail to decode are skipped and leave the stream without their bytes; every offset at +/// or past the first skipped block is then shifted by the bytes that are missing, and the reads report that: an extent +/// reaching into the shifted range throws, and names the boundary. public sealed class PlaStream { private readonly List _bytes; - internal PlaStream(List bytes) => _bytes = bytes; + /// The stream offset at or past which the offsets are shifted, because blocks failed to decode before it; + /// null when every block decoded and all offsets are exact. + public long? UnreliableFrom { get; } + + internal PlaStream(List bytes, long? unreliableFrom) + { + _bytes = bytes; + UnreliableFrom = unreliableFrom; + } /// Length of the decoded stream in bytes. public long Length => _bytes.Count; /// The bytes of one extent of the stream. /// The bounds are negative or reach past the stream. + /// The extent reaches into the range whose offsets are shifted, because + /// blocks before it failed to decode (). public byte[] ReadExtent(long position, long count) { ArgumentOutOfRangeException.ThrowIfNegative(position); ArgumentOutOfRangeException.ThrowIfNegative(count); if (position > Length || count > Length - position) throw new ArgumentOutOfRangeException(nameof(count), $"The extent at {position}+{count} reaches past the decoded stream ({Length} bytes)."); + if (UnreliableFrom is { } from && (position >= from || position + count > from)) + throw new InvalidDataException($"The extent at {position}+{count} reaches the offsets shifted by skipped blocks (from {from} on the offsets are not reliable)."); var extent = new byte[count]; for (long i = 0; i < count; i++) extent[i] = _bytes[(int)(position + i)]; return extent; } /// The bytes of the extent one directory record addresses. - /// The record's extent reaches past the decoded stream. + /// The record's extent reaches past the decoded stream, or reaches into the + /// range whose offsets are shifted because blocks before it failed to decode. public byte[] ReadExtent(ObjectDirectoryRecord record) { + // A record position wider than the stream's long is past the stream by definition; cast after the check. + if (record.Position > (ulong)Length) + throw new InvalidDataException($"The directory record of {record.ObjectId} (class {record.ClassNumber}) addresses {record.Position}+{record.Count}, past the decoded stream ({Length} bytes)."); long position = (long)record.Position; long count = record.Count; - if (position > Length || count > Length - position) + if (count > Length - position) throw new InvalidDataException($"The directory record of {record.ObjectId} (class {record.ClassNumber}) addresses {position}+{count}, past the decoded stream ({Length} bytes)."); + if (UnreliableFrom is { } from && (position >= from || position + count > from)) + throw new InvalidDataException($"The directory record of {record.ObjectId} (class {record.ClassNumber}) addresses {position}+{count}, into the offsets shifted by skipped blocks (from {from} on the offsets are not reliable)."); return ReadExtent(position, count); } } diff --git a/tests/PlaIO.Tests/PlaStreamTests.cs b/tests/PlaIO.Tests/PlaStreamTests.cs index 7821c21..cc80582 100644 --- a/tests/PlaIO.Tests/PlaStreamTests.cs +++ b/tests/PlaIO.Tests/PlaStreamTests.cs @@ -70,4 +70,52 @@ public void ARecordExtentPastTheStreamIsRejected() stream.ReadExtent(new ObjectDirectoryRecord(3, 1, 10, guid))); Assert.Contains(guid.ToString(), e.Message); } + + [Fact] + public void ARecordPositionWiderThanALongIsRejectedAsPastTheStream() + { + var guid = Guid.NewGuid(); + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray())))); + + var stream = document.OpenStream(); + var e = Assert.Throws(() => + stream.ReadExtent(new ObjectDirectoryRecord(3, ulong.MaxValue, 1, guid))); + Assert.Contains(guid.ToString(), e.Message); + } + + [Fact] + public void ExtentsPastASkippedBlockAreRejectedAsShifted() + { + // Block A: raw "AB". Block B: a mode 2 block that does not decode (its match distance reaches past the decoded + // stream, in both the strict and the buffer-mode attempt). Block C: raw "CD", its bytes are shifted in the + // stream by the skipped block. + var brokenLz = Synthetic.Concat([0x40], "ABCD"u8.ToArray(), [0xFF, 0xFF], [0x10]); + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray()), + Synthetic.Block(PlaBlockMode.Lz, brokenLz, unpacked: 6), + Synthetic.Block(PlaBlockMode.Raw, "CD"u8.ToArray())))); + + var stream = document.OpenStream(); + Assert.NotNull(stream.UnreliableFrom); + Assert.Equal(2, stream.UnreliableFrom); + // Before the boundary the reads are exact. + Assert.Equal("AB"u8.ToArray(), stream.ReadExtent(0, 2)); + // At and past the boundary the offsets are shifted: a read of the following record reports it. + var e = Assert.Throws(() => stream.ReadExtent(2, 2)); + Assert.Contains("shifted", e.Message); + Assert.Throws(() => stream.ReadExtent(new ObjectDirectoryRecord(3, 2, 2, Guid.NewGuid()))); + } + + [Fact] + public void AZeroLengthExtentAtTheUnreliableBoundaryIsStillRejected() + { + // A zero-mask block whose stream ends inside a group does not decode; the record after it is shifted. + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray()), + Synthetic.Block(PlaBlockMode.ZeroMask, [0x80], unpacked: 8)))); + var stream = document.OpenStream(); + Assert.Equal(2, stream.UnreliableFrom); + Assert.Throws(() => stream.ReadExtent(2, 0)); + } } diff --git a/tests/PlaIO.Tests/SampleTests.cs b/tests/PlaIO.Tests/SampleTests.cs index a3ea88f..3442bab 100644 --- a/tests/PlaIO.Tests/SampleTests.cs +++ b/tests/PlaIO.Tests/SampleTests.cs @@ -143,7 +143,7 @@ public void EveryLzBlockDecodesAndOnlyFalseEntriesAreSkipped() { sample.Document.DecodeGlobalWindow(out var skipped); string where = $"{sample.Name}: {skipped.Count} of {sample.Document.Blocks.Count} blocks skipped"; - Assert.True(skipped.All(b => b.Mode != PlaBlockMode.Lz), $"{where}; a mode-2 block did not decode"); + Assert.True(skipped.All(s => s.Block.Mode != PlaBlockMode.Lz), $"{where}; a mode-2 block did not decode"); Assert.True(skipped.Count <= 0.01 * sample.Document.Blocks.Count, where); } } @@ -160,6 +160,13 @@ public void EveryDirectoryRecordFitsTheGlobalStream() int checkedReads = 0; foreach (var r in d.Records) { + // Records past the unreliable boundary address shifted offsets and are reported by the read; the + // exact-fit checks only apply to the records before it. + if (stream.UnreliableFrom is { } from && r.Position + r.Count > (ulong)from) + { + Assert.Throws(() => stream.ReadExtent(r)); + continue; + } Assert.True(r.Position <= (ulong)stream.Length && r.Count <= (ulong)stream.Length - r.Position, $"{where}: record {r.ObjectId} (class {r.ClassNumber}) addresses {r.Position}+{r.Count} of a {stream.Length}-byte stream"); // A few full reads exercise the copy, not every record (the streams are large). From 123bb8e20b61f6cd377d7c10746ecfe0fccd7a03 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:35:26 +0300 Subject: [PATCH 3/3] Reject extents after a short zero-mask block --- README.md | 5 ++--- docs/cli.md | 4 ++-- docs/getting-started.md | 2 +- docs/public-api.md | 9 +++++---- src/PlaIO/PlaDocument.cs | 22 +++++----------------- src/PlaIO/PlaStream.cs | 9 ++++----- tests/PlaIO.Tests/PlaStreamTests.cs | 14 ++++++++++++++ tests/PlaIO.Tests/SampleTests.cs | 2 +- 8 files changed, 34 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 3f06114..65578dd 100644 --- a/README.md +++ b/README.md @@ -201,9 +201,8 @@ included in the repository. Files from other versions are not tested. ## Limitations - Version 0.1.0 is a preview. The API can change before 1.0. -- The meaning of the `pos` and `count` fields of a directory record is not known, so the addressing of objects is not - supported. Class numbers are not mapped to class names, and the contents of objects (elements, parameters, geometry) - are not read. +- `PlaDocument.OpenStream().ReadExtent(record)` reads object bytes for directory records that address the reliable range + of the decoded stream. Class names and the contents of objects (elements, parameters, geometry) are not interpreted. - Several header and block fields are exposed as raw values because their meaning is not documented. - The block index is built by scanning for block headers from offset 32. It is not checked against an index in the file, so completeness is not claimed. The scan can also take a byte run for a block header, so the index may contain false diff --git a/docs/cli.md b/docs/cli.md index 21a8e13..cc1be94 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -37,8 +37,8 @@ The limits are fixed; the tool has no option to change them. | Mode 2 (LZ) payloads | Listed by `blocks`. The CLI `directory` command reads raw blocks only. | | Object directories | Searched in raw (mode 0) blocks of at least 1920 bytes, at most one per block. A directory needs at least 64 records whose extents mostly abut. The run that is reported is an estimate and can be shorter than the real directory. | -The meaning of `pos` and `count` in a directory record is not known, class numbers are not mapped to class names and the -contents of objects are not read, so the tool reports none of them beyond the raw numbers. +The CLI reports `pos`, `count` and class numbers as stored and does not read object contents. The library exposes +extent reads through `PlaDocument.OpenStream()`. ## Output format diff --git a/docs/getting-started.md b/docs/getting-started.md index a914961..193b2b9 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -69,4 +69,4 @@ The supported surface is listed in [Public API](public-api.md); every type is in ## Status -PlaIO 0.1.0 is a preview and the API can change before 1.0. It does not interpret the position and count of directory records, does not map class numbers to class names and does not read object contents. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. The block index is found by scanning and may contain false entries. +PlaIO 0.1.0 is a preview and the API can change before 1.0. Use `PlaDocument.OpenStream().ReadExtent(record)` to read object bytes at a directory record's position and count. The stream rejects extents beyond its reliable range. Class names and object contents are not interpreted. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. The block index is found by scanning and may contain false entries. diff --git a/docs/public-api.md b/docs/public-api.md index bc7603a..105aba7 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -23,16 +23,17 @@ The `PlaIO` package is the supported surface listed here; every public type is i | `PlaDocument.Blocks` | The block index in file order, found by scanning from offset 32. No on-disk block map is known, so completeness is not claimed. The scan can take a byte run for a block header, so the index may contain false entries. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. | | `PlaDocument.ReadPayload(PlaBlock block)` | The decoded payload of a block of this document. Decodes all three storage modes: raw (mode 0), zero masks (mode 1) and the LZ token stream (mode 2). A mode 2 payload may start with a 9-byte stream header with a 0x46 or 0x47 marker and matching packed and unpacked sizes. The token stream produces the block's declared unpacked size — some blocks declare a buffer larger than the stream produces, the tail of the buffer stays zero — and may reference the output of any preceding block, so the payload is produced by decoding every preceding block of the file in order into one global window; the cost of the call grows with the size of the file. Preceding blocks that do not decode (false entries of the scan) are skipped and leave the window unchanged. Throws `InvalidDataException` when a back-reference reaches beyond the decoded stream or the file is cut short, and `ArgumentException` when the block is not from this document. | | `PlaDocument.FindDirectories()` | Searches every raw (mode 0) block large enough for 64 records of 30 bytes for an object directory, at most one per block. Recomputed on each call; mode 1 payloads are not searched. | -| `PlaDocument.OpenStream()` | The document's decoded global stream (`PlaStream`): every block's payload decoded in block order. Blocks that do not decode (false entries of the scan) are skipped. The stream is a snapshot — it holds the whole decoded file in memory and the document may be disposed afterwards; decoding it once costs like a full mode-2 read. | +| `PlaDocument.OpenStream()` | The document's decoded global stream (`PlaStream`): every block's payload decoded in block order. Blocks that fail to decode are skipped and mark the remaining offsets as unreliable. The stream holds the decoded bytes in memory and can outlive the document. | | `PlaDocument.Dispose()` | Releases the stream unless the document was opened with `leaveOpen`. | | `FdbHeader` | `Size` (64), `LayoutVersion` (u16 at offset 8), `FormatVersion` (u16 at offset 10), `Field12` (u32 at offset 12; meaning not documented), `Raw` (the first min(64, file length) bytes; bytes 32..63 overlap the first block). | | `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200). | | `PlaBlock` | One indexed block: `Offset`, `Tag` (`BL` or `DY`), `Id` and `Kind` (raw), `Version` (0 or 1), `Flags` (raw), `SizeClass` (`Flags & 0xF`), `Mode`, `Guid` (present when flag 0x20 is set), `PackedSize`, `UnpackedSize`, `Extra` (present when flag 0x400 is set; raw), `PayloadOffset`, `HeaderLength`, `End`. | | `ObjectDirectory` | A run of directory records inside a raw block: `Block`, `RecordOffset` (payload offset of the first record), `Phase` (`RecordOffset % 30`), `Records`, `AbuttingPairs`, `OverlappingPairs`, `DuplicatePositions`. The run is an estimate and can be shorter than the real directory: it stops after more than 8 consecutive records without an abutting neighbour. | | `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. The position and count name a byte extent of the decoded global stream — the object's data (see `PlaDocument.OpenStream`). The class number is not mapped to a class name. | -| `PlaStream.Length` | Length of the decoded stream in bytes. | -| `PlaStream.ReadExtent(long position, long count)` | The bytes of one extent of the stream. `ArgumentOutOfRangeException` for negative bounds or an extent past the stream. | -| `PlaStream.ReadExtent(ObjectDirectoryRecord record)` | The bytes of the extent one directory record addresses — the object's data. `InvalidDataException` when the record's extent reaches past the stream. | +| `PlaStream.Length` | Length of the decoded stream in bytes, including the bytes beyond the unreliable boundary. | +| `PlaStream.UnreliableFrom` | The offset of the first indexed block that failed to decode, or null when every indexed block decoded. | +| `PlaStream.ReadExtent(long position, long count)` | The bytes of one extent. Throws `ArgumentOutOfRangeException` for negative or out-of-bounds extents and `InvalidDataException` for extents that reach the unreliable range. | +| `PlaStream.ReadExtent(ObjectDirectoryRecord record)` | The bytes addressed by a directory record. Throws `InvalidDataException` if the extent exceeds the stream or reaches the unreliable range. | ## BIMx file (`.bimx`) diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 6ce51a6..d426c9a 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -159,25 +159,13 @@ internal byte[] ReadPayload(PlaBlock block, out int consumed) } /// Decodes the whole file once into the global stream: the raw payloads, the full zero-mask decodes and the - /// mode-2 outputs, in block order. Blocks that do not decode to their declared size (false entries of the scan) are - /// skipped: every stream offset at or past the first skipped block is shifted, and the reads of the stream report - /// that. The stream is a snapshot: it holds the whole decoded file in memory and the document may be disposed - /// afterwards. Object directory records address the stream by position and count. + /// mode-2 outputs, in block order. If any indexed block fails to decode, the stream rejects reads that reach + /// the resulting unreliable range. The stream holds the decoded bytes in memory independently of the document's + /// lifetime. Object directory records address the stream by position and count. public PlaStream OpenStream() { - ObjectDisposedException.ThrowIf(_disposed, this); - var window = new List(); - long? unreliableFrom = null; - foreach (var b in _blocks) - { - if (!TryAppendToWindow(b, window)) - { - // The skipped block contributes no bytes: every offset at or past the position it would have held is - // shifted, so reads that reach there are not reliable and report it. - unreliableFrom ??= window.Count; - } - } - return new PlaStream(window, unreliableFrom); + var window = DecodeGlobalWindow(out var skipped); + return new PlaStream(window, skipped.Count == 0 ? null : skipped[0].WindowPosition); } /// Appends the decoded payload of one block to the mode-2 global window, or leaves the window unchanged when diff --git a/src/PlaIO/PlaStream.cs b/src/PlaIO/PlaStream.cs index 80cb48c..98de6bf 100644 --- a/src/PlaIO/PlaStream.cs +++ b/src/PlaIO/PlaStream.cs @@ -6,15 +6,14 @@ namespace PlaIO; /// and name a byte extent of the /// stream, the object's data. The stream is a snapshot: it holds the whole decoded file in memory and never touches the /// document again, so the document may be disposed. Not thread-safe. -/// Blocks of the scan that fail to decode are skipped and leave the stream without their bytes; every offset at -/// or past the first skipped block is then shifted by the bytes that are missing, and the reads report that: an extent -/// reaching into the shifted range throws, and names the boundary. +/// When an indexed block fails to decode, offsets at and past that block may be shifted. An extent that +/// reaches the unreliable range throws, and names the boundary. public sealed class PlaStream { private readonly List _bytes; - /// The stream offset at or past which the offsets are shifted, because blocks failed to decode before it; - /// null when every block decoded and all offsets are exact. + /// The offset of the first indexed block that failed to decode, or null when every indexed block decoded. + /// Extent reads that reach this boundary throw because the following offsets may be shifted. public long? UnreliableFrom { get; } internal PlaStream(List bytes, long? unreliableFrom) diff --git a/tests/PlaIO.Tests/PlaStreamTests.cs b/tests/PlaIO.Tests/PlaStreamTests.cs index cc80582..6b8be27 100644 --- a/tests/PlaIO.Tests/PlaStreamTests.cs +++ b/tests/PlaIO.Tests/PlaStreamTests.cs @@ -107,6 +107,20 @@ public void ExtentsPastASkippedBlockAreRejectedAsShifted() Assert.Throws(() => stream.ReadExtent(new ObjectDirectoryRecord(3, 2, 2, Guid.NewGuid()))); } + [Fact] + public void AShortZeroMaskBlockAtAGroupBoundaryMakesLaterExtentsUnreliable() + { + using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb( + Synthetic.Block(PlaBlockMode.Raw, "AB"u8.ToArray()), + Synthetic.Block(PlaBlockMode.ZeroMask, [1, 9], unpacked: 16), + Synthetic.Block(PlaBlockMode.Raw, "CDEFGHIJKLMN"u8.ToArray())))); + + var stream = document.OpenStream(); + Assert.Equal(2, stream.UnreliableFrom); + Assert.Equal("AB"u8.ToArray(), stream.ReadExtent(0, 2)); + Assert.Throws(() => stream.ReadExtent(new ObjectDirectoryRecord(3, 2, 2, Guid.Empty))); + } + [Fact] public void AZeroLengthExtentAtTheUnreliableBoundaryIsStillRejected() { diff --git a/tests/PlaIO.Tests/SampleTests.cs b/tests/PlaIO.Tests/SampleTests.cs index 3442bab..8c5eb26 100644 --- a/tests/PlaIO.Tests/SampleTests.cs +++ b/tests/PlaIO.Tests/SampleTests.cs @@ -162,7 +162,7 @@ public void EveryDirectoryRecordFitsTheGlobalStream() { // Records past the unreliable boundary address shifted offsets and are reported by the read; the // exact-fit checks only apply to the records before it. - if (stream.UnreliableFrom is { } from && r.Position + r.Count > (ulong)from) + if (stream.UnreliableFrom is { } from && (r.Position >= (ulong)from || r.Count > (ulong)from - r.Position)) { Assert.Throws(() => stream.ReadExtent(r)); continue;