Repository navigation
feat(native): decode RT_STRING and RT_VERSION payloads in PE resources - #2887
thefolahan wants to merge 9 commits into
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 54ba142758
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8f7af3df1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ): PeResources["version_infos"] => | ||
| resources | ||
| .filter((resource) => isResourceType(resource, RT_VERSION)) | ||
| .map((resource) => { |
There was a problem hiding this comment.
Cache or yield repeated version payload decodes
When an image has many RT_VERSION leaves pointing to the same exact payload range (a shape that rejectOverlappingRanges permits and the hash loop already deduplicates), this map reparses the whole block tree synchronously for every resource. A valid 65,535-byte root can hold about 8,000 minimal children, so the default 16,384-entry tree can force tens of millions of parses; because no yield or signal check occurs until after both decoder passes in parsePeResources, cancellation cannot be delivered while the MCP event loop is blocked. Cache by payload range as hashing does, or make this traversal cancellable.
AGENTS.md reference: AGENTS.md:L46-L50
Useful? React with 👍 / 👎.
| const declared = | ||
| type === 1 ? Math.min(valueLength * 2, blockEnd - valueAt) : valueLength; | ||
| if (valueAt + declared > blockEnd) | ||
| malformed(`Version value for ${JSON.stringify(key)} leaves its block.`); |
There was a problem hiding this comment.
Reject impossible text value lengths
When a text node's wValueLength is larger than both the available byte count and the available UTF-16-unit count (for example, a short CompanyName node mutated to 0xffff), this clamp consumes the remaining block, makes the following bounds check ineffective for type 1, and reports the payload as decoded. The byte-counted compiler quirk only requires falling back to valueLength bytes when that count fits; values that fit neither interpretation should produce the promised malformed result.
AGENTS.md reference: AGENTS.md:L29-L29
Useful? React with 👍 / 👎.
| // part, and the resource inventory still succeeds. | ||
| string_tables: z.array( | ||
| z.strictObject({ | ||
| resource_index: uint, |
There was a problem hiding this comment.
Validate new payload references at the Evidence boundary
Whenever a PeResourcesPort returns schema-valid but inconsistent output—for example, a string table whose resource_index points to RT_ICON or a version string location outside its associated payload—the new fields pass both peResourcesSchema and PeResourcesService.validReport: that validator currently traverses resources and icon_groups only and never examines either new array. The service then publishes unattached ownership and locations as observed Evidence, so extend the application-boundary checks and tests to cover resource types, status invariants, and every nested range for these records.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| kind: "native-provider", | ||
| description: | ||
| "Inspect one explicit local PE32/PE32+ image's complete bounded type/name/language resource tree without executing it or opening a disassembler. Returns numeric IDs versus original UTF-16 names, directory/data-entry file locations, payload RVA/file ranges, complete SHA-256 hashes and static RT_GROUP_ICON image-resource candidates. Language fallback, image decoding and actual shell/window loading remain unobserved. Reads a stable regular file; malformed or ambiguous mappings, non-identical overlapping ranges and exhausted budgets return no partial success. Portable on supported Node hosts; no Windows SDK or engine installation required.", | ||
| "Inspect one explicit local PE32/PE32+ image's complete bounded type/name/language resource tree without executing it or opening a disassembler. Returns numeric IDs versus original UTF-16 names, directory/data-entry file locations, payload RVA/file ranges, complete SHA-256 hashes, static RT_GROUP_ICON image-resource candidates, decoded RT_STRING tables (string IDs, text and locations) and RT_VERSION details (fixed file and product versions, StringFileInfo values such as CompanyName and FileVersion, and translations). A malformed string or version payload is reported with a reason instead of failing the inventory. Language fallback, image decoding and actual shell/window loading remain unobserved. Reads a stable regular file; malformed or ambiguous mappings, non-identical overlapping ranges and exhausted budgets return no partial success. Portable on supported Node hosts; no Windows SDK or engine installation required.", |
There was a problem hiding this comment.
Advertise the new decoders in CLI and packaged skill
Although this contract now exposes RT_STRING and RT_VERSION decoding, the inspected CLI registration at src/cli/binaryDiagnosticsCommands.ts:24-26 still advertises only identities, hashes, and icons, while .agents/skills/reverse-engineer-anything/references/native-and-artifacts.md:241-248 still says the other payloads are opaque. Users and packaged agents discovering the capability through those surfaces will not know these arrays exist; update both source descriptions before regenerating the ignored skill output.
AGENTS.md reference: AGENTS.md:L71-L71
Useful? React with 👍 / 👎.
|
Source fixes and publication evidence for the review findings below. Tests and executable checks were skipped at the maintainer's request. Findings that still require a decision or execution evidence remain open. The version decoder now requires a binary root and verifies both the declared 52-byte fixed-info length and the complete in-root value range before reading fixed fields. Malformed blocks remain per-resource malformed results. Published on the live PR branch; targeted formatting and git diff --check passed; no tests run. readChildren now checks that two bytes remain in the parent before reading a child length, routing short tails through the existing MalformedPayload result path instead of leaking RangeError. Published on the live PR branch; targeted formatting and git diff --check passed; no tests run. |
e8f7af3 to
4d83c25
Compare
| ensureCapacity(textBytes(entry.location.bytes / 2)); | ||
| return { | ||
| key: entry.key, | ||
| value: entry.type === 1 ? textValue(bytes, entry.value) : null, |
There was a problem hiding this comment.
When a string entry has type = 0, readStringFileInfo replaces its value with null and reports the version payload as decoded. readTranslations also reads text entries as binary language/code-page pairs. Someone inspecting these broken resources gets missing text or misleading translations under a success label.
Check the required types before decoding these entries. A broken layout should return malformed with no decoded values, as the tool promises.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/pe/PeResourcePayloads.ts
Line: 241
Comment:
**Broken versions look decoded**
When a string entry has `type = 0`, `readStringFileInfo` replaces its value with `null` and reports the version payload as `decoded`. `readTranslations` also reads text entries as binary language/code-page pairs. Someone inspecting these broken resources gets missing text or misleading translations under a success label.
Check the required types before decoding these entries. A broken layout should return `malformed` with no decoded values, as the tool promises.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| report.string_tables.push({ | ||
| resource_index: report.resources.length - 1, | ||
| status: "decoded", | ||
| block_id: 1, | ||
| first_string_id: 0, | ||
| strings: [], | ||
| trailing_bytes: 0, | ||
| reason: null, | ||
| }); |
There was a problem hiding this comment.
The new bad-string-location and bad-version-location tests never check a bad location. The string case fails because strings is empty. The version case fails because resource_index is past the resource array, and its malformed row has no decoded locations.
Both tests would still pass if the new withinPayload checks were removed. Build otherwise-valid decoded rows, then move one location outside its resource payload so the tests catch that regression.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/binaryDiagnostics/PeResourcesService.test.ts
Line: 47-55
Comment:
**Location checks go untested**
The new `bad-string-location` and `bad-version-location` tests never check a bad location. The string case fails because `strings` is empty. The version case fails because `resource_index` is past the resource array, and its malformed row has no decoded locations.
Both tests would still pass if the new `withinPayload` checks were removed. Build otherwise-valid decoded rows, then move one location outside its resource payload so the tests catch that regression.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.0c8c9ea to
abade91
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: abade91531
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const { offset, bytes: size } = resource.payload.location; | ||
| let info: VersionInfo; | ||
| try { | ||
| const root = readBlock(bytes, offset, offset + size, offset); |
There was a problem hiding this comment.
Reject bytes outside the version root
When an RT_VERSION data entry is longer than the root's wLength—for example, a valid payload whose root length is corrupted to end after the 52-byte fixed info—readBlock returns that prefix and the decoder never checks root.location.bytes against size. It consequently publishes status: "decoded" while silently dropping trailing StringFileInfo/VarFileInfo bytes; reject or report non-padding bytes outside the root before publishing decoded facts.
AGENTS.md reference: AGENTS.md:L29-L29
Useful? React with 👍 / 👎.
| if (type === 1 && valueLength > available) | ||
| malformed(`Version value for ${JSON.stringify(key)} leaves its block.`); | ||
| const declared = | ||
| type === 1 ? Math.min(valueLength * 2, available) : valueLength; |
There was a problem hiding this comment.
Reject odd byte-counted version text values
When a type-1 child is truncated to a one-byte value with wValueLength = 1, the new greater-than guard passes and Math.min makes declared one byte; textValue then emits an empty string because no UTF-16 code unit fits, and the whole version record remains decoded. Only use the byte-count fallback for an even UTF-16 byte extent. This is fresh evidence beyond the earlier oversized-length case: the declared count equals available but is still impossible.
AGENTS.md reference: AGENTS.md:L29-L29
Useful? React with 👍 / 👎.
| table.block_id === null || | ||
| table.block_id < 1 || | ||
| table.block_id > 4096 || | ||
| table.first_string_id !== (table.block_id - 1) * 16 || |
There was a problem hiding this comment.
Match decoded string blocks to their resource names
When a provider returns a decoded table attached to an RT_STRING resource named block 1 but supplies block_id: 2 and IDs 16–31, these checks pass because the block ID is bounded but never compared with the owning resource's name, so the service publishes strings under the wrong IDs. Require a decoded table's owner name to be numeric and equal to block_id; the fresh evidence after the prior boundary fix is that its new type check still omits this ownership comparison.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
inspect_pe_resources returned string tables and version resources as opaque bytes, though both formats are fixed and documented. They answer the first questions of a Windows investigation: which build this is and which messages it shows. string_tables expands each RT_STRING block into its sixteen string IDs, keeping empty slots and every string's file location. version_infos decodes VS_FIXEDFILEINFO, each StringFileInfo table and the VarFileInfo translations. A payload that breaks its layout is reported as malformed with a reason while the inventory still succeeds. Fixes morluto#2812
abade91 to
fc350ff
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fc350ff5ce
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| readChildren(bytes, block, base) | ||
| .filter((entry) => entry.key === "Translation") | ||
| .flatMap((entry) => { | ||
| if (entry.value.bytes % 4 !== 0) |
There was a problem hiding this comment.
Validate Translation as binary before decoding
When a one-pair Translation node has only its wType corrupted from 0 to 1, its unchanged wValueLength = 4 and four-byte value still pass readBlock's byte-count text fallback, and this key-only path publishes those bytes as a language/code-page pair with status: "decoded". Translation values are binary, so check entry.type === 0 before deriving observed values and report this type corruption as malformed.
AGENTS.md reference: AGENTS.md:L29-L29
Useful? React with 👍 / 👎.
| const key = `${String(offset)}:${String(size)}`; | ||
| let cached = decodedByRange.get(key); | ||
| if (cached === undefined) { | ||
| cached = decode(resource); |
There was a problem hiding this comment.
Yield between distinct version payload decodes
When max_file_bytes is raised to 512 MiB, about 8,000 distinct 65-KiB RT_VERSION payloads fit under the 16,384-entry cap, and each can contain roughly 8,000 minimal children that are parsed and then discarded. The new cache only covers identical offset/size keys, so this fresh distinct-range case still executes tens of millions of synchronous node parses; in the inspected parsePeResources flow, there is no signal check or yield between invoking this decoder and building the report, blocking cancellation and other MCP work. Yield/check the signal during traversal or impose a decoding work bound.
AGENTS.md reference: AGENTS.md:L46-L50
Useful? React with 👍 / 👎.
| ) | ||
| return false; | ||
| if ( | ||
| !report.string_tables.every((table) => { |
There was a problem hiding this comment.
Require one payload result per matching resource
When a PeResourcesPort omits the row for an RT_STRING resource or repeats another resource_index, this .every check still passes because it validates only supplied rows and an empty string_tables array is vacuously valid; the identical version_infos check has the same gap. The new per-row checks therefore still allow complete Evidence to lose a decoded-or-malformed result for a resource, so compare the unique reported index set with all type-6/type-16 resource indices.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| info.string_file_info.every( | ||
| (table) => | ||
| withinPayload(table.location) && | ||
| table.strings.every((string) => withinPayload(string.location)), |
There was a problem hiding this comment.
Keep version string ranges inside their table
When a provider reports a StringFileInfo table range in one part of the payload but places a claimed child string range elsewhere in the same payload, both of these payload-level checks pass. This is fresh evidence beyond the earlier outside-payload case: the service then publishes a string under a table that does not own its source bytes, so validate each string range against its containing table.location, not only the resource payload.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
The repeated-range test built two version resources with separate payload copies, so their locations differed and the decode cache keyed by (offset, size) never ran. Point the second data entry at the first payload's RVA and size so both records come from one range and must still be independent clones. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
CI-fix track: the shard 6 and Portable failure came from this PR's own |
|
TL;DR: The PR's own 19 tests pass on Node 22, 24 and 26 at head 8bcb160. Six of the open bot findings still reproduce on this head with PEs I built myself. One does not. Edit: this comment first said I was testing. The results are below. The head is 977 commits behind main (7c6c25d), but its diff applies to main with Results at 8bcb160
Open bot findings I replayedI built each PE or report by hand with the repo's
Not run
Thanks, thefolahan, for the Test setupCommandsAll ran with exit 0, with 🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊 |
|
@thefolahan thanks for the PR — there are 13 open review threads here:
Could you address or reply to these? Once they're resolved and CI is green we can take another look. |
|
@thefolahan also, this branch has merge conflicts with |
Summary
Fixes #2812.
inspect_pe_resourcesnow decodesRT_STRINGandRT_VERSIONpayloads, which it previously returned as opaque bytes. Both formats are fixed and documented, and they answer two first questions of a Windows investigation: which build is this, and which messages does it contain.On Microsoft's own
dbghelp.dll(shipped inside WebStorm's async-profiler), the result now includes:and on
symsrv.dll, string blocks 63 to 66 expand to IDs such as1002="Symbol Server"and1022="Requests/sec".Change and scope
Two new arrays sit next to
icon_groups, both produced by a newsrc/native/pe/PeResourcePayloads.ts.string_tables, one perRT_STRINGresource:(N - 1) * 16through(N - 1) * 16 + 15.trailing_bytescounts padding after the sixteenth string instead of rejecting it.version_infos, one perRT_VERSIONresource:fixed_file_info: theVS_FIXEDFILEINFOsignature is checked. File and product versions come as text ("6.6.3.0") and as their original words, plus flags, OS, type, subtype and date.string_file_info: everyStringFileInfotable, with its key split into language and code page, and each value with its location.translations: theVarFileInfo\Translationlanguage and code page pairs.As the issue asks, a payload that breaks its documented layout becomes
status: "malformed"with areasonand no decoded values, while the resource inventory still succeeds. Decoded text is reserved against the existing 8 MiB metadata budget before allocation, and every row goes through the sameaccountpath as icon groups.Not included:
RT_MESSAGETABLEand other payload formats, which stay opaque, and LoadString/VerQueryValue language fallback, which is not observed. Both limitations are stated in the result.Contract and boundary impact
src/native/pe(payload decoding after the resource tree is read).peResourcesSchemaowns the contract.string_tablesandversion_infos, empty when an image has no such resources), an updated tool description and example title, and updated limitation text.docs/binary-diagnostics.mddescribes both decoders and the malformed status.Verification
Node 24.21.0 on macOS (Apple silicon):
src/native/pe/PeResourcePayloads.test.ts(new, 10 tests) builds payloads by hand, independent of the decoder. It covers a 16-ID block with empty slots and non-ASCII text checked against its byte range, trailing padding, a truncated block, a string past its block, a named block, full version info with string tables and translations, a byte-counted text value, a bad signature, a wrong root key, and a length past the payload. Each malformed case asserts the inventory still succeeds.src/native/pe(34 tests),tests/acceptance/applications/peResources.test.tsthrough the compiled CLI and real stdio MCP,tests/boundary/mcp/toolSchemaValidity.test.ts,tests/boundary/mcp/compactInputSchemaMcp.test.ts,src/contractsandtests/conformance/contracts: all pass.npm run check:fast,npm run docs:checkandnpm run verify:test-discovery: pass.dbghelp.dllandsymsrv.dll(version info and string tables as above), and Ghidra'sWinHelloCPP.exetraining sample, whose block 7 decodes to103="WinHello"and109="WINHELLO", the Visual Studio template'sIDS_APP_TITLEandIDC_WINHELLO. Other PE files without these resources return empty arrays.I did not have the issue's DATASUS sample, so it was not run.