Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
record the renderer accessibility mode in crash diagnostics (PRD-8179) (#3739)
Andrew Mikofalvy309ebd1c1c1b
diff --git a/.changeset/bug-report-accessibility-mode.md b/.changeset/bug-report-accessibility-mode.mdnew file mode 100644index 000000000..4526b6a75--- /dev/null+++ b/.changeset/bug-report-accessibility-mode.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Bug reports and crash logs from the desktop app now record whether assistive technology was active. A recurring family of editor crashes only happens when Chromium is building its accessibility tree, which it does lazily once it detects a screen reader, a voice-input tool, or an input method that reads the screen. Reports carried no trace of that at all, so the single most important fact about these crashes had to be guessed at from circumstance. Two records close the gap. Chromium already stamps the exact accessibility state onto every crash dump it writes, and reports now read it out and put it in the log rather than leaving it buried in a binary file nobody opens. Separately, the app now notes at startup, and again whenever it changes, whether assistive technology is attached, so the timing is visible even on reports that carry no crash dump. Nothing new is collected about you or your documents: the accessibility state is a Chromium setting, identical for everyone running the same assistive tool.diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.tsindex b4ba50bc6..20e19c0fa 100644--- a/packages/desktop/src/main/crash-detection.test.ts+++ b/packages/desktop/src/main/crash-detection.test.ts@@ -60,6 +60,12 @@ interface Rig {ownDump: Buffer;/** The same dump, plus the Crashpad annotations a real one carries. */ownDumpStamped(version: string): Buffer;+ /**+ * A dump stamped like `ownDumpStamped`, plus Chromium's `ax_mode` crash key+ * in the module annotation objects — the SEPARATE structure real dumps carry+ * it in, not the simple dictionary beside the version.+ */+ ownDumpWithAxMode(version: string, mode: string): Buffer;/*** Ours, but captured by `CRASHPAD_SIMULATE_CRASH()` rather than by a fault —* what Chromium's GPU watchdog leaves behind for a process it then lets keep@@ -114,6 +120,13 @@ function makeRig(): Rig {buildMinidump(ownModules, {annotations: { _productName: 'OpenKnowledge', _version: version, prod: 'Electron' },}),+ ownDumpWithAxMode: (version: string, mode: string) =>+ buildMinidump(ownModules, {+ annotations: { _productName: 'OpenKnowledge', _version: version, prod: 'Electron' },+ // A module carrying nothing comes first, as in a real dump, so a walk+ // that gave up at the first link would fail this.+ annotationObjects: [{}, { ax_mode: mode, process_type: 'renderer' }],+ }),setRendererAvailable(available: boolean) {rendererAvailable = available;},@@ -1411,6 +1424,66 @@ describe('the version a boot invitation attributes the crash to', () => {expect(breadcrumb?.crashedAppVersionParseFailed).toBe(false);});+ test('the boot breadcrumb names the accessibility mode the dead session ran with', () => {+ // The precondition the Blink accessibility CHECK crashes turn on: that+ // CHECK is only reachable with a live accessibility tree, and+ // OK_FORCE_A11Y is opt-in, so before this line the tree's presence could+ // only be argued from circumstance. Chromium records it on every dump;+ // nothing read it.+ const mode = 'kNativeAPIs | kWebContents | kInlineTextBoxes | kExtendedPropert';+ const rig = makeRig();+ const sessionA = createCrashDetection(rig.deps);+ sessionA.detectBootCrash();+ sessionA.markCleanQuit();+ seedMinidump(+ rig,+ 'pending/native.dmp',+ rig.tick(),+ rig.ownDumpWithAxMode(CRASHED_VERSION, mode),+ );++ const infoLines: Array<Record<string, unknown>> = [];+ rig.deps.logger = {+ info: (payload: Record<string, unknown>) => {+ infoLines.push(payload);+ },+ warn: () => {},+ };+ createCrashDetection(rig.deps).detectBootCrash();++ const breadcrumb = infoLines.find((line) => line.event === 'crash-detection.boot');+ expect(breadcrumb?.crashedAccessibilityMode).toBe(mode);+ expect(breadcrumb?.crashedAccessibilityModeParseFailed).toBe(false);+ // Read from the SAME dump as the version, so the two describe one death.+ expect(breadcrumb?.crashedAppVersion).toBe(CRASHED_VERSION);+ });++ test('a dump carrying no accessibility mode logs null, not a missing field', () => {+ // "We looked and the dump does not say" is itself the finding, and it is+ // NOT "accessibility was off" — a dump for a process with no renderer in it+ // never registers the key at all. A field that vanished here would make the+ // absent case indistinguishable from a build that predates this line.+ const rig = makeRig();+ const sessionA = createCrashDetection(rig.deps);+ sessionA.detectBootCrash();+ sessionA.markCleanQuit();+ seedMinidump(rig, 'pending/native.dmp', rig.tick(), rig.ownDumpStamped(CRASHED_VERSION));++ const infoLines: Array<Record<string, unknown>> = [];+ rig.deps.logger = {+ info: (payload: Record<string, unknown>) => {+ infoLines.push(payload);+ },+ warn: () => {},+ };+ createCrashDetection(rig.deps).detectBootCrash();++ const breadcrumb = infoLines.find((line) => line.event === 'crash-detection.boot');+ expect(breadcrumb).toHaveProperty('crashedAccessibilityMode');+ expect(breadcrumb?.crashedAccessibilityMode).toBeNull();+ expect(breadcrumb?.crashedAccessibilityModeParseFailed).toBe(false);+ });+test('a foreign dump does not make the event dump-driven', () => {// A descendant process crashing is not this app crashing, so its dump must// not flip the event off the sentinel path — and the sentinel, not thediff --git a/packages/desktop/src/main/crash-detection.ts b/packages/desktop/src/main/crash-detection.tsindex 0414ea359..9b630c901 100644--- a/packages/desktop/src/main/crash-detection.ts+++ b/packages/desktop/src/main/crash-detection.ts@@ -63,6 +63,7 @@ import {classifyMinidumpCrashKind,classifyMinidumpOwnership,type MinidumpOwnership,+ readMinidumpAccessibilityMode,readMinidumpAppVersion,} from './minidump-ownership.ts';@@ -793,6 +794,12 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {: undefined;const dumpVersion =eventDump === undefined ? null : readMinidumpAppVersion(eventDump.entry.path);+ // Chromium's own record of whether an accessibility tree was live in+ // the process that died. Read from the SAME dump the event id and the+ // version come from, so all three describe one death rather than+ // three separately-chosen dumps.+ const dumpAccessibilityMode =+ eventDump === undefined ? null : readMinidumpAccessibilityMode(eventDump.entry.path);const crashedAppVersion = dumpDriven ? (dumpVersion?.version ?? null) : prevAppVersion;const event: OkBugReportCrashDetectedEvent = {eventId,@@ -823,6 +830,16 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {// change both reach the report as no version at all, and they// send whoever debugs it in opposite directions.crashedAppVersionParseFailed: dumpVersion?.parseFailed ?? false,+ // Chromium's `ax_mode` for the process that died. The Blink+ // accessibility `CHECK` crashes are reachable only with a live+ // accessibility tree, and `OK_FORCE_A11Y` is opt-in, so before+ // this the precondition could only be guessed at from+ // circumstance. Logged even when null for the same reason the+ // version is — but null here is NOT "accessibility was off",+ // only "this dump does not say"; see+ // `MinidumpAccessibilityModeRead`.+ crashedAccessibilityMode: dumpAccessibilityMode?.mode ?? null,+ crashedAccessibilityModeParseFailed: dumpAccessibilityMode?.parseFailed ?? false,detectingAppVersion: deps.appVersion,},'previous session ended uncleanly — arming report invitation',diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 43eaccf5b..3df9c10e4 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -7465,10 +7465,54 @@ if (instanceLabel) {// because the always-on AX tree carries a small perpetual cost — set// `OK_FORCE_A11Y=1` when driving the app with an accessibility/automation tool.// Must run before `app` is ready (command-line switches are read at that point).-if (process.env.OK_FORCE_A11Y === '1') {+const A11Y_FORCED_BY_ENV = process.env.OK_FORCE_A11Y === '1';+if (A11Y_FORCED_BY_ENV) {app.commandLine.appendSwitch('force-renderer-accessibility');}+/**+ * Record whether assistive technology is attached, at boot and on every flip.+ *+ * A whole family of renderer crashes reaches a Blink `CHECK` that is only+ * reachable with a live accessibility tree. Chromium builds that tree lazily,+ * once it detects an AT client — so on a report where `OK_FORCE_A11Y` was not+ * set, the precondition of the entire diagnosis had to be argued from+ * circumstance. Not one accessibility line existed in any bundled log to argue+ * from.+ *+ * The companion signal is `ax_mode`, read off a minidump's Crashpad+ * annotations (see `readMinidumpAccessibilityMode`). That one is exact — the+ * full mode bitmask — but exists ONLY where there is a readable dump. This one+ * is coarse and always present, and it carries the thing a dump cannot: WHEN+ * the client attached, relative to everything else in the log.+ *+ * Read `supportEnabled` narrowly. It is Electron's `isAccessibilitySupportEnabled`,+ * the browser process's own summary of whether an AT client is attached — not+ * the renderer's `ui::AXMode`, and not a claim about which accessibility flags+ * any particular renderer had set. A false here does NOT establish that no+ * accessibility tree existed; only `ax_mode` answers that, and only for a+ * process that died.+ *+ * Each phase reports the value from its own authoritative source rather than+ * re-reading: the event hands the new value to the listener directly, and+ * whether the getter has already settled by then is Chromium's business, not a+ * thing this log should quietly depend on.+ */+function logAccessibilityPosture(phase: 'boot' | 'changed', supportEnabled: boolean): void {+ getRootDesktopLogger().info(+ {+ event: 'desktop.accessibility',+ phase,+ supportEnabled,+ // Whether the app itself forced the tree on, which makes `supportEnabled`+ // beside the point for reachability: with the switch set, every renderer+ // has a full tree whatever any AT client is doing.+ forcedByEnv: A11Y_FORCED_BY_ENV,+ },+ 'renderer accessibility posture',+ );+}+if (isDriverBootSmokeMode(process.env)) {app.whenReady().then(() => {runDriverBootSmokeInProduction();@@ -7680,6 +7724,12 @@ function bootPrimaryInstance(): void {// xterm's `screenReaderMode` in place. Cold-start value rides window// creation via `--ok-screen-reader-active` (see withDebugFlagIfAllowed).app.on('accessibility-support-changed', (_event, screenReaderActive) => {+ // Logged before the fan-out, so the record survives a send that throws.+ // The timestamp is the point: it places an AT client attaching against the+ // rest of the session, which is the one thing a crash dump's `ax_mode`+ // cannot say. `@platform darwin,win32` — this never fires on Linux, so a+ // Linux log carries the boot line alone.+ logAccessibilityPosture('changed', screenReaderActive);for (const win of BrowserWindow.getAllWindows()) {if (win.webContents.isDestroyed()) continue;sendToRenderer(win.webContents, 'ok:accessibility:changed', { screenReaderActive });@@ -7933,6 +7983,13 @@ function bootPrimaryInstance(): void {// its return tells the waterfall whether main spans are live.startupWaterfall.mark('appReady');startupWaterfall.otelEnabled = beginRoot();+ // The cold-start accessibility posture. Read HERE rather than beside the+ // `desktop.boot` line, which runs before `whenReady`:+ // `isAccessibilitySupportEnabled` reaches into browser-process state that+ // does not exist until then, and a pre-ready read would report a default+ // rather than an answer. `accessibility-support-changed` covers every+ // later flip, so between them the whole session is described.+ logAccessibilityPosture('boot', app.isAccessibilitySupportEnabled());// Login-shell SSH_AUTH_SOCK harvest — started here so its (2s-bounded)// shell spawn overlaps the bootstrap I/O below; awaited + applied just// before the window-open branch, ahead of the git preflight and bothdiff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.tsindex f8fb9766a..4d903c440 100644--- a/packages/desktop/src/main/ipc/bug-report.test.ts+++ b/packages/desktop/src/main/ipc/bug-report.test.ts@@ -65,6 +65,7 @@ import {sidecarPathForId,} from '../bug-report-sidecar.ts';import { createCrashDetection } from '../crash-detection.ts';+import { buildMinidump } from '../minidump.test-helper.ts';import { handleShellOpenExternal } from '../shell-allowlist.ts';import {type BugReportCreateDeps,@@ -1551,6 +1552,82 @@ describe('handleBugReportCreate — crash-dump opt-in', () => {);});+ test('the decision line names the accessibility mode the crashed process ran with', async () => {+ // The one fact that makes a Blink-accessibility-CHECK bundle diagnosable:+ // whether an accessibility tree was live. It rides this line specifically+ // because the line is written BEFORE collection, so it lands in the same+ // bundle as the dump it describes rather than in some later report.+ const mode = 'kNativeAPIs | kWebContents | kInlineTextBoxes | kExtendedPropert';+ const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');+ writeFileSync(+ dumpPath,+ buildMinidump(['/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge'], {+ annotationObjects: [{}, { ax_mode: mode, process_type: 'renderer' }],+ }),+ );+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(dumpPath),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).toMatchObject({+ event: 'bug-report.minidump-decision',+ accessibilityMode: mode,+ accessibilityModeParseFailed: false,+ });+ });++ test('a dump that names no accessibility mode records an explicit null', async () => {+ // "We read the dump and it does not say" and "no dump was ever read" are+ // different findings. The first is a null; the second is the field being+ // absent entirely, asserted in the next test.+ const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');+ writeFileSync(dumpPath, 'dump-bytes');+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(dumpPath),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).toHaveProperty('accessibilityMode');+ expect(recorder.intent()?.payload.accessibilityMode).toBeNull();+ });++ test('a report with no dump in play carries no accessibility field at all', async () => {+ // A null here would read as "we looked at a dump and it was silent", which+ // is a claim about a dump that does not exist.+ const recorder = makeLogRecorder();+ const deps = makeDeps({+ newestMinidumpForReport: () => dumpLookup(null),+ logger: recorder.logger,+ });++ const result = await handleBugReportCreate(deps, {+ kind: 'create',+ level: 'standard',+ includeCrashDump: true,+ });++ if (!result.ok) throw new Error(`expected ok, got: ${result.error}`);+ expect(recorder.intent()?.payload).not.toHaveProperty('accessibilityMode');+ expect(recorder.intent()?.payload).not.toHaveProperty('accessibilityModeParseFailed');+ });+test('without the opt-in no minidump is included even when one exists', async () => {const dumpPath = join(makeTmpDir(), 'renderer-crash.dmp');writeFileSync(dumpPath, 'dump-bytes');diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.tsindex 96aecf581..b369329ac 100644--- a/packages/desktop/src/main/ipc/bug-report.ts+++ b/packages/desktop/src/main/ipc/bug-report.ts@@ -44,6 +44,7 @@ import type { OkBugReportSendInput } from '@inkeep/open-knowledge-core/desktop-bimport { type BugReportSendTrace, beginSendTrace } from '../bug-report-trace.ts';import type { MinidumpReportLookup } from '../crash-detection.ts';import { logIpcError } from '../ipc-log.ts';+import { readMinidumpAccessibilityMode } from '../minidump-ownership.ts';import { isPathWithinProject } from '../path-containment.ts';import type { UpdateChannel } from '../state-store.ts';@@ -409,9 +410,22 @@ export async function handleBugReportCreate(: await stat(minidumpPath).then((s) => s.size).catch(() => undefined);+ // Chromium's own record of whether an accessibility tree was live in the+ // process that died. The Blink accessibility `CHECK` crashes are reachable+ // only with one, and `OK_FORCE_A11Y` is opt-in, so until this line existed no+ // bundle could tell a triager whether the precondition held — Crashpad had+ // been recording it on every dump and nothing read it.+ //+ // Read from the dump about to be attached, so the fact and the memory it+ // describes ride the same report rather than being correlated later.+ const dumpAccessibilityMode =+ minidumpPath === null ? null : readMinidumpAccessibilityMode(minidumpPath);+// Deliberately says nothing about WHICH dump: a minidump is unredactable// process memory and its filename is a per-crash identifier, so the record- // carries a size at most.+ // carries a size at most. The accessibility mode does not weaken that: it is+ // a Chromium flag string, identical for every user running the same assistive+ // technology, and names no dump.const decisionFacts = {event: 'bug-report.minidump-decision',requested: request.includeCrashDump === true,@@ -426,6 +440,17 @@ export async function handleBugReportCreate(}: {}),...(dumpSizeBytes !== undefined ? { sizeBytes: dumpSizeBytes } : {}),+ // Present as an explicit null whenever a dump was read, absent when none+ // was. "We looked and the dump does not say" and "nothing was ever looked+ // at" are different findings, and a field that vanished for both would make+ // them one. Null is never "accessibility was off" — see+ // `MinidumpAccessibilityModeRead`.+ ...(dumpAccessibilityMode === null+ ? {}+ : {+ accessibilityMode: dumpAccessibilityMode.mode,+ accessibilityModeParseFailed: dumpAccessibilityMode.parseFailed,+ }),};// Written BEFORE the bundle is collected, because the collector snapshotsdiff --git a/packages/desktop/src/main/minidump-ownership.test.ts b/packages/desktop/src/main/minidump-ownership.test.tsindex 590d36081..44520c3fd 100644--- a/packages/desktop/src/main/minidump-ownership.test.ts+++ b/packages/desktop/src/main/minidump-ownership.test.ts@@ -21,6 +21,7 @@ import { buildMinidump, type MinidumpPatch } from './minidump.test-helper.ts';import {classifyMinidumpCrashKind,classifyMinidumpOwnership,+ readMinidumpAccessibilityMode,readMinidumpAppVersion,} from './minidump-ownership.ts';@@ -625,3 +626,195 @@ describe('classifyMinidumpCrashKind', () => {expect(classifyMinidumpCrashKind(dumpPath, 'darwin')).toBe('non-crash');});});++describe('readMinidumpAccessibilityMode', () => {+ /**+ * The `ax_mode` value a real 0.49.0-beta.30 renderer dump carried, copied+ * exactly — including the cut-off `kExtendedPropert`, which is Crashpad's+ * 64-byte annotation cap and not damage. A fixture that quietly rounded it up+ * to `kExtendedProperties` would stop testing the truncation the parser has+ * to pass through untouched.+ */+ const REAL_AX_MODE = 'kNativeAPIs | kWebContents | kInlineTextBoxes | kExtendedPropert';++ /**+ * The annotation objects beside `ax_mode` in that same dump, in the order+ * Crashpad wrote them, so the lookup is exercised past the first entry and+ * against neighbours that really do sit there.+ */+ const REAL_NEIGHBOURS = {+ max_idle_tasks: '0',+ ax_mode: REAL_AX_MODE,+ renderer_foreground: 'true',+ v8_isolate_address: '0x13400780000',+ process_type: 'renderer',+ };++ function modeOf(patch: MinidumpPatch): string | null {+ const dir = makeDir();+ const dumpPath = join(dir, 'crash.dmp');+ writeFileSync(dumpPath, buildMinidump([ownModule(join(dir, 'OpenKnowledge.app'))], patch));+ const read = readMinidumpAccessibilityMode(dumpPath);+ // Every case below is a dump the parse DECLINES to trust, never one that+ // broke it — the distinction the flag carries. Asserted once here so each+ // case stays a plain value comparison.+ expect(read.parseFailed).toBe(false);+ return read.mode;+ }++ test('a renderer dump names the accessibility mode it died with', () => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS] })).toBe(REAL_AX_MODE);+ });++ test('the mode is found on a later module, not just the first', () => {+ // Measured on a real dump: the crash keys sit on the framework, and a+ // second link carrying no objects at all sits beside it. A walk that+ // stopped at link 0 would read that dump as having no mode.+ expect(modeOf({ annotationObjects: [{}, REAL_NEIGHBOURS] })).toBe(REAL_AX_MODE);+ });++ test('the simple dictionary is NOT where this lives', () => {+ // The whole reason this parse exists rather than another key passed to+ // `findSimpleAnnotation`. A dump carrying `ax_mode` as a simple annotation+ // is not a shape Chromium produces, and reading it from there would be the+ // parser agreeing with a fiction.+ expect(modeOf({ annotations: { ax_mode: REAL_AX_MODE, _version: '0.58.9' } })).toBeNull();+ });++ test('module annotations and the simple dictionary coexist without interfering', () => {+ // Real dumps carry both structures. Neither may be reached through the+ // other, and neither may cost the other its answer.+ const dir = makeDir();+ const dumpPath = join(dir, 'crash.dmp');+ writeFileSync(+ dumpPath,+ buildMinidump([ownModule(join(dir, 'OpenKnowledge.app'))], {+ annotations: { _productName: 'OpenKnowledge', _version: '0.58.9', ver: '41.9.1' },+ annotationObjects: [REAL_NEIGHBOURS],+ }),+ );+ expect(readMinidumpAccessibilityMode(dumpPath).mode).toBe(REAL_AX_MODE);+ expect(readMinidumpAppVersion(dumpPath).version).toBe('0.58.9');+ });++ test('a utility-process dump has no mode, and that is not "accessibility was off"', () => {+ // Measured shape: a NodeService dump carries `process_type=utility` and+ // simply never registers `ax_mode`. Null is the honest answer; the contract+ // that it must not be read as "off" is on `MinidumpAccessibilityModeRead`.+ expect(+ modeOf({ annotationObjects: [{ process_type: 'utility', chrome_trace_id: '69107426' }] }),+ ).toBeNull();+ });++ test('a dump with no crashpad stream at all has no mode', () => {+ expect(modeOf({})).toBeNull();+ });++ test('a dump registering no module annotations has no mode', () => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS], crashpadModuleListRva: 0 })).toBeNull();+ });++ test('a module carrying no annotation objects has no mode', () => {+ expect(modeOf({ annotationObjects: [{}] })).toBeNull();+ });++ test('a non-string annotation type is never decoded as text', () => {+ // A value of any other type is raw bytes — v8 addresses and counters live+ // in this same list. Decoding one because its key matched would put+ // arbitrary process bytes on a log line.+ expect(+ modeOf({ annotationObjects: [{ ax_mode: REAL_AX_MODE }], annotationObjectType: 2 }),+ ).toBe(null);+ });++ test('a value carrying a newline is refused rather than printed', () => {+ // The destination is a line-oriented log, and a dump is untrusted input: a+ // value with a line break could forge the context printed around it.+ expect(modeOf({ annotationObjects: [{ ax_mode: 'kNativeAPIs\nevent: forged' }] })).toBeNull();+ });++ test('an object count larger than the list holds is refused', () => {+ expect(+ modeOf({ annotationObjects: [{ ax_mode: REAL_AX_MODE }], annotationObjectCount: 4096 }),+ ).toBeNull();+ });++ test('a declared object-list size too small for its own entries is refused', () => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS], annotationObjectsSize: 8 })).toBeNull();+ });++ test('a link count larger than the list holds is refused', () => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS], moduleLinkCount: 4096 })).toBeNull();+ });++ test('a declared link-list size too small for its own links is refused', () => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS], crashpadModuleListSize: 4 })).toBeNull();+ });++ test('an object-list pointer past the end of the file is refused', () => {+ expect(+ modeOf({ annotationObjects: [REAL_NEIGHBOURS], annotationObjectsRva: 0x7fff_0000 }),+ ).toBeNull();+ });++ // The two lies below land on the FIRST object of the first module, so these+ // cases pass a single-key map — against `REAL_NEIGHBOURS` they would corrupt+ // `max_idle_tasks` and leave `ax_mode` perfectly readable, which is a test+ // that passes while checking nothing.+ test('a value pointer past the end of the file is refused', () => {+ expect(+ modeOf({+ annotationObjects: [{ ax_mode: REAL_AX_MODE }],+ annotationObjectValueRva: 0x7fff_0000,+ }),+ ).toBeNull();+ });++ test('a value length past the annotation ceiling is refused', () => {+ expect(+ modeOf({+ annotationObjects: [{ ax_mode: REAL_AX_MODE }],+ annotationObjectValueByteLength: 4096,+ }),+ ).toBeNull();+ });++ test('a dump truncated before its module annotations has no mode', () => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS], truncateTo: 80 })).toBeNull();+ });++ test.each([+ ['a bad signature', { signature: 'XXXX' }],+ ['a stream count past the ceiling', { streamCount: 100_000 }],+ ['a stream directory pointing nowhere', { streamDirectoryRva: 0x7fff_0000 }],+ ['a crashpad stream hidden behind another type', { crashpadStreamType: 99 }],+ ])('%s yields no mode and never throws', (_label, patch) => {+ expect(modeOf({ annotationObjects: [REAL_NEIGHBOURS], ...patch })).toBeNull();+ });++ test('reading the mode leaves the ownership verdict untouched', () => {+ // Ownership decides whether raw process memory may leave the machine. This+ // question rides its own file handle precisely so it cannot reach that+ // answer, and adding module annotations must not perturb it.+ const dir = makeDir();+ const bundleRoot = join(dir, 'OpenKnowledge.app');+ const dumpPath = join(dir, 'crash.dmp');+ mkdirSync(join(bundleRoot, 'Contents', 'MacOS'), { recursive: true });+ writeFileSync(+ dumpPath,+ buildMinidump([ownModule(bundleRoot)], { annotationObjects: [REAL_NEIGHBOURS] }),+ );+ expect(classifyMinidumpOwnership(dumpPath, bundleRoot)).toBe('ours');+ expect(readMinidumpAccessibilityMode(dumpPath).mode).toBe(REAL_AX_MODE);+ });++ test('an unreadable path declines rather than throwing, and is not a parse failure', () => {+ const absent = join(makeDir(), 'absent.dmp');+ expect(() => readMinidumpAccessibilityMode(absent)).not.toThrow();+ // An absent file is not a broken parser — it is the ordinary state during a+ // scan of a directory Crashpad is also writing to. `parseFailed` exists to+ // separate "this dump has no mode" from "the parser broke", and a flag that+ // fired on every missing file would say neither.+ expect(readMinidumpAccessibilityMode(absent)).toEqual({ mode: null, parseFailed: false });+ });+});diff --git a/packages/desktop/src/main/minidump-ownership.ts b/packages/desktop/src/main/minidump-ownership.tsindex c853fad02..3c2f685a4 100644--- a/packages/desktop/src/main/minidump-ownership.ts+++ b/packages/desktop/src/main/minidump-ownership.ts@@ -146,6 +146,60 @@ const CRASHPAD_INFO_PREFIX_BYTES = 44;const ANNOTATION_ENTRY_BYTES = 8;const APP_VERSION_ANNOTATION_KEY = '_version';+/**+ * Chromium's crash keys do NOT live in the simple dictionary above.+ *+ * `base::debug::AllocateCrashKeyString` registers into Crashpad's per-module+ * ANNOTATION OBJECT list, a second and entirely separate structure reached+ * through `MinidumpCrashpadInfo.module_list`. Measured on a real OK renderer+ * dump: the simple dictionary held exactly `_productName`, `_version`, `plat`,+ * `prod`, `ver` — Electron's own five — while `ax_mode` sat in the annotation+ * objects of one module alongside `process_type`, `renderer_foreground` and the+ * v8 addresses.+ *+ * Written down because the two structures look interchangeable from a key name+ * and are not: `findSimpleAnnotation` can never return `ax_mode` no matter how+ * well-formed the dump, and the failure is silent — a null that reads exactly+ * like "this dump predates the annotation".+ *+ * `MinidumpCrashpadInfo.module_list` (a location descriptor at +44/+48)+ * -> `MinidumpModuleCrashpadInfoList`: count u32, then N links of+ * `(minidumpModuleListIndex u32, dataSize u32, rva u32)`+ * -> `MinidumpModuleCrashpadInfo`: version u32, then THREE location+ * descriptors — list_annotations, simple_annotations, annotation_objects+ * -> `MinidumpAnnotationList`: count u32, then N of+ * `(nameRva u32, type u16, reserved u16, valueRva u32)`+ *+ * Name and value are both u32-length-prefixed byte runs, so `readAnnotationString`+ * reads either — but only for `type == kString`; every other type's bytes are+ * not text and must never be decoded as such.+ */+const CRASHPAD_MODULE_LIST_SIZE_OFFSET = 44;+const CRASHPAD_MODULE_LIST_RVA_OFFSET = 48;+/** Through `module_list`, the last field this file reads. Real streams are padded past it. */+const CRASHPAD_INFO_MODULE_LIST_PREFIX_BYTES = 52;+const MODULE_LINK_BYTES = 12;+const MODULE_LINK_RVA_OFFSET = 8;+/** `version u32` followed by three 8-byte location descriptors. */+const MODULE_CRASHPAD_INFO_BYTES = 28;+const MODULE_ANNOTATION_OBJECTS_SIZE_OFFSET = 20;+const MODULE_ANNOTATION_OBJECTS_RVA_OFFSET = 24;+const ANNOTATION_OBJECT_BYTES = 12;+const ANNOTATION_OBJECT_TYPE_OFFSET = 4;+const ANNOTATION_OBJECT_VALUE_RVA_OFFSET = 8;+/** `crashpad::Annotation::Type::kString`. Every other type's value is not text. */+const ANNOTATION_TYPE_STRING = 1;++/**+ * Chromium's crash key for the renderer's live `ui::AXMode`, recorded as the+ * flag names joined by ` | ` — e.g.+ * `kNativeAPIs | kWebContents | kInlineTextBoxes | kExtendedPropert`, cut mid-word+ * because Crashpad caps an annotation at 64 bytes. Truncation is ordinary here,+ * not damage: the flags that decide reachability of the accessibility code paths+ * are the leading ones, and a short tail still names them.+ */+const AX_MODE_ANNOTATION_KEY = 'ax_mode';+/*** Ceilings on every count read out of the file before any allocation. A* corrupt or hostile dump can name any u32 here, and a dump is untrusted input@@ -159,6 +213,20 @@ const MAX_MODULE_NAME_BYTES = 8192;const MAX_ANNOTATIONS = 256;/** Both keys and values: a version string is tens of bytes. */const MAX_ANNOTATION_STRING_BYTES = 256;+/** A dump names as many modules as the process loaded; a thousand is a normal count. */+const MAX_MODULE_LINKS = 4096;+/**+ * A whole-walk budget on annotation objects INSPECTED, not a per-list ceiling.+ *+ * The two bounds above are per-record, so on their own they multiply: a dump+ * claiming the maximum links each holding the maximum objects would cost+ * millions of positional reads, on the boot path, for a file we already distrust.+ * One budget across the walk keeps the cost linear in what a real dump contains+ * (one link, a dozen objects) and bounded for everything else. Exhausting it+ * ends the search as "not found", which is the same honest null as a dump that+ * never carried the key.+ */+const MAX_ANNOTATION_OBJECTS_SCANNED = 1024;/** Exact positional read, or null when the file is shorter than the request. */function readExactly(fd: number, length: number, position: number): Buffer | null {@@ -538,3 +606,246 @@ export function classifyMinidumpCrashKind(}}}++export interface MinidumpAccessibilityModeRead {+ /**+ * Chromium's `ax_mode` crash key as the crashed renderer recorded it, or null+ * when the dump does not carry one.+ *+ * Null is "we do not know", and it must never be read as "accessibility was+ * off". Chromium allocates this key when it first sets an accessibility mode,+ * so a renderer that never had a tree built may register nothing at all — and+ * so may a dump for a process that has no renderer in it, a Chromium revision+ * that renames the key, or a dump truncated before its Crashpad stream. Those+ * are four different situations wearing one null, and the only thing they all+ * rule out is a confident "off".+ *+ * Non-null has already been through `asReportableAnnotationValue`, so it is+ * safe to print on a line of its own.+ */+ mode: string | null;+ /**+ * The walk threw rather than declining. Separates "this dump has no mode to+ * give" from "the parser broke on a layout it no longer recognizes" — the same+ * distinction `MinidumpAppVersionRead.parseFailed` carries, and for the same+ * reason: both reach a reader as one absent field and point in opposite+ * directions.+ */+ parseFailed: boolean;+}++/** Bounds for `asReportableAnnotationValue`; see its contract below. */+const FIRST_PRINTABLE_ASCII = 0x20;+const LAST_PRINTABLE_ASCII = 0x7e;++/**+ * What a Crashpad annotation value must satisfy before it is printed.+ *+ * Deliberately NOT `asReportableAppVersion`. That function's stated contract is+ * that ONE gate decides what a version may be, so its two witnesses can never+ * come to disagree; routing a non-version through it would quietly make it a+ * gate for two different questions sharing one ceiling.+ *+ * The threat is the same one and worth restating: a dump is untrusted input, its+ * every string is attacker-shaped, and the destination is a line-oriented log. A+ * value carrying a line break could forge the context printed around it. Stated+ * as a whitelist because a reject list is always under-enumerated — U+0085,+ * U+2028/U+2029 and the bidi overrides all change how a line renders and none of+ * them is a C0 control.+ *+ * Chromium writes these values with `ui::AXMode`'s flag-name join, printable+ * ASCII by construction, so anything outside that range is not a value this app+ * can vouch for. Length needs no ceiling here: `readAnnotationString` already+ * refuses anything past `MAX_ANNOTATION_STRING_BYTES` before allocating.+ */+function asReportableAnnotationValue(value: string | null): string | null {+ if (value === null || value === '') return null;+ for (let i = 0; i < value.length; i += 1) {+ const code = value.charCodeAt(i);+ if (code < FIRST_PRINTABLE_ASCII || code > LAST_PRINTABLE_ASCII) return null;+ }+ return value;+}++/**+ * One module's annotation objects, searched for `key`. Returns what is left of+ * the scan budget alongside the hit, so the caller's ceiling spans the whole+ * walk instead of resetting at every module.+ */+function findAnnotationObjectInModule(+ fd: number,+ moduleInfoRva: number,+ key: string,+ budget: number,+): { value: string | null; budget: number } {+ const moduleInfo = readExactly(fd, MODULE_CRASHPAD_INFO_BYTES, moduleInfoRva);+ if (moduleInfo === null) return { value: null, budget };+ const listRva = moduleInfo.readUInt32LE(MODULE_ANNOTATION_OBJECTS_RVA_OFFSET);+ // A zero location is how a module with no annotation objects spells it, which+ // is the ordinary state for every module but the one holding the crash keys.+ if (listRva === 0) return { value: null, budget };++ const count = readExactly(fd, 4, listRva);+ if (count === null) return { value: null, budget };+ const objectCount = count.readUInt32LE(0);+ if (objectCount === 0 || objectCount > MAX_ANNOTATIONS) return { value: null, budget };+ // Floor rather than equality, so a future revision may pad the list without+ // this lookup silently going dark.+ const declaredBytes = moduleInfo.readUInt32LE(MODULE_ANNOTATION_OBJECTS_SIZE_OFFSET);+ if (declaredBytes < 4 + objectCount * ANNOTATION_OBJECT_BYTES) return { value: null, budget };++ const objects = readExactly(fd, objectCount * ANNOTATION_OBJECT_BYTES, listRva + 4);+ if (objects === null) return { value: null, budget };++ let remaining = budget;+ for (let i = 0; i < objectCount; i += 1) {+ if (remaining === 0) return { value: null, budget: 0 };+ remaining -= 1;+ const at = i * ANNOTATION_OBJECT_BYTES;+ // Type first: it is a two-byte compare against bytes already in hand, where+ // the name costs a positional read. Screening non-strings here also keeps a+ // colliding key of another type from ever having its bytes decoded as text.+ if (objects.readUInt16LE(at + ANNOTATION_OBJECT_TYPE_OFFSET) !== ANNOTATION_TYPE_STRING) {+ continue;+ }+ if (readAnnotationString(fd, objects.readUInt32LE(at)) !== key) continue;+ const value = readAnnotationString(+ fd,+ objects.readUInt32LE(at + ANNOTATION_OBJECT_VALUE_RVA_OFFSET),+ );+ return { value: asReportableAnnotationValue(value), budget: remaining };+ }+ return { value: null, budget: remaining };+}++/**+ * The walk below paired with whether it threw on the way. Never throws itself:+ * a failure here stays contained rather than unwinding the caller, and the flag+ * is what keeps that containment from also being silent.+ *+ * Deliberately narrower than the caller's own catch. An unopenable file, a torn+ * read or a dump that is not a minidump at all are ordinary states during a scan+ * of a directory Crashpad is also writing to — folding those in would make the+ * flag fire constantly and stop meaning "the parser broke", which is the only+ * thing it is for. Same split as `readAppVersionAnnotation`.+ */+function readModuleAnnotation(+ fd: number,+ infoRva: number,+ infoSize: number,+ key: string,+): { value: string | null; parseFailed: boolean } {+ try {+ return { value: findModuleAnnotation(fd, infoRva, infoSize, key), parseFailed: false };+ } catch {+ return { value: null, parseFailed: true };+ }+}++/** The annotation-object walk. Declines by returning null for any layout it distrusts. */+function findModuleAnnotation(+ fd: number,+ infoRva: number,+ infoSize: number,+ key: string,+): string | null {+ if (infoSize < CRASHPAD_INFO_MODULE_LIST_PREFIX_BYTES) return null;+ const info = readExactly(fd, CRASHPAD_INFO_MODULE_LIST_PREFIX_BYTES, infoRva);+ if (info === null) return null;+ const listRva = info.readUInt32LE(CRASHPAD_MODULE_LIST_RVA_OFFSET);+ if (listRva === 0) return null;++ const count = readExactly(fd, 4, listRva);+ if (count === null) return null;+ const linkCount = count.readUInt32LE(0);+ if (linkCount === 0 || linkCount > MAX_MODULE_LINKS) return null;+ const declaredBytes = info.readUInt32LE(CRASHPAD_MODULE_LIST_SIZE_OFFSET);+ if (declaredBytes < 4 + linkCount * MODULE_LINK_BYTES) return null;++ const links = readExactly(fd, linkCount * MODULE_LINK_BYTES, listRva + 4);+ if (links === null) return null;++ // Every link is searched rather than a known index: WHICH module carries+ // Chromium's crash keys is a build detail — the framework, not the executable+ // the ownership parse reads — and pinning an index would silently stop+ // answering the first time a build reorders its module list.+ let budget = MAX_ANNOTATION_OBJECTS_SCANNED;+ for (let i = 0; i < linkCount; i += 1) {+ const found = findAnnotationObjectInModule(+ fd,+ links.readUInt32LE(i * MODULE_LINK_BYTES + MODULE_LINK_RVA_OFFSET),+ key,+ budget,+ );+ if (found.value !== null) return found.value;+ budget = found.budget;+ if (budget === 0) return null;+ }+ return null;+}++/**+ * Read the accessibility mode the process described by `dumpPath` was running+ * with when it died.+ *+ * This is the recorded answer to the precondition a whole family of Blink+ * accessibility `CHECK` crashes turns on — `AXBlockFlowData::ComputeNeighborOnLine`+ * and its neighbours are reachable only with a live accessibility tree, and the+ * app's own `OK_FORCE_A11Y` switch is opt-in, so without this the tree's+ * presence can only ever be inferred from circumstance. Chromium has been+ * recording it on every dump all along; nothing was reading it.+ *+ * Opens its own descriptor rather than riding the ownership pass, for the same+ * reason `findSimpleAnnotation` does: ownership decides whether a report may+ * carry raw process memory at all, and keeping this question on its own handle+ * means a change here cannot reach that answer by accident.+ *+ * Like `readMinidumpAppVersion`, only meaningful for a dump this app has not+ * already disowned — Crashpad stamps our annotations onto dumps it writes for+ * descendant processes. Classify first.+ */+export function readMinidumpAccessibilityMode(dumpPath: string): MinidumpAccessibilityModeRead {+ let fd: number | null = null;+ try {+ fd = openSync(dumpPath, 'r');+ const header = readExactly(fd, HEADER_BYTES, 0);+ if (header === null || header.readUInt32LE(0) !== MINIDUMP_SIGNATURE) {+ return { mode: null, parseFailed: false };+ }+ const streamCount = header.readUInt32LE(NUMBER_OF_STREAMS_OFFSET);+ if (streamCount === 0 || streamCount > MAX_STREAMS) return { mode: null, parseFailed: false };++ const directory = readExactly(+ fd,+ streamCount * DIRECTORY_ENTRY_BYTES,+ header.readUInt32LE(STREAM_DIRECTORY_RVA_OFFSET),+ );+ if (directory === null) return { mode: null, parseFailed: false };++ for (let i = 0; i < streamCount; i += 1) {+ const at = i * DIRECTORY_ENTRY_BYTES;+ if (directory.readUInt32LE(at) !== CRASHPAD_INFO_STREAM_TYPE) continue;+ const read = readModuleAnnotation(+ fd,+ directory.readUInt32LE(at + DIRECTORY_ENTRY_RVA_OFFSET),+ directory.readUInt32LE(at + DIRECTORY_ENTRY_SIZE_OFFSET),+ AX_MODE_ANNOTATION_KEY,+ );+ return { mode: read.value, parseFailed: read.parseFailed };+ }+ return { mode: null, parseFailed: false };+ } catch {+ // Unopenable file, torn read, permissions change mid-scan, or a dump that+ // is not a minidump — none of which is a broken parser, so none of which+ // sets the flag. Matches what `readMinidumpFacts` does with the same shapes.+ return { mode: null, parseFailed: false };+ } finally {+ if (fd !== null) {+ try {+ closeSync(fd);+ } catch {+ // Descriptor already reclaimed; nothing left to release.+ }+ }+ }+}diff --git a/packages/desktop/src/main/minidump.test-helper.ts b/packages/desktop/src/main/minidump.test-helper.tsindex 70b7e71d0..159c2b3f6 100644--- a/packages/desktop/src/main/minidump.test-helper.ts+++ b/packages/desktop/src/main/minidump.test-helper.ts@@ -19,11 +19,36 @@ const MODULE_RECORD_BYTES = 108;const MODULE_NAME_RVA_OFFSET = 20;const MODULE_LIST_STREAM_TYPE = 4;const CRASHPAD_INFO_STREAM_TYPE = 0x4350_0001;-/** Real dumps size this stream at 64 bytes; the parse reads only the first 44. */+/**+ * Real dumps size this stream at 64 bytes — measured, not assumed — while the+ * struct through its last read field is 52. Emitted at the real size so a+ * fixture cannot pass by being conveniently short of the padding.+ */const CRASHPAD_INFO_BYTES = 64;const CRASHPAD_ANNOTATIONS_SIZE_OFFSET = 36;const CRASHPAD_ANNOTATIONS_RVA_OFFSET = 40;const ANNOTATION_ENTRY_BYTES = 8;+/**+ * The SECOND annotation structure, reached through `MinidumpCrashpadInfo.module_list`+ * rather than the simple dictionary above — where Chromium's own crash keys+ * (`ax_mode`, `process_type`, …) actually live. Emitting it takes three nested+ * records:+ *+ * `MinidumpModuleCrashpadInfoList` — count, then N `(moduleIndex, size, rva)` links+ * `MinidumpModuleCrashpadInfo` — version, then list/simple/objects descriptors+ * `MinidumpAnnotationList` — count, then N `(nameRva, type, reserved, valueRva)`+ */+const CRASHPAD_MODULE_LIST_SIZE_OFFSET = 44;+const CRASHPAD_MODULE_LIST_RVA_OFFSET = 48;+const MODULE_LINK_BYTES = 12;+const MODULE_CRASHPAD_INFO_BYTES = 28;+const MODULE_ANNOTATION_OBJECTS_SIZE_OFFSET = 20;+const MODULE_ANNOTATION_OBJECTS_RVA_OFFSET = 24;+const ANNOTATION_OBJECT_BYTES = 12;+const ANNOTATION_OBJECT_TYPE_OFFSET = 4;+const ANNOTATION_OBJECT_VALUE_RVA_OFFSET = 8;+/** `crashpad::Annotation::Type::kString`. */+const ANNOTATION_TYPE_STRING = 1;const EXCEPTION_STREAM_TYPE = 6;/*** `MINIDUMP_EXCEPTION_STREAM`: `ThreadId u32`, `__alignment u32`, the 152-byte@@ -100,15 +125,55 @@ export interface MinidumpPatch {* to distinguish those by annotation rather than by the stream's absence.*/exceptionCode?: number;+ /**+ * Per-module annotation OBJECTS — one map per module link, so the array's+ * length is the number of links. An empty map emits a module carrying no+ * objects at all, which is what every module but one looks like in a real+ * dump and is exactly what a walk that stops at the first link would skip.+ *+ * Absent by default, so every fixture written before it existed stays+ * byte-identical: the info record's module-list descriptor simply stays zero,+ * which is what a dump registering no module annotations looks like.+ *+ * Independent of `annotations`: either may appear without the other, because+ * the two are separate structures and a parser must not reach one through the+ * other.+ */+ annotationObjects?: Record<string, string>[];+ /** The link list's claimed count, independent of how many links follow it. */+ moduleLinkCount?: number;+ /** Crashpad info's pointer to the link list; 0 means "no module annotations". */+ crashpadModuleListRva?: number;+ /** Crashpad info's claimed byte size for the link-list block. */+ crashpadModuleListSize?: number;+ /** FIRST module's claimed object count, independent of what it holds. */+ annotationObjectCount?: number;+ /** FIRST module's pointer to its annotation-object list; 0 means "none". */+ annotationObjectsRva?: number;+ /** FIRST module's claimed byte size for its object-list block. */+ annotationObjectsSize?: number;+ /**+ * FIRST object's type tag. Anything but `kString` (1) marks a value whose+ * bytes are not text, and must never be decoded as such.+ */+ annotationObjectType?: number;+ /** FIRST object's pointer to its value block. */+ annotationObjectValueRva?: number;+ /** FIRST object's value block's claimed BYTE length. */+ annotationObjectValueByteLength?: number;}export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}): Buffer {const decoyStreams = patch.streamsBefore ?? 0;const annotationEntries =patch.annotations === undefined ? null : Object.entries(patch.annotations);+ const objectModules = patch.annotationObjects ?? null;+ // ONE stream carries both structures, so it is emitted for either — but each+ // section fills in only its own descriptor, which is what lets a fixture+ // carry module annotations with no simple dictionary and the other way round.+ const hasCrashpadStream = annotationEntries !== null || objectModules !== null;const hasException = patch.exceptionCode !== undefined;- const directoryEntries =- decoyStreams + 1 + (annotationEntries === null ? 0 : 1) + (hasException ? 1 : 0);+ const directoryEntries = decoyStreams + 1 + (hasCrashpadStream ? 1 : 0) + (hasException ? 1 : 0);const directoryRva = HEADER_BYTES;const moduleListRva = directoryRva + directoryEntries * DIRECTORY_ENTRY_BYTES;const moduleListBytes = 4 + modulePaths.length * MODULE_RECORD_BYTES;@@ -138,45 +203,161 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):// trailing NUL, the UTF-8 bytes, then that NUL — as real dumps write them.const crashpadBlocks: Buffer[] = [];const crashpadInfoRva = cursor;- if (annotationEntries !== null) {- const dictRva = crashpadInfoRva + CRASHPAD_INFO_BYTES;- const dictBytes = 4 + annotationEntries.length * ANNOTATION_ENTRY_BYTES;- const stringBlocks: Buffer[] = [];- let stringCursor = dictRva + dictBytes;- const appendString = (value: string): { rva: number; block: Buffer } => {- const encoded = Buffer.from(value, 'utf8');- const block = Buffer.alloc(4 + encoded.length + 1);- block.writeUInt32LE(encoded.length, 0);- encoded.copy(block, 4);- const rva = stringCursor;- stringBlocks.push(block);- stringCursor += block.length;- return { rva, block };- };-- const dict = Buffer.alloc(dictBytes);- dict.writeUInt32LE(patch.annotationCount ?? annotationEntries.length, 0);- annotationEntries.forEach(([key, value], index) => {- const keyString = appendString(key);- const valueString = appendString(value);- const at = 4 + index * ANNOTATION_ENTRY_BYTES;- const first = index === 0;- dict.writeUInt32LE(first ? (patch.annotationKeyRva ?? keyString.rva) : keyString.rva, at);- dict.writeUInt32LE(- first ? (patch.annotationValueRva ?? valueString.rva) : valueString.rva,- at + 4,- );- if (first && patch.annotationValueByteLength !== undefined) {- valueString.block.writeUInt32LE(patch.annotationValueByteLength, 0);- }- });-+ if (hasCrashpadStream) {+ // One info record carries BOTH descriptors, so each section below fills in+ // its own and leaves the other's zero — which is how a real dump spells+ // "registered none of that kind".const info = Buffer.alloc(CRASHPAD_INFO_BYTES);info.writeUInt32LE(1, 0); // struct version — unread by this parse- info.writeUInt32LE(patch.annotationsSize ?? dictBytes, CRASHPAD_ANNOTATIONS_SIZE_OFFSET);- info.writeUInt32LE(patch.annotationsRva ?? dictRva, CRASHPAD_ANNOTATIONS_RVA_OFFSET);- crashpadBlocks.push(info, dict, ...stringBlocks);- cursor = stringCursor;+ crashpadBlocks.push(info);+ cursor = crashpadInfoRva + CRASHPAD_INFO_BYTES;++ if (annotationEntries !== null) {+ const dictRva = cursor;+ const dictBytes = 4 + annotationEntries.length * ANNOTATION_ENTRY_BYTES;+ const stringBlocks: Buffer[] = [];+ let stringCursor = dictRva + dictBytes;+ const appendString = (value: string): { rva: number; block: Buffer } => {+ const encoded = Buffer.from(value, 'utf8');+ const block = Buffer.alloc(4 + encoded.length + 1);+ block.writeUInt32LE(encoded.length, 0);+ encoded.copy(block, 4);+ const rva = stringCursor;+ stringBlocks.push(block);+ stringCursor += block.length;+ return { rva, block };+ };++ const dict = Buffer.alloc(dictBytes);+ dict.writeUInt32LE(patch.annotationCount ?? annotationEntries.length, 0);+ annotationEntries.forEach(([key, value], index) => {+ const keyString = appendString(key);+ const valueString = appendString(value);+ const at = 4 + index * ANNOTATION_ENTRY_BYTES;+ const first = index === 0;+ dict.writeUInt32LE(first ? (patch.annotationKeyRva ?? keyString.rva) : keyString.rva, at);+ dict.writeUInt32LE(+ first ? (patch.annotationValueRva ?? valueString.rva) : valueString.rva,+ at + 4,+ );+ if (first && patch.annotationValueByteLength !== undefined) {+ valueString.block.writeUInt32LE(patch.annotationValueByteLength, 0);+ }+ });++ info.writeUInt32LE(patch.annotationsSize ?? dictBytes, CRASHPAD_ANNOTATIONS_SIZE_OFFSET);+ info.writeUInt32LE(patch.annotationsRva ?? dictRva, CRASHPAD_ANNOTATIONS_RVA_OFFSET);+ crashpadBlocks.push(dict, ...stringBlocks);+ cursor = stringCursor;+ }++ if (objectModules !== null) {+ // Laid out in three runs — every link, then every module record, then+ // every object list — so a record's forward pointers are all computable+ // before any of them is written.+ const linkListRva = cursor;+ const linkListBytes = 4 + objectModules.length * MODULE_LINK_BYTES;+ const moduleInfoRva = (i: number) =>+ linkListRva + linkListBytes + i * MODULE_CRASHPAD_INFO_BYTES;+ const objectListBytes = objectModules.map(+ (objects) => 4 + Object.keys(objects).length * ANNOTATION_OBJECT_BYTES,+ );+ const objectListsRva =+ linkListRva + linkListBytes + objectModules.length * MODULE_CRASHPAD_INFO_BYTES;+ const objectListRva = (i: number) =>+ objectListsRva + objectListBytes.slice(0, i).reduce((a, b) => a + b, 0);++ const stringBlocks: Buffer[] = [];+ let stringCursor = objectListsRva + objectListBytes.reduce((a, b) => a + b, 0);+ /**+ * A name is a NUL-terminated `MinidumpUTF8String`; a value is a bare+ * `MinidumpByteArray`. Both are u32-length-prefixed and the length+ * excludes any NUL, so the reader sees the same shape either way — the+ * distinction is kept because the dumps being imitated keep it.+ */+ const appendString = (value: string, nulTerminated: boolean) => {+ const encoded = Buffer.from(value, 'utf8');+ const block = Buffer.alloc(4 + encoded.length + (nulTerminated ? 1 : 0));+ block.writeUInt32LE(encoded.length, 0);+ encoded.copy(block, 4);+ const rva = stringCursor;+ stringBlocks.push(block);+ stringCursor += block.length;+ return { rva, block };+ };++ const linkList = Buffer.alloc(linkListBytes);+ linkList.writeUInt32LE(patch.moduleLinkCount ?? objectModules.length, 0);+ const moduleInfos: Buffer[] = [];+ const objectLists: Buffer[] = [];++ objectModules.forEach((objects, moduleIndex) => {+ const firstModule = moduleIndex === 0;+ const at = 4 + moduleIndex * MODULE_LINK_BYTES;+ // Index 0 is the main executable and never carries Chromium's crash+ // keys; starting at 1 mirrors what real dumps do.+ linkList.writeUInt32LE(moduleIndex + 1, at);+ linkList.writeUInt32LE(MODULE_CRASHPAD_INFO_BYTES, at + 4);+ linkList.writeUInt32LE(moduleInfoRva(moduleIndex), at + 8);++ const entries = Object.entries(objects);+ const list = Buffer.alloc(objectListBytes[moduleIndex] ?? 4);+ list.writeUInt32LE(+ firstModule ? (patch.annotationObjectCount ?? entries.length) : entries.length,+ 0,+ );+ entries.forEach(([key, value], index) => {+ const first = firstModule && index === 0;+ const name = appendString(key, true);+ const valueBlock = appendString(value, false);+ const objAt = 4 + index * ANNOTATION_OBJECT_BYTES;+ list.writeUInt32LE(name.rva, objAt);+ list.writeUInt16LE(+ first ? (patch.annotationObjectType ?? ANNOTATION_TYPE_STRING) : ANNOTATION_TYPE_STRING,+ objAt + ANNOTATION_OBJECT_TYPE_OFFSET,+ );+ list.writeUInt32LE(+ first ? (patch.annotationObjectValueRva ?? valueBlock.rva) : valueBlock.rva,+ objAt + ANNOTATION_OBJECT_VALUE_RVA_OFFSET,+ );+ if (first && patch.annotationObjectValueByteLength !== undefined) {+ valueBlock.block.writeUInt32LE(patch.annotationObjectValueByteLength, 0);+ }+ });+ objectLists.push(list);++ const moduleInfo = Buffer.alloc(MODULE_CRASHPAD_INFO_BYTES);+ moduleInfo.writeUInt32LE(1, 0); // struct version — unread by this parse+ // An empty map means "this module registered no objects", spelled the+ // way Crashpad spells it: a zero location, not an empty list.+ const hasObjects = entries.length > 0;+ const declaredSize = firstModule+ ? (patch.annotationObjectsSize ?? objectListBytes[moduleIndex] ?? 0)+ : (objectListBytes[moduleIndex] ?? 0);+ const declaredRva = firstModule+ ? (patch.annotationObjectsRva ?? (hasObjects ? objectListRva(moduleIndex) : 0))+ : hasObjects+ ? objectListRva(moduleIndex)+ : 0;+ moduleInfo.writeUInt32LE(+ hasObjects || firstModule ? declaredSize : 0,+ MODULE_ANNOTATION_OBJECTS_SIZE_OFFSET,+ );+ moduleInfo.writeUInt32LE(declaredRva, MODULE_ANNOTATION_OBJECTS_RVA_OFFSET);+ moduleInfos.push(moduleInfo);+ });++ info.writeUInt32LE(+ patch.crashpadModuleListSize ?? linkListBytes,+ CRASHPAD_MODULE_LIST_SIZE_OFFSET,+ );+ info.writeUInt32LE(+ patch.crashpadModuleListRva ?? linkListRva,+ CRASHPAD_MODULE_LIST_RVA_OFFSET,+ );+ crashpadBlocks.push(linkList, ...moduleInfos, ...objectLists, ...stringBlocks);+ cursor = stringCursor;+ }}// Laid out last so adding one cannot shift any offset an existing fixture@@ -209,7 +390,7 @@ export function buildMinidump(modulePaths: string[], patch: MinidumpPatch = {}):directory.writeUInt32LE(moduleListBytes, moduleListEntry + 4);directory.writeUInt32LE(patch.moduleListRva ?? moduleListRva, moduleListEntry + 8);let nextEntry = moduleListEntry + DIRECTORY_ENTRY_BYTES;- if (annotationEntries !== null) {+ if (hasCrashpadStream) {directory.writeUInt32LE(patch.crashpadStreamType ?? CRASHPAD_INFO_STREAM_TYPE, nextEntry);directory.writeUInt32LE(CRASHPAD_INFO_BYTES, nextEntry + 4);directory.writeUInt32LE(crashpadInfoRva, nextEntry + 8);