Skip to content

feat(managed): bind Portable PDB sequence points to selected methods - #2435

Open
vincent-peng wants to merge 9 commits into
morluto:mainfrom
vincent-peng:feat/portable-pdb-sequence-points
Open

vincent-peng wants to merge 9 commits into
morluto:mainfrom
vincent-peng:feat/portable-pdb-sequence-points

Conversation

@vincent-peng

Copy link
Copy Markdown

Summary

Fixes #2351. inspect_managed_members gains optional pdb_path / pdb_embedded selectors on both CLI (--pdb, --pdb-embedded) and MCP. When a Portable PDB is selected, the result carries a debug_map that verifies the PDB against the assembly's own declarations and reports documents, checksums and sequence points keyed to build-local MethodDef tokens and IL offsets.

Problem and expected behavior

Managed member inspection reported IL extents but no source-level sequence points. The issue asks to bind Portable PDB sequence points to the selected managed methods so callers can map IL offsets to source lines without guessing which PDB belongs to the build.

Change and scope

  • src/dotnet/ManagedDebugDirectory.ts parses PE debug-directory entries: CodeView RSDS (GUID, age, declared path) and MPDB embedded Portable PDB payloads (raw RFC 1951 Deflate, bounded inflation). Directory enumeration is capped at 4096 entries.
  • src/dotnet/PortablePdbLayout.ts parses the Portable PDB metadata root (BSJB), stream headers, the #Pdb stream (20-byte content ID, entry-point token, referenced type-system rows) and debug-table layouts using the existing ECMA-335 coded-index sizing.
  • src/dotnet/PortablePdbDebugMap.ts decodes Document rows (names, path parts, checksum algorithms/bytes, language GUIDs — unknown GUIDs retained), MethodDebugInformation rows, and sequence-point blobs including hidden points, document switches and signed line/column deltas per ECMA-335 II.23.2. MDI rows are bound to MethodDef tokens; rows not covered by MDI are counted in methods_without_debug_information.
  • Identity is verified CodeView RSDS GUID/age against the #Pdb content GUID/stamp and reported as matched / mismatched / undeclared / unverifiable without blocking the evidence.
  • Selectors are validated once in ManagedStaticProvider (mutually exclusive, pdb_path must be absolute, read through the existing bounded/cancellable snapshot path).
  • The PDB projection is charged to its own decode budget so oversized or malformed PDBs degrade debug_map to malformed without discarding member evidence; retained issues are bounded with an omitted count.
  • Intentionally not included: SourceLink resolution, source-file access, non-portable (Windows MSF) PDB support, portable-PDB reading of non-managed artifacts. Spec/plan/tasks/verification docs live in docs/specs/managed/portable-pdb-sequence-points/.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/dotnet/ readers own the format facts; ManagedStaticProvider owns the external file read; CLI/MCP expose the selectors unchanged elsewhere.
  • Contribution scope fit and linked maintainer decision: static format inspection and evidence reporting; no target interaction — not applicable.
  • CLI and MCP/tool-catalog contract: additive — two optional inputs, one nullable output field (debug_map, defaults null); selector exclusivity enforced in the provider so both adapters agree.
  • Provider, bridge, target-format, or platform compatibility: additive to the managed static provider; embedded PDBs extracted only when selected.
  • Evidence, artifact, provenance, or reconstruction contract: debug_map reports source path, byte_length and sha256; identity mismatch remains visible rather than blocking evidence.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): none — reads only caller-selected local files; no target code is loaded or executed.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none; the catalog is CI-generated from the edited contracts.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: src/dotnet/PortablePdbDebugMap.test.ts (22), tests/boundary/providers/managed/managedPortablePdb.test.ts (6), plus MCP and CLI parity cases. Fixtures are byte-built synthesizers (PortablePdb.fixture.ts, ManagedPe.fixture.ts debug-directory support), not binaries.
  • Base reproduction or other evidence: without a selector, debug_map is null and prior output is unchanged; with a selector, matching/mismatched/undeclared/malformed states are asserted end-to-end.
  • User-visible CLI/MCP output (if applicable): rea inspect-managed-members <pe> --pdb <pdb> --json reports normalized_result.debug_map with source, pdb provenance, identity, documents, methods[].sequence_points and coverage.
  • Remaining proof gaps: coverage uses synthesized Portable PDBs (including known-answer compressed-integer bytes); a real compiler-produced embedded-PDB round trip is not exercised, though inflateRawSync matches the DeflateStream wire format.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run test:focused -- src/dotnet/PortablePdbDebugMap.test.ts tests/boundary/providers/managed/managedPortablePdb.test.ts tests/boundary/mcp/managedMcp.test.ts tests/acceptance/managedCliOutput.test.ts — 39 tests passed.
  • npm run test:local -- src/dotnet/ManagedMemberInspector.test.ts src/dotnet/ManagedArtifactInspector.test.ts src/dotnet/ManagedArtifactFailures.test.ts (plus the other src/dotnet/ suites) — 183 tests passed.
  • npm run check:fast — typecheck + lint pass.
  • npm run docs:check — pass.
  • npm run verify:test-discovery — 1000 test files discovered.

Compatibility, safety, and release

  • Breaking changes or migration steps: none — inputs are optional and debug_map is a nullable additive field.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; the managed static path is provider-free.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: reads only the caller-selected PE/PDB paths through the existing bounded, cancellable snapshot path; embedded inflation is size-bounded; no network or SourceLink access; local file paths are caller-provided inputs echoed back as provenance.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Adds optional pdb_path / pdb_embedded selectors to inspect_managed_members
on both CLI and MCP. The PE debug directory is parsed for CodeView RSDS
identity and embedded MPDB entries (raw Deflate); the Portable PDB #Pdb
stream, Document and MethodDebugInformation tables are decoded with
ECMA-335 compressed-integer semantics, and sequence points are bound to
build-local MethodDef tokens. Identity mismatches, malformed rows and
unreadable declarations degrade to debug_map evidence rather than
discarding member output; the PDB projection is charged to its own decode
budget and issues are bounded. No source content is fetched and no target
code is executed.

Refs morluto#2351

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@matbrgz

matbrgz commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Technical Review & Findings

1. Incomplete Deflate Output Length Guard (extractEmbeddedPortablePdb)

In src/dotnet/ManagedDebugDirectory.ts:

const result = inflateRawSync(bytes.subarray(offset + 8, offset + size), {
  maxOutputLength: uncompressedSize + 1,
});

maxOutputLength limits the allocation that Node's zlib.inflateRawSync can return, but if the decompressed payload is smaller than uncompressedSize (or if result.length !== uncompressedSize), this is not validated. If an embedded MPDB stream terminates early or contains truncated deflate streams, result is returned with fewer bytes than declared, leading to out-of-bounds reads or confusing downstream parser errors when indexing metadata tables. Checking if (result.length !== uncompressedSize) ensures that truncated or corrupted embedded streams are flagged cleanly as invalid blobs.

2. Sequence Point Decoding: Document Record Offset in Sequence Points

In decodeSequencePoints (src/dotnet/PortablePdbDebugMap.ts):

const ilDelta = cursor.readUnsigned();
if (!first && ilDelta === 0) {
  const documentRow = cursor.readUnsigned();
  if (documentRow < 1 || documentRow > documentRowCount)
    throw new BlobFormatError(
      `document record selects row ${String(documentRow)} beyond the ${String(documentRowCount)}-row Document table`,
    );
  currentDocument = documentRow;
  continue;
}
ilOffset = first ? ilDelta : ilOffset + ilDelta;
first = false;

Per the ECMA-335 / Portable PDB specification (II.23.2 Sequence Points):
A sequence point record with IL offset delta == 0 after the first sequence point indicates a document switch record. However, if a method has multiple sequence points at the exact same IL offset across different instructions (or a sequence point at IL offset 0 where ilDelta == 0 for subsequent points), !first && ilDelta === 0 will misinterpret an identical IL offset delta as a document switch record, consuming the next compressed integer as a document row index instead of a line/column delta.
Per the Portable PDB spec, a document switch is only emitted when ilDelta == 0 AND the sequence point is a document-change record (which is disambiguated in the specification by whether a document change was expected or by the record structure). Specifically, if a non-first sequence point has ilDelta == 0, Portable PDB specifies that a document record consists of ilDelta == 0 followed by the document row. However, if the compiler emitted a zero IL delta for another sequence point without switching documents, treating any ilDelta === 0 strictly as a document switch without checking whether subsequent sequence points follow the document record will corrupt subsequent delta decoding.

3. Signed Compressed Integer Underflow on Signed Column Delta

In BlobCursor.readSigned():

readSigned(): number {
  const raw = this.readUnsigned();
  const payloadMask =
    this.#lastWidth === 1
      ? 0x3f
      : this.#lastWidth === 2
        ? 0x1fff
        : 0x0fffffff;
  const magnitude = raw >> 1;
  return (raw & 1) === 1 ? magnitude | ~payloadMask : magnitude;
}

In JavaScript, bitwise operators operate on 32-bit signed integers. When #lastWidth === 4:
payloadMask is 0x0fff_ffff.
~payloadMask is 0xf000_0000 (which is negative in 32-bit two's complement).
However, raw >> 1 performs a sign-propagating 32-bit right shift. If raw exceeds 0x7fff_ffff (a valid 29-bit compressed int representation up to 0x1fff_ffff), bit 31 is zero, so magnitude is positive.
However, if raw has bit 0 set (negative), magnitude | ~payloadMask correctly sign-extends to 32 bits. But notice:
In readUnsigned():

return (
  ((chunk[0] ?? 0) & 0x1f) * 0x01_00_00_00 +
  (chunk[1] ?? 0) * 0x01_00_00 +
  (chunk[2] ?? 0) * 0x0100 +
  (chunk[3] ?? 0)
);

readUnsigned() returns a standard JS number (which can be up to 0x1fff_ffff). In readSigned(), raw >> 1 coerces raw to a 32-bit signed integer. For the 4-byte case, the highest valid compressed integer is 29 bits (0x1fff_ffff), so raw fits in 32 bits. But for the 2-byte case: payloadMask is 0x1fff (13 bits). raw >> 1 gives up to 14 bits. If raw is odd (sign bit = 1), (raw & 1) === 1, and magnitude | ~0x1fff:
In JS, ~0x1fff is -0x2000 (0xffff_e000). If magnitude is e.g. 0, 0 | -0x2000 is -8192.
Per ECMA-335 II.23.2, signed compressed integers represent signed values by rotating the sign bit to bit 0: a value v is encoded as (v >= 0) ? (v << 1) : ((-v << 1) - 1) or two's complement rotation.
Verifying against ECMA-335:
"A signed integer is compressed similarly to an unsigned integer, except that the least-significant bit of the compressed representation is used to encode the sign bit." Specifically, if (raw & 1) return -(raw >> 1) - 1; else return raw >> 1; or two's complement.
Using magnitude | ~payloadMask assumes two's complement payload in bits 1..N. If the PDB producer uses sign-magnitude or two's complement representation, confirm whether v < 0 is represented as two's complement shifted left by 1, or sign bit with magnitude, because ECMA-335 II.23.2 states:
"If the least significant bit is 1, the value is negative and the remaining bits are the two's complement representation of the absolute value negated."

@vincent-peng

Copy link
Copy Markdown
Author

Thanks for the detailed review — verified each finding against the code and the System.Reflection.Metadata reference implementation. Disposition per item:

1. Deflate output length guard — already handled in the pushed diff. The check sits directly below the quoted call in extractEmbeddedPortablePdb:

const result = inflateRawSync(bytes.subarray(offset + 8, offset + size), {
  maxOutputLength: uncompressedSize + 1,
});
if (result.length !== uncompressedSize) {
  pushIssue(issues, `Embedded Portable PDB inflated to ${result.length} bytes, expected ${uncompressedSize}`, offset + 4);
  return null;
}

maxOutputLength bounds the upper side (excess output throws), and the equality check flags a deflated stream that terminates early — truncated MPDBs surface as "malformed" debug_map evidence rather than feeding short buffers into the metadata reader. This path is covered by the embedded-payload malformed tests.

2. Non-first δILOffset == 0 as document record — this is spec-conformant, not ambiguous. Per the Portable PDB sequence-points encoding, a non-first record is either a document-record (δILOffset == 0, followed by a document row) or a sequence point with δILOffset > 0; sequence point IL offsets are strictly increasing by construction, so a zero-delta sequence point is not representable in the format. The reference decoder in SequencePointCollection.Enumerator.MoveNext makes the same unconditional choice:

// skip all document records and update the current document accordingly:
int deltaOffset;
while ((deltaOffset = _reader.ReadCompressedInteger()) == 0)
    document = ReadDocumentHandle();
offset = AddOffsets(_current.Offset, deltaOffset);

Our continue-to-loop-top structure is equivalent (it re-reads the delta and consumes consecutive document records the same way). The "two sequence points at the same IL offset" scenario can't be produced by a conforming writer, so no disambiguation signal exists — or is needed — in the wire format.

3. Signed compressed integer decode — the current decode is the ECMA-335 II.23.2 semantics, verified bit-for-bit against BlobReader.TryReadCompressedSignedInteger in System.Reflection.Metadata:

bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend) {
    case 1: value |= unchecked((int)0xffffffc0); break;  // ~0x3f
    case 2: value |= unchecked((int)0xffffe000); break;  // ~0x1fff
    default: value |= unchecked((int)0xf0000000); break; // ~0x0fffffff
}

Bit 0 is the sign and bits 1..(6|13|28) carry the two's-complement payload, sign-extended by encoded width — exactly magnitude | ~payloadMask. The alternative -(raw >> 1) - 1 is the zigzag convention and would misdecode a real -1 (which encodes as 0x7F) as -64; it is also not what Roslyn/Portable PDB producers emit. PeekCompressedInteger bounds the raw value to 0..0x1fffffff, so raw >> 1 never touches bit 31. This is covered by a known-answer test with hand-verified bytes (-2 → 0x7d, -3 → 0x7b) exercising negative δStartLine, δStartColumn, and ΔColumns deltas.

Net: no code changes from this review — finding 1 was already implemented, and findings 2–3 describe the correct ECMA-335 behavior as verified against the reference implementation.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

@greptileai review

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; no new blocking issue was found.

Summary

Adds optional external and embedded Portable PDB selection to managed member inspection.

  • Managed member results can include source sequence points from a Portable PDB.
  • Callers can select an external or embedded PDB for managed inspection.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Managed assembly] --> B[Read members and debug declarations]
  C[External PDB selector] --> D[Bounded file read]
  E[Embedded PDB selector] --> F[Bounded extraction]
  D --> G[Read PDB identity and tables]
  F --> G
  B --> H[Compare declared identity]
  G --> H
  H --> I[Decode documents and selected method points]
  I --> J{Within PDB budget?}
  J -->|Yes| K[Bound debug map]
  J -->|No| L[Malformed debug map with source and identity]
  B --> M[Member result]
  K --> M
  L --> M
Loading

Reviews (7) · Last reviewed commit: "Merge branch 'main' into feat/portable-p..." · Reviewed by Greptile

Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/ManagedMemberInspector.ts Resolved
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdb.fixture.ts Resolved
Comment thread src/dotnet/ManagedDebugDirectory.ts Resolved
Address greptile review on PR morluto#2435:

- Match PDBs by CodeView GUID + debug-entry TimeDateStamp, not RSDS Age;
  portable records keep Age=1 while the entry stamp completes the 20-byte
  PDB ID, so real compiler pairs no longer report mismatched.
- A degraded debug-directory declaration (unreadable entries, truncated
  RSDS, enumeration issues) now marks identity unverifiable instead of
  undeclared or absent.
- Map decode or admission failures after identity resolution keep the
  source digest, PDB facts, and declared identity instead of a bare stub.
- Hidden sequence points validate IL-offset range and ordering; only
  source-line constraints stay non-hidden.
- Document columns decode independently so a bad GUID or blob index
  cannot suppress readable sibling fields.
- The fixture's signed compressed encoder keeps the selected width so
  two- and four-byte negative deltas encode correctly.
- Debug-directory issue accounting counts drops from every reporter and
  forwards the omitted total instead of a summary issue the map sink
  could discard; non-RSDS CodeView records are now visible issues.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@vincent-peng

Copy link
Copy Markdown
Author

Thanks @greptile-apps[bot] — all seven findings verified against the PE-COFF and Portable PDB specs plus the SRM reference implementation. All were valid (with two clarifications noted below) and are addressed in 5cf979bfa.

Fixes

P1 — Portable PDBs looked mismatched ✅ Confirmed and fixed. Per PE-COFF §"Debug Directory", portable CodeView records keep Age = 1 and the 20-byte PDB ID is Guid + the entry's TimeDateStamp — not Age. CodeViewIdentity now carries stamp (entry TimeDateStamp), matching compares GUID + stamp, and the fixture models a real producer pair (age: 1, stamp distinct from age) so the old comparison would fail its own tests.

P2 — Unreadable declarations looked absent ✅ identityUnknown now covers declaration.issues, not just the optional-header-level pe.debugIssue: truncated RSDS, unmappable entry data, and enumeration failures report unverifiable (external) / malformed (embedded) instead of undeclared / absent. Non-RSDS CodeView signatures are also surfaced as issues rather than dropped silently.

P2 — Failed maps lost identity ✅ The decode + projection-admission section now returns a malformed map that retains the already-resolved source (incl. sha256), pdb facts, identity.status, declared, and checks instead of the bare inspector-level stub.

P2 — Invalid hidden offsets passed ✅ The IL-offset range and ordering checks now run before the hidden early-return, and previousIl tracks hidden points too. Clarification on the mechanism: per the spec only non-hidden points carry source-line constraints, and strictly-decreasing offsets aren't reachable (non-first point records always have δIL ≥ 1) — so the change validates the bound as defense-in-depth rather than a spec requirement.

P2 — Bad document fields hid readable data ✅ Each Document column decodes independently (same isolation pattern as the name column): an out-of-range language GUID now nulls only language/language_guid while name, hash algorithm, and checksum survive with a per-column issue.

P2 — Fixture signed-compressed width ✅ Confirmed: compressedSigned(-8192) emitted 1 byte instead of the 2-byte form (masked payload shrank below the unsigned re-selection boundary). The fixture now emits the branch's fixed width; boundary regressions cover the 2-byte (-8192) and 4-byte (-268402689) negative-delta sets that previously round-tripped wrong.

P2 — Dropped directory issues undercounted ✅ Every directory parse failure now flows through a counted reporter, and ManagedDebugDeclaration carries omitted as a field the map sink sums into its own omitted count — so the retained-issue summary reports the true drop count instead of silently losing it (or burying a summary issue inside it).

Regression coverage

New/extended tests: producer-shaped Age=1 identity match, truncated RSDS → unverifiable, unreadable embedded entry → malformed, 100 unmappable entries → "36 further" summary, hidden point at 0x20000000 → malformed, signed-width boundary round-trip, per-column document isolation, and budget-failure identity preservation.

Validation: 29 unit + 46 focused boundary/MCP/CLI + 183 src/dotnet tests pass; check:fast, docs:check, verify:test-discovery clean.

Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Address greptile round-2 review on PR morluto#2435:

- Bound the CodeView RSDS path at its producer (64 KiB cap plus a
  coverage issue) so a declared_path that exceeded the projection
  budget cannot ride the malformed-map fallback into oversized output.
- Bound the #Pdb version string (1 KiB) for the same reason; real roots
  carry "PDB v1.0".
- Replace issues-based identityUnknown with a dedicated degraded flag:
  only structural directory failures and unreadable or unusable
  CodeView/embedded-PDB entries hide PDB presence; unrelated entry
  failures stay in coverage and embedded selection still reports
  absent.

Regression tests cover unrelated-entry absence, oversized-path
truncation, and the unchanged truncated-RSDS unverifiable case.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@vincent-peng

Copy link
Copy Markdown
Author

Thanks @greptile-apps[bot] — both round-2 findings verified and addressed in 93e60e7b2.

P2 (security) — Failed maps keep oversized paths ✅ Fixed at the producing boundary. readCodeView now caps the retained RSDS path at 64 KiB (real paths are far smaller) and records a coverage issue when truncating, so declared_path stays bounded on every path — bound map, all stubs, and the budget-failure fallback alike. A follow-up audit of every field reaching the early-return/catch stubs found one sibling vector: pdb.version could carry up to the full input-file size into the unadmitted stub. The metadata root now rejects a decoded version over 1 KiB as invalid-metadata-root (real roots carry "PDB v1.0"). Everything else in the stubs is caller-supplied input, hex digests, numbers, or issue strings built from fixed messages.

P2 — Missing PDBs look unreadable ✅ Valid — the first-round issues.length > 0 signal was too broad. ManagedDebugDeclaration now carries a dedicated degraded flag: it is set only when evidence that could hide a PDB declaration is lost — structural directory failures (non-multiple size, enumeration cap, unmappable directory RVA), an unmappable payload on a CodeView or embedded-PDB typed entry, or a CodeView record that fails to parse or carries a non-RSDS signature. An unmappable payload on an unrelated entry type keeps its coverage issue but no longer degrades identity: external selection reports undeclared, embedded selection reports absent, and a successful RSDS parse still yields matched/mismatched.

Regression tests: unrelated-type entry failure → undeclared/absent, 70 KiB RSDS path → truncated to 64 KiB with matched identity intact, plus the earlier truncated-RSDS → unverifiable and embedded-unreadable → malformed cases confirming the degraded path still works.

Validation: 31 unit + 48 focused boundary/MCP/CLI tests pass; check:fast clean.

@morluto morluto added enhancement New feature or request area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior area: cli CLI adapter and one-shot commands area: server Server layer and tool wiring P2: medium Medium priority issue labels Oct 13, 2026
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdbDebugMap.ts Resolved
Comment thread src/dotnet/PortablePdbLayout.ts Resolved
vincent-peng and others added 2 commits October 14, 2026 11:08
A crafted document-name blob can list millions of empty parts at one
encoded byte each while each retains an array slot and string, so charge
a per-part projection before allocating. Name parts are stored strings
rather than text files, so the decoder now keeps a leading U+FEFF like
the metadata heap readers do.

The initial document record in a sequence-points blob was decoded
without the row bound applied to mid-blob records, letting nil or
out-of-range rows report decoded null-document points. Validate it
against the Document table immediately.

#Pdb row counts are unvalidated claims about the assembly, so bound
Document and StandAloneSig validity checks at the 24-bit token row space
instead of trusting declared counts; rows above 0xffffff can no longer
forge a token for another table. The fixture adds small heap columns
before the name blob so oversized names still fit two-byte indexes.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The describe block merged from main (morluto#2704) runs 162 lines, over the
150-line lint bound, so the operand-width matrix moves into its own
describe.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@vincent-peng

Copy link
Copy Markdown
Author

Verified and addressed all four findings in 777ba665f:

P1 — Empty path parts exhaust memory (decodeDocumentName): Confirmed, and worse than described — each 0x00 part byte allocates an array slot plus a decoded string (~70–110 B real vs 2 B charged), and parts.join replicates the separator uncharged; ~33 M parts could be admitted before the 64 MiB representation budget noticed. The loop now reserves DOCUMENT_NAME_PART_BYTES (128 B) per part before allocating, mirroring the SEQUENCE_POINT_PROJECTION_BYTES convention, so a hostile name trips resource-limit at ~524 K parts and degrades the map to malformed while member evidence survives.

P2 — BOM stripping in document names: Confirmed. ignoreBOM defaults to false, so a leading EF BB BF in a name part was silently dropped — and a BOM-encoded separator would have decoded to "". Document name parts are stored strings, not text files; the decoder now uses ignoreBOM: true, matching the #Strings heap reader in ManagedMetadataHeaps.ts.

P2 — Invalid initial document row accepted: Confirmed, including the no-points escape path — mid-blob document records were range-checked but the initial record was not, so a nil or out-of-range row produced state: "decoded" points with document_token: null. The initial record is now validated against the Document table immediately after the blob header.

P2 — Row counts above the 24-bit token range: Confirmed — metadataToken(0x11, 0x1000000) produces 0x12000000 (table byte 0x12), and #Pdb type-system counts are unvalidated u32 claims. Fixed by bounding the row-validity checks at MAX_TOKEN_ROW (documentRowCount and standaloneSignatureRows are Math.min(declared, 0xffffff)) rather than rejecting at readPdbStream: the declared counts are still needed for table-index sizing, and a PDB overstating the assembly's StandAloneSig table is only dangerous when a row is actually tokenized. Rows above 0xffffff now report malformed instead of emitting forged tokens.

Regression coverage added: 600 K empty name parts → resource-limit; /src/\uFEFFProgram.cs name round-trips; three invalid initial-document blobs (nil row, out-of-range, and the no-points escape); declared StandAloneSig = 0x1000000 → malformed with local_signature_token: null.

Also pushed a1e3e2a11: a mechanical split of ManagedCilDecoding.test.ts's operand-extent describe — the block merged from main in 44366a23a runs 162 lines, over the 150-line lint bound, and was failing check:fast on this branch independent of these changes.

Validation: 35 Portable PDB unit tests, 52 tests across the focused provider/MCP/CLI lanes, 183 src/dotnet tests — all pass; npm run check:fast clean.

Keep the Portable PDB selection alongside the new userStrings member
inspection option, report #US literals next to the bound debug_map, and
carry the upstream operand-width describe split name.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The new --pdb and --pdb-embedded options work on Node 24 and 26. On head 807c35a, a matching, a mismatched, an embedded and a truncated PDB each report the right state. Base has no such option, and GitHub says head now conflicts with main.

I tested head 807c35a as pushed, on the PR's own byte-built fixtures. I wrote one throwaway test that saves those fixtures as files, then ran the real CLI on them. Base is bbf0638 (#3044).

Results

Check Node 24.18.0 Node 26.11.1
The PR's four test files on head (52 tests) pass pass
CLI --pdb, matching pair, head identity matched, 3 points kept same as Node 24
CLI --pdb, PDB with another GUID, head identity mismatched, map still bound same as Node 24
CLI --pdb-embedded, head identity matched, source embedded same as Node 24
CLI --pdb, PE with no debug entry, head identity undeclared same as Node 24
CLI --pdb on a file cut short at 90 bytes, head map malformed, identity unverifiable same as Node 24
CLI relative --pdb, or both selectors, head rejected, exit 1 same as Node 24
Selector commands on main b7dcf78 (#3825), 7 runs "Unknown flag", exit 1 not run
Selector commands on base bbf0638 (#3044), 2 runs "Unknown flag", exit 1 not run
No selector: head against base all fields equal except the new debug_map: null not run

The matching pair uses age 1 with a different stamp. That is the shape of a real compiler pair, and it is the case the P1 fix was about. It reads as matched.

Hidden points show start and end line 16,707,566 (0xFEEFEE) next to hidden: true. The PR's own code sets this marker as HIDDEN_LINE (0xfe_efee), so it is by design. Callers should read the flag.

With no selector, evidence_id differs between head and base. I did not check why. It may hash the new null field (unverified).

I also joined head with main b7dcf78 (#3825) as text, outside git. It gives 4 conflict regions in 3 files: docs/managed-code-analysis.md, managedToolContracts.ts and ManagedMemberInspector.ts (2 regions). GitHub's own check was not repeated.

Not run

  • A real compiler-built DLL and PDB. This box has no .NET SDK, and I did not install one. The PR body names the same gap.
  • Head merged onto current main.
  • The wider src/dotnet suites, check:fast, docs:check and verify:test-discovery.
  • Node 22, Windows and macOS.
  • Base against Node 26.

Thanks, Vincent Peng, for the feature and for the fast, careful answers to every review round.

Test setup
Commands
npm ci && npm run build && npm run test:prepare
node scripts/run-development-tests.mjs focused src/dotnet/PortablePdbDebugMap.test.ts tests/boundary/providers/managed/managedPortablePdb.test.ts tests/boundary/mcp/managedMcp.test.ts tests/acceptance/managedCliOutput.test.ts
node scripts/rea.mjs inspect-managed-members <exe> [--pdb <pdb> | --pdb-embedded] --json

Each build and run sat under nice -n 19 and systemd-run --user --scope -p MemoryMax=6G, with a throwaway home folder. Other test jobs shared the box.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@vincent-peng thanks for the PR — this branch has merge conflicts with main. Could you merge or rebase onto the latest main and resolve them? Once it's clean and CI is green we can take another look.
cc @gensokyo-dev @dandgabr

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: cli CLI adapter and one-shot commands area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior area: server Server layer and tool wiring enhancement New feature or request P2: medium Medium priority issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Bind Portable PDB sequence points to selected managed methods

4 participants