From 37e078f634d61aa25f4062e4b3e1c85cee7585db Mon Sep 17 00:00:00 2001 From: Vincent Vollers <59395529+vvollers@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:48:42 +0100 Subject: [PATCH 1/2] Add Windows PDB metadata preparation and native ISF overlays PdbMetadata reads MSF 7 / CodeView V70 and V80 PDB metadata from selected streams and writes a deterministic ISF 6.2.0 profile offline: - Identity: GUID, both age fields, original DBI machine; an explicit targetMachine is required when the DBI machine is zero. - Types: structs, classes, unions, enums, arrays, bitfields and flat 32/64-bit pointers (legacy records without size bits keep their kind's width). C++ field lists export instance members and skip methods, bases, nested types, static members and vtable entries; the declared count is an upper bound when such elements are present. - Symbols: public, global and unambiguous file-local addresses after OMAP; absolute values kept separately; file-local names with several addresses are omitted with a diagnostic; a PDB without a symbol stream still loads. - Limits: maxMetadataBytes and per-table maxRecords bound loading; WriteIsf has its own maxTraversalSteps export limit. ISF import: - Accepts format 6.1.0 as well as 6.2.0. - Members whose physical bits overlap are grouped into a generated union held by a promoted __overlay_{offset} member, so original paths still resolve and unrelated members keep struct semantics. - An explicit pointer storage base supplies the pointer's width and byte order, so native and WOW64 pointers coexist. Memory sources: - MappedMemorySource.Read returns a positive short count at a mapping boundary (breaking for direct callers; region APIs assemble transfers and keep confirmed prefixes across missing extents). - CachedMemorySource stores positive short reads and evicts by retained bytes. The MemoryProjectionTests pointer case now stores its big-endian pointer in big-endian order; it previously passed only because pointer byte order was ignored. --- CHANGELOG.md | 38 + PERFORMANCE.md | 52 + apps/explorer/tests/catalog-baseline.json | 4 +- .../api/managed/CStructSharp.public-api.txt | 17 + contracts/api/managed/manifest.json | 40 +- contracts/memory/v1.json | 4 +- docs/config/cspell-terms.txt | 2 + docs/guides/memory-analysis.md | 20 +- docs/guides/memory-schemas.md | 101 +- docs/guides/memory-sources.md | 20 +- src/CStructSharp/Memory/CachedMemorySource.cs | 22 +- src/CStructSharp/Memory/MappedMemorySource.cs | 51 +- src/CStructSharp/Memory/MemorySchema.cs | 160 ++- .../Memory/MemoryTypeDefinition.cs | 3 + .../Memory/Metadata/IsfMetadata.cs | 44 +- .../Memory/Metadata/MetadataImportOptions.cs | 4 +- .../Memory/Metadata/PdbExportBudget.cs | 33 + .../Memory/Metadata/PdbMetadata.Isf.cs | 639 ++++++++++++ .../Memory/Metadata/PdbMetadata.Symbols.cs | 338 ++++++ .../Memory/Metadata/PdbMetadata.cs | 363 +++++++ .../Memory/Metadata/PdbMsfFile.cs | 238 +++++ .../Memory/Metadata/PdbRecordReader.cs | 163 +++ tests/CStructSharp.AotConsumer/Program.cs | 17 + .../Api/PublicApiSurfaceTests.cs | 1 + .../Memory/MemoryFuzzTests.cs | 2 +- .../Memory/MemoryIsfCoverageTests.cs | 3 +- .../Memory/MemoryIsfOverlayTests.cs | 192 ++++ .../Memory/MemoryIsfPointerStorageTests.cs | 89 ++ .../Memory/MemoryPdbMetadataTests.cs | 958 ++++++++++++++++++ .../Memory/MemoryProjectionTests.cs | 4 +- .../Memory/MemorySourceContractTests.cs | 92 +- 31 files changed, 3613 insertions(+), 101 deletions(-) create mode 100644 src/CStructSharp/Memory/Metadata/PdbExportBudget.cs create mode 100644 src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs create mode 100644 src/CStructSharp/Memory/Metadata/PdbMetadata.Symbols.cs create mode 100644 src/CStructSharp/Memory/Metadata/PdbMetadata.cs create mode 100644 src/CStructSharp/Memory/Metadata/PdbMsfFile.cs create mode 100644 src/CStructSharp/Memory/Metadata/PdbRecordReader.cs create mode 100644 tests/CStructSharpTests/Memory/MemoryIsfOverlayTests.cs create mode 100644 tests/CStructSharpTests/Memory/MemoryIsfPointerStorageTests.cs create mode 100644 tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a49997e..84b1464b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,44 @@ Related changes are consolidated; routine formatting and benchmark bookkeeping a headings in this order and omits the empty ones: *Breaking changes* (each with its migration), *Added*, *Changed*, *Fixed*, *Performance*, and *Documentation and tooling*. +## Unreleased + +### Breaking changes + +- `MappedMemorySource.Read` (`IMemorySource.Read`) now returns a positive short count at a mapping boundary instead + of filling the whole destination from successive mappings. Migration: callers that invoke `Read` directly must + continue from the returned count, or use `MemoryRegion.ReadExactly` or `ReadPartial`, which assemble complete + transfers. Bytes from completed mappings stay confirmed when a later mapping or backing extent is missing, + including through nested mappings, and failures keep their original coordinates. + +### Added + +- Import native ISF 6.1.0 documents alongside 6.2.0 without changing their declared version. +- Preserve flattened native member aliases. Only members whose physical bits overlap are grouped into a generated + union, held by a promoted `__overlay_{offset}` member, so every original member path still resolves and unrelated + members keep struct semantics. A whole-value write supplies each group as a `UnionValue`. Native descriptions keep + their original kind and fields. Ordinary struct validation remains strict. +- Prepare native MSF 7/CodeView V70 and V80 Windows PDB metadata as deterministic ISF 6.2.0 with `PdbMetadata`, without + a debugger or network dependency. Selected stream reads and per-table record limits bound loading; `WriteIsf` has its + own `maxTraversalSteps` limit. Public/global/file-local image-relative addresses, absolute symbol values, both native + age fields and ambiguous type identities stay distinct; file-local names with several addresses are reported in + `Diagnostics` instead of being exported. C++ classes export their instance members and skip methods, base classes, + nested types, static members and vtable entries. A PDB without a symbol stream still provides its types. +- `PdbMetadata` reads pointer storage from CodeView itself: explicit 32-bit and 64-bit pointers keep their own widths + (also when legacy records omit the size bits), and the ISF `pointer` base records the target machine's width. When + the DBI machine is zero, construction requires an explicit `targetMachine`; `Machine` keeps the original value and + a nonzero original machine cannot be overridden. +- Keep every original complete type when a forward declaration has several same-extent definitions. Prepared metadata + exposes an explicit union of those views instead of silently selecting a definition by its display name. + +### Fixed + +- Honor an ISF pointer's explicit integer storage base independently of the default target pointer width, including + that base's byte order. Native and WOW64 representations can coexist in one schema and in field-directed imports + without widening, truncating or byte-swapping stored addresses. +- `CachedMemorySource` stores positive short reads with their confirmed count, so repeated transfers that cross a + mapped boundary are answered from the cache. Eviction releases the bytes each entry actually retained. + ## 0.18.0 — 2026-10-28 ### Added diff --git a/PERFORMANCE.md b/PERFORMANCE.md index 9034f08a..3779d15f 100644 --- a/PERFORMANCE.md +++ b/PERFORMANCE.md @@ -38,3 +38,55 @@ The 16-byte text comparison includes raw ownership, ASCII decoding and all NUL c The recorded campaign retains library-samples.jsonl (48 cases, 480 measured samples plus 96 warmup samples), text-samples.jsonl (20 measured samples plus four warmups), immutable-manifest.json and summary JSON files. The reproduction guide generates new samples without requiring that local archive. Read-set output memory is bounded by its prepared envelope; matching scratch is pooled and operation-local. Unknown-input coverage, gap recovery, final unsigned addresses and cancellation are correctness tests, not timing claims. The repository-wide Impact screen and targeted SerializeScalar confirmation retained unstable/canary warnings. Those results are inconclusive and establish neither improvement nor equivalence. Reports remain under artifacts/perf/development/runs/2026-10-28T13-23-03-743Z-babed2 and 2026-10-28T13-25-11-044Z-83f8d1. Client complete-operation findings, rejected indexes/shared filters, sparse coverage and cancellation are in the client's PERFORMANCE.md. + +## Native ISF compatibility controls (4 November 2026) + +Windows x64, Ryzen 9 9950X, SDK 10.0.403/runtime 10.0.14, hyperfine 1.20.0. +The reference assembly is the immutable `windows-isf-before` bundle from clean revision +`334bb8990138cdb5071e187d4312a822a3036fc5`; the candidate contains native 6.1.0 acceptance and alias-view import. +Both run the same independently authored, nonoverlapping 6.2.0 control: a 16-byte record with a `uint32` and +a recursive eight-byte pointer. Each process warms 16 imports, then performs 1,000 fresh parse/import/selected-read +operations and verifies every result, with checksum 42,000. The allocation counter covers those 1,000 operations, +not startup or output. Process timings include startup and warmup. + +One process warmup precedes five measured processes in each before-JIT, after-JIT, before-AOT and after-AOT group. +Default tiering/PGO and OS caching are retained; affinity is unrestricted. No owned build, test, UI or source edit +overlaps timing. Allocation values are single observed counter samples, not an allocation distribution. + +| Build | Mean ms | Standard deviation ms | Minimum–maximum ms | Allocated B / 1,000 operations | +| --- | ---: | ---: | ---: | ---: | +| Reference JIT | 165.54 | 1.88 | 163.40–168.05 | 39,340,496 | +| Candidate JIT | 165.63 | 3.34 | 161.35–169.62 | 39,180,496 | +| Reference Native AOT | 32.78 | 4.33 | 29.43–39.42 | 39,452,000 | +| Candidate Native AOT | 29.27 | 1.09 | 28.43–31.17 | 39,290,952 | + +Hyperfine reported statistical outliers. Ranges overlap; these controls establish neither a speed improvement nor +equivalence, and do not isolate the allocation difference. Native 6.1.0/overlaid imports had no successful reference +implementation, so their new functionality is verified separately rather than compared with a failing baseline. +All four publications emitted no IL diagnostics. The ignored local qualification payloads and raw samples are +`artifacts/qualification/windows-isf-perf/` and the client's `dist/windows-isf-control-performance.json`. + + +## Portable native PDB preparation (4 November 2026) + +Windows x64, Ryzen 9 9950X, SDK 10.0.403/runtime 10.0.14, hyperfine 1.20.0. +The ignored native-PDB consumer reads an explicitly acquired 8,571,904-byte Microsoft PDB, +writes deterministic ISF, strictly imports seven native/WOW64 roots, then decodes and +round-trips a complete independently exported 2,624-byte captured record. Timings include +startup, selected metadata reads, output, imports and complete byte verification. Neither +the original input nor recovered record values are stored in this repository. + +One process warmup precedes five measured fresh processes in each JIT and Native AOT group. +Default tiering/PGO and OS caching remain enabled; affinity is unrestricted. No owned build, +test or UI job overlaps timing. + +| Runtime | Mean ms | Standard deviation ms | Minimum–maximum ms | +| --- | ---: | ---: | ---: | +| Release JIT | 315.18 | 7.76 | 308.70–324.77 | +| Native AOT | 69.53 | 5.37 | 66.43–79.10 | + +These are feature costs, not a before/after optimization or allocation comparison. +Hyperfine flags an AOT outlier; the original samples remain intact. The native publication +emits no IL diagnostics. Qualification source and payloads are under the ignored +`artifacts/qualification/native-pdb/` and `artifacts/qualification/native-pdb-aot/`; +raw timing samples are in the client's `dist/windows-native-pdb-performance.json`. diff --git a/apps/explorer/tests/catalog-baseline.json b/apps/explorer/tests/catalog-baseline.json index 1cbb3e94..079d2017 100644 --- a/apps/explorer/tests/catalog-baseline.json +++ b/apps/explorer/tests/catalog-baseline.json @@ -1,7 +1,7 @@ { - "totalTests": 2288, + "totalTests": 2327, "runnableTests": 160, - "testInputsSha256": "69cc2d873d740eb06c328d74dbba00ae55dfbdee3c39562da3ed324974f1e4d9", + "testInputsSha256": "fc2dd272403f7285c01f55e6181bd4be79e2f6afe246bc1adcd1f581b84ad681", "lessonIds": [ "header", "header-serialize", diff --git a/contracts/api/managed/CStructSharp.public-api.txt b/contracts/api/managed/CStructSharp.public-api.txt index 57a29e04..8f1accfe 100644 --- a/contracts/api/managed/CStructSharp.public-api.txt +++ b/contracts/api/managed/CStructSharp.public-api.txt @@ -1287,6 +1287,23 @@ namespace CStructSharp.Memory.Metadata public CStructSharp.Memory.MemorySchema Schema { get; init; } public System.Collections.Generic.IReadOnlyList? SelectedPaths { get; } } + public sealed class PdbMetadata + { + public PdbMetadata(System.IO.Stream input, int maxMetadataBytes = 67108864, int maxRecords = 1000000, System.Threading.CancellationToken cancellationToken = default, ushort? targetMachine = default) { } + public System.Collections.Generic.IReadOnlyDictionary AbsoluteSymbols { get; } + public uint DbiAge { get; } + public System.Collections.Generic.IReadOnlyList Diagnostics { get; } + public System.Guid Guid { get; } + public uint InformationAge { get; } + public ushort Machine { get; } + public int PointerSize { get; } + public System.Collections.Generic.IReadOnlyDictionary SymbolRecordKinds { get; } + public System.Collections.Generic.IReadOnlyDictionary Symbols { get; } + public ushort TargetMachine { get; } + public int UnmappedSymbolCount { get; } + public System.Collections.Generic.IReadOnlyList UserTypeNames { get; } + public void WriteIsf(System.IO.Stream output, string pdbName, long maxTraversalSteps = 100000000, System.Threading.CancellationToken cancellationToken = default) { } + } } namespace CStructSharp.Values { diff --git a/contracts/api/managed/manifest.json b/contracts/api/managed/manifest.json index 58cf313e..887d907e 100644 --- a/contracts/api/managed/manifest.json +++ b/contracts/api/managed/manifest.json @@ -1,10 +1,10 @@ { "schemaVersion": 1, "baselineId": "managed", - "baselineRevision": 74, - "packageVersion": "0.17.0", + "baselineRevision": 77, + "packageVersion": "0.18.0", "assembly": "CStructSharp.dll", - "exportedTypes": 123, + "exportedTypes": 124, "generator": { "package": "PublicApiGenerator.Tool", "version": "11.5.4", @@ -12,22 +12,22 @@ }, "canonical": { "path": "contracts/api/managed/CStructSharp.public-api.txt", - "lines": 1413, - "normalizedSha256": "6B6A8400AC0DB6BB2007194B1D0476CD1B4785248827013FF10C7FF4AD0E8188" + "lines": 1430, + "normalizedSha256": "E4D45E50B19A3AB23FDBE505B4672512389DC80387E3846022380AC727EF6652" }, "frameworks": [ { "tfm": "net8.0", "targetFramework": ".NETCoreApp,Version=v8.0", "frameworkDisplayName": ".NET 8.0", - "normalizedSha256": "A4374F093979B3050482FA9D51E6348212D8C442DF733C8EB13DE8D77B6D0264", + "normalizedSha256": "B1D7389DC6B0BCE22BBEA0AF4C86D02FEF20DFCBA286DF0F7EC4002281A4FCFA", "aotCompatible": false }, { "tfm": "net10.0", "targetFramework": ".NETCoreApp,Version=v10.0", "frameworkDisplayName": ".NET 10.0", - "normalizedSha256": "FDDA57B35D95312A8D44E2EE78A6E92E4AAB10A58B55755716773150CA5E98CF", + "normalizedSha256": "6C66C79C92122E6DD7F4F39CE0438A8D3FD21D61A0323B5E4B18385362253E8E", "aotCompatible": true } ], @@ -472,12 +472,30 @@ }, { "revision": 74, - "kind": "additive", "date": "2026-10-28", "packageVersion": "0.17.0", - "combinedSha256": "338C96526AE37ACD8F088E5CA384158B1159D7D41BA968437F3F1409CC80CB26", - "rationale": "Prepared recognition and bounded validity-aware discovery mechanisms", - "releaseImpact": "Existing calls retain behavior; clients may opt into prepared matching, raw bytes, sparse scans, selected capture, dynamic provenance and streaming graphs" + "combinedSha256": "338C96526AE37ACD8F088E5CA384158B1159D7D41BA968437F3F1409CC80CB26" + }, + { + "revision": 75, + "date": "2026-11-04", + "packageVersion": "0.18.0", + "combinedSha256": "C2884AC39B5D67E4DE2D49568744A01EAF53D4360A088623DE600ADAABA45CEA" + }, + { + "revision": 76, + "date": "2026-11-08", + "packageVersion": "0.18.0", + "combinedSha256": "CFBB37FC0F0124F33EDDA033E80393DDAED3F00140D5C6DC622ACBE65ECFAF4F" + }, + { + "revision": 77, + "kind": "additive", + "date": "2026-11-16", + "packageVersion": "0.18.0", + "combinedSha256": "83CA5F370907795397B9C1F4727A3964F28CE13AD5C34D54AEF01E00D139A480", + "rationale": "PdbMetadata.WriteIsf takes an explicit maxTraversalSteps export limit, independent of the constructor's per-table maxRecords input limit. PdbMetadata itself is new since 0.18.0, so revision 76's targetMachine parameter is also additive for released consumers.", + "releaseImpact": "No released API changes. Unreleased callers that passed a CancellationToken positionally to WriteIsf pass it by name (cancellationToken:)." } ] } diff --git a/contracts/memory/v1.json b/contracts/memory/v1.json index 8f43e046..245cdb3f 100644 --- a/contracts/memory/v1.json +++ b/contracts/memory/v1.json @@ -17,7 +17,7 @@ { "kind": "RawBytes", "read": "raw byte[] of the declared size", "inspect": true, "resolve": "whole value only; no members", "serialize": "exact-size raw byte[]", "plan-update": "raw bytes", "commit": "requires writable backing", "select": true, "bind": false, "read-exact": "finite region operation, independent of type", "read-array": false } ], "failureRules": ["never zero-fill holes", "checked unsigned extent arithmetic", "cancellation propagates", "budgets shared across nested operations", "no ownership transfer", "source changes invalidate cached bytes", "patch expectations prevalidated", "commit failure identifies completed prefix and uncertain fragment", "no atomicity or rollback promise", "MemoryAccessException is a CStructReadException: ReadLimitExceeded for BudgetExceeded, otherwise ReadFailed", "source coordinates are null when a failure has no source address", "path errors are CStructPathException, value errors CStructWriteException, definition and metadata errors CStructLayoutException", "MemoryPatchCommitException is a CStructWriteException", "parameter-contract violations, read-only sources, and cancellation keep .NET exception types"], - "metadata": { "btf": "v1 reachable or field-directed value types and split tables; no ELF extraction", "isf": "6.2.0 reachable or field-directed type subsets; shallow user-type descriptions; document-owned bounded successful scalar compilation; no profile matching or relocations", "portable": "fixed compiled layouts only" }, + "metadata": { "btf": "v1 reachable or field-directed value types and split tables; no ELF extraction", "isf": "6.1.0 and 6.2.0 reachable or field-directed type subsets; members with overlapping physical bits are grouped into promoted generated unions while every original path resolves; explicit integer pointer storage retains its own width and byte order; shallow descriptions retain native kind; document-owned bounded successful scalar compilation; no profile matching or relocations", "pdb": "MSF 7 / CodeView V70 and V80 headers with supported explicit storage; offline ISF preparation from selected metadata streams; zero pointer size bits retain near32/near64 widths; unknown DBI machine requires explicit targetMachine while Machine and exported machine_type preserve the original zero; nonzero machine contradictions reject; original information/DBI ages, public/global RVAs, absolute values and ambiguous type identities remain distinct; file-local names with several coordinates are omitted with diagnostics; a missing symbol stream yields empty symbol tables; C++ field lists export instance members only; maxRecords bounds input tables while WriteIsf maxTraversalSteps bounds export work; cancellation; no capture opening or network acquisition", "portable": "fixed compiled layouts only" }, "projection": { "paths": "explicit member/index/pointer paths; terminal composites and arrays include by-value closure; pointer targets require an explicit value path or another selected by-value use", "placement": "original IDs, root sizes, array stride, field offsets, byte order and bit slices are preserved", "availability": "IsProjected and UnselectedMembers describe omitted composite members; IsUnselected distinguishes deliberately address-only target identities from missing metadata; schemas never expand implicitly", "validation": "selected descriptors and placements, direct names and promoted ambiguity candidates; omitted ordinary descriptors are not validated; full Import keeps full reachable validation", "limits": "MaxTypes bounds distinct planning and emitted descriptors; MaxProjectionWork bounds path-text/path-step/native-member/promotion/closure work; promotion search memoizes shared DAGs and stops after two matches", "writes": "whole-value encoding rejects composites with omitted members; selected-field updates preserve unrelated bytes" }, "prepared": { "schemaIdentity": "identical schema instance required", "lifetime": "immutable schema decisions only; no retained source bytes, pointer values or operation contexts", "fixedOffset": "root-relative byte offset only without a pointer value step", "typed": "8/16/24/32/64-bit integers, bool, float32/float64, enum results, bit slices and StoredPointer; other scalar codecs bind as object", "failure": "Try operations distinguish schema, path, type, pointer, extent, codec and storage failures; cancellation and budgets terminate" }, "exactReads": "destination must fit the finite region before transport; positive short reads continue; zero length checks cancellation without requests; copied prefix remains and unread bytes stay untouched", @@ -26,5 +26,5 @@ "resolver": "Func; pointer storage, translation and target reads share the active context; no context retention", "traversalIdentity": "source object and address by default; an explicit caller callback may canonicalize aliased views while returned nodes retain their original sources", "discovery": {"buffer":"fixed scalar fields use exact selected extents and explicit validity; predicates never see unknown bytes","bytes":"prepared one-byte arrays preserve raw bits and bypass custom codecs; text policy is application-owned","scan":"borrowed bounded windows, owned starts, same-source adjacency only, no holes joined, explicit stride and stop reasons","snapshot":"bounded fixed field selections; elementwise default; coalescing opt-in with independent gap recovery; owned validity and generation observations","provenance":"optional dynamic mapping descriptions; source identity and unsigned coordinates; no atomicity; patch flattening remains static","graph":"ordered streaming BFS/DFS; caller canonical identity; bounded nodes, edges, depth and frontier; explicit partial stop reasons"}, - "tests": ["MemoryDiscoveryTests", "MemoryReadSetAndGraphTests", "PreparedMatcherTests", "MemoryProjectionTests", "MemoryPreparedReaderTests", "MemoryAnalysisTests", "MemoryMetadataTests", "MemoryBtfCoverageTests", "MemoryBtfBoundaryTests", "MemoryIsfCoverageTests", "MemoryAdapterTests", "MemoryFailureTests", "MemoryExplicitLayoutTests", "MemoryValidationTests", "MemoryOperationMatrixTests", "MemorySourceContractTests", "MemoryPortableProjectionTests", "MemoryAcceptanceBoundaryTests", "MemoryFuzzTests", "MemoryPathAndCodecTests"] + "tests": ["MemoryDiscoveryTests", "MemoryReadSetAndGraphTests", "PreparedMatcherTests", "MemoryProjectionTests", "MemoryPreparedReaderTests", "MemoryAnalysisTests", "MemoryMetadataTests", "MemoryBtfCoverageTests", "MemoryBtfBoundaryTests", "MemoryIsfCoverageTests", "MemoryIsfOverlayTests", "MemoryIsfPointerStorageTests", "MemoryPdbMetadataTests", "MemoryAdapterTests", "MemoryFailureTests", "MemoryExplicitLayoutTests", "MemoryValidationTests", "MemoryOperationMatrixTests", "MemorySourceContractTests", "MemoryPortableProjectionTests", "MemoryAcceptanceBoundaryTests", "MemoryFuzzTests", "MemoryPathAndCodecTests"] } diff --git a/docs/config/cspell-terms.txt b/docs/config/cspell-terms.txt index becfcf85..658314e7 100644 --- a/docs/config/cspell-terms.txt +++ b/docs/config/cspell-terms.txt @@ -111,3 +111,5 @@ ifdef offsetof PWSTR LINQ +OMAP +discontiguous diff --git a/docs/guides/memory-analysis.md b/docs/guides/memory-analysis.md index c3476cc8..390d0b1f 100644 --- a/docs/guides/memory-analysis.md +++ b/docs/guides/memory-analysis.md @@ -154,14 +154,30 @@ subset and fails explicitly on anything else rather than guessing a layout. | --- | --- | --- | | Compiled Portable layout | Fixed scalars, named structs/unions, typedefs, arrays, pointers, bitfields, promoted storage | No inferred native ABI; no conditional or runtime-sized projection | | BTF v1 | Integers, floats with core codecs, pointers, arrays, structs, unions, enum/ENUM64, qualifiers/typedefs, member bit slices, split tables | Caller supplies pointer width and root ID; no ELF extraction or symbol discovery; functions/forward declarations are address-only | -| ISF 6.2.0 | Base integers/floats/bool, user structs/classes/unions, arrays, enums, pointers, bitfields | Caller supplies root, pointer width, and default order; no profile matching, relocations, symbol evaluation, or older schema guessing | +| ISF 6.1.0 / 6.2.0 | Base integers/floats/bool, user structs/classes/unions, arrays, enums, pointers, bitfields; overlapping native aliases become promoted union groups; explicit pointer storage preserves mixed widths and byte order | Caller supplies root, default pointer width and order; no profile matching or older schema guessing | +| Native MSF 7 / CodeView V70 and V80 headers | Explicit offline preparation of supported storage into ISF; native type identities, public/global image-relative symbols, OMAP and separate absolute values | No capture opening, acquisition or profile matching; unsupported encodings fail; original ages/machine and source ambiguities remain visible | BTF's magic number determines the metadata's byte order. Split BTF receives a previously loaded `BtfMetadata` as its base; IDs and string offsets keep their base identity. ISF respects explicit base-type endianness. Import follows reachable type references from the chosen root and records address-only types in `Diagnostics`. +CodeView's flat `near32` and `near64` pointer kinds define four- and eight-byte storage. +Some producers leave the separate size bits zero; the kind still determines the width. +A nonzero size must agree with that kind. Segmented and member-pointer encodings are +not ordinary flat addresses and are rejected. Explicit field widths do not inherit +the database's default pointer width, including inside arrays. + +An original DBI machine value of zero means that the producer did not record the +target architecture. Pass `targetMachine` to `PdbMetadata` only from explicit target +evidence, for example `0x014C` for an independently identified x86 image. `Machine` +and the exported `machine_type` retain the original zero; `TargetMachine` and the +native pointer base describe the supplied ABI. Without a target the parser rejects +the unknown case, and an explicit target cannot override a contradictory nonzero +DBI machine. Host architecture and object-path names are not fallback evidence. + The source specifications are the [Linux BTF documentation](https://docs.kernel.org/bpf/btf.html) and the -[Volatility ISF 6.2.0 schema](https://github.com/volatilityfoundation/volatility3/blob/develop/volatility3/schemas/schema-6.2.0.json). +[Volatility ISF 6.1.0](https://github.com/volatilityfoundation/volatility3/blob/77ff0b1932d77527f850c8ced01d85805ea7bf97/volatility3/schemas/schema-6.1.0.json) +and [6.2.0 schemas](https://github.com/volatilityfoundation/volatility3/blob/77ff0b1932d77527f850c8ced01d85805ea7bf97/volatility3/schemas/schema-6.2.0.json). The tests and examples in this repository use independently authored synthetic data, not operating-system captures or profiles. diff --git a/docs/guides/memory-schemas.md b/docs/guides/memory-schemas.md index 8113bdba..5459a42a 100644 --- a/docs/guides/memory-schemas.md +++ b/docs/guides/memory-schemas.md @@ -147,12 +147,44 @@ types as pointer targets without making those targets readable, and a best-effor with raw-bytes placeholders. `new IsfMetadata(json)` parses the document once; `Import(rootName, options)` then compiles one root and -everything it references, so several roots can share one parsed document. ISF import requires format `6.2.0`. It +everything it references, so several roots can share one parsed document. ISF import accepts formats `6.1.0` and `6.2.0`. It supports base integers, floats and booleans, structs, classes, unions, arrays, enums, pointers, and member bitfields. A base type's explicit endianness overrides the schema default that the constructor's `isLittleEndian` sets. The constructor's `maxBytes` bounds the document (16 MiB by default; a full kernel profile is often larger, so pass a bigger limit for one). Relocations, profile matching, and guesses about older formats are outside its scope. +### Native member aliases + +Native debug metadata can flatten several interpretations of the same bytes into a struct's immediate fields. +For example, a four-byte flags integer and its individual bitfields may all be listed at byte zero. In C you would +write such alternatives as an anonymous `union` inside the struct. ISF import does the same: members whose physical +bits overlap are moved into a generated union, and the struct holds that union through a **promoted** member, one +whose own members are visible directly in the parent. Members that do not overlap stay ordinary struct members. + +Take this ISF struct of eight bytes: + +```text +a offset 0, u32 +whole offset 4, u32 +low offset 4, u16 +``` + +`whole` and `low` share bytes 4 and 5, so they become one union of four bytes. The imported struct has two members: +`a` at offset 0 and a promoted `__overlay_4` at offset 4. The number is the group's byte offset from the start of the +struct; a suffix is added if the struct already uses that name. The paths `a`, `whole` and `low` all keep working. +For the input bytes `44 33 22 11 78 56 34 12`, reading `whole` gives `0x12345678`, and reading `low` gives `0x5678`. +`IsfMetadata.Describe` still reports the original kind and fields. + +A whole-value read returns a `StructValue` whose keys are the original member names, as for any promoted union. +To write a whole value, supply each group by its overlay name as a `UnionValue`: `UnionValue.FromMember("__overlay_4", +"whole", 0x12345678U)` selects one interpretation, and a `UnionValue` read from the path `__overlay_4` reproduces +the group's exact bytes. A dictionary that names only the aliased members is rejected rather than silently choosing +which overlapping value wins. Writing a group never clears unrelated members such as `a`. A selected-field update +changes only that field's bits. Disjoint bit slices sharing one integer are not aliases and stay plain members. + +These rules do not relax ordinary `MemorySchema` struct validation or BTF placement checks: those structs must +still have disjoint physical bits. Bounds, by-value cycles, descriptor budgets and cancellation remain enforced. + ### Symbols, type names, and forward declarations A real profile also lists **symbols**: named addresses of kernel variables and functions, such as `init_task`, the @@ -194,7 +226,7 @@ Both importers take the same `MetadataImportOptions`: | Option | Default | Meaning | | --- | --- | --- | -| `PointerSize` | 8 | The analyzed image's pointer width in bytes. Set 4 for a 32-bit capture, even on a 64-bit host. | +| `PointerSize` | 8 | Default target pointer width in bytes. Set 4 for a 32-bit target. An ISF pointer's explicit integer storage base overrides this default, and the schema byte order, for that pointer, so native and WOW64 widths can coexist. | | `BestEffort` | false | Demote a type that fails validation to a `RawBytes` placeholder instead of failing (see below). | | `MaxTypes` | 100,000 | The most type descriptors one import may create, bitfield storage and generated types included. | @@ -203,6 +235,71 @@ not run into a depth limit. Types nested by value (a struct inside an array insi levels deep, the same default limit that applies to a compiled layout; a deeper graph fails with `CStructLayoutException`. ISF documents are likewise limited to 256 levels of JSON nesting. +## Prepare native Windows PDB metadata + +A native **PDB** (Program Database) file stores compiler type records and symbol coordinates in an **MSF** +(Multi-Stream File) container. Its streams can occupy discontiguous blocks. `PdbMetadata` reads the directory and +selected metadata streams rather than loading the whole containing file. + +Preparation is explicit and offline. Obtain the matching PDB separately, then write an ISF profile: + +```csharp +using CStructSharp.Memory.Metadata; + +using var input = File.OpenRead("kernel.pdb"); +var pdb = new PdbMetadata(input); +using (var output = File.Create("kernel.json.preparing")) +{ + pdb.WriteIsf(output, "ntkrnlmp.pdb"); +} + +File.Move("kernel.json.preparing", "kernel.json", overwrite: false); +``` + +The caller owns both streams. Construction restores the original input position. `WriteIsf` leaves the output open; +publish it only after success. Use the resulting JSON with `IsfMetadata` and the normal memory-schema operations. +Neither operation opens a capture, queries a symbol server, or chooses a profile for an image. + +The source's `Guid`, `InformationAge` and `DbiAge` remain separate observations. The output profile records the DBI +age and original machine identifier in `metadata.windows.pdb`. Record both age fields, the original input hash, +any explicitly supplied target machine and the target's exact CodeView request in the application's preparation +manifest; do not assume the age fields are equal. `Symbols` contains image-relative addresses, including +recorded OMAP relocation. `AbsoluteSymbols` keeps absolute values separately so they are not accidentally relocated +as memory addresses. `SymbolRecordKinds` inventories original records, including references that do not directly +encode an image coordinate. `UnmappedSymbolCount` counts distinct names that are absolute or have no OMAP coordinate. + +Public and global symbols must agree on one address per name. File-local data, such as a C `static` variable, can +repeat a name in different source files. Such a name appears in `Symbols` only when it has one address and no public +or global symbol of that name disagrees; otherwise it is left out and explained in `Diagnostics`. A PDB without a +symbol stream, such as a stripped or types-only file, has empty symbol tables but still provides its types. + +Native type names need not be unique. Distinct complete definitions retain their original type-index-qualified +names. When a forward declaration has several complete definitions of the same extent, preparation creates an +explicit union whose `cv_XXXXXXXX` members expose each original definition. It does not pick a layout by name. +Different extents remain unresolved rather than acquiring an invented by-value size. Inspect `Diagnostics` and +retain these transformations in the preparation manifest. + +The ISF `base_types.pointer` entry records the unsigned integer width selected by `TargetMachine`. +Usually this comes from the original DBI machine. When that original value is zero, construction requires +an explicit `targetMachine` from independent target evidence; `Machine` and the exported machine value +still retain zero. A supplied target cannot override a contradictory nonzero DBI value. +Explicit `__cv_pointer32` and `__cv_pointer64` bases remain distinct, so individual fields do not widen +or narrow to the default address width. Flat `near32` and `near64` kinds define four and eight bytes +even when their separate size bits are zero; a nonzero size must agree with the kind. + +Supported input is MSF 7 with CodeView V70 or V80 type-stream headers and the supported storage leaves: +flat 32/64-bit pointers, integer/float storage descriptions, arrays, enums, instance members and bitfields. +A C++ class exports its instance data members only. Methods, static members, nested types and virtual-function table entries +have no storage in the object and are skipped. A base class does occupy bytes, but its members are not copied +into the derived type, so those bytes remain unnamed; import the base type separately to read them. +Segmented/member-pointer encodings and unsupported leaves fail explicitly. The constructor's `maxMetadataBytes` bounds +retained metadata bytes and `maxRecords` bounds each input table. `WriteIsf` has a separate `maxTraversalSteps` limit +(100,000,000 by default), shared across types, repeated field-list references, descriptors and symbols, because one +loaded record can be visited several times. Cancellation applies to metadata reads and CPU traversal. The format references are the +[MSF specification](https://llvm.org/docs/PDB/MsfFile.html), +[CodeView type records](https://llvm.org/docs/PDB/CodeViewTypes.html) and +[Microsoft's DBI section documentation](https://github.com/microsoft/pdb-rs/blob/main/docs/pdb/dbi_sections.md). + ## Import BTF and split tables **BTF** (BPF Type Format) is a compact binary type description emitted for the Linux kernel and its modules. A diff --git a/docs/guides/memory-sources.md b/docs/guides/memory-sources.md index 172a71af..825162ad 100644 --- a/docs/guides/memory-sources.md +++ b/docs/guides/memory-sources.md @@ -71,14 +71,13 @@ nothing this record uses. The example below builds this arrangement from a `Byte as part of the [memory examples](../examples/memory-analysis/index.md), so the numbers in this text are checked against the implementation. -Here is what `MappedMemorySource` does when the session asks it for four bytes at `...0ffe`: +Here is how the finite region and `MappedMemorySource` answer the session's four-byte request at `...0ffe`: -1. It looks up the mapping that contains `...0ffe` using a binary search over its sorted table. The first mapping - starts at `...0ffe` and is two bytes long, so it can supply at most two bytes. -2. It asks the backing source `image` for two bytes at image offset 0 and copies them into the first half of the - destination. -3. It looks up `...1000`, finds the second mapping, and asks `image` for two bytes at offset 4. -4. It returns the four bytes in logical order. It has not reinterpreted them; byte order is the schema's business. +1. The mapped source finds the first two-byte mapping with a binary search. +2. It asks `image` for two bytes at image offset 0 and returns that confirmed count to the region. +3. The region retains those two bytes and asks for the remainder at `...1000`. The mapped source finds the second + mapping, reads two bytes at image offset 4, and returns their count. +4. The region now has four consecutive logical bytes. The schema interprets their byte order. The result is `0x12345678U`. `inspection.Selection.Region.Address` is the logical address, while `inspection.BackingRegions` identifies image ranges `(0, 2)` and `(4, 2)`. Removing the second mapping causes @@ -94,6 +93,13 @@ full. A missing byte raises a structured memory failure; the copied prefix remai untouched. `TryReadExactly` returns the failure as data. Both forms propagate cancellation and exhausted budgets. An empty destination checks cancellation and makes no source requests. +The low-level `IMemorySource.Read` may return a positive short count. In particular, a mapped read stops within +its current mapping after one backing read. Use the region APIs when a consumer needs a complete transfer. +`ReadPartial` reports the confirmed count and the original unavailable coordinate if a later extent is missing; +bytes from completed reads do not disappear merely because the next mapping contains a hole. +A `CachedMemorySource` in front of a mapped source stores such a short answer with its count, so a repeated +transfer across the same mapping boundary is answered from the cache. + `BorrowedMemorySource` exposes a `ReadOnlyMemory` at an explicit unsigned base address without copying it. The caller keeps its backing memory alive and stable. A read-only view does not freeze a mutable array. The source's generation stays zero, so caches and patches rely on that stability promise. A readable-prefix argument excludes bytes diff --git a/src/CStructSharp/Memory/CachedMemorySource.cs b/src/CStructSharp/Memory/CachedMemorySource.cs index 8f8672e8..6bd97754 100644 --- a/src/CStructSharp/Memory/CachedMemorySource.cs +++ b/src/CStructSharp/Memory/CachedMemorySource.cs @@ -5,16 +5,18 @@ namespace CStructSharp.Memory; /// /// Analyzers read the same few ranges repeatedly: the link field of every list node, the header of every page. /// When the backing source is a file or a remote transport, answering those repeats from memory is much cheaper. -/// This cache stores the result of each complete read under the key (address, requested length) and -/// returns it for an identical later request. +/// This cache stores the bytes of each successful read under the key (address, requested length) and +/// returns the same bytes and count for an identical later request. /// /// /// The design is deliberately simple so its behavior can be predicted. There is no page prefetch and no merging /// of overlapping ranges, so the cache never reads neighboring bytes that might be unavailable; reading four bytes /// and then two bytes at the same address are two different entries. Capacity is a retained byte count with /// first-in, first-out eviction; a hit does not refresh an entry's position. Requests larger than the capacity are -/// answered but not stored, and short reads are not stored because they do not describe the whole range. A hit -/// still charges one request (so loops remain bounded) but charges no backing bytes. +/// answered but not stored. A positive short read, such as a mapped read that stops at a mapping boundary, is stored +/// with its confirmed count; the caller continues from the next byte as it would without the cache. A read that +/// fails or returns zero bytes is not stored. A hit still charges one request (so loops remain bounded) but charges +/// no backing bytes. /// /// /// Correctness depends entirely on : the cache empties itself when the @@ -55,7 +57,7 @@ public CachedMemorySource(string id, IMemorySource source, int capacity = 1024 * /// Gets the backing source's generation; a change is acted on at the next read. public long Generation => this.source.Generation; - /// Answers from the cache when the exact range is present; otherwise reads the backing source and stores a complete result. + /// Answers from the cache when the exact request is present; otherwise reads the backing source and stores its positive result. /// Unsigned address in the backing source's coordinate system. /// Caller-owned destination used only during this call. /// Shared operation budget and cancellation; a hit charges one request and zero bytes. @@ -94,17 +96,19 @@ public int Read(ulong address, Span destination, MemoryAccessContext conte throw new MemoryAccessException(MemoryFailure.StaleSource, this.Id, address, destination.Length, "Backing source changed during a cached read."); } - // Store only complete reads that fit; evict oldest entries until this one fits. - if (read == destination.Length && read > 0 && read <= this.capacity) + // Store every positive read that fits, including a short one: its count is the backing source's own answer + // for this exact request in this generation (a mapped source stops at a mapping boundary, for example), + // so a repeat is answered with the same confirmed prefix. Evict oldest entries until this one fits. + if (read > 0 && read <= this.capacity) { while (read > this.capacity - this.retained) { (ulong Address, int Length) oldest = this.order.Dequeue(); + this.retained -= this.entries[oldest].Length; this.entries.Remove(oldest); - this.retained -= oldest.Length; } - this.entries.Add(key, destination.ToArray()); + this.entries.Add(key, destination[..read].ToArray()); this.order.Enqueue(key); this.retained += read; } diff --git a/src/CStructSharp/Memory/MappedMemorySource.cs b/src/CStructSharp/Memory/MappedMemorySource.cs index 83ae3b91..b90bb586 100644 --- a/src/CStructSharp/Memory/MappedMemorySource.cs +++ b/src/CStructSharp/Memory/MappedMemorySource.cs @@ -3,12 +3,11 @@ namespace CStructSharp.Memory; /// An address space assembled from a table of mappings, each translating a logical range to a range of another source. /// /// -/// This is the type that turns a scattered capture into something that looks like a process. A process sees -/// consecutive pages; the capture stores them at arbitrary offsets, in one file or several. Each -/// records one placement, and this source answers a read by finding the mapping that -/// contains the address, asking the backing source for as many bytes as that mapping can supply, and continuing -/// with the next mapping until the request is complete. A read that crosses a boundary is therefore split and -/// reassembled in logical order without the caller noticing. +/// A process sees consecutive pages; the capture stores them at arbitrary offsets, in one file or several. Each +/// records one placement. A read returns the positive count supplied by one backing +/// read within the current mapping. and +/// continue across mappings. Returning each confirmed prefix before reading another extent lets those callers +/// retain its validity if the next extent is absent. /// /// /// The table is sorted once at construction so each lookup is a binary search. Logical ranges must not overlap, @@ -126,7 +125,18 @@ public int Read(ulong address, Span destination, MemoryAccessContext conte context.EnterSource(); try { - return this.ReadMapped(address, destination, context); + if (destination.IsEmpty) + { + return 0; + } + + MemoryMapping mapping = this.Find(address, context); + long offset = checked((long)(address - mapping.Address)); + int count = (int)Math.Min(destination.Length, mapping.Backing.Length - offset); + int read = mapping.Backing.Source.Read(checked(mapping.Backing.Address + (ulong)offset), destination[..count], context); + MemorySourceChecks.ThrowIfInvalidReadCount(read, count, this.Id, address); + MemorySourceChecks.ThrowIfUnavailable(read, count, this.Id, address, "Mapped backing bytes are unavailable."); + return read; } finally { @@ -134,33 +144,6 @@ public int Read(ulong address, Span destination, MemoryAccessContext conte } } - /// Fills the destination from successive mappings, advancing by the bytes each backing read actually returned. - /// Two different events can end a backing read early, and they must be told apart. Reaching the end of - /// a mapping is normal: the loop looks up the next mapping and continues. A backing source returning fewer bytes - /// than asked is a short read: the loop asks again from the next byte. A backing source returning zero before - /// the mapping is exhausted means the capture is missing data, which is an error. A failure part-way through may - /// leave a prefix of the destination filled. - private int ReadMapped(ulong address, Span destination, MemoryAccessContext context) - { - int done = 0; - while (done < destination.Length) - { - ulong current = checked(address + (ulong)done); - MemoryMapping mapping = this.Find(current, context); - long offset = checked((long)(current - mapping.Address)); - - // Ask for no more than this mapping can supply; the next iteration handles the remainder. - int count = (int)Math.Min(destination.Length - done, mapping.Backing.Length - offset); - int read = mapping.Backing.Source.Read(checked(mapping.Backing.Address + (ulong)offset), destination.Slice(done, count), context); - MemorySourceChecks.ThrowIfInvalidReadCount(read, count, this.Id, current); - MemorySourceChecks.ThrowIfUnavailable(read, count, this.Id, current, "Mapped backing bytes are unavailable."); - - done += read; - } - - return done; - } - /// Binary-searches the sorted table for the mapping containing , charging one lookup request. /// The lookup is charged even when it fails, so an address-guessing loop over unmapped space still /// consumes budget. A miss throws naming the address. diff --git a/src/CStructSharp/Memory/MemorySchema.cs b/src/CStructSharp/Memory/MemorySchema.cs index 44d53f64..d320847e 100644 --- a/src/CStructSharp/Memory/MemorySchema.cs +++ b/src/CStructSharp/Memory/MemorySchema.cs @@ -127,7 +127,10 @@ internal MemorySchema(IEnumerable types, bool isLittleEndi cancellationToken.ThrowIfCancellationRequested(); try { - this.Validate(type, sharedScalars, layoutCache); + if (this.Validate(type, sharedScalars, layoutCache) is { } aliases) + { + this.GroupOverlappingViews(type, aliases, definitions, sharedScalars, layoutCache); + } } catch (CStructLayoutException error) when (bestEffort) { @@ -336,7 +339,11 @@ private CStruct CompileScalarLayout(string source, bool littleEndian, CStructCom /// Constructor-local built-in codecs, or null when options may invoke caller code. /// The definition is invalid. /// Optional metadata-owned cache of successful core compilations with exact settings. - private void Validate(MemoryTypeDefinition type, Dictionary<(string Root, bool LittleEndian), MemoryScalarCodec>? sharedScalars, CStructLayoutCache? layoutCache) + /// + /// Null for a valid definition; for a struct that may preserve recorded native aliases and has overlapping members, + /// the sorted physical bit intervals of its members, tagged with each member's index, for . + /// + private List<(long Start, long End, int Field)>? Validate(MemoryTypeDefinition type, Dictionary<(string Root, bool LittleEndian), MemoryScalarCodec>? sharedScalars, CStructLayoutCache? layoutCache) { if (!Enum.IsDefined(type.Kind)) { @@ -409,9 +416,10 @@ private void Validate(MemoryTypeDefinition type, Dictionary<(string Root, bool L } var names = new HashSet(StringComparer.Ordinal); - var intervals = new List<(long Start, long End)>(); - foreach (MemoryField field in type.Fields) + var intervals = new List<(long Start, long End, int Field)>(); + for (int index = 0; index < type.Fields.Count; index++) { + MemoryField field = type.Fields[index]; if (type.Kind is not (MemoryTypeKind.Struct or MemoryTypeKind.Union) || !names.Add(field.Name) || field.Name.Length == 0) { throw new CStructLayoutException($"Invalid or duplicate member in '{type.Id}'."); @@ -476,13 +484,13 @@ private void Validate(MemoryTypeDefinition type, Dictionary<(string Root, bool L int byteIndex = littleEndian ? bit / 8 : member.Size - 1 - (bit / 8); int bitsInByte = Math.Min(8 - (bit % 8), field.BitOffset.Value + width - bit); long physicalBit = (((long)field.Offset + byteIndex) * 8) + (bit % 8); - intervals.Add((physicalBit, physicalBit + bitsInByte)); + intervals.Add((physicalBit, physicalBit + bitsInByte, index)); bit += bitsInByte; } } else { - intervals.Add((start, checked(start + length))); + intervals.Add((start, checked(start + length), index)); } if (field.Promoted && member.Kind is not (MemoryTypeKind.Struct or MemoryTypeKind.Union or MemoryTypeKind.RawBytes)) @@ -496,16 +504,154 @@ private void Validate(MemoryTypeDefinition type, Dictionary<(string Root, bool L if (type.Kind == MemoryTypeKind.Struct) { long end = 0; - foreach ((long start, long nextEnd) in intervals) + foreach ((long start, long nextEnd, _) in intervals) { if (start < end && nextEnd > start) { + if (type.PreserveOverlappingViews) + { + return intervals; + } + throw new CStructLayoutException($"Overlapping members in struct '{type.Id}'. Use a union for overlays."); } end = Math.Max(end, nextEnd); } } + + return null; + } + + /// Replaces each group of aliased native members with one promoted union, leaving every other member in the struct. + /// + /// + /// Native debug metadata can list several interpretations of the same bytes (a flags word and its bitfields, for + /// example) as ordinary struct members. Members are first grouped by transitive byte overlap, so each group covers + /// a byte range that no other member touches. A group whose physical bits really overlap becomes a generated union + /// {struct id}::overlay@{offset}, placed by a promoted member named __overlay_{offset} (made unique + /// if the struct already uses that name). Offsets are bytes from the start of the struct. + /// + /// + /// Promotion keeps every original member path valid. Only the aliased bytes acquire union semantics: writing + /// one interpretation clears the rest of that group, never unrelated members. A group whose members share bytes + /// but not bits (disjoint bitfields in one storage unit) stays as plain struct members. + /// + /// + /// The validated struct whose members overlap. + /// Its sorted physical bit intervals, tagged with member indices. + /// The schema's definitions, updated in place with the unions and the regrouped struct. + /// Constructor-local built-in codecs, or null. + /// Optional metadata-owned layout cache. + /// A generated definition fails validation. + private void GroupOverlappingViews(MemoryTypeDefinition type, List<(long Start, long End, int Field)> bits, Dictionary definitions, Dictionary<(string Root, bool LittleEndian), MemoryScalarCodec>? sharedScalars, CStructLayoutCache? layoutCache) + { + IReadOnlyList fields = type.Fields; + + // Group members by transitive byte overlap: sorted by start, a member joins the open group while it starts + // before that group's running end. + int[] group = new int[fields.Count]; + var starts = new List(); + var ends = new List(); + foreach (int index in Enumerable.Range(0, fields.Count).OrderBy(index => fields[index].Offset)) + { + int start = fields[index].Offset; + int end = start + this.Types[fields[index].TypeId].Size; + if (starts.Count == 0 || start >= ends[^1]) + { + starts.Add(start); + ends.Add(end); + } + else + { + ends[^1] = Math.Max(ends[^1], end); + } + + group[index] = starts.Count - 1; + } + + // The bit intervals are sorted by start, so a per-group running end finds the groups with real aliasing. + bool[] aliased = new bool[starts.Count]; + long[] reached = new long[starts.Count]; + foreach ((long start, long end, int field) in bits) + { + int owner = group[field]; + if (start < reached[owner] && end > start) + { + aliased[owner] = true; + } + + reached[owner] = Math.Max(reached[owner], end); + } + + var names = new HashSet(fields.Select(field => field.Name), StringComparer.Ordinal); + var overlays = new MemoryField?[starts.Count]; + for (int owner = 0; owner < starts.Count; owner++) + { + if (!aliased[owner]) + { + continue; + } + + string id = $"{type.Id}::overlay@{starts[owner]}"; + while (definitions.ContainsKey(id)) + { + id += "_"; + } + + string name = $"__overlay_{starts[owner]}"; + while (!names.Add(name)) + { + name += "_"; + } + + // Union members keep their order, bit slices and promotion; offsets become relative to the group start. + int origin = starts[owner]; + MemoryField[] members = Enumerable.Range(0, fields.Count).Where(index => group[index] == owner) + .Select(index => fields[index]) + .Select(field => new MemoryField(field.Name, field.TypeId, field.Offset - origin, field.BitOffset, field.BitWidth, field.Signed, field.Promoted)) + .ToArray(); + var union = new MemoryTypeDefinition(id, name, MemoryTypeKind.Union, ends[owner] - origin, members, provenance: type.Provenance); + definitions.Add(id, union); + this.Validate(union, sharedScalars, layoutCache); + overlays[owner] = new MemoryField(name, id, origin, promoted: true); + } + + // The struct keeps its unaliased members in place; each union takes the position of its first member. + var regrouped = new List(fields.Count); + bool[] placed = new bool[starts.Count]; + for (int index = 0; index < fields.Count; index++) + { + int owner = group[index]; + if (overlays[owner] is not { } overlay) + { + regrouped.Add(fields[index]); + } + else if (!placed[owner]) + { + placed[owner] = true; + regrouped.Add(overlay); + } + } + + // The first validation registered bit-slice codecs under the original struct; the moved slices now belong to + // the unions, and the remaining ones are registered again below. + foreach ((string Type, string Field) key in this.bitLayouts.Keys.Where(key => key.Type == type.Id).ToList()) + { + this.bitLayouts.Remove(key); + } + + var grouped = new MemoryTypeDefinition(type.Id, type.Name, MemoryTypeKind.Struct, type.Size, regrouped, provenance: type.Provenance) + { + IsProjected = type.IsProjected, + IsUnselected = type.IsUnselected, + UnselectedMembers = type.UnselectedMembers, + }; + definitions[type.Id] = grouped; + if (this.Validate(grouped, sharedScalars, layoutCache) is not null) + { + throw new CStructLayoutException($"Overlapping members in struct '{type.Id}' could not be grouped into union views."); + } } /// Rejects types that contain themselves by value; pointers stop the search so recursive native types stay legal. diff --git a/src/CStructSharp/Memory/MemoryTypeDefinition.cs b/src/CStructSharp/Memory/MemoryTypeDefinition.cs index 46d93483..695cc6b4 100644 --- a/src/CStructSharp/Memory/MemoryTypeDefinition.cs +++ b/src/CStructSharp/Memory/MemoryTypeDefinition.cs @@ -97,4 +97,7 @@ public MemoryTypeDefinition(string id, string name, MemoryTypeKind kind, int siz /// Gets immediate member names deliberately omitted from this composite, in metadata order; their descriptors have not been validated. public IReadOnlyList UnselectedMembers { get; internal init; } = Array.Empty(); + + /// Gets whether recorded native member aliases are grouped into promoted union views instead of failing struct validation. + internal bool PreserveOverlappingViews { get; init; } } diff --git a/src/CStructSharp/Memory/Metadata/IsfMetadata.cs b/src/CStructSharp/Memory/Metadata/IsfMetadata.cs index 77ee4545..544f60d3 100644 --- a/src/CStructSharp/Memory/Metadata/IsfMetadata.cs +++ b/src/CStructSharp/Memory/Metadata/IsfMetadata.cs @@ -6,7 +6,7 @@ namespace CStructSharp.Memory.Metadata; using CStructSharp.Compilation; using CStructSharp.Diagnostics; -/// A parsed Volatility ISF 6.2.0 document, from which the value types reachable from one user type can be imported into a . +/// A parsed Volatility ISF 6.1.0 or 6.2.0 document, from which the value types reachable from one user type can be imported into a . /// /// /// ISF (Intermediate Symbol Format) is the JSON metadata the Volatility 3 memory-forensics framework uses to @@ -41,12 +41,20 @@ namespace CStructSharp.Memory.Metadata; /// recorded placement. /// /// +/// Native profiles can flatten several aliases of the same storage into a struct's immediate field list. When their +/// physical bits overlap, an import groups only those aliased members into a generated +/// that the struct holds through a promoted member named __overlay_{offset}. Every original member path still +/// resolves, and unrelated members keep struct semantics. A whole-value write supplies each group by its overlay name +/// as a rather than silently choosing among conflicting fields. +/// still reports the source's original fields. Disjoint fields, including disjoint bit slices, remain plain members. +/// +/// /// , and read the user_types and /// symbols tables directly. A symbol's address is reported as recorded: relocations such as kernel address space /// layout randomization (KASLR) are not applied, and no file is opened. /// /// -/// A document that is not valid JSON, is not ISF 6.2.0, or lacks or mistypes a property the import needs throws +/// A document that is not valid JSON, is neither ISF 6.1.0 nor 6.2.0, or lacks or mistypes a property the import needs throws /// , as an invalid layout declaration does. Parameter errors keep their .NET /// exception types. /// @@ -54,6 +62,7 @@ namespace CStructSharp.Memory.Metadata; public sealed partial class IsfMetadata { private readonly JsonElement root; + private readonly string format; private readonly Lazy> userTypes; private readonly Lazy> baseTypes; private readonly Lazy> enums; @@ -63,13 +72,13 @@ public sealed partial class IsfMetadata /// Successful scalar layouts shared across this document's imports, bounded independently of root graphs. private CStructLayoutCache? layoutCache; - /// Parses a UTF-8 ISF 6.2.0 document. + /// Parses a UTF-8 ISF 6.1.0 or 6.2.0 document. /// The UTF-8 document. /// Byte order of the imported schemas; base types with an explicit order override it. /// Maximum accepted document length in bytes. JSON nesting is limited to 256 levels, the default layout nesting limit. /// Checked before parsing. /// is not positive. - /// The document exceeds its budget, is not valid JSON, or is not ISF 6.2.0. + /// The document exceeds its budget, is not valid JSON, or declares an unsupported ISF revision. /// was cancelled. public IsfMetadata(ReadOnlyMemory json, bool isLittleEndian = true, int maxBytes = 16 * 1024 * 1024, CancellationToken cancellationToken = default) { @@ -94,11 +103,12 @@ public IsfMetadata(ReadOnlyMemory json, bool isLittleEndian = true, int ma if (this.root.ValueKind != JsonValueKind.Object || !this.root.TryGetProperty("metadata", out JsonElement metadata) || metadata.ValueKind != JsonValueKind.Object || !metadata.TryGetProperty("format", out JsonElement format) || - format.ValueKind != JsonValueKind.String || !format.ValueEquals("6.2.0")) + format.ValueKind != JsonValueKind.String || !(format.ValueEquals("6.1.0") || format.ValueEquals("6.2.0"))) { - throw new CStructLayoutException("Only ISF format 6.2.0 is supported."); + throw new CStructLayoutException("Only ISF formats 6.1.0 and 6.2.0 are supported."); } + this.format = format.ValueEquals("6.1.0") ? "6.1.0" : "6.2.0"; this.IsLittleEndian = isLittleEndian; // The tables are indexed on first use, so a caller that only reads symbols never indexes types and vice versa. @@ -626,6 +636,7 @@ private void ResumeComposite(CompositeImport composite, Stack work) { this.Types[composite.Id] = new(composite.Id, composite.Name, composite.Kind, composite.Size, composite.Fields, provenance: composite.Id) { + PreserveOverlappingViews = true, IsProjected = this.projection is not null, UnselectedMembers = this.projection?.Unselected(composite.Id) ?? Array.Empty(), }; @@ -688,14 +699,25 @@ private void FinishReference(string id, JsonElement descriptor, string element) bool isArray = descriptor.GetProperty("kind").GetString() == "array"; int count = isArray ? descriptor.GetProperty("count").GetInt32() : 0; int size = isArray ? checked(count * this.Types[element].Size) : this.pointerSize; + bool? littleEndian = null; - // A pointer may name its own storage base type; it must agree with the supplied pointer width. - if (descriptor.TryGetProperty("base", out JsonElement pointerBase) && this.Types[this.ImportBase(pointerBase.GetString()!)].Size != this.pointerSize) + // WOW64 and explicit __ptr32 fields can coexist with native pointers in one type graph. The explicit base + // supplies both the stored width and the byte order; a pointer without one inherits the schema default. + if (!isArray && descriptor.TryGetProperty("base", out JsonElement pointerBase)) { - throw new CStructLayoutException("ISF pointer base differs from the supplied pointer width."); + MemoryTypeDefinition storage = this.Types[this.ImportBase(pointerBase.GetString()!)]; + if (storage.Kind != MemoryTypeKind.Scalar || storage.Size is not (1 or 2 or 4 or 8) + || storage.ScalarType is not { } codec + || !(codec.StartsWith("uint", StringComparison.Ordinal) || codec.StartsWith("int", StringComparison.Ordinal))) + { + throw new CStructLayoutException("ISF pointer storage must be an integer of 1, 2, 4 or 8 bytes."); + } + + size = storage.Size; + littleEndian = storage.IsLittleEndian; } - this.Add(id, new(id, string.Empty, isArray ? MemoryTypeKind.Array : MemoryTypeKind.Pointer, size, elementTypeId: element, count: count, provenance: "ISF 6.2.0 " + (isArray ? "array" : "pointer"))); + this.Add(id, new(id, string.Empty, isArray ? MemoryTypeKind.Array : MemoryTypeKind.Pointer, size, elementTypeId: element, count: count, provenance: "ISF " + this.document.format + (isArray ? " array" : " pointer"), isLittleEndian: littleEndian)); } /// Imports an enum as a scalar whose codec is a generated Portable enum declaration over an integer of the enum's size. @@ -828,7 +850,7 @@ private string UnsignedStorage(int size, bool littleEndian) string id = "isf:bitfield-storage:" + scalar + (littleEndian ? ":little" : ":big"); if (!this.Types.ContainsKey(id)) { - this.Add(id, new(id, scalar, MemoryTypeKind.Scalar, size, scalarType: scalar, provenance: "ISF 6.2.0 bitfield storage", isLittleEndian: littleEndian)); + this.Add(id, new(id, scalar, MemoryTypeKind.Scalar, size, scalarType: scalar, provenance: "ISF " + this.document.format + " bitfield storage", isLittleEndian: littleEndian)); } return id; diff --git a/src/CStructSharp/Memory/Metadata/MetadataImportOptions.cs b/src/CStructSharp/Memory/Metadata/MetadataImportOptions.cs index acd8050d..7bca3157 100644 --- a/src/CStructSharp/Memory/Metadata/MetadataImportOptions.cs +++ b/src/CStructSharp/Memory/Metadata/MetadataImportOptions.cs @@ -16,8 +16,8 @@ public MetadataImportOptions() public static MetadataImportOptions Default { get; } = new(); /// - /// Gets the target pointer width in bytes. It describes the analyzed image, not the metadata's own word size or - /// the .NET process running the import, so a 32-bit capture analyzed on a 64-bit host must say 4. + /// Gets the default target pointer width in bytes, not the analyzing process's width. A 32-bit target must say 4. + /// ISF pointers with an explicit integer storage base retain that base's own width, including mixed native/WOW64 records. /// public int PointerSize { get; init; } = 8; diff --git a/src/CStructSharp/Memory/Metadata/PdbExportBudget.cs b/src/CStructSharp/Memory/Metadata/PdbExportBudget.cs new file mode 100644 index 00000000..9db6cdac --- /dev/null +++ b/src/CStructSharp/Memory/Metadata/PdbExportBudget.cs @@ -0,0 +1,33 @@ +namespace CStructSharp.Memory.Metadata; + +using CStructSharp.Diagnostics; + +/// Bounds aggregate preparation work, including repeated references to shared native field lists. +internal sealed class PdbExportBudget +{ + private readonly CancellationToken cancellationToken; + private long remaining; + + /// Creates operation-local state so concurrent exports never share counters or cancellation. + /// Maximum type, member, descriptor and symbol traversal steps. + /// Cancellation for CPU work as well as output traversal. + internal PdbExportBudget(long maximum, CancellationToken cancellationToken) + { + this.remaining = maximum; + this.cancellationToken = cancellationToken; + } + + /// Charges before traversing another node, including aliases that do not allocate a new identity. + /// The shared operation budget is exhausted. + /// Cancellation was requested. + internal void Take() + { + this.cancellationToken.ThrowIfCancellationRequested(); + if (this.remaining == 0) + { + throw new CStructLayoutException("Native PDB preparation exceeds its shared traversal budget."); + } + + this.remaining--; + } +} diff --git a/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs b/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs new file mode 100644 index 00000000..45c16a3c --- /dev/null +++ b/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs @@ -0,0 +1,639 @@ +namespace CStructSharp.Memory.Metadata; + +using System.Globalization; +using System.Text.Json; + +/// Normalizes original CodeView storage descriptions into the existing ISF interchange contract. +public sealed partial class PdbMetadata +{ + private static readonly Dictionary SimpleTypes = new() + { + [0x00] = new("__cv_no_type", "void", 0, false), + [0x03] = new("void", "void", 0, false), + [0x08] = new("HRESULT", "int", 4, true), + [0x10] = new("signed char", "char", 1, true), + [0x20] = new("unsigned char", "char", 1, false), + [0x70] = new("char", "char", 1, true), + [0x71] = new("wchar_t", "char", 2, false), + [0x7A] = new("char16_t", "char", 2, false), + [0x7B] = new("char32_t", "char", 4, false), + [0x7C] = new("char8_t", "char", 1, false), + [0x68] = new("__int8", "int", 1, true), + [0x69] = new("unsigned __int8", "int", 1, false), + [0x11] = new("short", "int", 2, true), + [0x21] = new("unsigned short", "int", 2, false), + [0x72] = new("__int16", "int", 2, true), + [0x73] = new("unsigned __int16", "int", 2, false), + [0x12] = new("long", "int", 4, true), + [0x22] = new("unsigned long", "int", 4, false), + [0x74] = new("int", "int", 4, true), + [0x75] = new("unsigned int", "int", 4, false), + [0x13] = new("long long", "int", 8, true), + [0x23] = new("unsigned long long", "int", 8, false), + [0x76] = new("__int64", "int", 8, true), + [0x77] = new("unsigned __int64", "int", 8, false), + [0x14] = new("__int128", "int", 16, true), + [0x24] = new("unsigned __int128", "int", 16, false), + [0x78] = new("__int128_t", "int", 16, true), + [0x79] = new("__uint128_t", "int", 16, false), + [0x30] = new("bool", "bool", 1, false), + [0x31] = new("__bool16", "bool", 2, false), + [0x32] = new("__bool32", "bool", 4, false), + [0x33] = new("__bool64", "bool", 8, false), + [0x40] = new("float", "float", 4, true), + [0x41] = new("double", "float", 8, true), + [0x42] = new("__float80", "float", 10, true), + [0x43] = new("__float128", "float", 16, true), + [0x46] = new("__float16", "float", 2, true), + }; + + /// Writes a deterministic Windows ISF 6.2.0 profile without opening another input or acquiring symbols. + /// + /// The Windows identity records the original DBI age. The separate remains available + /// for the caller's preparation manifest; it is not silently replaced or asserted equal. Incomplete declarations + /// remain references without invented layouts. Unsupported storage encodings fail rather than becoming raw-byte types. + /// The caller owns the output and should publish it atomically only after this operation succeeds. + /// + /// Writable destination; it stays open. + /// Original PDB basename from the target's CodeView request, not a local path. + /// + /// Maximum traversal steps for this export, counted across types, field-list records, members, storage + /// descriptors and symbols. It is independent of the constructor's input limits because one loaded record can + /// be visited several times (for example a field list shared by several types). + /// + /// Checked between types, members and symbols. + /// The destination or PDB name is null. + /// The destination is not writable or the name is not a basename. + /// is not positive. + /// A required storage description is malformed, unsupported or exceeds the traversal limit. + /// Cancellation was requested. + public void WriteIsf(Stream output, string pdbName, long maxTraversalSteps = 100_000_000, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentException.ThrowIfNullOrWhiteSpace(pdbName); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTraversalSteps); + if (!output.CanWrite || pdbName.IndexOfAny(['/', '\\', ':', '\0']) >= 0) + { + throw new ArgumentException("ISF preparation needs a writable output and the original PDB basename."); + } + + var budget = new PdbExportBudget(maxTraversalSteps, cancellationToken); + budget.Take(); + using var writer = new Utf8JsonWriter(output); + writer.WriteStartObject(); + writer.WriteStartObject("metadata"); + writer.WriteString("format", "6.2.0"); + writer.WriteStartObject("windows"); + writer.WriteStartObject("pdb"); + writer.WriteString("GUID", this.Guid.ToString("N").ToUpperInvariant()); + writer.WriteNumber("age", this.DbiAge); + writer.WriteNumber("machine_type", this.Machine); + writer.WriteString("database", pdbName); + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.WriteStartObject("base_types"); + foreach (SimpleType simple in SimpleTypes.Values.OrderBy(type => type.Name, StringComparer.Ordinal)) + { + WriteBase(writer, simple); + } + + WriteBase(writer, new("pointer", "int", this.PointerSize, false)); + WriteBase(writer, new("__cv_pointer32", "int", 4, false)); + WriteBase(writer, new("__cv_pointer64", "int", 8, false)); + writer.WriteEndObject(); + writer.WriteStartObject("user_types"); + foreach (NamedType type in this.definitions.Where(type => type.Kind != 0x1507).OrderBy(type => this.names[type.Index], StringComparer.Ordinal)) + { + budget.Take(); + writer.WriteStartObject(this.names[type.Index]); + writer.WriteString("kind", type.Kind == 0x1506 ? "union" : "struct"); + writer.WriteNumber("size", type.Size); + writer.WriteStartObject("fields"); + List fields = this.ReadFields(type, budget); + var used = new HashSet(StringComparer.Ordinal); + for (int index = 0; index < fields.Count; index++) + { + budget.Take(); + Field field = fields[index]; + string name = field.Name.Length == 0 ? $"__anonymous_cv_{index:X}" : field.Name; + if (!used.Add(name)) + { + throw Invalid($"type '{type.Name}' has repeated instance-member names"); + } + + writer.WriteStartObject(name); + writer.WriteNumber("offset", field.Offset); + if (field.Name.Length == 0) + { + writer.WriteBoolean("anonymous", true); + } + + writer.WritePropertyName("type"); + this.WriteDescriptor(writer, field.Type, 0, budget); + writer.WriteEndObject(); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + foreach ((uint index, List alternatives) in this.ambiguousViews.OrderBy(entry => this.names[entry.Key], StringComparer.Ordinal)) + { + budget.Take(); + writer.WriteStartObject(this.names[index]); + writer.WriteString("kind", "union"); + writer.WriteNumber("size", alternatives[0].Size); + writer.WriteStartObject("fields"); + foreach (NamedType alternative in alternatives) + { + budget.Take(); + writer.WriteStartObject($"cv_{alternative.Index:X8}"); + writer.WriteNumber("offset", 0); + writer.WriteStartObject("type"); + writer.WriteString("kind", alternative.Kind == 0x1506 ? "union" : "struct"); + writer.WriteString("name", this.names[alternative.Index]); + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + writer.WriteEndObject(); + writer.WriteStartObject("enums"); + foreach (NamedType type in this.definitions.Where(type => type.Kind == 0x1507).OrderBy(type => this.names[type.Index], StringComparer.Ordinal)) + { + budget.Take(); + SimpleType storage = this.EnumBase(type.Underlying, 0, budget); + writer.WriteStartObject(this.names[type.Index]); + writer.WriteString("base", storage.Name); + writer.WriteNumber("size", storage.Size); + writer.WriteStartObject("constants"); + var used = new HashSet(StringComparer.Ordinal); + foreach (Field field in this.ReadFields(type, budget)) + { + if (field.Value is not { } value || !used.Add(field.Name)) + { + throw Invalid($"enum '{type.Name}' has malformed or repeated constants"); + } + + writer.WritePropertyName(field.Name); + writer.WriteRawValue(value.ToString(CultureInfo.InvariantCulture)); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + writer.WriteEndObject(); + writer.WriteStartObject("symbols"); + foreach ((string name, ulong address) in this.symbols.OrderBy(entry => entry.Key, StringComparer.Ordinal)) + { + budget.Take(); + writer.WriteStartObject(name); + writer.WriteNumber("address", address); + if (this.symbolTypes.TryGetValue(name, out uint type)) + { + writer.WritePropertyName("type"); + this.WriteDescriptor(writer, type, 0, budget); + } + + writer.WriteEndObject(); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + writer.Flush(); + } + + /// Writes a recorded primitive's width and signedness, independent of the host C ABI. + /// The preparation output. + /// Explicit target primitive description. + private static void WriteBase(Utf8JsonWriter writer, SimpleType type) + { + writer.WriteStartObject(type.Name); + writer.WriteString("kind", type.Kind); + writer.WriteNumber("size", type.Size); + writer.WriteString("endian", "little"); + writer.WriteBoolean("signed", type.Signed); + writer.WriteEndObject(); + } + + /// Reads one complete native pointer representation, rejecting member-pointer encodings. + /// Original LF_POINTER payload. + /// Original target identity and width defined by the flat pointer kind. + /// The representation is not a supported flat 32/64-bit pointer. + private static (uint Target, int Width) Pointer(ReadOnlySpan bytes) + { + var reader = new PdbRecordReader(bytes); + uint target = reader.UInt32(); + uint attributes = reader.UInt32(); + reader.End(); + uint kind = attributes & 31; + uint mode = (attributes >> 5) & 7; + int width = (int)((attributes >> 13) & 63); + int kindWidth = kind switch { 10 => 4, 12 => 8, _ => 0 }; + + // Older CodeView records omit size bits, but their near32/near64 kind still fixes storage width. + if (mode is not (0 or 1 or 4) || kindWidth == 0 || (width != 0 && width != kindWidth)) + { + throw Invalid("a native pointer is not a supported flat 32/64-bit representation"); + } + + return (target, kindWidth); + } + + /// Reads an array's declared byte extent without traversing its element graph. + /// Original LF_ARRAY payload. + /// Original byte size. + private static int ArraySize(ReadOnlySpan bytes) + { + var reader = new PdbRecordReader(bytes); + _ = reader.UInt32(); + _ = reader.UInt32(); + return reader.Size(); + } + + /// Maps CodeView's explicit simple-pointer mode to stored width. + /// Original mode bits. + /// Four or eight bytes. + /// The pointer is segmented or uses an unsupported width. + private static int SimplePointerWidth(uint mode) => mode switch + { + 0x400 => 4, + 0x600 => 8, + _ => throw Invalid("a simple pointer uses an unsupported segmented or nonnative width"), + }; + + /// Looks up an explicitly sized CodeView primitive. + /// Original direct primitive index. + /// The target primitive description. + /// The primitive is not supported. + private static SimpleType Primitive(uint index) => SimpleTypes.TryGetValue(index, out SimpleType type) ? type : throw Invalid($"primitive 0x{index:X4} is not supported"); + + /// Consumes one C++ field-list element that has no instance storage of its own. + /// + /// Methods, static members, nested types, vtable pointers and base classes are skipped. A base-class subobject + /// does occupy bytes, but its members are not exported into the derived type; those bytes remain unnamed. + /// Layouts follow the CodeView field-leaf definitions referenced by the memory-schema guide. + /// + /// Reader positioned after the leaf code and its leading two-byte word. + /// Original field leaf code. + /// The leading word: member attributes, padding or an overload count. + /// True when the leaf was recognized and consumed; false for an unsupported leaf. + /// A recognized leaf is truncated or malformed. + private static bool SkipNonStorageField(ref PdbRecordReader reader, ushort kind, ushort attributes) + { + switch (kind) + { + case 0x1400 or 0x151A: + // LF_BCLASS, LF_BINTERFACE: base type and its offset within the derived object. + _ = reader.UInt32(); + _ = reader.Integer(); + return true; + case 0x1401 or 0x1402: + // LF_VBCLASS, LF_IVBCLASS: base type, virtual-base pointer type, pointer offset and table index. + _ = reader.UInt32(); + _ = reader.UInt32(); + _ = reader.Integer(); + _ = reader.Integer(); + return true; + case 0x1409: + // LF_VFUNCTAB: the vtable pointer's type. + _ = reader.UInt32(); + return true; + case 0x140C: + // LF_VFUNCOFF: vtable pointer type and offset. + _ = reader.UInt32(); + _ = reader.UInt32(); + return true; + case 0x150E or 0x1510 or 0x1512: + // LF_STMEMBER, LF_NESTTYPE, LF_NESTTYPEEX: a type index and a name. + _ = reader.UInt32(); + _ = reader.Name(); + return true; + case 0x150F: + // LF_METHOD: overload count (the leading word), method-list index and name. + _ = reader.UInt32(); + _ = reader.Name(); + return true; + case 0x1511: + // LF_ONEMETHOD: an introducing virtual method (property 4 or 6) also records its vtable offset. + _ = reader.UInt32(); + if (((attributes >> 2) & 7) is 4 or 6) + { + _ = reader.UInt32(); + } + + _ = reader.Name(); + return true; + default: + return false; + } + } + + /// Writes a storage reference; named composites terminate recursive pointer graphs. + /// The preparation output. + /// Original CodeView type identity. + /// Current modifier/reference nesting, not graph-wide type count. + /// Operation-local shared work and cancellation limit. + /// The storage kind, extent or nesting is invalid. + private void WriteDescriptor(Utf8JsonWriter writer, uint index, int depth, PdbExportBudget budget) + { + budget.Take(); + if (depth >= MemorySchema.MaxDefinitionNestingDepth) + { + throw Invalid("storage descriptor nesting exceeds its depth limit"); + } + + if (index < 0x1000) + { + uint mode = index & 0xF00; + if (mode != 0) + { + int width = SimplePointerWidth(mode); + writer.WriteStartObject(); + writer.WriteString("kind", "pointer"); + writer.WriteString("base", width == 4 ? "__cv_pointer32" : "__cv_pointer64"); + writer.WritePropertyName("subtype"); + this.WriteDescriptor(writer, index & 0xFF, depth + 1, budget); + writer.WriteEndObject(); + return; + } + + SimpleType simple = Primitive(index); + writer.WriteStartObject(); + writer.WriteString("kind", "base"); + writer.WriteString("name", simple.Name); + writer.WriteEndObject(); + return; + } + + TypeRecord record = this.Type(index); + var reader = new PdbRecordReader(record.Bytes.Span); + if (this.namedTypes.TryGetValue(index, out NamedType? named)) + { + writer.WriteStartObject(); + writer.WriteString("kind", this.ambiguousViews.ContainsKey(index) || named.Kind == 0x1506 ? "union" : named.Kind == 0x1507 ? "enum" : "struct"); + writer.WriteString("name", this.names[index]); + writer.WriteEndObject(); + return; + } + + switch (record.Kind) + { + case 0x1001: + uint modified = reader.UInt32(); + ushort flags = reader.UInt16(); + reader.End(); + if ((flags & ~7) != 0) + { + throw Invalid("a modifier contains unknown qualifier bits"); + } + + this.WriteDescriptor(writer, modified, depth + 1, budget); + break; + case 0x1002: + (uint target, int width) = Pointer(record.Bytes.Span); + writer.WriteStartObject(); + writer.WriteString("kind", "pointer"); + writer.WriteString("base", width == 4 ? "__cv_pointer32" : "__cv_pointer64"); + writer.WritePropertyName("subtype"); + this.WriteDescriptor(writer, target, depth + 1, budget); + writer.WriteEndObject(); + break; + case 0x1503: + uint element = reader.UInt32(); + _ = reader.UInt32(); + int bytes = reader.Size(); + _ = reader.Name(); + reader.End(); + int elementSize = this.StorageSize(element, depth + 1, budget); + if (elementSize <= 0 || bytes % elementSize != 0) + { + throw Invalid("an array extent is not a whole number of its recorded element type"); + } + + writer.WriteStartObject(); + writer.WriteString("kind", "array"); + writer.WriteNumber("count", bytes / elementSize); + writer.WritePropertyName("subtype"); + this.WriteDescriptor(writer, element, depth + 1, budget); + writer.WriteEndObject(); + break; + case 0x1205: + uint storage = reader.UInt32(); + byte bits = reader.Byte(); + byte position = reader.Byte(); + reader.End(); + int storageSize = this.StorageSize(storage, depth + 1, budget); + if (bits == 0 || position + bits > storageSize * 8) + { + throw Invalid("a bitfield extends outside its recorded storage integer"); + } + + writer.WriteStartObject(); + writer.WriteString("kind", "bitfield"); + writer.WriteNumber("bit_position", position); + writer.WriteNumber("bit_length", bits); + writer.WritePropertyName("type"); + this.WriteDescriptor(writer, storage, depth + 1, budget); + writer.WriteEndObject(); + break; + case 0x1008 or 0x1009: + int minimum = record.Kind == 0x1008 ? 12 : 24; + if (record.Bytes.Length < minimum) + { + throw Invalid("a function description is truncated"); + } + + writer.WriteStartObject(); + writer.WriteString("kind", "function"); + writer.WriteEndObject(); + break; + default: + throw Invalid($"storage leaf 0x{record.Kind:X4} is not supported"); + } + } + + /// Reads every instance member or enum constant, following bounded original field-list continuations. + /// Original containing type. + /// Operation-local shared work and cancellation limit. + /// Members in original order, without expanding pointed-to graphs. + /// A list cycles, is truncated or contradicts its declared count. + private List ReadFields(NamedType type, PdbExportBudget budget) + { + var result = new List(type.Count); + var visited = new HashSet(); + bool onlyStorage = true; + uint next = type.Fields; + while (next != 0) + { + // Each continuation charges the shared budget, which also bounds the visited set's size. + budget.Take(); + if (!visited.Add(next)) + { + throw Invalid("an original field-list continuation cycles"); + } + + TypeRecord record = this.Type(next); + if (record.Kind != 0x1203) + { + throw Invalid("a member-list reference does not name a field list"); + } + + var reader = new PdbRecordReader(record.Bytes.Span); + next = 0; + while (reader.Remaining != 0) + { + budget.Take(); + if (reader.Padding()) + { + continue; + } + + ushort kind = reader.UInt16(); + if (kind == 0x1404) + { + if (reader.UInt16() != 0) + { + throw Invalid("a continuation has nonzero reserved bytes"); + } + + next = reader.UInt32(); + reader.End(); + break; + } + + if (result.Count >= this.maximumRecords) + { + throw Invalid("an original member list exceeds its record budget"); + } + + // Every field leaf starts with a two-byte word: attributes, padding or a method-overload count. + ushort attributes = reader.UInt16(); + if (kind == 0x150D && type.Kind != 0x1507) + { + uint storage = reader.UInt32(); + int offset = reader.Size(); + string name = reader.Name(); + result.Add(new(name, storage, offset, null)); + } + else if (kind == 0x1502 && type.Kind == 0x1507) + { + Int128 value = reader.Integer(); + string name = reader.Name(); + result.Add(new(name, 0, 0, value)); + } + else if (type.Kind != 0x1507 && SkipNonStorageField(ref reader, kind, attributes)) + { + onlyStorage = false; + } + else + { + throw Invalid($"field leaf 0x{kind:X4} is not supported for this containing type"); + } + } + } + + // CodeView's count also includes C++ methods, bases, nested types and similar elements. It can be compared + // exactly only when the lists contain instance storage alone; otherwise it is an upper bound. + if (onlyStorage ? result.Count != type.Count : result.Count > type.Count) + { + throw Invalid($"type '{type.Name}' has a different original member count from its field lists"); + } + + return result; + } + + /// Gets a fixed target storage size for array strides and bitfield bounds. + /// Original type identity. + /// Current by-value/modifier nesting. + /// Operation-local shared work and cancellation limit. + /// The recorded byte extent. + /// No complete fixed extent can be established. + private int StorageSize(uint index, int depth, PdbExportBudget budget) + { + budget.Take(); + if (depth >= MemorySchema.MaxDefinitionNestingDepth) + { + throw Invalid("by-value storage nesting exceeds its depth limit"); + } + + if (index < 0x1000) + { + uint mode = index & 0xF00; + return mode != 0 ? SimplePointerWidth(mode) : Primitive(index).Size; + } + + if (this.namedTypes.TryGetValue(index, out NamedType? type)) + { + if (type.Forward) + { + if (this.ambiguousViews.TryGetValue(index, out List? alternatives)) + { + return alternatives[0].Size; + } + + if (!this.forwardTypes.TryGetValue(index, out uint complete)) + { + throw Invalid("an array element has only an incomplete forward declaration"); + } + + return this.StorageSize(complete, depth + 1, budget); + } + + return type.Kind == 0x1507 ? this.StorageSize(type.Underlying, depth + 1, budget) : type.Size; + } + + TypeRecord record = this.Type(index); + var reader = new PdbRecordReader(record.Bytes.Span); + return record.Kind switch + { + 0x1001 => this.StorageSize(reader.UInt32(), depth + 1, budget), + 0x1002 => Pointer(record.Bytes.Span).Width, + 0x1503 => ArraySize(record.Bytes.Span), + _ => throw Invalid($"storage size for leaf 0x{record.Kind:X4} is not available"), + }; + } + + /// Finds an enum's integral storage without assuming the host's long width. + /// Original underlying type reference. + /// Modifier depth. + /// Operation-local shared work and cancellation limit. + /// The explicit primitive storage type. + /// The enum does not have bounded integral storage. + private SimpleType EnumBase(uint index, int depth, PdbExportBudget budget) + { + budget.Take(); + if (depth >= MemorySchema.MaxDefinitionNestingDepth) + { + throw Invalid("enum storage nesting exceeds its depth limit"); + } + + if (index < 0x100) + { + SimpleType type = Primitive(index); + return type.Kind is "int" or "char" ? type : throw Invalid("an enum has nonintegral storage"); + } + + TypeRecord record = this.Type(index); + return record.Kind == 0x1001 ? this.EnumBase(U32(record.Bytes.Span, 0), depth + 1, budget) : throw Invalid("an enum has unsupported storage"); + } + + /// Explicit primitive storage independent of the host ABI. + /// Stable ISF base-type name. + /// ISF scalar category. + /// Recorded byte width. + /// Whether integral storage is signed. + private readonly record struct SimpleType(string Name, string Kind, int Size, bool Signed); + + /// An original instance member or enum constant in declaration order. + /// Complete original name. + /// Native storage reference for an instance member. + /// Original byte offset within the containing record. + /// Original enum value, or null for an instance member. + private readonly record struct Field(string Name, uint Type, int Offset, Int128? Value); +} diff --git a/src/CStructSharp/Memory/Metadata/PdbMetadata.Symbols.cs b/src/CStructSharp/Memory/Metadata/PdbMetadata.Symbols.cs new file mode 100644 index 00000000..2a55d008 --- /dev/null +++ b/src/CStructSharp/Memory/Metadata/PdbMetadata.Symbols.cs @@ -0,0 +1,338 @@ +namespace CStructSharp.Memory.Metadata; + +/// Joins original symbol coordinates to their recorded section and optional OMAP metadata. +public sealed partial class PdbMetadata +{ + private readonly Dictionary symbolRecordKinds = new(); + private readonly HashSet unmappedSymbols = new(StringComparer.Ordinal); + + /// File-local data candidates by name; a null address marks a name already proved ambiguous. + private readonly Dictionary localSymbols = new(StringComparer.Ordinal); + + /// Reads an optional DBI debug-stream index, treating the recorded 0xFFFF sentinel as absent. + /// Original optional DBI debug header. + /// Zero-based debug-header slot. + /// A present stream index, or -1 for an absent slot. + private static int OptionalStream(ReadOnlySpan bytes, int index) + { + int offset = checked(index * 2); + return offset >= bytes.Length || U16(bytes, offset) == ushort.MaxValue ? -1 : U16(bytes, offset); + } + + /// Requires complete, strictly ordered source-to-image remapping entries before binary lookup. + /// Original OMAP_FROM_SRC stream, or empty when no remapping was recorded. + /// Checked between entries. + /// The map is truncated, duplicated or unordered. + private static void ValidateOmap(ReadOnlySpan bytes, CancellationToken cancellationToken) + { + if (bytes.Length % 8 != 0) + { + throw Invalid("the original OMAP table is truncated"); + } + + uint previous = 0; + for (int offset = 0; offset < bytes.Length; offset += 8) + { + cancellationToken.ThrowIfCancellationRequested(); + uint source = U32(bytes, offset); + if (offset != 0 && source <= previous) + { + throw Invalid("the original OMAP coordinates are duplicated or unordered"); + } + + previous = source; + } + } + + /// Maps one original RVA without inventing bytes for deleted or uncovered OMAP intervals. + /// Original section-relative coordinate after applying its section base. + /// Validated original OMAP_FROM_SRC entries. + /// The mapped image-relative coordinate, or null for an unrepresented interval. + /// The mapped coordinate wraps. + private static uint? Map(uint source, ReadOnlySpan bytes) + { + if (bytes.IsEmpty) + { + return source; + } + + int low = 0; + int high = bytes.Length / 8; + while (low < high) + { + int middle = low + ((high - low) / 2); + if (U32(bytes, middle * 8) <= source) + { + low = middle + 1; + } + else + { + high = middle; + } + } + + if (low == 0) + { + return null; + } + + int offset = (low - 1) * 8; + uint destination = U32(bytes, offset + 4); + if (destination == 0) + { + return null; + } + + ulong mapped = (ulong)destination + source - U32(bytes, offset); + return mapped <= uint.MaxValue ? (uint)mapped : throw Invalid("an OMAP coordinate wraps"); + } + + /// Resolves the recorded logical segment through DBI before applying PE section bases. + /// One-based original logical segment. + /// Original offset within that segment. + /// Original DBI segment descriptors, or empty for direct PE segment indices. + /// Original PE section headers used by the symbol producer. + /// The original absolute value or image-relative coordinate, explicitly distinguished. + /// A segment, frame or resulting coordinate is inconsistent. + private static (bool Absolute, uint Coordinate) SectionCoordinate(ushort segment, uint offset, ReadOnlySpan sectionMap, ReadOnlySpan sections) + { + if (segment == 0) + { + return (true, offset); + } + + ulong coordinate = offset; + if (!sectionMap.IsEmpty) + { + if (segment > U16(sectionMap, 0)) + { + throw Invalid("a symbol names a nonexistent logical segment"); + } + + int entry = 4 + ((segment - 1) * 20); + ushort flags = U16(sectionMap, entry); + coordinate += U32(sectionMap, entry + 12); + if ((flags & 0x200) != 0) + { + return coordinate <= uint.MaxValue ? (true, (uint)coordinate) : throw Invalid("an absolute symbol coordinate wraps"); + } + + if (U16(sectionMap, entry + 2) != 0 || U16(sectionMap, entry + 4) != 0) + { + throw Invalid("overlay or grouped logical segments are not supported"); + } + + segment = U16(sectionMap, entry + 6); + } + + if (segment == 0 || segment > sections.Length / 40) + { + throw Invalid("a symbol names a nonexistent original section"); + } + + coordinate += U32(sections, ((segment - 1) * 40) + 12); + return coordinate <= uint.MaxValue ? (false, (uint)coordinate) : throw Invalid("an image-relative symbol coordinate wraps"); + } + + /// Reads only the DBI substream index, section table, optional OMAP and global symbol records. + /// + /// A PDB without a symbol-record stream (DBI slot 0xFFFF, as in a stripped or types-only file) has no symbols; + /// its type information remains available. Public and global records must agree on one address per name. + /// File-local data (S_LDATA32) can legitimately repeat a name across compilation units, so such a + /// name is exported only when it has one coordinate and no public or global record contradicts it. + /// + /// Validated borrowed MSF file. + /// Original fixed DBI header. + /// Checked between symbol and remapping records. + /// A coordinate, substream or record is inconsistent. + private void ReadSymbols(PdbMsfFile file, ReadOnlySpan debug, CancellationToken cancellationToken) + { + int symbolIndex = U16(debug, 20); + if (symbolIndex == ushort.MaxValue) + { + return; + } + + ulong optionalOffset = 64; + ReadOnlySpan substreamSizes = [24, 28, 32, 36, 40, 52]; + foreach (int offset in substreamSizes) + { + uint size = U32(debug, offset); + if (size > int.MaxValue) + { + throw Invalid("a DBI substream has a negative length"); + } + + optionalOffset += size; + } + + uint optionalLength = U32(debug, 48); + if (optionalLength > int.MaxValue || (optionalLength & 1) != 0 + || optionalOffset + optionalLength > file.StreamLength(3)) + { + throw Invalid("the DBI substreams extend beyond their original stream"); + } + + uint sectionMapLength = U32(debug, 32); + ulong sectionMapOffset = 64UL + U32(debug, 24) + U32(debug, 28); + byte[] sectionMap = file.ReadStreamRange(3, (uint)sectionMapOffset, (int)sectionMapLength); + if (sectionMap.Length != 0 + && (sectionMap.Length < 4 || 4UL + (20UL * U16(sectionMap, 0)) != (ulong)sectionMap.Length + || U16(sectionMap, 2) > U16(sectionMap, 0))) + { + throw Invalid("the original DBI section-map table is inconsistent"); + } + + byte[] optional = file.ReadStreamRange(3, (uint)optionalOffset, (int)optionalLength); + int omapIndex = OptionalStream(optional, 4); + int sectionIndex = OptionalStream(optional, omapIndex >= 0 ? 10 : 5); + if (sectionIndex < 0) + { + throw Invalid("original section headers required to resolve symbol coordinates are absent"); + } + + byte[] sections = file.ReadStream(sectionIndex); + if (sections.Length == 0 || sections.Length % 40 != 0 || sections.Length / 40 > 65_535) + { + throw Invalid("the original section-header table is truncated or oversized"); + } + + byte[] mapping = omapIndex >= 0 ? file.ReadStream(omapIndex) : []; + if (mapping.Length / 8 > this.maximumRecords) + { + throw Invalid("the original OMAP table exceeds its record budget"); + } + + ValidateOmap(mapping, cancellationToken); + byte[] bytes = file.ReadStream(symbolIndex); + int cursor = 0; + int records = 0; + while (cursor < bytes.Length) + { + cancellationToken.ThrowIfCancellationRequested(); + if (++records > this.maximumRecords || bytes.Length - cursor < 4) + { + throw Invalid("the symbol table is truncated or exceeds its record budget"); + } + + int length = U16(bytes, cursor); + ushort kind = U16(bytes, cursor + 2); + if (length < 2 || length > bytes.Length - cursor - 2) + { + throw Invalid("a symbol record extends beyond its original stream"); + } + + this.symbolRecordKinds[kind] = this.symbolRecordKinds.GetValueOrDefault(kind) + 1; + if (kind is 0x110C or 0x110D or 0x110E) + { + var reader = new PdbRecordReader(bytes.AsSpan(cursor + 4, length - 2)); + uint flagsOrType = reader.UInt32(); + uint offset = reader.UInt32(); + ushort segment = reader.UInt16(); + string name = reader.Name(); + reader.EndSymbol(); + (bool absolute, uint original) = SectionCoordinate(segment, offset, sectionMap, sections); + if (absolute) + { + if (this.absoluteSymbols.TryGetValue(name, out ulong previous) && previous != original) + { + throw Invalid($"absolute symbol '{name}' has conflicting original values"); + } + + this.absoluteSymbols[name] = original; + this.unmappedSymbols.Add(name); + } + else + { + uint? mapped = Map(original, mapping); + if (mapped is not { } address) + { + this.unmappedSymbols.Add(name); + } + else if (kind == 0x110C) + { + this.AddLocalSymbol(name, address, flagsOrType); + } + else + { + this.AddSymbol(name, address, kind == 0x110E ? null : flagsOrType); + } + } + } + + cursor += length + 2; + } + + this.MergeLocalSymbols(); + } + + /// Records one file-local data coordinate, marking the name ambiguous when another coordinate or type disagrees. + /// Original undecorated local name. + /// Resolved image-relative coordinate. + /// Original storage type. + private void AddLocalSymbol(string name, uint address, uint type) + { + if (!this.localSymbols.TryGetValue(name, out (uint? Address, uint Type) previous)) + { + this.localSymbols.Add(name, (address, type)); + } + else if (previous.Address is { } known && (known != address || previous.Type != type)) + { + this.localSymbols[name] = (null, 0); + } + } + + /// Publishes unambiguous file-local names after every public and global record has been seen. + /// Merging last makes the outcome independent of record order: a global always wins over a local. + private void MergeLocalSymbols() + { + foreach ((string name, (uint? address, uint type)) in this.localSymbols.OrderBy(entry => entry.Key, StringComparer.Ordinal)) + { + if (address is not { } local) + { + this.resolutionDiagnostics.Add($"File-local symbol '{name}' has several original coordinates or storage types; none of its file-local records is exported."); + } + else if (this.symbols.TryGetValue(name, out ulong global)) + { + if (global != local) + { + this.resolutionDiagnostics.Add($"File-local symbol '{name}' differs from the public or global symbol of that name; only the public or global address is exported."); + } + else + { + // A public record carries no type; an agreeing local record can still supply the storage type. + this.symbolTypes.TryAdd(name, type); + } + } + else + { + this.symbols.Add(name, local); + this.symbolTypes.Add(name, type); + } + } + } + + /// Preserves equal-address aliases while rejecting contradictory definitions with one lookup name. + /// Complete original symbol name. + /// Resolved original image-relative coordinate. + /// Original storage type, if the source recorded one. + /// One name has conflicting coordinates or storage identities. + private void AddSymbol(string name, uint address, uint? type) + { + if (this.symbols.TryGetValue(name, out ulong previous) && previous != address) + { + throw Invalid($"symbol '{name}' has conflicting original coordinates"); + } + + this.symbols[name] = address; + if (type is { } index) + { + if (this.symbolTypes.TryGetValue(name, out uint previousType) && previousType != index) + { + throw Invalid($"symbol '{name}' has conflicting original storage types"); + } + + this.symbolTypes[name] = index; + } + } +} diff --git a/src/CStructSharp/Memory/Metadata/PdbMetadata.cs b/src/CStructSharp/Memory/Metadata/PdbMetadata.cs new file mode 100644 index 00000000..1c195578 --- /dev/null +++ b/src/CStructSharp/Memory/Metadata/PdbMetadata.cs @@ -0,0 +1,363 @@ +namespace CStructSharp.Memory.Metadata; + +using System.Buffers.Binary; +using System.Collections.ObjectModel; +using CStructSharp.Diagnostics; + +/// Reads native MSF 7/CodeView PDB metadata for explicit, portable ISF preparation. +/// +/// Only metadata streams are retained; the containing PDB is never copied as a whole. The input stays owned by its +/// caller and its position is restored. No file, network connection, symbol server or native debugger is opened. +/// Exported ISF uses the existing importer and memory-schema codecs for inspection. +/// +public sealed partial class PdbMetadata +{ + private readonly TypeRecord[] types; + private readonly uint firstType; + private readonly Dictionary namedTypes = new(); + private readonly Dictionary names = new(); + private readonly Dictionary forwardTypes = new(); + private readonly Dictionary> ambiguousViews = new(); + private readonly List definitions = new(); + private readonly List resolutionDiagnostics = new(); + private readonly Dictionary symbols = new(StringComparer.Ordinal); + private readonly Dictionary symbolTypes = new(StringComparer.Ordinal); + private readonly Dictionary absoluteSymbols = new(StringComparer.Ordinal); + private readonly int maximumRecords; + + /// Parses the original stream directory, identity, type records and global/public symbol records. + /// Readable, seekable original PDB stream, borrowed only during construction. + /// Shared retained directory/stream byte limit; not the containing file's length. + /// Maximum records per input table: type records, symbol records, OMAP entries and members of one composite. + /// Checked during original block reads and record enumeration. + /// Explicit target PE machine when the original DBI machine is zero; a recorded nonzero machine must agree. + /// The input is null. + /// The input cannot be read and sought. + /// A budget is not positive or an explicit target machine is unsupported. + /// Metadata is malformed, exceeds a budget or uses an unsupported native revision. + /// Cancellation was requested. + public PdbMetadata(Stream input, int maxMetadataBytes = 64 * 1024 * 1024, int maxRecords = 1_000_000, CancellationToken cancellationToken = default, ushort? targetMachine = null) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxMetadataBytes); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxRecords); + if (targetMachine is not null and not (0x014C or 0x8664 or 0xAA64)) + { + throw new ArgumentOutOfRangeException(nameof(targetMachine), "The explicit target machine must be x86, x64 or ARM64."); + } + + cancellationToken.ThrowIfCancellationRequested(); + this.maximumRecords = maxRecords; + if (!input.CanSeek) + { + throw new ArgumentException("Native PDB metadata requires a seekable stream.", nameof(input)); + } + + long originalPosition = input.Position; + try + { + var file = new PdbMsfFile(input, maxMetadataBytes, cancellationToken); + + // ReadStreamRange returns exactly the requested extent or throws, so only the header values need checks. + byte[] information = file.ReadStreamRange(1, 0, 28); + byte[] debug = file.ReadStreamRange(3, 0, 64); + if (U32(information, 0) < 20000404 || U32(debug, 0) != uint.MaxValue + || U32(debug, 4) is not (19990903 or 20091201)) + { + throw Invalid("the identity or debug-information stream has an unsupported header"); + } + + this.Guid = new Guid(information.AsSpan(12, 16)); + this.InformationAge = U32(information, 8); + this.DbiAge = U32(debug, 8); + this.Machine = U16(debug, 58); + if (this.Machine != 0 && targetMachine is { } expectedMachine && this.Machine != expectedMachine) + { + throw Invalid($"recorded machine 0x{this.Machine:X4} contradicts explicit target 0x{expectedMachine:X4}"); + } + + this.TargetMachine = targetMachine ?? this.Machine; + this.PointerSize = this.TargetMachine switch + { + 0x014C => 4, + 0x8664 or 0xAA64 => 8, + 0 when this.Machine == 0 => throw Invalid("the DBI machine is unspecified; provide an explicit targetMachine instead of inferring the host architecture"), + _ => throw Invalid($"machine 0x{this.Machine:X4} is not supported"), + }; + if (this.Guid == System.Guid.Empty || this.InformationAge == 0 || this.DbiAge == 0) + { + throw Invalid("the original GUID or age fields are empty"); + } + + byte[] typeBytes = file.ReadStream(2); + if (typeBytes.Length < 56 || U32(typeBytes, 0) is not (19990903 or 20040203)) + { + throw Invalid("the type stream does not use a supported CodeView V70/V80 header"); + } + + uint headerSize = U32(typeBytes, 4); + this.firstType = U32(typeBytes, 8); + uint typeEnd = U32(typeBytes, 12); + uint typeLength = U32(typeBytes, 16); + if (headerSize < 56 || headerSize > typeBytes.Length || this.firstType != 0x1000 + || typeEnd < this.firstType || typeEnd - this.firstType > maxRecords + || typeLength > (ulong)typeBytes.Length - headerSize) + { + throw Invalid("the type index interval or record extent is inconsistent"); + } + + this.types = new TypeRecord[typeEnd - this.firstType]; + int cursor = (int)headerSize; + int end = checked(cursor + (int)typeLength); + for (int index = 0; index < this.types.Length; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + if (end - cursor < 4) + { + throw Invalid("the type record table is truncated"); + } + + int length = U16(typeBytes, cursor); + if (length < 2 || length > end - cursor - 2) + { + throw Invalid("a type record extends beyond its declared table"); + } + + this.types[index] = new(U16(typeBytes, cursor + 2), typeBytes.AsMemory(cursor + 4, length - 2)); + cursor += length + 2; + } + + if (cursor != end) + { + throw Invalid("the type count and original record-byte extent disagree"); + } + + this.IndexNames(cancellationToken); + this.ReadSymbols(file, debug, cancellationToken); + this.UserTypeNames = Array.AsReadOnly(this.definitions.Where(type => type.Kind != 0x1507).Select(type => this.names[type.Index]) + .Concat(this.ambiguousViews.Keys.Select(index => this.names[index])).Order(StringComparer.Ordinal).ToArray()); + this.Symbols = new ReadOnlyDictionary(this.symbols); + this.SymbolRecordKinds = new ReadOnlyDictionary(this.symbolRecordKinds); + this.Diagnostics = this.resolutionDiagnostics.AsReadOnly(); + this.AbsoluteSymbols = new ReadOnlyDictionary(this.absoluteSymbols); + } + finally + { + input.Position = originalPosition; + } + } + + /// Gets the exact GUID in the original PDB-information stream. + public Guid Guid { get; } + + /// Gets the original PDB-information stream's write counter, without substituting the DBI value. + public uint InformationAge { get; } + + /// Gets the separate original DBI age, without hiding a difference from . + public uint DbiAge { get; } + + /// Gets the original DBI PE machine identifier, including zero when the producer did not record one. + public ushort Machine { get; } + + /// Gets the recorded or explicitly supplied target machine without replacing the original value. + public ushort TargetMachine { get; } + + /// Gets the target pointer width from , never the analyzing host. + public int PointerSize { get; } + + /// Gets complete composite names in deterministic ordinal order; ambiguous names retain their type indices. + public IReadOnlyList UserTypeNames { get; } + + /// Gets original public, global and unambiguous file-local image-relative addresses after any recorded OMAP transformation. + public IReadOnlyDictionary Symbols { get; } + + /// Gets original absolute symbol values, kept separate from image-relative memory coordinates. + public IReadOnlyDictionary AbsoluteSymbols { get; } + + /// Gets counts of every original global-symbol record kind, including non-address records not exported to ISF. + public IReadOnlyDictionary SymbolRecordKinds { get; } + + /// Gets the number of distinct symbol names that are absolute or OMAP-unrepresented, so none is misrepresented as an image-relative address. + /// A name recorded by both a public and a global record counts once. + public int UnmappedSymbolCount => this.unmappedSymbols.Count; + + /// Gets source identity ambiguities that were preserved or omitted rather than silently resolved by name. + /// + /// Type entries describe display names shared by several complete definitions. Symbol entries describe + /// file-local data names (S_LDATA32) that have several addresses, or that differ from a public or global + /// symbol of the same name; such a local name is omitted from . + /// + public IReadOnlyList Diagnostics { get; } + + /// Keeps struct/class, union and enum identity namespaces separate during forward resolution. + /// Original named type. + /// A lookup key, not an exported type name. + private static string TypeKey(NamedType type) => $"{(type.Kind is 0x1504 or 0x1505 ? 0x1505 : type.Kind):X4}:{type.UniqueName}"; + + /// Reads a bounded original little-endian word. + /// Containing metadata record. + /// Byte offset within that record. + /// The original unsigned value. + private static ushort U16(ReadOnlySpan bytes, int offset) + { + if ((uint)offset > (uint)bytes.Length || bytes.Length - offset < 2) + { + throw Invalid("a two-byte metadata field is truncated"); + } + + return BinaryPrimitives.ReadUInt16LittleEndian(bytes[offset..]); + } + + /// Reads a bounded original little-endian double word. + /// Containing metadata record. + /// Byte offset within that record. + /// The original unsigned value. + private static uint U32(ReadOnlySpan bytes, int offset) + { + if ((uint)offset > (uint)bytes.Length || bytes.Length - offset < 4) + { + throw Invalid("a four-byte metadata field is truncated"); + } + + return BinaryPrimitives.ReadUInt32LittleEndian(bytes[offset..]); + } + + /// Preserves a source-specific malformed-metadata diagnostic. + /// The violated native format invariant. + /// The layout exception reported by the public metadata boundary. + private static CStructLayoutException Invalid(string reason) => new($"Native PDB metadata is invalid: {reason}."); + + /// Indexes complete and forward-declared identities without conflating equal display names. + /// Checked between type records. + /// A named record is malformed or its native extent is invalid. + private void IndexNames(CancellationToken cancellationToken) + { + var complete = new Dictionary>(StringComparer.Ordinal); + var displayCounts = new Dictionary(StringComparer.Ordinal); + for (int index = 0; index < this.types.Length; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + TypeRecord record = this.types[index]; + if (record.Kind is not (0x1504 or 0x1505 or 0x1506 or 0x1507)) + { + continue; + } + + uint identity = this.firstType + (uint)index; + var reader = new PdbRecordReader(record.Bytes.Span); + ushort count = reader.UInt16(); + ushort properties = reader.UInt16(); + uint underlying = 0; + uint fields; + int size = 0; + if (record.Kind == 0x1507) + { + underlying = reader.UInt32(); + fields = reader.UInt32(); + } + else + { + fields = reader.UInt32(); + if (record.Kind is 0x1504 or 0x1505) + { + _ = reader.UInt32(); + _ = reader.UInt32(); + } + + size = reader.Size(); + } + + string name = reader.Name(); + string unique = (properties & 0x200) != 0 ? reader.Name() : name; + reader.End(); + var type = new NamedType(identity, record.Kind, count, fields, underlying, size, name, unique, (properties & 0x80) != 0); + this.namedTypes.Add(identity, type); + if (type.Forward) + { + continue; + } + + this.definitions.Add(type); + string key = TypeKey(type); + if (!complete.TryGetValue(key, out List? alternatives)) + { + alternatives = []; + complete.Add(key, alternatives); + } + + alternatives.Add(type); + displayCounts[name] = displayCounts.GetValueOrDefault(name) + 1; + } + + foreach (NamedType type in this.definitions) + { + string name = type.Name.Length == 0 ? $"__cv_{type.Index:X8}" : type.Name; + this.names.Add(type.Index, displayCounts[type.Name] > 1 ? $"{name}@cv-{type.Index:X8}" : name); + } + + foreach (NamedType type in this.namedTypes.Values) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!type.Forward) + { + continue; + } + + if (complete.TryGetValue(TypeKey(type), out List? alternatives)) + { + if (alternatives.Count != 1) + { + this.names.Add(type.Index, $"{type.Name}@cv-{type.Index:X8}"); + bool sameExtent = alternatives[0].Kind != 0x1507 && alternatives[0].Size > 0 + && alternatives.All(candidate => candidate.Kind != 0x1507 && candidate.Size == alternatives[0].Size); + if (sameExtent) + { + this.ambiguousViews.Add(type.Index, alternatives); + } + + string interpretation = sameExtent ? "an explicit same-extent union of the original complete views" : "address-only because the complete extents disagree"; + this.resolutionDiagnostics.Add($"Forward type 0x{type.Index:X8} '{type.Name}' has several complete identities ({string.Join(", ", alternatives.Select(candidate => $"0x{candidate.Index:X8}"))}); each is preserved separately and the target is {interpretation}."); + continue; + } + + this.names.Add(type.Index, this.names[alternatives[0].Index]); + this.forwardTypes.Add(type.Index, alternatives[0].Index); + } + else + { + this.names.Add(type.Index, $"{type.Name}@cv-{type.Index:X8}"); + } + } + } + + /// Finds one original type record by its CodeView identity. + /// Original type index, not a display-name lookup. + /// The bounded original record. + /// The reference is outside the declared type table. + private TypeRecord Type(uint index) + { + if (index < this.firstType || index - this.firstType >= this.types.Length) + { + throw Invalid($"type reference 0x{index:X8} is outside the type table"); + } + + return this.types[index - this.firstType]; + } + + /// A type leaf and its original payload, sharing the retained TPI stream. + /// CodeView leaf code. + /// Payload excluding the length and leaf code. + private readonly record struct TypeRecord(ushort Kind, ReadOnlyMemory Bytes); + + /// Original named storage metadata, before forward resolution or output-name qualification. + /// Native type index. + /// Native storage leaf. + /// Declared immediate-member count. + /// Native field-list index. + /// Enum storage type, or zero. + /// Declared composite byte size. + /// Original display name. + /// Original unique name, or the display name if none was recorded. + /// Whether this is an incomplete forward declaration. + private sealed record NamedType(uint Index, ushort Kind, ushort Count, uint Fields, uint Underlying, int Size, string Name, string UniqueName, bool Forward); +} diff --git a/src/CStructSharp/Memory/Metadata/PdbMsfFile.cs b/src/CStructSharp/Memory/Metadata/PdbMsfFile.cs new file mode 100644 index 00000000..0aa30886 --- /dev/null +++ b/src/CStructSharp/Memory/Metadata/PdbMsfFile.cs @@ -0,0 +1,238 @@ +namespace CStructSharp.Memory.Metadata; + +using System.Buffers.Binary; +using CStructSharp.Diagnostics; + +/// Reads selected streams from a borrowed MSF 7 file without materializing the containing file. +internal sealed class PdbMsfFile +{ + private readonly Stream input; + private readonly long length; + private readonly int blockSize; + private readonly byte[] directory; + private readonly StreamLocation[] streams; + private readonly CancellationToken cancellationToken; + private int remainingBytes; + + /// Validates the directory and every recorded block reference before reading metadata streams. + /// Readable, seekable input; ownership stays with the caller. + /// Shared limit for retained directory and stream bytes. + /// Checked during directory traversal and every block read. + /// The input cannot be read and sought. + /// The file or directory is malformed or exceeds the metadata limit. + internal PdbMsfFile(Stream input, int maximumBytes, CancellationToken cancellationToken) + { + if (!input.CanRead || !input.CanSeek) + { + throw new ArgumentException("Native PDB metadata requires a readable, seekable stream.", nameof(input)); + } + + this.input = input; + this.length = input.Length; + this.remainingBytes = maximumBytes; + this.cancellationToken = cancellationToken; + Span header = stackalloc byte[56]; + this.ReadAt(0, header); + if (!header[..32].SequenceEqual("Microsoft C/C++ MSF 7.00\r\n\u001aDS\0\0\0"u8)) + { + throw Invalid("the MSF 7 signature is absent"); + } + + uint width = BinaryPrimitives.ReadUInt32LittleEndian(header[32..]); + uint freeMap = BinaryPrimitives.ReadUInt32LittleEndian(header[36..]); + uint blockCount = BinaryPrimitives.ReadUInt32LittleEndian(header[40..]); + uint directoryLength = BinaryPrimitives.ReadUInt32LittleEndian(header[44..]); + uint mapBlock = BinaryPrimitives.ReadUInt32LittleEndian(header[52..]); + if (width is not (512 or 1024 or 2048 or 4096) || freeMap is not (1 or 2) + || blockCount < 3 || ((long)blockCount * width) != this.length) + { + throw Invalid("the block size, free-map selector or declared file extent is inconsistent"); + } + + this.blockSize = (int)width; + int directoryBlocks = this.BlocksFor(directoryLength); + if (directoryLength < 4 || directoryBlocks > this.blockSize / 4) + { + throw Invalid("the stream directory does not fit its recorded block map"); + } + + this.Charge(directoryLength); + this.directory = new byte[(int)directoryLength]; + var occupied = new HashSet { 0 }; + this.ValidateBlock(mapBlock, blockCount, occupied); + byte[] map = new byte[checked(directoryBlocks * 4)]; + this.ReadAt((long)mapBlock * this.blockSize, map); + int copied = 0; + for (int index = 0; index < directoryBlocks; index++) + { + uint block = BinaryPrimitives.ReadUInt32LittleEndian(map.AsSpan(index * 4)); + this.ValidateBlock(block, blockCount, occupied); + int count = Math.Min(this.blockSize, this.directory.Length - copied); + this.ReadAt((long)block * this.blockSize, this.directory.AsSpan(copied, count)); + copied += count; + } + + uint streamCount = BinaryPrimitives.ReadUInt32LittleEndian(this.directory); + if (streamCount > 65_536 || 4UL + (streamCount * 4UL) > (ulong)this.directory.Length) + { + throw Invalid("the stream-size table is truncated or exceeds its record limit"); + } + + this.Charge(streamCount * 8); + this.streams = new StreamLocation[streamCount]; + int cursor = checked(4 + ((int)streamCount * 4)); + for (int index = 0; index < this.streams.Length; index++) + { + this.cancellationToken.ThrowIfCancellationRequested(); + uint size = BinaryPrimitives.ReadUInt32LittleEndian(this.directory.AsSpan(4 + (index * 4))); + int blocks = size == uint.MaxValue ? 0 : this.BlocksFor(size); + if ((ulong)blocks * 4 > (ulong)(this.directory.Length - cursor)) + { + throw Invalid("a stream's block list extends beyond the directory"); + } + + this.streams[index] = new(size, cursor); + for (int blockIndex = 0; blockIndex < blocks; blockIndex++) + { + uint block = BinaryPrimitives.ReadUInt32LittleEndian(this.directory.AsSpan(cursor)); + this.ValidateBlock(block, blockCount, occupied); + cursor += 4; + } + } + + if (cursor != this.directory.Length) + { + throw Invalid("the stream directory has unclaimed bytes"); + } + } + + /// Gets the original logical extent of one present metadata stream. + /// Zero-based MSF stream index. + /// The original logical byte length. + /// The required stream is absent. + internal uint StreamLength(int index) + { + if ((uint)index >= (uint)this.streams.Length || this.streams[index].Length == uint.MaxValue) + { + throw Invalid($"required stream {index} is absent"); + } + + return this.streams[index].Length; + } + + /// Copies only the requested metadata stream, joining its original discontiguous blocks. + /// Zero-based MSF stream index. + /// The complete original stream bytes. + /// The stream is absent, unreadable or exceeds the shared limit. + internal byte[] ReadStream(int index) + { + uint length = this.StreamLength(index); + if (length > int.MaxValue) + { + throw Invalid("a required metadata stream exceeds the byte budget"); + } + + return this.ReadStreamRange(index, 0, (int)length); + } + + /// Copies a selected original extent without retaining unrelated compiland or source information. + /// Zero-based MSF stream index. + /// Logical byte offset within that stream. + /// Number of original bytes to retain. + /// The exact original extent, including fields split across physical blocks. + /// The extent is absent, truncated or exceeds the shared limit. + internal byte[] ReadStreamRange(int index, uint offset, int count) + { + uint length = this.StreamLength(index); + if (count < 0 || offset > length || (uint)count > length - offset) + { + throw Invalid("a required metadata extent exceeds its stream"); + } + + this.Charge((uint)count); + byte[] bytes = count == 0 ? [] : new byte[count]; + int cursor = checked(this.streams[index].BlockOffset + ((int)(offset / (uint)this.blockSize) * 4)); + int within = (int)(offset % (uint)this.blockSize); + for (int copied = 0; copied < bytes.Length; cursor += 4) + { + uint block = BinaryPrimitives.ReadUInt32LittleEndian(this.directory.AsSpan(cursor)); + int take = Math.Min(this.blockSize - within, bytes.Length - copied); + this.ReadAt(((long)block * this.blockSize) + within, bytes.AsSpan(copied, take)); + copied += take; + within = 0; + } + + return bytes; + } + + /// Names the source format on a malformed-metadata failure. + /// The violated format or budget invariant. + /// A domain-specific layout exception. + private static CStructLayoutException Invalid(string reason) => new($"Native PDB metadata is invalid: {reason}."); + + /// Bounds retained metadata before any length-controlled allocation. + /// Additional byte count. + /// The shared metadata limit would be exceeded. + private void Charge(uint bytes) + { + if (bytes > this.remainingBytes) + { + throw Invalid("metadata exceeds its shared byte budget"); + } + + this.remainingBytes -= (int)bytes; + } + + /// Converts a logical stream extent to its number of physical blocks without unsigned wrap. + /// Logical byte count. + /// The required block count. + private int BlocksFor(uint bytes) => checked((int)(((ulong)bytes + (uint)this.blockSize - 1) / (uint)this.blockSize)); + + /// Rejects directory/data aliases, reserved pages and repeated ownership. + /// Original physical block index. + /// Declared number of blocks in the original file. + /// Previously assigned metadata and stream blocks. + /// The block is reserved, outside the file or already assigned. + private void ValidateBlock(uint block, uint count, HashSet occupied) + { + this.cancellationToken.ThrowIfCancellationRequested(); + uint interval = block % (uint)this.blockSize; + if (block >= count || interval is 1 or 2 || !occupied.Add(block)) + { + throw Invalid("a stream or directory references a reserved, repeated or out-of-file block"); + } + } + + /// Reads a confirmed original extent and rejects short reads or a changing file length. + /// Absolute byte coordinate in the input. + /// Destination for the complete original extent. + /// The extent is outside the file, changes, or cannot be read completely. + private void ReadAt(long offset, Span bytes) + { + this.cancellationToken.ThrowIfCancellationRequested(); + if (offset < 0 || offset > this.length || bytes.Length > this.length - offset || this.input.Length != this.length) + { + throw Invalid("an original stream extent is outside the file or its length changed"); + } + + try + { + this.input.Position = offset; + this.input.ReadExactly(bytes); + } + catch (EndOfStreamException exception) + { + throw new CStructLayoutException("Native PDB metadata has a truncated original extent.", exception); + } + + if (this.input.Length != this.length) + { + throw Invalid("the input length changed during a metadata read"); + } + } + + /// A stream's declared size and its first block-index coordinate in the retained directory. + /// Original logical byte length, or uint.MaxValue for an absent stream. + /// Byte offset of its block list inside the directory. + private readonly record struct StreamLocation(uint Length, int BlockOffset); +} diff --git a/src/CStructSharp/Memory/Metadata/PdbRecordReader.cs b/src/CStructSharp/Memory/Metadata/PdbRecordReader.cs new file mode 100644 index 00000000..f8ca71c6 --- /dev/null +++ b/src/CStructSharp/Memory/Metadata/PdbRecordReader.cs @@ -0,0 +1,163 @@ +namespace CStructSharp.Memory.Metadata; + +using System.Buffers.Binary; +using System.Text; +using CStructSharp.Diagnostics; + +/// Reads CodeView wire fields within one already bounded native PDB record. +internal ref struct PdbRecordReader +{ + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + private readonly ReadOnlySpan bytes; + private int position; + + /// Starts at the first byte of a record payload, excluding its length and leaf code. + /// The original bounded record payload. + internal PdbRecordReader(ReadOnlySpan bytes) => this.bytes = bytes; + + /// Gets the number of unconsumed original bytes. + internal readonly int Remaining => this.bytes.Length - this.position; + + /// Reads an unsigned one-byte wire value. + /// The original value. + internal byte Byte() => this.Take(1)[0]; + + /// Reads a little-endian unsigned two-byte wire value. + /// The original value. + internal ushort UInt16() => BinaryPrimitives.ReadUInt16LittleEndian(this.Take(2)); + + /// Reads a little-endian unsigned four-byte wire value. + /// The original value. + internal uint UInt32() => BinaryPrimitives.ReadUInt32LittleEndian(this.Take(4)); + + /// Reads a CodeView integral numeric leaf without narrowing unsigned 64-bit values. + /// The recorded signed or unsigned integer. + /// The leaf is truncated or is not a supported integral encoding. + internal Int128 Integer() + { + ushort leaf = this.UInt16(); + if (leaf < 0x8000) + { + return leaf; + } + + return leaf switch + { + 0x8000 => unchecked((sbyte)this.Byte()), + 0x8001 => BinaryPrimitives.ReadInt16LittleEndian(this.Take(2)), + 0x8002 => this.UInt16(), + 0x8003 => BinaryPrimitives.ReadInt32LittleEndian(this.Take(4)), + 0x8004 => this.UInt32(), + 0x8009 => BinaryPrimitives.ReadInt64LittleEndian(this.Take(8)), + 0x800A => BinaryPrimitives.ReadUInt64LittleEndian(this.Take(8)), + _ => throw new CStructLayoutException($"Native PDB numeric leaf 0x{leaf:X4} is not a supported integral encoding."), + }; + } + + /// Reads a nonnegative byte or element count that fits the memory-schema extent model. + /// The original bounded count. + /// The count is negative, too large or malformed. + internal int Size() + { + Int128 value = this.Integer(); + if (value < 0 || value > int.MaxValue) + { + throw new CStructLayoutException("Native PDB metadata contains an out-of-range storage size or member offset."); + } + + return (int)value; + } + + /// Reads a terminated UTF-8 name without replacing malformed source bytes. + /// The complete recorded name, excluding its terminator. + /// The name is unterminated, oversized or malformed UTF-8. + internal string Name() + { + ReadOnlySpan rest = this.bytes[this.position..]; + int length = rest.IndexOf((byte)0); + if (length < 0 || length > 65_535) + { + throw new CStructLayoutException("Native PDB metadata has an unterminated or oversized name."); + } + + ReadOnlySpan name = this.Take(length + 1)[..length]; + try + { + return StrictUtf8.GetString(name); + } + catch (DecoderFallbackException exception) + { + throw new CStructLayoutException("Native PDB metadata has a malformed UTF-8 name.", exception); + } + } + + /// Consumes one complete CodeView alignment run if it precedes the next field. + /// True when padding was present. + /// The declared padding is truncated or inconsistent. + internal bool Padding() + { + if (this.Remaining == 0 || this.bytes[this.position] < 0xF0) + { + return false; + } + + int count = this.Byte() - 0xF0; + if (count == 0) + { + throw new CStructLayoutException("Native PDB metadata has a zero-length padding run."); + } + + for (int remaining = count - 1; remaining > 0; remaining--) + { + if (this.Byte() != 0xF0 + remaining) + { + throw new CStructLayoutException("Native PDB metadata has an inconsistent padding run."); + } + } + + return true; + } + + /// Accepts at most three uninterpreted symbol-alignment bytes after the terminated name. + /// More than one alignment interval remains. + internal void EndSymbol() + { + if (this.Remaining <= 3) + { + this.position = this.bytes.Length; + return; + } + + this.End(); + } + + /// Requires the known record to end after its optional CodeView alignment bytes. + /// Unclaimed bytes remain after the known fields. + internal void End() + { + while (this.Padding()) + { + } + + if (this.Remaining != 0) + { + throw new CStructLayoutException("Native PDB metadata has unclaimed bytes after a known record."); + } + } + + /// Advances only after the entire requested field has been proved inside the record. + /// Number of bytes to consume. + /// The original field bytes. + /// The field is truncated. + private ReadOnlySpan Take(int count) + { + if (count < 0 || count > this.Remaining) + { + throw new CStructLayoutException("Native PDB metadata contains a truncated CodeView record."); + } + + ReadOnlySpan value = this.bytes.Slice(this.position, count); + this.position += count; + return value; + } +} diff --git a/tests/CStructSharp.AotConsumer/Program.cs b/tests/CStructSharp.AotConsumer/Program.cs index 24acf80a..20b6d156 100644 --- a/tests/CStructSharp.AotConsumer/Program.cs +++ b/tests/CStructSharp.AotConsumer/Program.cs @@ -151,6 +151,23 @@ Check(callerValues[0] == 42, "caller-owned bulk array"); Check(!memorySchema.TryBind("word", string.Empty, out _, out _), "structured wrong type"); +// Native aliases become a promoted union group: distinct scalar views and exact group storage without a runtime layout. +var nativeMetadata = new CStructSharp.Memory.Metadata.IsfMetadata(System.Text.Encoding.UTF8.GetBytes(""" +{"metadata":{"format":"6.1.0"},"base_types":{"u16":{"kind":"int","size":2,"signed":false,"endian":"little"},"u32":{"kind":"int","size":4,"signed":false,"endian":"little"}},"user_types":{"native":{"kind":"struct","size":4,"fields":{"whole":{"offset":0,"type":{"kind":"base","name":"u32"}},"low":{"offset":0,"type":{"kind":"base","name":"u16"}}}}}} +""")); +var nativeImport = nativeMetadata.Import("native"); +var nativeSession = new MemorySession(nativeImport.Schema); +byte[] nativeBytes = [0x78, 0x56, 0x34, 0x12,]; +var nativeSource = new ByteArrayMemorySource("native input", nativeBytes); +var nativeRegion = new MemoryRegion(nativeSource, 0, nativeBytes.Length); +var nativeValue = (IReadOnlyDictionary)nativeSession.Read(nativeRegion, nativeImport.RootTypeId)!; +Check((uint)nativeValue["whole"]! == 0x12345678 && (ushort)nativeValue["low"]! == 0x5678, "native alias values"); +var nativeGroup = (UnionValue)nativeSession.Read(nativeRegion, nativeImport.RootTypeId, "__overlay_0")!; +var nativeWhole = new Dictionary { ["__overlay_0"] = nativeGroup, }; +Check(nativeSession.Serialize(nativeImport.RootTypeId, nativeWhole).AsSpan().SequenceEqual(nativeBytes), "native storage round trip"); +nativeSession.PlanUpdate(nativeRegion, nativeImport.RootTypeId, "low", (ushort)0xCAFE).Commit(); +Check(nativeSource.ToArray().AsSpan().SequenceEqual(new byte[] { 0xFE, 0xCA, 0x34, 0x12, }), "native selected write"); + Console.WriteLine("PASS Native AOT consumer"); return 0; diff --git a/tests/CStructSharpTests/Api/PublicApiSurfaceTests.cs b/tests/CStructSharpTests/Api/PublicApiSurfaceTests.cs index d784c4d4..52819ac7 100644 --- a/tests/CStructSharpTests/Api/PublicApiSurfaceTests.cs +++ b/tests/CStructSharpTests/Api/PublicApiSurfaceTests.cs @@ -117,6 +117,7 @@ public class PublicApiSurfaceTests "CStructSharp.Memory.Metadata.IsfTypeDescription", "CStructSharp.Memory.Metadata.MetadataImportOptions", "CStructSharp.Memory.Metadata.MetadataImportResult", + "CStructSharp.Memory.Metadata.PdbMetadata", "CStructSharp.Memory.OverlayMemorySource", "CStructSharp.Memory.PointerRequest", "CStructSharp.Memory.PortableMemorySchema", diff --git a/tests/CStructSharpTests/Memory/MemoryFuzzTests.cs b/tests/CStructSharpTests/Memory/MemoryFuzzTests.cs index e080c1ac..cdb07d6a 100644 --- a/tests/CStructSharpTests/Memory/MemoryFuzzTests.cs +++ b/tests/CStructSharpTests/Memory/MemoryFuzzTests.cs @@ -29,7 +29,7 @@ public void Mappings_RandomRangesMatchIndependentBytes() int count = random.Next(1, expected.Length - start + 1); byte[] actual = new byte[count]; var budget = new MemoryAccessContext { MaxTotalBytes = count, MaxRequests = 20, }; - Assert.AreEqual(count, mapped.Read(address + (uint)start, actual, budget)); + new MemoryRegion(mapped, address + (uint)start, count).ReadExactly(actual, budget); CollectionAssert.AreEqual(expected.AsSpan(start, count).ToArray(), actual); Assert.AreEqual(count, budget.BytesRequested); Assert.AreEqual(count, mapped.Describe(address + (uint)start, count).Sum(region => region.Length)); diff --git a/tests/CStructSharpTests/Memory/MemoryIsfCoverageTests.cs b/tests/CStructSharpTests/Memory/MemoryIsfCoverageTests.cs index 25faa05d..213f8158 100644 --- a/tests/CStructSharpTests/Memory/MemoryIsfCoverageTests.cs +++ b/tests/CStructSharpTests/Memory/MemoryIsfCoverageTests.cs @@ -76,7 +76,7 @@ public void Isf_ExercisesValueKindsAndProvenance() Assert.AreEqual(42U, values["number"]); } - /// Wrong versions, unsupported kinds, invalid references, and mismatched target settings fail explicitly. + /// Wrong versions, unsupported kinds and invalid references fail explicitly. [TestMethod] public void Isf_RejectsMalformedRepresentations() { @@ -87,7 +87,6 @@ public void Isf_RejectsMalformedRepresentations() ("\"kind\":\"class\"", "\"kind\":\"unknown\""), ("\"kind\":\"bool\"", "\"kind\":\"unknown\""), ("\"kind\":\"array\"", "\"kind\":\"unknown\""), - ("\"base\":\"u64\"", "\"base\":\"u32\""), ("\"count\":2", "\"count\":-1"), ("\"ZERO_0\"", "\"bad-name\""), }) diff --git a/tests/CStructSharpTests/Memory/MemoryIsfOverlayTests.cs b/tests/CStructSharpTests/Memory/MemoryIsfOverlayTests.cs new file mode 100644 index 00000000..f0840f4d --- /dev/null +++ b/tests/CStructSharpTests/Memory/MemoryIsfOverlayTests.cs @@ -0,0 +1,192 @@ +namespace CStructSharp.Tests; + +using System.Text; +using CStructSharp.Diagnostics; +using CStructSharp.Memory; +using CStructSharp.Memory.Metadata; +using CStructSharp.Values; + +/// Independent native-style ISF aliases preserve named byte views without relaxing ordinary struct validation. +[TestClass] +public class MemoryIsfOverlayTests +{ + private const string Overlaid = """ + {"metadata":{"format":"6.2.0"}, + "base_types":{ + "u16":{"kind":"int","size":2,"signed":false,"endian":"little"}, + "u32":{"kind":"int","size":4,"signed":false,"endian":"little"} + }, + "user_types":{"record":{"kind":"struct","size":8,"fields":{ + "whole":{"offset":0,"type":{"kind":"base","name":"u32"}}, + "part":{"offset":0,"type":{"kind":"base","name":"u16"}}, + "flag":{"offset":0,"type":{"kind":"bitfield","bit_position":16,"bit_length":8,"type":{"kind":"base","name":"u32"}}}, + "tail":{"offset":6,"type":{"kind":"base","name":"u16"}} + }}},"enums":{},"symbols":{}} + """; + + /// Both documented revisions import native scalar records without rewriting the input version. + /// The source document's declared revision. + [TestMethod] + [DataRow("6.1.0")] + [DataRow("6.2.0")] + public void SupportedVersions_ImportTheirOriginalBytes(string version) + { + string json = "{\"metadata\":{\"format\":\"" + version + "\"},\"base_types\":{\"u32\":{\"kind\":\"int\",\"size\":4,\"signed\":false,\"endian\":\"little\"}},\"user_types\":{\"record\":{\"kind\":\"struct\",\"size\":4,\"fields\":{\"value\":{\"offset\":0,\"type\":{\"kind\":\"base\",\"name\":\"u32\"}}}}},\"enums\":{},\"symbols\":{}}"; + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(json)); + MetadataImportResult imported = metadata.Import("record"); + var session = new MemorySession(imported.Schema); + var region = new MemoryRegion(new ByteArrayMemorySource("input", [0x78, 0x56, 0x34, 0x12,]), 0, 4); + + Assert.AreEqual(MemoryTypeKind.Struct, imported.Schema.GetType(imported.RootTypeId).Kind); + Assert.AreEqual(0x12345678U, session.Read(region, imported.RootTypeId, "value")); + Assert.AreEqual("struct", metadata.Describe("record").Kind); + } + + /// Flat aliases move into one promoted union view; original paths, offsets and bit slices stay valid. + [TestMethod] + public void FlatAliases_GroupIntoPromotedUnionAndKeepOriginalPaths() + { + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(Overlaid)); + MetadataImportResult imported = metadata.Import("record"); + MemoryTypeDefinition record = imported.Schema.GetType(imported.RootTypeId); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0x78, 0x56, 0x34, 0x12, 0xA5, 0x5A, 0xEF, 0xBE,]; + var source = new ByteArrayMemorySource("input", bytes); + var region = new MemoryRegion(source, 0, bytes.Length); + + Assert.AreEqual(MemoryTypeKind.Struct, record.Kind); + Assert.AreEqual("struct", metadata.Describe("record").Kind); + CollectionAssert.AreEqual(new[] { "__overlay_0", "tail", }, record.Fields.Select(field => field.Name).ToArray()); + Assert.IsTrue(record.Fields[0].Promoted); + MemoryTypeDefinition overlay = imported.Schema.GetType(record.Fields[0].TypeId); + Assert.AreEqual(MemoryTypeKind.Union, overlay.Kind); + Assert.AreEqual(4, overlay.Size); + CollectionAssert.AreEqual(new[] { "whole", "part", "flag", }, overlay.Fields.Select(field => field.Name).ToArray()); + Assert.AreEqual(6, imported.Schema.GetField(record.Id, "tail").Offset); + Assert.AreEqual(0x12345678U, session.Read(region, record.Id, "whole")); + Assert.AreEqual((ushort)0x5678, session.Read(region, record.Id, "part")); + Assert.AreEqual(0x34, session.Read(region, record.Id, "flag")); + Assert.AreEqual((ushort)0xBEEF, session.Read(region, record.Id, "tail")); + + // A whole value names the group by its overlay member; the aliased bytes round-trip from the read union. + var group = (UnionValue)session.Read(region, record.Id, "__overlay_0")!; + var whole = new Dictionary { ["__overlay_0"] = group, ["tail"] = (ushort)0xBEEF, }; + CollectionAssert.AreEqual(new byte[] { 0x78, 0x56, 0x34, 0x12, 0, 0, 0xEF, 0xBE, }, session.Serialize(record.Id, whole)); + Assert.Throws(() => session.Serialize(record.Id, new Dictionary { ["whole"] = 1U, ["part"] = (ushort)2, ["tail"] = (ushort)3, })); + session.PlanUpdate(region, record.Id, "part", (ushort)0xCAFE).Commit(); + CollectionAssert.AreEqual(new byte[] { 0xFE, 0xCA, 0x34, 0x12, 0xA5, 0x5A, 0xEF, 0xBE, }, source.ToArray()); + } + + /// Selecting one alias of a group rewrites only that group; unrelated struct members keep their values. + [TestMethod] + public void OverlayWrite_LeavesUnrelatedMembersIntact() + { + const string Profile = """ + {"metadata":{"format":"6.2.0"},"base_types":{ + "u16":{"kind":"int","size":2,"signed":false,"endian":"little"}, + "u32":{"kind":"int","size":4,"signed":false,"endian":"little"} + },"user_types":{"record":{"kind":"struct","size":8,"fields":{ + "a":{"offset":0,"type":{"kind":"base","name":"u32"}}, + "whole":{"offset":4,"type":{"kind":"base","name":"u32"}}, + "low":{"offset":4,"type":{"kind":"base","name":"u16"}} + }}},"enums":{},"symbols":{}} + """; + MetadataImportResult imported = new IsfMetadata(Encoding.UTF8.GetBytes(Profile)).Import("record"); + MemoryTypeDefinition record = imported.Schema.GetType(imported.RootTypeId); + var session = new MemorySession(imported.Schema); + + Assert.AreEqual(MemoryTypeKind.Struct, record.Kind); + CollectionAssert.AreEqual(new[] { "a", "__overlay_4", }, record.Fields.Select(field => field.Name).ToArray()); + var value = new Dictionary + { + ["a"] = 0x11223344U, + ["__overlay_4"] = UnionValue.FromMember("__overlay_4", "whole", 0xAABBCCDDU), + }; + byte[] bytes = session.Serialize(record.Id, value); + CollectionAssert.AreEqual(new byte[] { 0x44, 0x33, 0x22, 0x11, 0xDD, 0xCC, 0xBB, 0xAA, }, bytes); + var region = new MemoryRegion(new ByteArrayMemorySource("input", bytes), 0, bytes.Length); + Assert.AreEqual(0x11223344U, session.Read(region, record.Id, "a")); + Assert.AreEqual((ushort)0xCCDD, session.Read(region, record.Id, "low")); + } + + /// A selected overlay stays addressable by its original member paths and keeps projection metadata. + [TestMethod] + public void SelectedAliases_PreserveProjectionAndOriginalPaths() + { + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(Overlaid)); + MetadataImportResult imported = metadata.ImportProjection("record", ["whole", "part"]); + var session = new MemorySession(imported.Schema); + var region = new MemoryRegion(new ByteArrayMemorySource("input", [0x78, 0x56, 0x34, 0x12,]), 0, 8); + + Assert.AreEqual(MemoryTypeKind.Struct, imported.Schema.GetType(imported.RootTypeId).Kind); + Assert.IsTrue(imported.Schema.GetType(imported.RootTypeId).IsProjected); + CollectionAssert.AreEqual(new[] { "flag", "tail", }, imported.Schema.GetType(imported.RootTypeId).UnselectedMembers.ToArray()); + Assert.AreEqual((ushort)0x5678, session.Read(region, imported.RootTypeId, "part")); + Assert.AreEqual(0x12345678U, session.Read(region, imported.RootTypeId, "whole")); + Assert.Throws(() => session.Read(region, imported.RootTypeId, "tail")); + } + + /// Disjoint physical bits remain a struct even when their scalar storage units overlap in bytes. + [TestMethod] + public void DisjointBigEndianBits_AreNotChangedIntoAlternativeViews() + { + const string Profile = """ + {"metadata":{"format":"6.2.0"},"base_types":{ + "u8":{"kind":"int","size":1,"signed":false,"endian":"little"}, + "u16":{"kind":"int","size":2,"signed":false,"endian":"big"} + },"user_types":{"record":{"kind":"struct","size":2,"fields":{ + "first":{"offset":0,"type":{"kind":"base","name":"u8"}}, + "low":{"offset":0,"type":{"kind":"bitfield","bit_position":0,"bit_length":4,"type":{"kind":"base","name":"u16"}}} + }}},"enums":{},"symbols":{}} + """; + MetadataImportResult imported = new IsfMetadata(Encoding.UTF8.GetBytes(Profile)).Import("record"); + var session = new MemorySession(imported.Schema); + var region = new MemoryRegion(new ByteArrayMemorySource("input", [0x12, 0x3F,]), 0, 2); + + Assert.AreEqual(MemoryTypeKind.Struct, imported.Schema.GetType(imported.RootTypeId).Kind); + Assert.AreEqual((byte)0x12, session.Read(region, imported.RootTypeId, "first")); + Assert.AreEqual(15, session.Read(region, imported.RootTypeId, "low")); + } + + /// Allowing native aliases does not make out-of-extent members or by-value recursive records valid. + [TestMethod] + public void InvalidNativeViews_StillFailTheirIndependentSchemaConstraints() + { + string outside = Overlaid.Replace("\"offset\":6", "\"offset\":7", StringComparison.Ordinal); + Assert.Throws(() => new IsfMetadata(Encoding.UTF8.GetBytes(outside)).Import("record")); + string recursive = Overlaid.Replace("\"whole\":{\"offset\":0,\"type\":{\"kind\":\"base\",\"name\":\"u32\"}}", "\"whole\":{\"offset\":0,\"type\":{\"kind\":\"struct\",\"name\":\"record\"}}", StringComparison.Ordinal); + Assert.Throws(() => new IsfMetadata(Encoding.UTF8.GetBytes(recursive)).Import("record")); + var scalar = new MemoryTypeDefinition("u32", "u32", MemoryTypeKind.Scalar, 4, scalarType: "uint32"); + var ordinary = new MemoryTypeDefinition("ordinary", "ordinary", MemoryTypeKind.Struct, 4, [new("first", "u32", 0), new("second", "u32", 0),]); + Assert.Throws(() => new MemorySchema([scalar, ordinary])); + } + + /// Recursive native pointers retain the requested target width and aliases do not consume extra descriptor identities. + /// The captured target's pointer width in bytes. + [TestMethod] + [DataRow(4)] + [DataRow(8)] + public void NativePointers_KeepTargetWidthAndDescriptorBudget(int pointerSize) + { + const string Profile = """ + {"metadata":{"format":"6.1.0"},"base_types":{"u32":{"kind":"int","size":4,"signed":false,"endian":"little"}}, + "user_types":{"record":{"kind":"struct","size":16,"fields":{ + "value":{"offset":0,"type":{"kind":"base","name":"u32"}}, + "alias":{"offset":0,"type":{"kind":"base","name":"u32"}}, + "next":{"offset":8,"type":{"kind":"pointer","subtype":{"kind":"struct","name":"record"}}} + }}},"enums":{},"symbols":{}} + """; + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(Profile)); + MetadataImportResult imported = metadata.Import("record", new MetadataImportOptions { PointerSize = pointerSize, MaxTypes = 3, }); + var session = new MemorySession(imported.Schema); + byte[] bytes = new byte[32]; + bytes[0] = 42; + bytes[8] = 16; + bytes[16] = 99; + var region = new MemoryRegion(new ByteArrayMemorySource("input", bytes), 0, 16); + + Assert.AreEqual(new StoredPointer(16, pointerSize), session.Read(region, imported.RootTypeId, "next")); + Assert.AreEqual(99U, session.Read(region, imported.RootTypeId, "next.value.alias")); + Assert.Throws(() => metadata.Import("record", new MetadataImportOptions { PointerSize = pointerSize, MaxTypes = 2, })); + } +} diff --git a/tests/CStructSharpTests/Memory/MemoryIsfPointerStorageTests.cs b/tests/CStructSharpTests/Memory/MemoryIsfPointerStorageTests.cs new file mode 100644 index 00000000..4a496587 --- /dev/null +++ b/tests/CStructSharpTests/Memory/MemoryIsfPointerStorageTests.cs @@ -0,0 +1,89 @@ +namespace CStructSharp.Tests; + +using System.Text; +using CStructSharp.Diagnostics; +using CStructSharp.Memory; +using CStructSharp.Memory.Metadata; + +/// Explicit ISF pointer storage survives native/WOW64 records independently of the schema's default pointer width. +[TestClass] +public class MemoryIsfPointerStorageTests +{ + private const string Mixed = """ + {"metadata":{"format":"6.2.0"},"base_types":{ + "byte":{"kind":"int","size":1,"signed":false,"endian":"little"}, + "ptr32":{"kind":"int","size":4,"signed":false,"endian":"little"}, + "ptr64":{"kind":"int","size":8,"signed":false,"endian":"little"}}, + "user_types":{"record":{"kind":"struct","size":12,"fields":{ + "narrow":{"offset":0,"type":{"kind":"pointer","base":"ptr32","subtype":{"kind":"base","name":"byte"}}}, + "wide":{"offset":4,"type":{"kind":"pointer","base":"ptr64","subtype":{"kind":"base","name":"byte"}}}}}}, + "enums":{},"symbols":{}} + """; + + /// Explicit stored widths decode, round-trip and update without widening or truncating a neighboring pointer. + /// Default target width for pointers without explicit storage. + [TestMethod] + [DataRow(4)] + [DataRow(8)] + public void ExplicitPointerWidths_KeepStoredBitsAndNeighboringBytes(int defaultWidth) + { + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(Mixed)); + MetadataImportResult imported = metadata.Import("record", new MetadataImportOptions { PointerSize = defaultWidth }); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0x78, 0x56, 0x34, 0x12, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01,]; + var source = new ByteArrayMemorySource("mixed-native-pointers", bytes); + var region = new MemoryRegion(source, 0, bytes.Length); + Assert.AreEqual(new StoredPointer(0x12345678, 4), session.Read(region, imported.RootTypeId, "narrow")); + Assert.AreEqual(new StoredPointer(0x0123456789ABCDEF, 8), session.Read(region, imported.RootTypeId, "wide")); + CollectionAssert.AreEqual(bytes, session.Serialize(imported.RootTypeId, session.Read(region, imported.RootTypeId))); + session.PlanUpdate(region, imported.RootTypeId, "narrow", new StoredPointer(0xAABBCCDD, 4)).Commit(); + CollectionAssert.AreEqual(new byte[] { 0xDD, 0xCC, 0xBB, 0xAA, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, }, source.ToArray()); + } + + /// Field-directed inspection retains each pointer's explicit representation rather than replacing it with the target default. + [TestMethod] + public void ProjectedPointerWidths_KeepBothRepresentations() + { + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(Mixed)); + MetadataImportResult imported = metadata.ImportProjection("record", ["narrow", "wide"]); + var session = new MemorySession(imported.Schema); + var region = new MemoryRegion(new ByteArrayMemorySource("mixed", [0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,]), 0, 12); + Assert.AreEqual(new StoredPointer(uint.MaxValue, 4), session.Read(region, imported.RootTypeId, "narrow")); + Assert.AreEqual(new StoredPointer(ulong.MaxValue - 1, 8), session.Read(region, imported.RootTypeId, "wide")); + } + + /// An explicit storage base supplies the pointer's byte order as well as its width, overriding the schema default. + /// Recorded byte order of the pointer's storage base. + /// Default byte order passed to the importer. + [TestMethod] + [DataRow("big", true)] + [DataRow("little", false)] + public void ExplicitPointerStorage_KeepsItsByteOrder(string baseEndian, bool schemaLittleEndian) + { + string profile = Mixed.Replace("\"ptr32\":{\"kind\":\"int\",\"size\":4,\"signed\":false,\"endian\":\"little\"}", $"\"ptr32\":{{\"kind\":\"int\",\"size\":4,\"signed\":false,\"endian\":\"{baseEndian}\"}}", StringComparison.Ordinal); + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(profile), isLittleEndian: schemaLittleEndian); + MetadataImportResult imported = metadata.Import("record"); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0x12, 0x34, 0x56, 0x78, 0, 0, 0, 0, 0, 0, 0, 0,]; + var region = new MemoryRegion(new ByteArrayMemorySource("ordered-pointer", bytes), 0, bytes.Length); + ulong expected = baseEndian == "big" ? 0x12345678UL : 0x78563412UL; + + Assert.AreEqual(new StoredPointer(expected, 4), session.Read(region, imported.RootTypeId, "narrow")); + CollectionAssert.AreEqual(bytes, session.Serialize(imported.RootTypeId, session.Read(region, imported.RootTypeId))); + } + + /// A pointer cannot borrow floating-point, boolean or unsupported-width storage from a malformed profile. + /// Recorded base category. + /// Recorded storage width in bytes. + [TestMethod] + [DataRow("float", 4)] + [DataRow("bool", 4)] + [DataRow("int", 3)] + [DataRow("int", 16)] + public void InvalidPointerStorage_RejectsNonintegralOrUnsupportedRepresentations(string kind, int size) + { + string profile = Mixed.Replace("\"ptr32\":{\"kind\":\"int\",\"size\":4", $"\"ptr32\":{{\"kind\":\"{kind}\",\"size\":{size}", StringComparison.Ordinal); + var metadata = new IsfMetadata(Encoding.UTF8.GetBytes(profile)); + Assert.Throws(() => metadata.Import("record")); + } +} diff --git a/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs b/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs new file mode 100644 index 00000000..17bb94d0 --- /dev/null +++ b/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs @@ -0,0 +1,958 @@ +namespace CStructSharp.Tests; + +using System.Buffers.Binary; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using CStructSharp.Diagnostics; +using CStructSharp.Memory; +using CStructSharp.Memory.Metadata; + +/// Independent MSF/CodeView fixtures exercise native preparation without a debugger or publisher PDB dependency. +[TestClass] +public class MemoryPdbMetadataTests +{ + /// Target identities, logical segments and mixed-width fields survive preparation and real memory reads. + [TestMethod] + public void PreparedProfile_KeepsIdentitySymbolsAndMixedPointerStorage() + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new MemoryStream(fixture.Bytes); + input.Position = 17; + var metadata = new PdbMetadata(input); + Assert.AreEqual(17L, input.Position); + Assert.AreEqual(new Guid("12345678-9abc-def0-1234-56789abcdef0"), metadata.Guid); + Assert.AreEqual(7U, metadata.InformationAge); + Assert.AreEqual(2U, metadata.DbiAge); + Assert.AreEqual(0x1020UL, metadata.Symbols["OriginalData"]); + Assert.AreEqual(0x1040UL, metadata.Symbols["TypedData"]); + Assert.AreEqual(0x12345678UL, metadata.AbsoluteSymbols["absoluteGuard"]); + Assert.IsFalse(metadata.Symbols.ContainsKey("absoluteGuard")); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + byte[] prepared = output.ToArray(); + using JsonDocument profile = JsonDocument.Parse(prepared); + Assert.AreEqual(0x8664, profile.RootElement.GetProperty("metadata").GetProperty("windows").GetProperty("pdb").GetProperty("machine_type").GetInt32()); + var isf = new IsfMetadata(prepared); + MetadataImportResult imported = isf.Import("record"); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0xD4, 0xC3, 0xB2, 0xA1, 0x78, 0x56, 0x34, 0x12, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01,]; + var region = new MemoryRegion(new ByteArrayMemorySource("native-record", bytes), 0, bytes.Length); + Assert.AreEqual(0xA1B2C3D4U, session.Read(region, imported.RootTypeId, "value")); + Assert.AreEqual(new StoredPointer(0x12345678, 4), session.Read(region, imported.RootTypeId, "narrow")); + Assert.AreEqual(new StoredPointer(0x0123456789ABCDEF, 8), session.Read(region, imported.RootTypeId, "wide")); + CollectionAssert.AreEqual(bytes, session.Serialize(imported.RootTypeId, session.Read(region, imported.RootTypeId))); + Assert.AreEqual(0x1040UL, isf.Symbols["TypedData"]); + } + + /// Conventional native-pointer references decode with the DBI machine width independently of explicit narrow storage. + /// Original COFF machine identifier. + /// Expected native address storage, in bytes. + [TestMethod] + [DataRow(0x14C, 4)] + [DataRow(0x8664, 8)] + [DataRow(0xAA64, 8)] + public void PreparedNativePointerBase_DecodesOriginalArchitectureWidth(int machine, int nativeWidth) + { + Fixture fixture = CreateFixture(BasicTypes()); + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 58), checked((ushort)machine)); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + JsonNode profile = JsonNode.Parse(output.ToArray())!; + + // An ordinary ISF consumer can reference the native pointer base instead of a CodeView-width alias. + profile["user_types"]!["record"]!["fields"]!["wide"]!["type"]!["base"] = "pointer"; + var isf = new IsfMetadata(Encoding.UTF8.GetBytes(profile.ToJsonString())); + MetadataImportResult imported = isf.Import("record"); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0xD4, 0xC3, 0xB2, 0xA1, 0x78, 0x56, 0x34, 0x12, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01,]; + var region = new MemoryRegion(new ByteArrayMemorySource("native-pointer-consumer", bytes), 0, bytes.Length); + ulong address = nativeWidth == 4 ? 0x89ABCDEFUL : 0x0123456789ABCDEFUL; + + Assert.AreEqual(new StoredPointer(address, nativeWidth), session.Read(region, imported.RootTypeId, "wide")); + Assert.AreEqual(new StoredPointer(0x12345678, 4), session.Read(region, imported.RootTypeId, "narrow")); + } + + /// Legacy flat-pointer kinds retain their own width when no size bits were written, including mixed-width arrays. + /// The independently recorded native machine, not the width of every pointer. + [TestMethod] + [DataRow(0x14C)] + [DataRow(0x8664)] + public void LegacyFlatPointerKinds_DecodeImplicitWidthsAndArrayExtents(int machine) + { + byte[][] types = + [ + + // Older producers omit the separate size bits even though the flat kind defines four bytes. + Record(0x1002, Payload(writer => + { + writer.Write(0x75U); + writer.Write(10U); + })), + + // A near64 pointer stays eight bytes even inside an x86 database. + Record(0x1002, Payload(writer => + { + writer.Write(0x75U); + writer.Write(12U); + })), + + // Array element sizing must use that same implicit pointer representation. + Record(0x1503, Payload(writer => + { + writer.Write(0x1000U); + writer.Write(0x75U); + writer.Write((ushort)8); + writer.Write((byte)0); + })), + Record(0x1203, [.. Member("narrow", 0x1000, 0), .. Member("wide", 0x1001, 4), .. Member("links", 0x1002, 12)]), + Composite("record", 3, 0x1003, 20), + ]; + Fixture fixture = CreateFixture(types, rootType: 0x1004); + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 58), checked((ushort)machine)); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + var isf = new IsfMetadata(output.ToArray()); + MetadataImportResult imported = isf.Import("record"); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0x44, 0x33, 0x22, 0x11, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0x88, 0x77, 0x66, 0x55, 0xCC, 0xBB, 0xAA, 0x99]; + var region = new MemoryRegion(new ByteArrayMemorySource("legacy-native-pointers", bytes), 0, bytes.Length); + + Assert.AreEqual(new StoredPointer(0x11223344, 4), session.Read(region, imported.RootTypeId, "narrow")); + Assert.AreEqual(new StoredPointer(0x0123456789ABCDEF, 8), session.Read(region, imported.RootTypeId, "wide")); + Assert.AreEqual(new StoredPointer(0x55667788, 4), session.Read(region, imported.RootTypeId, "links[0]")); + Assert.AreEqual(new StoredPointer(0x99AABBCC, 4), session.Read(region, imported.RootTypeId, "links[1]")); + CollectionAssert.AreEqual(bytes, session.Serialize(imported.RootTypeId, session.Read(region, imported.RootTypeId))); + } + + /// Implicit legacy sizes do not admit contradictory widths, segmented storage or member-pointer modes. + /// Original CodeView kind, mode and optional size bits. + [TestMethod] + [DataRow(10U | (8U << 13))] + [DataRow(12U | (4U << 13))] + [DataRow(11U)] + [DataRow(10U | (2U << 5))] + public void LegacyFlatPointerKinds_RejectContradictoryOrNonflatRepresentations(uint attributes) + { + byte[][] types = + [ + + // Keep the conflicting attributes intact until ordinary descriptor validation. + Record(0x1002, Payload(writer => + { + writer.Write(0x75U); + writer.Write(attributes); + })), + Record(0x1203, Member("value", 0x1000, 0)), + Composite("record", 1, 0x1001, 8), + ]; + Fixture fixture = CreateFixture(types, rootType: 0x1002); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + + // Invalid native storage must not become an apparently usable imported field. + Assert.Throws(() => metadata.WriteIsf(output, "fixture.pdb")); + } + + /// An explicit target supplies missing ABI information without changing the original DBI machine. + /// Caller-declared target, independent of the host and zero original DBI field. + /// The resulting native pointer storage in bytes. + [TestMethod] + [DataRow(0x14C, 4)] + [DataRow(0x8664, 8)] + public void LegacyUnknownMachine_RequiresExplicitTargetAndPreservesOriginalZero(int targetMachine, int pointerSize) + { + Fixture fixture = CreateFixture(BasicTypes()); + Put32(fixture.Bytes, fixture.StreamStarts[2], 19990903); + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 58), 0); + using var input = new MemoryStream(fixture.Bytes); + input.Position = 17; + var metadata = new PdbMetadata(input, targetMachine: checked((ushort)targetMachine)); + Assert.AreEqual(17L, input.Position); + Assert.AreEqual((ushort)0, metadata.Machine); + Assert.AreEqual(checked((ushort)targetMachine), metadata.TargetMachine); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + JsonNode profile = JsonNode.Parse(output.ToArray())!; + Assert.AreEqual(0, profile["metadata"]!["windows"]!["pdb"]!["machine_type"]!.GetValue()); + Assert.AreEqual(pointerSize, profile["base_types"]!["pointer"]!["size"]!.GetValue()); + + // An ordinary consumer can use the supplied native pointer base while retaining the unknown original machine. + profile["user_types"]!["record"]!["fields"]!["wide"]!["type"]!["base"] = "pointer"; + var isf = new IsfMetadata(Encoding.UTF8.GetBytes(profile.ToJsonString())); + MetadataImportResult imported = isf.Import("record"); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0xD4, 0xC3, 0xB2, 0xA1, 0x78, 0x56, 0x34, 0x12, 0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01]; + var region = new MemoryRegion(new ByteArrayMemorySource("explicit-legacy-abi", bytes), 0, bytes.Length); + ulong address = pointerSize == 4 ? 0x89ABCDEFUL : 0x0123456789ABCDEFUL; + + Assert.AreEqual(new StoredPointer(address, pointerSize), session.Read(region, imported.RootTypeId, "wide")); + } + + /// Unknown original architecture cannot silently adopt the analyzer's ABI. + [TestMethod] + public void LegacyUnknownMachine_WithoutExplicitTargetRejectsAndRestoresBorrowedInput() + { + Fixture fixture = CreateFixture(BasicTypes()); + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 58), 0); + using var input = new MemoryStream(fixture.Bytes); + input.Position = 17; + + // The database remains valid evidence, but it cannot choose a native ABI without target information. + Assert.Throws(() => new PdbMetadata(input)); + Assert.AreEqual(17L, input.Position); + Assert.IsTrue(input.CanRead); + } + + /// An explicit target cannot override contradictory recorded architecture, even at the same pointer width. + /// Original nonzero DBI machine. + /// Conflicting caller declaration. + [TestMethod] + [DataRow(0x14C, 0x8664)] + [DataRow(0x8664, 0x14C)] + [DataRow(0xAA64, 0x8664)] + public void ExplicitTarget_RejectsRecordedMachineContradictions(int machine, int targetMachine) + { + Fixture fixture = CreateFixture(BasicTypes()); + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 58), checked((ushort)machine)); + using var input = new MemoryStream(fixture.Bytes); + input.Position = 17; + + // Matching widths alone do not make different instruction-set identities interchangeable. + Assert.Throws(() => new PdbMetadata(input, targetMachine: checked((ushort)targetMachine))); + Assert.AreEqual(17L, input.Position); + } + + /// Invalid caller architecture declarations fail before consuming the borrowed stream. + /// An unspecified or unsupported target machine. + [TestMethod] + [DataRow(0)] + [DataRow(0x1C4)] + public void ExplicitTarget_RejectsInvalidDeclarations(int targetMachine) + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new MemoryStream(fixture.Bytes); + input.Position = 17; + + // A caller hint cannot turn an unsupported target into a valid native layout. + Assert.Throws(() => new PdbMetadata(input, targetMachine: checked((ushort)targetMachine))); + Assert.AreEqual(17L, input.Position); + } + + /// Unknown header revisions are not accepted just because one legacy layout is supported. + /// Absent, earlier or unrecognized future TPI revision. + [TestMethod] + [DataRow(0U)] + [DataRow(19970605U)] + [DataRow(20040204U)] + public void LegacyTpiHeader_RejectsOtherRevisions(uint revision) + { + Fixture fixture = CreateFixture(BasicTypes()); + Put32(fixture.Bytes, fixture.StreamStarts[2], revision); + using var input = new MemoryStream(fixture.Bytes); + + // The shared fixed-header bounds apply only to explicitly supported revisions. + Assert.Throws(() => new PdbMetadata(input)); + } + + /// Discontiguous streams and positive short reads are joined without reading unrelated file payloads. + [TestMethod] + public void MetadataReads_StayBoundedAndHandlePositiveShortReads() + { + Fixture fixture = CreateFixture(BasicTypes(), unrelatedBytes: 2 * 1024 * 1024); + using var input = new ShortReadStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + Assert.AreEqual(0x1020UL, metadata.Symbols["OriginalData"]); + Assert.IsTrue(input.ObservedBytes < 128 * 1024, $"Only selected metadata should be read, not {input.ObservedBytes} bytes."); + Assert.IsTrue(input.CanRead); + } + + /// Malformed directory and identity claims fail at their boundary rather than becoming prepared profiles. + /// Independent wire invariant to violate. + [TestMethod] + [DataRow("magic")] + [DataRow("block-width")] + [DataRow("free-map")] + [DataRow("file-extent")] + [DataRow("reserved-map")] + [DataRow("duplicate-stream-block")] + [DataRow("stream-count")] + [DataRow("identity-version")] + [DataRow("debug-version")] + [DataRow("type-count")] + [DataRow("type-record-length")] + public void MalformedNativeInput_RejectsContradictoryMetadata(string corruption) + { + Fixture fixture = CreateFixture(BasicTypes()); + byte[] bytes = fixture.Bytes; + switch (corruption) + { + case "magic": bytes[0] = 0; break; + case "block-width": Put32(bytes, 32, 3); break; + case "free-map": Put32(bytes, 36, 3); break; + case "file-extent": Put32(bytes, 40, uint.MaxValue); break; + case "reserved-map": Put32(bytes, 52, 1); break; + case "duplicate-stream-block": Put32(bytes, fixture.Directory + 36, (uint)(fixture.StreamStarts[1] / 512)); break; + case "stream-count": Put32(bytes, fixture.Directory, uint.MaxValue); break; + case "identity-version": Put32(bytes, fixture.StreamStarts[1], 0); break; + case "debug-version": Put32(bytes, fixture.StreamStarts[3] + 4, 0); break; + case "type-count": Put32(bytes, fixture.StreamStarts[2] + 12, 0x1000); break; + case "type-record-length": BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(fixture.StreamStarts[2] + 56), 1); break; + default: throw new ArgumentException("Unknown synthetic corruption.", nameof(corruption)); + } + + using var input = new MemoryStream(bytes); + Assert.Throws(() => new PdbMetadata(input)); + } + + /// A truncated original extent is an invalid input, including a file shorter than its superblock. + /// Retained prefix of the otherwise valid fixture. + [TestMethod] + [DataRow(0)] + [DataRow(55)] + [DataRow(512)] + public void TruncatedNativeInput_RejectsMissingOriginalBytes(int length) + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new MemoryStream(fixture.Bytes, 0, length, writable: false); + Assert.Throws(() => new PdbMetadata(input)); + } + + /// Input, record and export work budgets remain separate from each other and from the containing file size. + [TestMethod] + public void PreparationBudgets_RejectExcessWorkAndRetainInputOwnership() + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new MemoryStream(fixture.Bytes); + Assert.Throws(() => new PdbMetadata(input, maxMetadataBytes: 16)); + Assert.Throws(() => new PdbMetadata(input, maxRecords: 1)); + + // Input tables that fit maxRecords must not make the default export fail: export work has its own limit. + var metadata = new PdbMetadata(input, maxRecords: 4); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + Assert.IsTrue(output.Length > 0); + using var limited = new MemoryStream(); + Assert.Throws(() => metadata.WriteIsf(limited, "fixture.pdb", maxTraversalSteps: 4)); + Assert.Throws(() => metadata.WriteIsf(limited, "fixture.pdb", maxTraversalSteps: 0)); + Assert.AreEqual(0L, input.Position); + Assert.IsTrue(input.CanRead); + } + + /// C++ methods, bases, nested types, static members and vtable entries are skipped without failing the export. + [TestMethod] + public void CppFieldLists_SkipNonStorageElementsAndKeepInstanceMembers() + { + byte[] derivedFields = + [ + .. FieldLeaf(0x1400, writer => + { + // LF_BCLASS: public base at offset 8. + writer.Write((ushort)3); + writer.Write(0x1001U); + writer.Write((ushort)8); + }), + .. FieldLeaf(0x1409, writer => + { + // LF_VFUNCTAB: padding word and vtable-pointer type. + writer.Write((ushort)0); + writer.Write(0x0603U); + }), + .. FieldLeaf(0x1511, writer => + { + // LF_ONEMETHOD, introducing virtual (property 4): the extra vtable offset must be consumed. + writer.Write((ushort)((4 << 2) | 3)); + writer.Write(0x75U); + writer.Write(0x10U); + WriteName(writer, "Run"); + }), + .. FieldLeaf(0x1511, writer => + { + // LF_ONEMETHOD, plain method: no vtable offset. + writer.Write((ushort)3); + writer.Write(0x75U); + WriteName(writer, "Stop"); + }), + .. FieldLeaf(0x150F, writer => + { + // LF_METHOD: two overloads in a method list. + writer.Write((ushort)2); + writer.Write(0x75U); + WriteName(writer, "Reset"); + }), + .. FieldLeaf(0x150E, writer => + { + // LF_STMEMBER: static storage lives elsewhere, not in the instance. + writer.Write((ushort)3); + writer.Write(0x75U); + WriteName(writer, "instances"); + }), + .. FieldLeaf(0x1510, writer => + { + // LF_NESTTYPE: a type declared inside the class. + writer.Write((ushort)0); + writer.Write(0x1001U); + WriteName(writer, "Inner"); + }), + .. Member("value", 0x75, 12), + ]; + byte[][] types = + [ + Record(0x1203, Member("baseValue", 0x75, 0)), + Composite("base", 1, 0x1000, 4), + Record(0x1203, derivedFields), + Composite("derived", 8, 0x1002, 16), + ]; + Fixture fixture = CreateFixture(types, rootType: 0x1003); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + var isf = new IsfMetadata(output.ToArray()); + MetadataImportResult imported = isf.Import("derived"); + CollectionAssert.AreEqual(new[] { "value", }, imported.Schema.GetType(imported.RootTypeId).Fields.Select(field => field.Name).ToArray()); + byte[] bytes = new byte[16]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(12), 0xCAFEF00D); + var session = new MemorySession(imported.Schema); + Assert.AreEqual(0xCAFEF00DU, session.Read(new MemoryRegion(new ByteArrayMemorySource("cpp", bytes), 0, 16), imported.RootTypeId, "value")); + } + + /// The declared count is an upper bound with C++ elements present, but more instance members than declared still fail. + [TestMethod] + public void CppFieldLists_RejectMoreInstanceMembersThanDeclared() + { + byte[] stMember = FieldLeaf(0x150E, writer => + { + writer.Write((ushort)3); + writer.Write(0x75U); + WriteName(writer, "instances"); + }); + byte[][] types = [Record(0x1203, [.. stMember, .. Member("first", 0x75, 0), .. Member("second", 0x75, 4)]), Composite("record", 1, 0x1000, 8)]; + Fixture fixture = CreateFixture(types, rootType: 0x1001); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + Assert.Throws(() => metadata.WriteIsf(output, "fixture.pdb")); + } + + /// A PDB without a symbol-record stream still provides its types and an empty symbol table. + [TestMethod] + public void MissingSymbolStream_KeepsTypesWithEmptySymbols() + { + Fixture fixture = CreateFixture(BasicTypes()); + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 20), ushort.MaxValue); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + Assert.AreEqual(0, metadata.Symbols.Count); + Assert.AreEqual(0, metadata.AbsoluteSymbols.Count); + Assert.AreEqual(0, metadata.UnmappedSymbolCount); + CollectionAssert.Contains(metadata.UserTypeNames.ToArray(), "record"); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + MetadataImportResult imported = new IsfMetadata(output.ToArray()).Import("record"); + Assert.AreEqual(MemoryTypeKind.Struct, imported.Schema.GetType(imported.RootTypeId).Kind); + } + + /// File-local data names repeated across compilation units do not reject the database or publish a guessed address. + [TestMethod] + public void FileLocalSymbols_KeepUnambiguousNamesAndReportConflicts() + { + byte[] locals = + [ + .. SymbolRecord("s_lock", 0x110C, 0x75, 0x50, 1), + .. SymbolRecord("s_lock", 0x110C, 0x75, 0x60, 1), + .. SymbolRecord("solo", 0x110C, 0x75, 0x70, 1), + .. SymbolRecord("TypedData", 0x110C, 0x1001, 0x40, 1), + .. SymbolRecord("OriginalData", 0x110C, 0x75, 0x90, 1), + ]; + Fixture fixture = CreateFixture(BasicTypes(), extraSymbols: locals); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + + Assert.IsFalse(metadata.Symbols.ContainsKey("s_lock")); + Assert.AreEqual(0x1070UL, metadata.Symbols["solo"]); + Assert.AreEqual(0x1040UL, metadata.Symbols["TypedData"]); + Assert.AreEqual(0x1020UL, metadata.Symbols["OriginalData"]); + Assert.IsTrue(metadata.Diagnostics.Any(message => message.Contains("'s_lock'", StringComparison.Ordinal))); + Assert.IsTrue(metadata.Diagnostics.Any(message => message.Contains("'OriginalData'", StringComparison.Ordinal))); + Assert.AreEqual(5, metadata.SymbolRecordKinds[0x110C]); + + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + JsonNode profile = JsonNode.Parse(output.ToArray())!; + Assert.AreEqual(0x1070, profile["symbols"]!["solo"]!["address"]!.GetValue()); + Assert.AreEqual("unsigned int", profile["symbols"]!["solo"]!["type"]!["name"]!.GetValue()); + Assert.IsNull(profile["symbols"]!["s_lock"]); + } + + /// A name recorded by both a public and a global record counts once among unmapped symbols. + [TestMethod] + public void UnmappedSymbolCount_CountsDistinctNames() + { + Fixture fixture = CreateFixture(BasicTypes(), extraSymbols: SymbolRecord("absoluteGuard", 0x110D, 0x75, 0x12345678, 2)); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + Assert.AreEqual(0x12345678UL, metadata.AbsoluteSymbols["absoluteGuard"]); + Assert.AreEqual(1, metadata.UnmappedSymbolCount); + } + + /// Cancellation refuses both original reads and CPU-only output traversal without owning either stream. + [TestMethod] + public void Cancellation_LeavesBorrowedStreamsOpen() + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new MemoryStream(fixture.Bytes); + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + Assert.Throws(() => new PdbMetadata(input, cancellationToken: cancelled.Token)); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + Assert.Throws(() => metadata.WriteIsf(output, "fixture.pdb", cancellationToken: cancelled.Token)); + Assert.AreEqual(0L, output.Length); + Assert.IsTrue(input.CanRead && output.CanWrite); + } + + /// A self-referencing continuation cannot spin or publish a field list with invented members. + [TestMethod] + public void FieldListContinuationCycle_RejectsPreparation() + { + // This continuation points back to its own native type index. + byte[] continuation = Record(0x1203, Payload(writer => + { + writer.Write((ushort)0x1404); + writer.Write((ushort)0); + writer.Write(0x1000U); + })); + Fixture fixture = CreateFixture([continuation, Composite("record", 0, 0x1000, 16)]); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + Assert.Throws(() => metadata.WriteIsf(output, "fixture.pdb")); + } + + /// Every original duplicate same-extent definition remains inspectable through an explicit union, including embedded forward uses. + [TestMethod] + public void DuplicateNativeDefinitions_PreserveAllEmbeddedInterpretations() + { + byte[][] types = + [ + Composite("alternative", 0, 0, 0, forward: true), + Record(0x1203, Member("first", 0x75, 0)), + Composite("alternative", 1, 0x1001, 4), + Record(0x1203, Member("second", 0x75, 0)), + Composite("alternative", 1, 0x1003, 4), + Record(0x1203, Member("embedded", 0x1000, 0)), + Composite("record", 1, 0x1005, 4), + ]; + Fixture fixture = CreateFixture(types, rootType: 0x1006); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + var isf = new IsfMetadata(output.ToArray()); + MetadataImportResult imported = isf.Import("record"); + var session = new MemorySession(imported.Schema); + byte[] bytes = [0x78, 0x56, 0x34, 0x12,]; + var region = new MemoryRegion(new ByteArrayMemorySource("ambiguous-originals", bytes), 0, 4); + Assert.AreEqual(0x12345678U, session.Read(region, imported.RootTypeId, "embedded.cv_00001002.first")); + Assert.AreEqual(0x12345678U, session.Read(region, imported.RootTypeId, "embedded.cv_00001004.second")); + CollectionAssert.AreEqual(bytes, session.Serialize(imported.RootTypeId, session.Read(region, imported.RootTypeId))); + } + + /// OMAP changes only represented image coordinates; deleted intervals never become fake zero-RVA symbols. + [TestMethod] + public void OriginalOmap_PreservesMappedDeletedAndAbsoluteCoordinates() + { + byte[] map = new byte[16]; + Put32(map, 0, 0x1000); + Put32(map, 4, 0x2000); + Put32(map, 8, 0x1030); + Fixture fixture = CreateFixture(BasicTypes(), omap: map); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + Assert.AreEqual(0x2020UL, metadata.Symbols["OriginalData"]); + Assert.IsFalse(metadata.Symbols.ContainsKey("TypedData")); + Assert.AreEqual(0x12345678UL, metadata.AbsoluteSymbols["absoluteGuard"]); + Assert.AreEqual(2, metadata.UnmappedSymbolCount); + } + + /// Truncated, unordered, duplicate and wrapping remaps cannot publish invented symbol coordinates. + /// Original OMAP invariant to violate. + [TestMethod] + [DataRow("truncated")] + [DataRow("unordered")] + [DataRow("duplicate")] + [DataRow("wrap")] + [DataRow("missing-original-sections")] + public void InvalidOmap_RejectsAmbiguousOrUnboundedCoordinates(string corruption) + { + byte[] map = new byte[16]; + Put32(map, 0, 0x1000); + Put32(map, 4, 0x2000); + Put32(map, 8, 0x1030); + switch (corruption) + { + case "truncated": map = map[..7]; break; + case "unordered": Put32(map, 8, 0x0FFF); break; + case "duplicate": Put32(map, 8, 0x1000); break; + case "wrap": Put32(map, 4, uint.MaxValue); break; + case "missing-original-sections": break; + default: throw new ArgumentException("Unknown synthetic remap corruption.", nameof(corruption)); + } + + Fixture fixture = CreateFixture(BasicTypes(), omap: map); + if (corruption == "missing-original-sections") + { + BinaryPrimitives.WriteUInt16LittleEndian(fixture.Bytes.AsSpan(fixture.StreamStarts[3] + 128), ushort.MaxValue); + } + + using var input = new MemoryStream(fixture.Bytes); + Assert.Throws(() => new PdbMetadata(input)); + } + + /// A source that changes its original extent during a read cannot produce trusted metadata. + [TestMethod] + public void SourceLengthChange_RejectsThePreparationInput() + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new ChangedLengthStream(fixture.Bytes); + Assert.Throws(() => new PdbMetadata(input)); + } + + /// Malformed original UTF-8 type names fail instead of acquiring replacement characters. + [TestMethod] + public void InvalidNativeName_RejectsLossyMetadata() + { + byte[][] types = BasicTypes(); + Fixture fixture = CreateFixture(types); + int name = fixture.StreamStarts[2] + 56 + types[0].Length + 4 + 18; + fixture.Bytes[name] = 0xFF; + using var input = new MemoryStream(fixture.Bytes); + Assert.Throws(() => new PdbMetadata(input)); + } + + /// Creates independently declared native storage records, including explicit 32/64-bit pointer modes. + /// Full CodeView records in original index order. + private static byte[][] BasicTypes() => + [ + Record(0x1203, [.. Member("value", 0x75, 0), .. Member("narrow", 0x403, 4), .. Member("wide", 0x603, 8)]), + Composite("record", 3, 0x1000, 16), + ]; + + /// Builds a small native MSF container with original identities, logical/absolute segments and nonzero symbol padding. + /// Full original CodeView type records. + /// Optional non-metadata stream that the reader must not materialize. + /// Actual complete record identity for the typed global. + /// Optional original source-to-image remapping entries. + /// Optional complete symbol records appended after the standard public, global and absolute records. + /// The original bytes and mutation coordinates for boundary tests. + private static Fixture CreateFixture(byte[][] types, int unrelatedBytes = 0, uint rootType = 0x1001, byte[]? omap = null, byte[]? extraSymbols = null) + { + byte[] information = new byte[28]; + Put32(information, 0, 20000404); + Put32(information, 8, 7); + new Guid("12345678-9abc-def0-1234-56789abcdef0").TryWriteBytes(information.AsSpan(12)); + byte[] tpi = new byte[56 + types.Sum(type => type.Length)]; + Put32(tpi, 0, 20040203); + Put32(tpi, 4, 56); + Put32(tpi, 8, 0x1000); + Put32(tpi, 12, 0x1000U + (uint)types.Length); + Put32(tpi, 16, (uint)tpi.Length - 56); + int typeOffset = 56; + foreach (byte[] type in types) + { + type.CopyTo(tpi, typeOffset); + typeOffset += type.Length; + } + + int optionalLength = omap is null ? 12 : 22; + byte[] debug = new byte[108 + optionalLength]; + Put32(debug, 0, uint.MaxValue); + Put32(debug, 4, 19990903); + Put32(debug, 8, 2); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(20), 6); + Put32(debug, 32, 44); + Put32(debug, 48, (uint)optionalLength); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(58), 0x8664); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(64), 2); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(66), 2); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(68), 0x109); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(74), 1); + Put32(debug, 84, 0x2000); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(88), 0x208); + Put32(debug, 104, uint.MaxValue); + debug.AsSpan(108, optionalLength).Fill(0xFF); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(118), 5); + if (omap is not null) + { + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(116), 7); + BinaryPrimitives.WriteUInt16LittleEndian(debug.AsSpan(128), 8); + } + + byte[] sections = new byte[40]; + Put32(sections, 8, 0x2000); + Put32(sections, 12, 0x1000); + byte[] symbols = [.. SymbolRecord("OriginalData", 0x110E, 0, 0x20, 1), .. SymbolRecord("TypedData", 0x110D, rootType, 0x40, 1), .. SymbolRecord("absoluteGuard", 0x110E, 0, 0x12345678, 2), .. extraSymbols ?? []]; + byte[][] streams = omap is not null + ? [[], information, tpi, debug, [], sections, symbols, omap, sections] + : unrelatedBytes == 0 ? [[], information, tpi, debug, [], sections, symbols] : [[], information, tpi, debug, [], sections, symbols, new byte[unrelatedBytes]]; + int directoryLength = 4 + (streams.Length * 4) + (streams.Sum(bytes => (bytes.Length + 511) / 512) * 4); + int nextBlock = 4; + + // Directory pages must be reserved before assigning discontiguous stream payloads. + int[] directoryBlocks = Enumerable.Range(0, (directoryLength + 511) / 512).Select(_ => AllocateBlock(ref nextBlock)).ToArray(); + int[][] blocks = new int[streams.Length][]; + for (int index = 0; index < streams.Length; index++) + { + blocks[index] = new int[(streams[index].Length + 511) / 512]; + for (int page = 0; page < blocks[index].Length; page++) + { + blocks[index][page] = AllocateBlock(ref nextBlock); + } + } + + byte[] file = new byte[nextBlock * 512]; + "Microsoft C/C++ MSF 7.00\r\n\u001aDS\0\0\0"u8.CopyTo(file); + Put32(file, 32, 512); + Put32(file, 36, 1); + Put32(file, 40, (uint)nextBlock); + Put32(file, 44, (uint)directoryLength); + Put32(file, 52, 3); + byte[] directory = new byte[directoryLength]; + Put32(directory, 0, (uint)streams.Length); + int cursor = 4 + (streams.Length * 4); + int[] starts = new int[streams.Length]; + for (int index = 0; index < streams.Length; index++) + { + Put32(directory, 4 + (index * 4), (uint)streams[index].Length); + starts[index] = blocks[index].Length == 0 ? 0 : blocks[index][0] * 512; + for (int page = 0; page < blocks[index].Length; page++) + { + int block = blocks[index][page]; + Put32(directory, cursor, (uint)block); + cursor += 4; + streams[index].AsSpan(page * 512, Math.Min(512, streams[index].Length - (page * 512))).CopyTo(file.AsSpan(block * 512)); + } + } + + for (int page = 0; page < directoryBlocks.Length; page++) + { + Put32(file, (3 * 512) + (page * 4), (uint)directoryBlocks[page]); + directory.AsSpan(page * 512, Math.Min(512, directory.Length - (page * 512))).CopyTo(file.AsSpan(directoryBlocks[page] * 512)); + } + + return new(file, directoryBlocks[0] * 512, starts); + } + + /// Allocates a data block without using either periodic free-map slot. + /// Next unassigned physical block. + /// One original data-block index. + private static int AllocateBlock(ref int next) + { + while (next % 512 is 1 or 2) + { + next++; + } + + return next++; + } + + /// Creates a complete named structure record with explicit byte size and member-list identity. + /// Original native name. + /// Declared field count. + /// Original field-list index. + /// Original byte extent. + /// Whether the record is an incomplete declaration. + /// A full native type record. + private static byte[] Composite(string name, ushort count, uint fields, ushort size, bool forward = false) + { + // Native sizes and field-list identities are explicit, not recomputed from a host ABI. + return Record(0x1505, Payload(writer => + { + writer.Write(count); + writer.Write((ushort)(forward ? 0x80 : 0)); + writer.Write(fields); + writer.Write(0U); + writer.Write(0U); + writer.Write(size); + WriteName(writer, name); + })); + } + + /// Creates an instance-member leaf with a known storage reference and original placement. + /// Original member name. + /// Original storage-type index. + /// Byte offset in the containing record. + /// The unframed field leaf including alignment. + private static byte[] Member(string name, uint type, ushort offset) + { + // Field-list leaves have their own alignment but no enclosing length prefix. + byte[] bytes = Payload(writer => + { + writer.Write((ushort)0x150D); + writer.Write((ushort)0); + writer.Write(type); + writer.Write(offset); + WriteName(writer, name); + }); + return Pad(bytes); + } + + /// Creates one aligned field-list leaf from its code and payload. + /// Original field leaf code. + /// Payload writer, starting with the leaf's leading two-byte word. + /// The unframed field leaf including alignment. + private static byte[] FieldLeaf(ushort kind, Action write) + { + return Pad(Payload(writer => + { + writer.Write(kind); + write(writer); + })); + } + + /// Frames one original CodeView type record and applies its descending leaf-padding bytes. + /// Original leaf code. + /// Original payload excluding prefix. + /// The complete aligned type record. + private static byte[] Record(ushort kind, byte[] payload) + { + // The native length excludes only its own two-byte prefix. + byte[] bytes = Payload(writer => + { + writer.Write((ushort)(payload.Length + 2)); + writer.Write(kind); + writer.Write(payload); + }); + byte[] padded = Pad(bytes); + BinaryPrimitives.WriteUInt16LittleEndian(padded, (ushort)(padded.Length - 2)); + return padded; + } + + /// Creates public or typed-global symbols whose nonzero alignment bytes are not part of the name. + /// Original symbol name. + /// Native symbol kind. + /// Stored type identity or public flags. + /// Original logical segment offset. + /// Original logical segment. + /// A full native symbol record. + private static byte[] SymbolRecord(string name, ushort kind, uint type, uint offset, ushort segment) + { + // Public flags and typed-global indices share the same wire slot. + byte[] payload = Payload(writer => + { + writer.Write(type); + writer.Write(offset); + writer.Write(segment); + WriteName(writer, name); + }); + int length = (payload.Length + 7) & ~3; + byte[] bytes = new byte[length]; + bytes.AsSpan().Fill(0xA5); + BinaryPrimitives.WriteUInt16LittleEndian(bytes, (ushort)(length - 2)); + BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(2), kind); + payload.CopyTo(bytes, 4); + return bytes; + } + + /// Builds wire payloads through explicit little-endian primitive writes. + /// Independent fixture fields. + /// The original payload bytes. + private static byte[] Payload(Action write) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true); + write(writer); + writer.Flush(); + return stream.ToArray(); + } + + /// Terminates original fixture names without introducing replacement text. + /// Fixture output. + /// Complete synthetic name. + private static void WriteName(BinaryWriter writer, string name) + { + writer.Write(Encoding.UTF8.GetBytes(name)); + writer.Write((byte)0); + } + + /// Appends descending CodeView alignment bytes to a four-byte boundary. + /// Original unaligned storage. + /// A complete aligned record. + private static byte[] Pad(byte[] bytes) + { + int padding = (4 - (bytes.Length & 3)) & 3; + byte[] result = new byte[bytes.Length + padding]; + bytes.CopyTo(result, 0); + for (int index = 0; index < padding; index++) + { + result[bytes.Length + index] = (byte)(0xF0 + padding - index); + } + + return result; + } + + /// Writes a fixture's explicit little-endian unsigned field. + /// Containing fixture. + /// Byte coordinate in the fixture. + /// Original wire value. + private static void Put32(byte[] bytes, int offset, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(offset), value); + + /// Mutation coordinates belong only to this independently authored synthetic fixture. + /// Complete original bytes. + /// First directory page. + /// First physical byte of each present stream. + private sealed record Fixture(byte[] Bytes, int Directory, int[] StreamStarts); + + /// Changes the declared source length after a successful transport operation. + private sealed class ChangedLengthStream : MemoryStream + { + private int reads; + + /// Wraps independently authored mutable storage for the source-change control. + /// Original synthetic input. + public ChangedLengthStream(byte[] bytes) + : base(bytes, writable: true) + { + } + + /// + public override int Read(Span buffer) + { + int read = base.Read(buffer); + if (++this.reads == 2) + { + this.SetLength(this.Length - 1); + } + + return read; + } + } + + /// Forces positive short reads while observing only confirmed original bytes transferred. + private sealed class ShortReadStream : MemoryStream + { + /// Wraps synthetic bytes without copying their storage. + /// Original fixture bytes. + public ShortReadStream(byte[] bytes) + : base(bytes, writable: false) + { + } + + /// Gets the confirmed original byte count observed by the metadata parser. + public long ObservedBytes { get; private set; } + + /// + public override int Read(Span buffer) + { + int read = base.Read(buffer[..Math.Min(buffer.Length, 7)]); + this.ObservedBytes += read; + return read; + } + } +} diff --git a/tests/CStructSharpTests/Memory/MemoryProjectionTests.cs b/tests/CStructSharpTests/Memory/MemoryProjectionTests.cs index bc772dd2..d8a2c3ac 100644 --- a/tests/CStructSharpTests/Memory/MemoryProjectionTests.cs +++ b/tests/CStructSharpTests/Memory/MemoryProjectionTests.cs @@ -191,7 +191,9 @@ public void Isf_BitStorageDependenciesAndEnumsRetainNormalDecoding() MetadataImportResult result = metadata.ImportProjection("root", ["pointer", "bits", "tag"], new MetadataImportOptions { PointerSize = 4, }); Assert.IsFalse(result.Schema.GetType("isf:base:u32").IsUnselected); byte[] bytes = new byte[16]; - BinaryPrimitives.WriteUInt32LittleEndian(bytes, 0xF0000001); + + // The pointer's explicit storage base is big-endian u32, so the pointer is stored in that byte order. + BinaryPrimitives.WriteUInt32BigEndian(bytes, 0xF0000001); BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(4), 15); BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(8), 1); var session = new MemorySession(result.Schema); diff --git a/tests/CStructSharpTests/Memory/MemorySourceContractTests.cs b/tests/CStructSharpTests/Memory/MemorySourceContractTests.cs index 2494e886..fe9f73ab 100644 --- a/tests/CStructSharpTests/Memory/MemorySourceContractTests.cs +++ b/tests/CStructSharpTests/Memory/MemorySourceContractTests.cs @@ -17,15 +17,43 @@ public void MappedGenerations_TrackDistinctSourcesWithoutSummingSnapshots() var cache = new CachedMemorySource("cache", mapped); byte[] bytes = new byte[3]; Assert.AreEqual(0L, mapped.Generation); - Assert.AreEqual(3, cache.Read(100, bytes, new MemoryAccessContext())); + new MemoryRegion(cache, 100, bytes.Length).ReadExactly(bytes, new MemoryAccessContext()); CollectionAssert.AreEqual(new byte[] { 1, 2, 3, }, bytes); mutable.Write(0, new byte[] { 9, }, new MemoryAccessContext()); Assert.AreEqual(1L, mapped.Generation); Assert.AreEqual(1L, mapped.Generation); - Assert.AreEqual(3, cache.Read(100, bytes, new MemoryAccessContext())); + new MemoryRegion(cache, 100, bytes.Length).ReadExactly(bytes, new MemoryAccessContext()); CollectionAssert.AreEqual(new byte[] { 1, 2, 9, }, bytes); } + /// Completed mapped bytes remain confirmed when a later mapping or backing extent is absent. + /// The logical mapping extends past its backing instead of containing a logical gap. + /// A second mapped space translates the same original unavailable coordinate. + [TestMethod] + [DataRow(false, false)] + [DataRow(false, true)] + [DataRow(true, false)] + [DataRow(true, true)] + public void MappedPartialRead_PreservesConfirmedPrefixAcrossMissingExtents(bool missingBacking, bool nested) + { + var physical = new ByteArrayMemorySource("physical", missingBacking ? new byte[] { 1, 2, 3, } : new byte[] { 1, 2, 3, 4, 5, }); + MemoryMapping[] mappings = missingBacking + ? [new(100, new MemoryRegion(physical, 0, 5))] + : [new(100, new MemoryRegion(physical, 0, 3)), new(104, new MemoryRegion(physical, 4, 1))]; + var mapped = new MappedMemorySource("mapped", mappings); + MemoryRegion region = nested + ? new(new MappedMemorySource("outer", [new(200, new MemoryRegion(mapped, 100, 5))]), 200, 5) + : new(mapped, 100, 5); + byte[] bytes = [99, 99, 99, 99, 99]; + MemoryReadResult result = region.ReadPartial(bytes, new MemoryAccessContext()); + Assert.AreEqual(3, result.BytesRead); + Assert.IsFalse(result.IsComplete); + Assert.AreEqual(missingBacking ? MemoryFailure.MissingBytes : MemoryFailure.Unmapped, result.Failure!.MemoryFailure); + Assert.AreEqual("mapped", result.Failure.SourceId); + Assert.AreEqual(103UL, result.Failure.Address); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 99, 99, }, bytes); + } + /// Short reads continue across a mapping, while an absent byte and malformed adapter count are distinct failures. [TestMethod] public void MappedSources_HandleShortAndInvalidReads() @@ -33,7 +61,7 @@ public void MappedSources_HandleShortAndInvalidReads() var source = new ControlledSource(); var mapped = new MappedMemorySource("logical", [new(100, new MemoryRegion(source, 0, 4)),]); byte[] buffer = new byte[4]; - Assert.AreEqual(4, mapped.Read(100, buffer, new MemoryAccessContext())); + new MemoryRegion(mapped, 100, buffer.Length).ReadExactly(buffer, new MemoryAccessContext()); CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, }, buffer); Assert.AreEqual(4, source.Reads); Assert.AreEqual(0L, mapped.Generation); @@ -64,16 +92,20 @@ public void Cache_HandlesPartialReadsAndChangingSnapshots() var source = new ControlledSource(); var cached = new CachedMemorySource("cache", source, 1); byte[] bytes = new byte[2]; + + // A positive short read is the source's confirmed answer for this request, so a repeat is a hit. Assert.AreEqual(1, cached.Read(0, bytes, new MemoryAccessContext())); Assert.AreEqual(1, cached.Read(0, bytes, new MemoryAccessContext())); - Assert.AreEqual(2, source.Reads); + Assert.AreEqual(1, source.Reads); + + // A complete read larger than the capacity bypasses storage. source.ReturnCount = 2; - cached.Read(0, bytes, new MemoryAccessContext()); - cached.Read(0, bytes, new MemoryAccessContext()); - Assert.AreEqual(4, source.Reads); + cached.Read(1, bytes, new MemoryAccessContext()); + cached.Read(1, bytes, new MemoryAccessContext()); + Assert.AreEqual(3, source.Reads); source.ReturnCount = 1; source.ChangeGeneration = true; - MemoryAccessException stale = Assert.Throws(() => cached.Read(0, bytes, new MemoryAccessContext())); + MemoryAccessException stale = Assert.Throws(() => cached.Read(2, bytes, new MemoryAccessContext())); Assert.AreEqual(MemoryFailure.StaleSource, stale.Failure); Assert.AreEqual(source.Generation, cached.Generation); source.ChangeGeneration = false; @@ -83,6 +115,50 @@ public void Cache_HandlesPartialReadsAndChangingSnapshots() Assert.AreEqual(MemoryFailure.SourceFailure, Assert.Throws(() => cached.Read(0, bytes, new MemoryAccessContext())).Failure); } + /// A cache over a mapped source answers repeated boundary-crossing transfers without new backing reads. + [TestMethod] + public void Cache_OverMappedSource_ReusesBoundaryCrossingReads() + { + var physical = new ByteArrayMemorySource("physical", new byte[] { 1, 2, 3, 4, 5, 6, }); + var mapped = new MappedMemorySource("mapped", [new(100, new MemoryRegion(physical, 0, 2)), new(102, new MemoryRegion(physical, 4, 2)),]); + var cache = new CachedMemorySource("cache", mapped, capacity: 64); + var region = new MemoryRegion(cache, 100, 4); + byte[] bytes = new byte[4]; + + var first = new MemoryAccessContext(); + region.ReadExactly(bytes, first); + CollectionAssert.AreEqual(new byte[] { 1, 2, 5, 6, }, bytes); + Assert.AreEqual(4L, first.BytesRequested); + + // Both the short first segment and its continuation are cached, so a repeat charges no backing bytes. + Array.Clear(bytes); + var second = new MemoryAccessContext(); + region.ReadExactly(bytes, second); + CollectionAssert.AreEqual(new byte[] { 1, 2, 5, 6, }, bytes); + Assert.AreEqual(0L, second.BytesRequested); + } + + /// Eviction releases the bytes an entry actually retained, so short entries cannot exhaust the capacity. + [TestMethod] + public void Cache_EvictsShortEntriesByRetainedBytes() + { + var source = new ControlledSource(); + var cached = new CachedMemorySource("cache", source, 2); + byte[] bytes = new byte[2]; + for (ulong address = 0; address < 3; address++) + { + Assert.AreEqual(1, cached.Read(address, bytes, new MemoryAccessContext())); + } + + // Capacity 2 holds two one-byte entries; the third evicted only the first. + Assert.AreEqual(3, source.Reads); + cached.Read(2, bytes, new MemoryAccessContext()); + cached.Read(1, bytes, new MemoryAccessContext()); + Assert.AreEqual(3, source.Reads); + cached.Read(0, bytes, new MemoryAccessContext()); + Assert.AreEqual(4, source.Reads); + } + /// Overlays reject stale backing, check capacity before mutation, and do not leak patch byte arrays. [TestMethod] public void Overlay_RejectsStaleBackingAndPreservesPreparedBytes() From d520d527a72cfd15e0eed324993d39fe47f30285 Mon Sep 17 00:00:00 2001 From: Vincent Vollers <59395529+vvollers@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:46:11 +0100 Subject: [PATCH 2/2] Cover the PDB storage export and fix its switch formatting CI's coverage gate rated PdbMetadata.Isf.cs high risk (74% lines, 59% branches) and PdbRecordReader.cs critical (66%, 45%): enum export, modifiers, bitfields, function pointers, nested and forward-element arrays, unions, anonymous members, continuations, most numeric-leaf encodings and nearly every rejection path had no test. - RichStorageForms_ExportAndReadBack exports one record using every supported storage form and reads it back through IsfMetadata and MemorySession. - MalformedStorage_RejectsTheExport covers 28 malformed or unsupported descriptions, each of which must fail instead of publishing a layout. - WriteIsf_RejectsUnwritableOutputAndPathNames covers argument validation. Both files now rate low risk (99%/96% and 96%/95%). dotnet format: switch labels in SkipNonStorageField and the OMAP test follow the repository's unindented case style. --- apps/explorer/tests/catalog-baseline.json | 4 +- .../Memory/Metadata/PdbMetadata.Isf.cs | 216 ++++----- .../Memory/MemoryPdbMetadataTests.cs | 419 +++++++++++++++++- 3 files changed, 523 insertions(+), 116 deletions(-) diff --git a/apps/explorer/tests/catalog-baseline.json b/apps/explorer/tests/catalog-baseline.json index 079d2017..d7a0f778 100644 --- a/apps/explorer/tests/catalog-baseline.json +++ b/apps/explorer/tests/catalog-baseline.json @@ -1,7 +1,7 @@ { - "totalTests": 2327, + "totalTests": 2330, "runnableTests": 160, - "testInputsSha256": "fc2dd272403f7285c01f55e6181bd4be79e2f6afe246bc1adcd1f581b84ad681", + "testInputsSha256": "bacbaaf6c87c4e5586b493e30e1654d75a772cf2e80a1997cab900bc96a41d65", "lessonIds": [ "header", "header-serialize", diff --git a/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs b/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs index 56014784..b17fac89 100644 --- a/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs +++ b/src/CStructSharp/Memory/Metadata/PdbMetadata.Isf.cs @@ -288,49 +288,49 @@ private static bool SkipNonStorageField(ref PdbRecordReader reader, ushort kind, { switch (kind) { - case 0x1400 or 0x151A: - // LF_BCLASS, LF_BINTERFACE: base type and its offset within the derived object. - _ = reader.UInt32(); - _ = reader.Integer(); - return true; - case 0x1401 or 0x1402: - // LF_VBCLASS, LF_IVBCLASS: base type, virtual-base pointer type, pointer offset and table index. - _ = reader.UInt32(); - _ = reader.UInt32(); - _ = reader.Integer(); - _ = reader.Integer(); - return true; - case 0x1409: - // LF_VFUNCTAB: the vtable pointer's type. - _ = reader.UInt32(); - return true; - case 0x140C: - // LF_VFUNCOFF: vtable pointer type and offset. - _ = reader.UInt32(); - _ = reader.UInt32(); - return true; - case 0x150E or 0x1510 or 0x1512: - // LF_STMEMBER, LF_NESTTYPE, LF_NESTTYPEEX: a type index and a name. - _ = reader.UInt32(); - _ = reader.Name(); - return true; - case 0x150F: - // LF_METHOD: overload count (the leading word), method-list index and name. - _ = reader.UInt32(); - _ = reader.Name(); - return true; - case 0x1511: - // LF_ONEMETHOD: an introducing virtual method (property 4 or 6) also records its vtable offset. + case 0x1400 or 0x151A: + // LF_BCLASS, LF_BINTERFACE: base type and its offset within the derived object. + _ = reader.UInt32(); + _ = reader.Integer(); + return true; + case 0x1401 or 0x1402: + // LF_VBCLASS, LF_IVBCLASS: base type, virtual-base pointer type, pointer offset and table index. + _ = reader.UInt32(); + _ = reader.UInt32(); + _ = reader.Integer(); + _ = reader.Integer(); + return true; + case 0x1409: + // LF_VFUNCTAB: the vtable pointer's type. + _ = reader.UInt32(); + return true; + case 0x140C: + // LF_VFUNCOFF: vtable pointer type and offset. + _ = reader.UInt32(); + _ = reader.UInt32(); + return true; + case 0x150E or 0x1510 or 0x1512: + // LF_STMEMBER, LF_NESTTYPE, LF_NESTTYPEEX: a type index and a name. + _ = reader.UInt32(); + _ = reader.Name(); + return true; + case 0x150F: + // LF_METHOD: overload count (the leading word), method-list index and name. + _ = reader.UInt32(); + _ = reader.Name(); + return true; + case 0x1511: + // LF_ONEMETHOD: an introducing virtual method (property 4 or 6) also records its vtable offset. + _ = reader.UInt32(); + if (((attributes >> 2) & 7) is 4 or 6) + { _ = reader.UInt32(); - if (((attributes >> 2) & 7) is 4 or 6) - { - _ = reader.UInt32(); - } + } - _ = reader.Name(); - return true; - default: - return false; + _ = reader.Name(); + return true; + default: + return false; } } @@ -384,77 +384,77 @@ private void WriteDescriptor(Utf8JsonWriter writer, uint index, int depth, PdbEx switch (record.Kind) { - case 0x1001: - uint modified = reader.UInt32(); - ushort flags = reader.UInt16(); - reader.End(); - if ((flags & ~7) != 0) - { - throw Invalid("a modifier contains unknown qualifier bits"); - } + case 0x1001: + uint modified = reader.UInt32(); + ushort flags = reader.UInt16(); + reader.End(); + if ((flags & ~7) != 0) + { + throw Invalid("a modifier contains unknown qualifier bits"); + } - this.WriteDescriptor(writer, modified, depth + 1, budget); - break; - case 0x1002: - (uint target, int width) = Pointer(record.Bytes.Span); - writer.WriteStartObject(); - writer.WriteString("kind", "pointer"); - writer.WriteString("base", width == 4 ? "__cv_pointer32" : "__cv_pointer64"); - writer.WritePropertyName("subtype"); - this.WriteDescriptor(writer, target, depth + 1, budget); - writer.WriteEndObject(); - break; - case 0x1503: - uint element = reader.UInt32(); - _ = reader.UInt32(); - int bytes = reader.Size(); - _ = reader.Name(); - reader.End(); - int elementSize = this.StorageSize(element, depth + 1, budget); - if (elementSize <= 0 || bytes % elementSize != 0) - { - throw Invalid("an array extent is not a whole number of its recorded element type"); - } + this.WriteDescriptor(writer, modified, depth + 1, budget); + break; + case 0x1002: + (uint target, int width) = Pointer(record.Bytes.Span); + writer.WriteStartObject(); + writer.WriteString("kind", "pointer"); + writer.WriteString("base", width == 4 ? "__cv_pointer32" : "__cv_pointer64"); + writer.WritePropertyName("subtype"); + this.WriteDescriptor(writer, target, depth + 1, budget); + writer.WriteEndObject(); + break; + case 0x1503: + uint element = reader.UInt32(); + _ = reader.UInt32(); + int bytes = reader.Size(); + _ = reader.Name(); + reader.End(); + int elementSize = this.StorageSize(element, depth + 1, budget); + if (elementSize <= 0 || bytes % elementSize != 0) + { + throw Invalid("an array extent is not a whole number of its recorded element type"); + } - writer.WriteStartObject(); - writer.WriteString("kind", "array"); - writer.WriteNumber("count", bytes / elementSize); - writer.WritePropertyName("subtype"); - this.WriteDescriptor(writer, element, depth + 1, budget); - writer.WriteEndObject(); - break; - case 0x1205: - uint storage = reader.UInt32(); - byte bits = reader.Byte(); - byte position = reader.Byte(); - reader.End(); - int storageSize = this.StorageSize(storage, depth + 1, budget); - if (bits == 0 || position + bits > storageSize * 8) - { - throw Invalid("a bitfield extends outside its recorded storage integer"); - } + writer.WriteStartObject(); + writer.WriteString("kind", "array"); + writer.WriteNumber("count", bytes / elementSize); + writer.WritePropertyName("subtype"); + this.WriteDescriptor(writer, element, depth + 1, budget); + writer.WriteEndObject(); + break; + case 0x1205: + uint storage = reader.UInt32(); + byte bits = reader.Byte(); + byte position = reader.Byte(); + reader.End(); + int storageSize = this.StorageSize(storage, depth + 1, budget); + if (bits == 0 || position + bits > storageSize * 8) + { + throw Invalid("a bitfield extends outside its recorded storage integer"); + } - writer.WriteStartObject(); - writer.WriteString("kind", "bitfield"); - writer.WriteNumber("bit_position", position); - writer.WriteNumber("bit_length", bits); - writer.WritePropertyName("type"); - this.WriteDescriptor(writer, storage, depth + 1, budget); - writer.WriteEndObject(); - break; - case 0x1008 or 0x1009: - int minimum = record.Kind == 0x1008 ? 12 : 24; - if (record.Bytes.Length < minimum) - { - throw Invalid("a function description is truncated"); - } + writer.WriteStartObject(); + writer.WriteString("kind", "bitfield"); + writer.WriteNumber("bit_position", position); + writer.WriteNumber("bit_length", bits); + writer.WritePropertyName("type"); + this.WriteDescriptor(writer, storage, depth + 1, budget); + writer.WriteEndObject(); + break; + case 0x1008 or 0x1009: + int minimum = record.Kind == 0x1008 ? 12 : 24; + if (record.Bytes.Length < minimum) + { + throw Invalid("a function description is truncated"); + } - writer.WriteStartObject(); - writer.WriteString("kind", "function"); - writer.WriteEndObject(); - break; - default: - throw Invalid($"storage leaf 0x{record.Kind:X4} is not supported"); + writer.WriteStartObject(); + writer.WriteString("kind", "function"); + writer.WriteEndObject(); + break; + default: + throw Invalid($"storage leaf 0x{record.Kind:X4} is not supported"); } } diff --git a/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs b/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs index 17bb94d0..0f1114db 100644 --- a/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs +++ b/tests/CStructSharpTests/Memory/MemoryPdbMetadataTests.cs @@ -597,12 +597,12 @@ public void InvalidOmap_RejectsAmbiguousOrUnboundedCoordinates(string corruption Put32(map, 8, 0x1030); switch (corruption) { - case "truncated": map = map[..7]; break; - case "unordered": Put32(map, 8, 0x0FFF); break; - case "duplicate": Put32(map, 8, 0x1000); break; - case "wrap": Put32(map, 4, uint.MaxValue); break; - case "missing-original-sections": break; - default: throw new ArgumentException("Unknown synthetic remap corruption.", nameof(corruption)); + case "truncated": map = map[..7]; break; + case "unordered": Put32(map, 8, 0x0FFF); break; + case "duplicate": Put32(map, 8, 0x1000); break; + case "wrap": Put32(map, 4, uint.MaxValue); break; + case "missing-original-sections": break; + default: throw new ArgumentException("Unknown synthetic remap corruption.", nameof(corruption)); } Fixture fixture = CreateFixture(BasicTypes(), omap: map); @@ -636,6 +636,274 @@ public void InvalidNativeName_RejectsLossyMetadata() Assert.Throws(() => new PdbMetadata(input)); } + /// + /// Every supported storage form survives export: enums with each integral numeric encoding, modifiers, bitfields, + /// function pointers, nested arrays, forward-declared and enum array elements, unions, anonymous unions, wide + /// member offsets, field-list continuations and skipped C++ elements. + /// + [TestMethod] + public void RichStorageForms_ExportAndReadBack() + { + byte[][] types = + [ + // 0x1000: enum constants in every integral numeric-leaf encoding CodeView defines. + FieldList( + Enumerate("Small", Leaf(5)), + Enumerate("Negative", Leaf(0x8000, Le(-1, 1))), + Enumerate("Short", Leaf(0x8001, Le(-300, 2))), + Enumerate("Word", Leaf(0x8002, Le(40000, 2))), + Enumerate("Int", Leaf(0x8003, Le(-70000, 4))), + Enumerate("UInt", Leaf(0x8004, Le(3_000_000_000, 4))), + Enumerate("Long", Leaf(0x8009, Le(-5_000_000_000, 8))), + Enumerate("One", Leaf(0x800A, Le(1, 8)))), + + // 0x1001: const __int64, the enum's storage through a modifier. + Modifier(0x76, 1), + + // 0x1002: an enum stored as that modifier. + Enum("Mode", 8, 0x1001, 0x1000), + + // 0x1003: three bits starting at bit 4. + Bitfield(0x75, 3, 4), + + // 0x1004: a function type. + Procedure(), + + // 0x1005: pointer to function. + Pointer64(0x1004), + + // 0x1006: two enum elements. + ArrayOf(0x1002, Leaf(16)), + + // 0x1007: const int[2], so the outer stride needs the modifier's size. + ArrayOf(0x1013, Leaf(8)), + + // 0x1008: int[2][2]. + ArrayOf(0x1007, Leaf(0x8002, Le(16, 2))), + + // 0x1009: one 64-bit simple pointer. + ArrayOf(0x0603, Leaf(8)), + + // 0x100A: a forward declaration of inner. + Composite("inner", 0, 0, 0, forward: true), + + // 0x100B: inner's members. + FieldList(Member("x", 0x75, 0)), + + // 0x100C: the complete inner. + Composite("inner", 1, 0x100B, 4), + + // 0x100D: elements named only by a forward declaration. + ArrayOf(0x100A, Leaf(8)), + + // 0x100E: two overlapping union members. + FieldList(Member("u32", 0x75, 0), Member("u16", 0x21, 0)), + + // 0x100F: the union. + Union("choice", 2, 0x100E, 4), + + // 0x1010: the first members, then a continuation. + FieldList( + Member("mode", 0x1002, 0), + Member("constant", 0x1001, 8), + Member("flags", 0x1003, 12), + Member(string.Empty, 0x100F, 16), + Member("callback", 0x1005, 24), + Member("modes", 0x1006, 32), + Continuation(0x1011)), + + // 0x1011: the remaining members, with C++ elements that hold no instance storage. + FieldList( + Member("ints", 0x1008, 48), + Member("pointers", 0x1009, 64), + Member("inners", 0x100D, 72), + Member("choice", 0x100F, 80), + MemberLeaf("far", 0x75, Leaf(0x8002, Le(84, 2))), + FieldLeaf(0x1401, writer => + { + // LF_VBCLASS: base, virtual-base pointer, pointer offset and table index. + writer.Write((ushort)3); + writer.Write(0x100CU); + writer.Write(0x0603U); + writer.Write((ushort)0); + writer.Write((ushort)1); + }), + FieldLeaf(0x140C, writer => + { + // LF_VFUNCOFF: vtable pointer type and offset. + writer.Write((ushort)0); + writer.Write(0x0603U); + writer.Write(0U); + }), + FieldLeaf(0x1512, writer => + { + // LF_NESTTYPEEX: a nested type with attributes. + writer.Write((ushort)3); + writer.Write(0x100CU); + WriteName(writer, "Nested"); + }), + FieldLeaf(0x151A, writer => + { + // LF_BINTERFACE: an interface base at offset zero. + writer.Write((ushort)3); + writer.Write(0x100CU); + writer.Write((ushort)0); + })), + + // 0x1012: the root composite. + Composite("rich", 11, 0x1010, 88), + + // 0x1013: const int + Modifier(0x74, 1), + ]; + + Fixture fixture = CreateFixture(types, rootType: 0x1012); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + metadata.WriteIsf(output, "fixture.pdb"); + JsonNode profile = JsonNode.Parse(output.ToArray())!; + + JsonNode mode = profile["enums"]!["Mode"]!; + Assert.AreEqual("__int64", mode["base"]!.GetValue()); + Assert.AreEqual(8, mode["size"]!.GetValue()); + JsonNode constants = mode["constants"]!; + Assert.AreEqual(5L, constants["Small"]!.GetValue()); + Assert.AreEqual(-1L, constants["Negative"]!.GetValue()); + Assert.AreEqual(-300L, constants["Short"]!.GetValue()); + Assert.AreEqual(40000L, constants["Word"]!.GetValue()); + Assert.AreEqual(-70000L, constants["Int"]!.GetValue()); + Assert.AreEqual(3_000_000_000L, constants["UInt"]!.GetValue()); + Assert.AreEqual(-5_000_000_000L, constants["Long"]!.GetValue()); + Assert.AreEqual(1L, constants["One"]!.GetValue()); + + JsonNode fields = profile["user_types"]!["rich"]!["fields"]!; + Assert.AreEqual("enum", fields["mode"]!["type"]!["kind"]!.GetValue()); + Assert.AreEqual("__int64", fields["constant"]!["type"]!["name"]!.GetValue()); + Assert.AreEqual(4, fields["flags"]!["type"]!["bit_position"]!.GetValue()); + Assert.AreEqual(3, fields["flags"]!["type"]!["bit_length"]!.GetValue()); + Assert.IsTrue(fields["__anonymous_cv_3"]!["anonymous"]!.GetValue()); + Assert.AreEqual("function", fields["callback"]!["type"]!["subtype"]!["kind"]!.GetValue()); + Assert.AreEqual(2, fields["modes"]!["type"]!["count"]!.GetValue()); + Assert.AreEqual(2, fields["ints"]!["type"]!["subtype"]!["count"]!.GetValue()); + Assert.AreEqual(1, fields["pointers"]!["type"]!["count"]!.GetValue()); + Assert.AreEqual("inner", fields["inners"]!["type"]!["subtype"]!["name"]!.GetValue()); + Assert.AreEqual("union", fields["choice"]!["type"]!["kind"]!.GetValue()); + Assert.AreEqual(84, fields["far"]!["offset"]!.GetValue()); + + MetadataImportResult imported = new IsfMetadata(output.ToArray()).Import("rich"); + var session = new MemorySession(imported.Schema); + byte[] bytes = new byte[88]; + bytes[12] = 0x50; + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(16), 0x00030002); + BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(56), 3); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(76), 0x77); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(80), 0x00020001); + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(84), 0xDEADBEEF); + var region = new MemoryRegion(new ByteArrayMemorySource("rich", bytes), 0, bytes.Length); + Assert.AreEqual(5, session.Read(region, imported.RootTypeId, "flags")); + Assert.AreEqual(3, session.Read(region, imported.RootTypeId, "ints[1][0]")); + Assert.AreEqual(0x77U, session.Read(region, imported.RootTypeId, "inners[1].x")); + Assert.AreEqual((ushort)1, session.Read(region, imported.RootTypeId, "choice.u16")); + + // The anonymous union's members are promoted into the containing record. + Assert.AreEqual((ushort)2, session.Read(region, imported.RootTypeId, "u16")); + Assert.AreEqual(0x00030002U, session.Read(region, imported.RootTypeId, "u32")); + Assert.AreEqual(0xDEADBEEFU, session.Read(region, imported.RootTypeId, "far")); + } + + /// Malformed or unsupported storage descriptions fail the export instead of publishing a guessed layout. + /// The original invariant to violate. + [TestMethod] + [DataRow("numeric-leaf")] + [DataRow("enum-float")] + [DataRow("enum-record")] + [DataRow("enum-depth")] + [DataRow("enum-repeated")] + [DataRow("enum-member")] + [DataRow("struct-enumerate")] + [DataRow("modifier-bits")] + [DataRow("modifier-depth")] + [DataRow("array-extent")] + [DataRow("array-forward")] + [DataRow("array-function")] + [DataRow("storage-depth")] + [DataRow("bitfield-zero")] + [DataRow("bitfield-outside")] + [DataRow("function-truncated")] + [DataRow("storage-leaf")] + [DataRow("not-field-list")] + [DataRow("continuation-reserved")] + [DataRow("repeated-member")] + [DataRow("simple-pointer-mode")] + [DataRow("primitive")] + [DataRow("negative-offset")] + [DataRow("padding-zero")] + [DataRow("padding-inconsistent")] + [DataRow("unclaimed")] + [DataRow("unterminated-name")] + [DataRow("truncated-integer")] + public void MalformedStorage_RejectsTheExport(string corruption) + { + byte[] small = Enumerate("A", Leaf(1)); + byte[] bad = Member("bad", 0x1000, 0); + byte[] record = Composite("record", 1, 0x1001, 64); + byte[][] types = corruption switch + { + "numeric-leaf" => [FieldList(Enumerate("A", Leaf(0x8005, Le(0x3F800000, 4)))), Enum("bad", 1, 0x74, 0x1000)], + "enum-float" => [FieldList(small), Enum("bad", 1, 0x40, 0x1000)], + "enum-record" => [FieldList(small), Enum("bad", 1, 0x1002, 0x1000), Pointer64(0x75)], + "enum-depth" => [FieldList(small), Enum("bad", 1, 0x1002, 0x1000), Modifier(0x1002, 0)], + "enum-repeated" => [FieldList(small, small), Enum("bad", 2, 0x74, 0x1000)], + "enum-member" => [FieldList(Member("a", 0x74, 0)), Enum("bad", 1, 0x74, 0x1000)], + "struct-enumerate" => [FieldList(small), Composite("record", 1, 0x1000, 4)], + "modifier-bits" => [Modifier(0x75, 0x10), FieldList(bad), record], + "modifier-depth" => [Modifier(0x1000, 0), FieldList(bad), record], + "array-extent" => [ArrayOf(0x75, Leaf(6)), FieldList(bad), record], + "array-forward" => [Composite("missing", 0, 0, 0, forward: true), ArrayOf(0x1000, Leaf(8)), FieldList(Member("bad", 0x1001, 0)), Composite("record", 1, 0x1002, 8)], + "array-function" => [Procedure(), ArrayOf(0x1000, Leaf(8)), FieldList(Member("bad", 0x1001, 0)), Composite("record", 1, 0x1002, 8)], + "storage-depth" => [Modifier(0x1000, 0), ArrayOf(0x1000, Leaf(8)), FieldList(Member("bad", 0x1001, 0)), Composite("record", 1, 0x1002, 8)], + "bitfield-zero" => [Bitfield(0x75, 0, 0), FieldList(bad), record], + "bitfield-outside" => [Bitfield(0x75, 30, 4), FieldList(bad), record], + "function-truncated" => [Record(0x1008, Payload(writer => writer.Write(0UL))), Pointer64(0x1000), FieldList(Member("bad", 0x1001, 0)), Composite("record", 1, 0x1002, 8)], + "storage-leaf" => [Record(0x1201, Payload(writer => writer.Write(0U))), FieldList(bad), record], + "not-field-list" => [Modifier(0x75, 0), Composite("record", 1, 0x1000, 4)], + "continuation-reserved" => [Record(0x1203, [.. Le(0x1404, 2), .. Le(1, 2), .. Le(0x1000, 4)]), Composite("record", 0, 0x1000, 4)], + "repeated-member" => [FieldList(Member("a", 0x75, 0), Member("a", 0x75, 4)), Composite("record", 2, 0x1000, 8)], + "simple-pointer-mode" => [FieldList(Member("bad", 0x0175, 0)), Composite("record", 1, 0x1000, 8)], + "primitive" => [FieldList(Member("bad", 0x0005, 0)), Composite("record", 1, 0x1000, 8)], + "negative-offset" => [FieldList(MemberLeaf("bad", 0x75, Leaf(0x8000, Le(-1, 1)))), Composite("record", 1, 0x1000, 8)], + "padding-zero" => [Record(0x1203, [.. Member("a", 0x75, 0), 0xF0, 0, 0, 0]), Composite("record", 1, 0x1000, 4)], + "padding-inconsistent" => [Record(0x1203, [.. Member("a", 0x75, 0), 0xF3, 0xF1, 0xF1, 0]), Composite("record", 1, 0x1000, 4)], + "unclaimed" => [Record(0x1002, [.. Le(0x75, 4), .. Le(12 | (8 << 13), 4), .. Le(0x01020304, 4)]), FieldList(bad), record], + "unterminated-name" => [Record(0x1203, Pad([.. Le(0x150D, 2), .. Le(0, 2), .. Le(0x75, 4), .. Leaf(0), .. "bad"u8])), Composite("record", 1, 0x1000, 4)], + "truncated-integer" => [Record(0x1203, Pad([.. Le(0x150D, 2), .. Le(0, 2), .. Le(0x75, 4), .. Le(0x8003, 2)])), Composite("record", 1, 0x1000, 4)], + _ => throw new ArgumentException("Unknown synthetic storage corruption.", nameof(corruption)), + }; + + // The typed global must name a real record; the last record is the containing type in every case. + Fixture fixture = CreateFixture(types, rootType: 0x1000U + (uint)types.Length - 1); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var output = new MemoryStream(); + Assert.Throws(() => metadata.WriteIsf(output, "fixture.pdb")); + } + + /// The export needs a writable destination and a bare PDB file name. + [TestMethod] + public void WriteIsf_RejectsUnwritableOutputAndPathNames() + { + Fixture fixture = CreateFixture(BasicTypes()); + using var input = new MemoryStream(fixture.Bytes); + var metadata = new PdbMetadata(input); + using var readOnly = new MemoryStream(new byte[16], writable: false); + using var output = new MemoryStream(); + Assert.Throws(() => metadata.WriteIsf(readOnly, "fixture.pdb")); + Assert.Throws(() => metadata.WriteIsf(output, "symbols/fixture.pdb")); + Assert.Throws(() => metadata.WriteIsf(output, "C:fixture.pdb")); + Assert.AreEqual(0L, output.Length); + } + /// Creates independently declared native storage records, including explicit 32/64-bit pointer modes. /// Full CodeView records in original index order. private static byte[][] BasicTypes() => @@ -816,6 +1084,145 @@ private static byte[] FieldLeaf(ushort kind, Action write) })); } + /// Frames already aligned field leaves as one LF_FIELDLIST record. + /// Complete field leaves in original order. + /// A full native type record. + private static byte[] FieldList(params byte[][] leaves) => Record(0x1203, [.. leaves.SelectMany(leaf => leaf)]); + + /// Creates an LF_INDEX leaf that continues a field list in another record. + /// Type index of the continuing LF_FIELDLIST. + /// The unframed field leaf. + private static byte[] Continuation(uint next) => FieldLeaf(0x1404, writer => + { + writer.Write((ushort)0); + writer.Write(next); + }); + + /// Creates an LF_ENUMERATE leaf with a public attribute word. + /// Constant name. + /// The encoded numeric leaf (see ). + /// The unframed field leaf including alignment. + private static byte[] Enumerate(string name, byte[] value) => FieldLeaf(0x1502, writer => + { + writer.Write((ushort)3); + writer.Write(value); + WriteName(writer, name); + }); + + /// Creates an LF_MEMBER leaf whose offset uses a caller-chosen numeric-leaf encoding. + /// Member name. + /// Storage type index. + /// The encoded numeric leaf for the byte offset. + /// The unframed field leaf including alignment. + private static byte[] MemberLeaf(string name, uint type, byte[] offset) => FieldLeaf(0x150D, writer => + { + writer.Write((ushort)3); + writer.Write(type); + writer.Write(offset); + WriteName(writer, name); + }); + + /// Encodes a CodeView numeric leaf: a value below 0x8000 directly, or a leaf code followed by its payload. + /// The direct value, or the numeric leaf code (0x8000 and above). + /// The value bytes that follow a leaf code; empty for a direct value. + /// The encoded leaf. + private static byte[] Leaf(ushort code, params byte[] payload) => [.. Le(code, 2), .. payload]; + + /// Encodes the low bytes of a value in little-endian order, as CodeView stores every integer. + /// The value; negative values keep their two's-complement low bytes. + /// Number of bytes to write. + /// The encoded bytes. + private static byte[] Le(long value, int width) + { + byte[] bytes = new byte[8]; + BinaryPrimitives.WriteInt64LittleEndian(bytes, value); + return bytes[..width]; + } + + /// Creates an LF_ENUM record. + /// Enum name. + /// Declared constant count. + /// Storage type index. + /// Field-list index holding the constants. + /// A full native type record. + private static byte[] Enum(string name, ushort count, uint underlying, uint fields) => Record(0x1507, Payload(writer => + { + writer.Write(count); + writer.Write((ushort)0); + writer.Write(underlying); + writer.Write(fields); + WriteName(writer, name); + })); + + /// Creates an LF_UNION record with a direct byte size. + /// Union name. + /// Declared member count. + /// Field-list index. + /// Byte extent. + /// A full native type record. + private static byte[] Union(string name, ushort count, uint fields, ushort size) => Record(0x1506, Payload(writer => + { + writer.Write(count); + writer.Write((ushort)0); + writer.Write(fields); + writer.Write(size); + WriteName(writer, name); + })); + + /// Creates an LF_MODIFIER record. + /// Modified type index. + /// Qualifier bits: 1 const, 2 volatile, 4 unaligned. + /// A full native type record. + private static byte[] Modifier(uint target, ushort flags) => Record(0x1001, Payload(writer => + { + writer.Write(target); + writer.Write(flags); + })); + + /// Creates an LF_BITFIELD record. + /// Storage integer type index. + /// Bit length. + /// First bit, counted from the least significant bit of the storage integer. + /// A full native type record. + private static byte[] Bitfield(uint storage, byte bits, byte position) => Record(0x1205, Payload(writer => + { + writer.Write(storage); + writer.Write(bits); + writer.Write(position); + })); + + /// Creates a minimal complete LF_PROCEDURE record returning void with no arguments. + /// A full native type record. + private static byte[] Procedure() => Record(0x1008, Payload(writer => + { + writer.Write(0x03U); + writer.Write((byte)0); + writer.Write((byte)0); + writer.Write((ushort)0); + writer.Write(0U); + })); + + /// Creates a flat near64 LF_POINTER record with explicit eight-byte size bits. + /// Pointed-to type index. + /// A full native type record. + private static byte[] Pointer64(uint target) => Record(0x1002, Payload(writer => + { + writer.Write(target); + writer.Write(12U | (8U << 13)); + })); + + /// Creates an unnamed LF_ARRAY record with an unsigned int index type. + /// Element type index. + /// The array's total byte size as an encoded numeric leaf. + /// A full native type record. + private static byte[] ArrayOf(uint element, byte[] size) => Record(0x1503, Payload(writer => + { + writer.Write(element); + writer.Write(0x75U); + writer.Write(size); + writer.Write((byte)0); + })); + /// Frames one original CodeView type record and applies its descending leaf-padding bytes. /// Original leaf code. /// Original payload excluding prefix.