react-native-update-cli 2.26.1 → 2.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -87,7 +87,7 @@ const publishResult = await provider.publish({
87
87
 
88
88
  Hermes projects: `bundle` always runs hermesc with `-output-source-map`, so the debug info section is stripped from the bytecode (15–40% smaller, same as React Native's own release builds). The Hermes sourcemap stays in the intermediate directory (`.pushy/intermedia/<platform>/<bundle>.map`, never packed into the ppk) and is composed with the packager map — `--sourcemap` is on by default since 2.23 (`--no-sourcemap` opts out). When `bundle` publishes, that final map is uploaded and archived with the version (`sourceMapKey`), so `pushy symbolicate` can map crash stacks — including Hermes `address at` frames — back to source later. `pushy publish <ppk> --sourcemap <file.map>` archives a map for a ppk built elsewhere; publishing without a map prints a warning.
89
89
 
90
- Hermes delta mode (`-base-bytecode`): by default (`--hermesBase auto`) `bundle` compiles against the previous HBC of the same app, which keeps Hermes string IDs stable and makes hot-update patches 5–30× smaller. The base comes from the server (`GET /app/:id/hermesBase`), verified by sha256 and kept in a local cache (`.pushy/cache/<sha256>`, 500 MB / 20 files, `PUSHY_CACHE_DIR` / `--cacheMaxMb` to tune, `pushy cache [clean]` to inspect or clear). `--hermesBase none` disables it; `--hermesBase <file.hbc|.ppk|.apk|.ipa>` uses a local artifact (for example the store build). `--verifyHermesBase` (default on) additionally compiles without the base (concurrently with the base compile) and compares both disassemblies — literal buffers by content, then function by function, with only representation differences (string ids, operand widths, jump distances, buffer offsets) folded away; on any mismatch or failure the CLI falls back to the plain compile, so the feature can never block a release. The log names the first difference (function, line, both sides) or, separately, a dump that could not be read; set `PUSHY_HERMES_BASE_DEBUG=1` to keep both disassemblies (`hermes-base-dump-base.txt` / `hermes-base-dump-plain.txt` next to the intermediate directory) for a bug report. What the check covers, what it does not yet, and how to triage a rejection: [docs/hermes-base-verification.md](docs/hermes-base-verification.md). The result is reported at publish (`hermesBaseOutcome`: `used` / `rejected` / `dump-failed` / `none`, plus the first difference) so the server can watch the rejection rate across apps. `HERMESC=<path> bun run fuzz:hermes-base --rounds 300` compiles random programs against random bases and reports any build the check would wrongly reject (differential fuzzing of the normalization rules). Only hermesc builds that include the upstream delta-mode fix are used (classic `react-native/sdks/hermesc`, or `hermes-compiler` ≥ 250829098). If a base compile fails, the full hermesc output is written to `hermes-base-error.log` next to the intermediate directory. `--resetCache false` skips Metro's `--reset-cache` and reuses its transform cache, which makes repeated bundles much faster.
90
+ Hermes delta mode (`-base-bytecode`): by default (`--hermesBase auto`) `bundle` compiles against the previous HBC of the same app, which keeps Hermes string IDs stable and makes hot-update patches 5–30× smaller. The base comes from the server (`GET /app/:id/hermesBase`), verified by sha256 and kept in a local cache (`.pushy/cache/<sha256>`, 500 MB / 20 files, `PUSHY_CACHE_DIR` / `--cacheMaxMb` to tune, `pushy cache [clean]` to inspect or clear). `--hermesBase none` disables it; `--hermesBase <file.hbc|.ppk|.apk|.ipa>` uses a local artifact (for example the store build). `--verifyHermesBase` (default on) additionally compiles without the base (concurrently with the base compile) and checks both artifacts in two passes: readable disassembly followed by raw operands resolved against complete binary strings, constants, function references and control-flow targets. Quoted whitespace and branch destinations are preserved; unsupported or unreadable layouts fail closed. On a mismatch, verification failure or compiler timeout the CLI falls back to the plain compile; failures of the plain compiler or the final sourcemap still fail the build. The raw pass adds verification time and holds both HBC files in memory, but does not add another compile. The log names the first difference (function, line, both sides) or, separately, a dump that could not be read; set `PUSHY_HERMES_BASE_DEBUG=1` to keep both disassemblies (`hermes-base-dump-base.txt` / `hermes-base-dump-plain.txt` next to the intermediate directory) for a bug report. Probe, verification and compile/sourcemap process deadlines default to 30/120/300 seconds respectively, configurable in milliseconds via `PUSHY_HERMES_PROBE_TIMEOUT_MS`, `PUSHY_HERMES_VERIFY_TIMEOUT_MS` and `PUSHY_HERMES_COMPILE_TIMEOUT_MS`. What the check covers, what it does not yet, and how to triage a rejection: [docs/hermes-base-verification.md](docs/hermes-base-verification.md). The result is reported at publish (`hermesBaseOutcome`: `used` / `rejected` / `dump-failed` / `none`, plus the first difference) so the server can watch the rejection rate across apps. `HERMESC=<path> bun run fuzz:hermes-base --rounds 300` compiles random programs against random bases and reports any build the check would wrongly reject (differential fuzzing of the normalization rules). Only hermesc builds that include the upstream delta-mode fix are used (classic `react-native/sdks/hermesc`, or `hermes-compiler` ≥ 250829098). If a base compile fails, the full hermesc output is written to `hermes-base-error.log` next to the intermediate directory. `--resetCache false` skips Metro's `--reset-cache` and reuses its transform cache, which makes repeated bundles much faster.
91
91
 
92
92
  ### Version
93
93
 
package/README.zh-CN.md CHANGED
@@ -78,7 +78,7 @@ const publishResult = await provider.publish({
78
78
 
79
79
  Hermes 工程:`bundle` 调用 hermesc 时始终带 `-output-source-map`,因此字节码不含 debug info 段(小 15%~40%,与 React Native 自身 release 构建一致)。Hermes sourcemap 保留在中间目录(`.pushy/intermedia/<platform>/<bundle>.map`,不会打进 ppk),并与 packager map 合成——自 2.23 起 `--sourcemap` 默认开启(`--no-sourcemap` 关闭)。`bundle` 发布时会把这份最终 map 上传并随版本归档(`sourceMapKey`),之后用 `pushy symbolicate` 即可把崩溃堆栈(含 Hermes 的 `address at` 帧)还原到源码。别处打好的 ppk 可用 `pushy publish <ppk> --sourcemap <file.map>` 归档;不带 map 发布会打印警告。
80
80
 
81
- Hermes delta 模式(`-base-bytecode`):默认 `--hermesBase auto`,`bundle` 会以同一应用上一版的 HBC 为 base 编译,让 Hermes 字符串 ID 跨版本稳定,热更 patch 可缩小 5~30 倍。base 由服务端(`GET /app/:id/hermesBase`)给出、按 sha256 校验并存入本地缓存(`.pushy/cache/<sha256>`,默认 500 MB / 20 个,可用 `PUSHY_CACHE_DIR` / `--cacheMaxMb` 调整,`pushy cache [clean]` 查看或清空)。`--hermesBase none` 关闭;`--hermesBase <file.hbc|.ppk|.apk|.ipa>` 指定本地文件(比如商店包)作 base。`--verifyHermesBase`(默认开)会并行再做一次普通编译并比对两份反汇编——先按内容比对字面量缓冲区,再逐函数比对,只折叠纯表示层差异(字符串 id、操作数宽度、跳转距离、缓冲区偏移);任何不一致或失败都回退到普通编译,不会阻塞发版。日志会给出第一处差异(函数、行、两侧内容),dump 读取失败会单独说明;设置 `PUSHY_HERMES_BASE_DEBUG=1` 可把两份反汇编保留在中间目录旁(`hermes-base-dump-base.txt` / `hermes-base-dump-plain.txt`)用于提 issue。校验覆盖什么、还缺什么、如何排查一次拒绝:见 [docs/hermes-base-verification.md](docs/hermes-base-verification.md)。校验结果会随发布上报(`hermesBaseOutcome`:`used` / `rejected` / `dump-failed` / `none`,附第一处差异),服务端可据此观察全体应用的拒绝率。`HERMESC=<path> bun run fuzz:hermes-base --rounds 300` 会用随机程序配随机 base 编译并报告校验误杀的构建(对归一化规则做差分模糊测试)。只有包含上游 delta 模式修复的 hermesc 才会启用(经典 `react-native/sdks/hermesc`,或 `hermes-compiler` ≥ 250829098)。base 编译失败时,完整的 hermesc 输出会写到中间目录旁边的 `hermes-base-error.log`。`--resetCache false` 可跳过 Metro 的 `--reset-cache`,复用其转换缓存,重复打包会快很多。
81
+ Hermes delta 模式(`-base-bytecode`):默认 `--hermesBase auto`,`bundle` 会以同一应用上一版的 HBC 为 base 编译,让 Hermes 字符串 ID 跨版本稳定,热更 patch 可缩小 5~30 倍。base 由服务端(`GET /app/:id/hermesBase`)给出、按 sha256 校验并存入本地缓存(`.pushy/cache/<sha256>`,默认 500 MB / 20 个,可用 `PUSHY_CACHE_DIR` / `--cacheMaxMb` 调整,`pushy cache [clean]` 查看或清空)。`--hermesBase none` 关闭;`--hermesBase <file.hbc|.ppk|.apk|.ipa>` 指定本地文件(比如商店包)作 base。`--verifyHermesBase`(默认开)会并行再做一次普通编译并进行两遍校验:先比较易读反汇编,再将 raw 操作数与二进制中的完整字符串、常量、函数引用和控制流目标核对。字符串内部空白和分支目的地不会被抹掉;不支持或无法解析的布局不能判为等价。发现差异、无法完成校验或 base 编译超时会回退到普通编译;真正的 plain 编译或最终 sourcemap 失败仍会使构建失败。raw 核对增加验证时间并在内存中持有两份 HBC,但不增加编译次数。日志会给出第一处差异(函数、行、两侧内容),dump 读取失败会单独说明;设置 `PUSHY_HERMES_BASE_DEBUG=1` 可把两份反汇编保留在中间目录旁(`hermes-base-dump-base.txt` / `hermes-base-dump-plain.txt`)用于提 issue。版本探测、完整验证、单个编译/sourcemap 子进程的期限默认分别为 30/120/300 秒,可用 `PUSHY_HERMES_PROBE_TIMEOUT_MS`、`PUSHY_HERMES_VERIFY_TIMEOUT_MS`、`PUSHY_HERMES_COMPILE_TIMEOUT_MS`(毫秒)调整。校验覆盖什么、还缺什么、如何排查一次拒绝:见 [docs/hermes-base-verification.md](docs/hermes-base-verification.md)。校验结果会随发布上报(`hermesBaseOutcome`:`used` / `rejected` / `dump-failed` / `none`,附第一处差异),服务端可据此观察全体应用的拒绝率。`HERMESC=<path> bun run fuzz:hermes-base --rounds 300` 会用随机程序配随机 base 编译并报告校验误杀的构建(对归一化规则做差分模糊测试)。只有包含上游 delta 模式修复的 hermesc 才会启用(经典 `react-native/sdks/hermesc`,或 `hermes-compiler` ≥ 250829098)。base 编译失败时,完整的 hermesc 输出会写到中间目录旁边的 `hermes-base-error.log`。`--resetCache false` 可跳过 Metro 的 `--reset-cache`,复用其转换缓存,重复打包会快很多。
82
82
 
83
83
  ### Version
84
84
 
@@ -63,6 +63,7 @@ const path_1 = __importDefault(require("path"));
63
63
  const api_1 = require("./api");
64
64
  const dep_versions_1 = require("./utils/dep-versions");
65
65
  const hermes_base_1 = require("./utils/hermes-base");
66
+ const hermes_timeout_1 = require("./utils/hermes-timeout");
66
67
  const i18n_1 = require("./utils/i18n");
67
68
  const runtime_1 = require("./utils/runtime");
68
69
  const g2js = require('gradle-to-js/lib/parser');
@@ -678,6 +679,8 @@ function runProcess(command, args, captureStderr) {
678
679
  return new Promise((resolve) => {
679
680
  const child = (0, child_process_1.spawn)(command, args, {
680
681
  stdio: ['ignore', 'ignore', captureStderr ? 'pipe' : 'ignore'],
682
+ timeout: (0, hermes_timeout_1.hermesTimeout)(process.env.PUSHY_HERMES_COMPILE_TIMEOUT_MS, 300_000),
683
+ killSignal: 'SIGKILL',
681
684
  });
682
685
  // hermesc echoes whole (minified) source lines per diagnostic: keep the
683
686
  // head and the tail, never an unbounded transcript
@@ -723,7 +726,7 @@ const HERMES_BASE_WAIT_MS = 60_000;
723
726
  * bounded time for it — a stalled download must never hold up the compile.
724
727
  */
725
728
  async function awaitPendingBase(pending) {
726
- const waitMs = Number(process.env.PUSHY_HERMES_BASE_WAIT_MS) || HERMES_BASE_WAIT_MS;
729
+ const waitMs = (0, hermes_timeout_1.hermesTimeout)(process.env.PUSHY_HERMES_BASE_WAIT_MS, HERMES_BASE_WAIT_MS);
727
730
  let timer;
728
731
  const gaveUp = new Promise((resolve) => {
729
732
  timer = setTimeout(() => resolve({
@@ -842,7 +845,10 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
842
845
  const fullStderr = attempt.error
843
846
  ? String(attempt.error.message ?? attempt.error)
844
847
  : attempt.stderr;
845
- const reason = summarizeHermescStderr(fullStderr);
848
+ const reason = summarizeHermescStderr(fullStderr) ||
849
+ (attempt.signal
850
+ ? `signal ${attempt.signal} (compiler deadline or external termination)`
851
+ : '');
846
852
  console.warn((0, i18n_1.t)('hermesBaseCompileFailed', {
847
853
  reason: reason || `exit ${attempt.status}`,
848
854
  }));
@@ -862,7 +868,7 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
862
868
  // compose the base output's map while the disassembly compare runs; it is
863
869
  // redone from the plain map in the rare case the base is rejected
864
870
  const speculativeCompose = usedBase && sourcemapOutput
865
- ? composeSourceMaps(packagerMap, hermesMap, sourcemapOutput)
871
+ ? composeSourceMaps(packagerMap, hermesMap, sourcemapOutput).then((value) => ({ ok: true, value }), (error) => ({ ok: false, error }))
866
872
  : null;
867
873
  if (usedBase && wantPlain) {
868
874
  if (!plainOk) {
@@ -921,12 +927,10 @@ async function compileHermesByteCode({ bundleName, outputFolder, sourcemapOutput
921
927
  }
922
928
  }
923
929
  if (speculativeCompose) {
924
- const done = await speculativeCompose.catch((error) => {
925
- if (usedBase)
926
- throw error;
927
- return false;
928
- });
929
- composed = usedBase && done;
930
+ const done = await speculativeCompose;
931
+ if (!done.ok && usedBase)
932
+ throw done.error;
933
+ composed = usedBase && done.ok && done.value;
930
934
  }
931
935
  if (!usedBase) {
932
936
  if (plainOk) {
@@ -23,4 +23,11 @@ exports.pricingPageUrl = exports.IS_CRESC
23
23
  : 'https://pushy.reactnative.cn/pricing.html';
24
24
  exports.defaultEndpoints = exports.IS_CRESC
25
25
  ? ['https://api.cresc.dev', 'https://api.cresc.app']
26
- : ['https://update.reactnative.cn/api', 'https://update.react-native.cn/api'];
26
+ : [
27
+ 'https://1.rnupdate.online/api',
28
+ 'https://2.rnupdate.online/api',
29
+ 'https://3.rnupdate.online/api',
30
+ 'https://4.rnupdate.online/api',
31
+ 'https://update.reactnative.cn/api',
32
+ 'https://update.react-native.cn/api',
33
+ ];
@@ -205,10 +205,13 @@ export interface HermesEquivalenceOptions {
205
205
  withBase: string;
206
206
  plain: string;
207
207
  };
208
+ /** Total deadline for both verification passes. */
209
+ timeoutMs?: number;
210
+ signal?: AbortSignal;
208
211
  }
209
212
  /**
210
- * Compare two HBC files by disassembly (see normalizeDisassemblyLine): the
211
- * literal buffers by content, then function by function. `-b` forces hermesc
213
+ * Compare two HBC files by pretty disassembly, then audit the raw operands
214
+ * against full binary strings, literals, function identities and addresses. `-b` forces hermesc
212
215
  * to treat inputs as bytecode whatever their extension. Both dumps are
213
216
  * consumed as streams so the ~100 MB of text never touches the disk (unless
214
217
  * `dumpTo` asks for it). A dump process that fails or ends early is reported
@@ -1,4 +1,14 @@
1
1
  "use strict";
2
+ // Hermes `-base-bytecode` (delta optimizing mode) support.
3
+ //
4
+ // Hermes re-sorts its string table by identifier frequency on every compile, so
5
+ // any source change renumbers most string IDs and the bytecode diff explodes
6
+ // (see hermes-base-bytecode-方案.md). Compiling with the previous HBC of the
7
+ // same app as `-base-bytecode` keeps old IDs stable and shrinks patches 5-30×.
8
+ // This module resolves that base: gating by hermesc build, HBC version probe,
9
+ // server lookup, a sha256-named local cache, download + verification, and the
10
+ // optional disassembly equivalence check. Every failure degrades to the plain
11
+ // compile — nothing here may block a release.
2
12
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
13
  if (k2 === undefined) k2 = k;
4
14
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -62,16 +72,7 @@ exports.truncateHermesBaseDetail = truncateHermesBaseDetail;
62
72
  exports.normalizeDisassemblyLine = normalizeDisassemblyLine;
63
73
  exports.compareHermesBytecode = compareHermesBytecode;
64
74
  exports.verifyHermesBaseEquivalence = verifyHermesBaseEquivalence;
65
- // Hermes `-base-bytecode` (delta optimizing mode) support.
66
- //
67
- // Hermes re-sorts its string table by identifier frequency on every compile, so
68
- // any source change renumbers most string IDs and the bytecode diff explodes
69
- // (see hermes-base-bytecode-方案.md). Compiling with the previous HBC of the
70
- // same app as `-base-bytecode` keeps old IDs stable and shrinks patches 5-30×.
71
- // This module resolves that base: gating by hermesc build, HBC version probe,
72
- // server lookup, a sha256-named local cache, download + verification, and the
73
- // optional disassembly equivalence check. Every failure degrades to the plain
74
- // compile — nothing here may block a release.
75
+ const node_string_decoder_1 = require("node:string_decoder");
75
76
  const child_process_1 = require("child_process");
76
77
  const crypto_1 = require("crypto");
77
78
  const fs_extra_1 = __importDefault(require("fs-extra"));
@@ -82,6 +83,8 @@ const promises_1 = require("stream/promises");
82
83
  const constants_1 = require("./constants");
83
84
  const hbcTransform_1 = require("./hbcTransform");
84
85
  const hermes_literals_1 = require("./hermes-literals");
86
+ const hermes_raw_1 = require("./hermes-raw");
87
+ const hermes_timeout_1 = require("./hermes-timeout");
85
88
  const i18n_1 = require("./i18n");
86
89
  const runtime_1 = require("./runtime");
87
90
  const zip_entries_1 = require("./zip-entries");
@@ -276,7 +279,11 @@ function compileProbe(hermesCommand) {
276
279
  const input = path_1.default.join(dir, 'probe.js');
277
280
  const output = path_1.default.join(dir, 'probe.hbc');
278
281
  fs_extra_1.default.writeFileSync(input, '');
279
- const result = (0, child_process_1.spawnSync)(hermesCommand, ['-emit-binary', '-out', output, input, '-O', '-w'], { stdio: 'ignore' });
282
+ const result = (0, child_process_1.spawnSync)(hermesCommand, ['-emit-binary', '-out', output, input, '-O', '-w'], {
283
+ stdio: 'ignore',
284
+ timeout: (0, hermes_timeout_1.hermesTimeout)(process.env.PUSHY_HERMES_PROBE_TIMEOUT_MS, 30_000),
285
+ killSignal: 'SIGKILL',
286
+ });
280
287
  if (result.status !== 0 || !fs_extra_1.default.existsSync(output)) {
281
288
  return null;
282
289
  }
@@ -843,8 +850,7 @@ exports.LITERAL_SEPARATOR = '\u001f';
843
850
  * those offsets, so two builds that lay their buffers out differently still
844
851
  * compare by what each instruction builds. The shape index is dropped like an
845
852
  * offset: it only locates the keys. Null when the operands do not fit the
846
- * layout; an offset that cannot be decoded is spelled out (and so never
847
- * equals a decoded one).
853
+ * layout; an offset or reference that cannot be decoded fails closed.
848
854
  */
849
855
  function renderBufferInstruction(opcode, operands, literals) {
850
856
  const [sizeHint, count] = operands;
@@ -852,7 +858,9 @@ function renderBufferInstruction(opcode, operands, literals) {
852
858
  if (operands.length !== 3)
853
859
  return null;
854
860
  const entries = literals.array(operands[2], count);
855
- return `size=${sizeHint} n=${count} [${entries ? entries.join(exports.LITERAL_SEPARATOR) : `<undecodable@${operands[2]}>`}]`;
861
+ if (!entries)
862
+ throw new Error(`undecodable array literal at ${operands[2]}`);
863
+ return `size=${sizeHint} n=${count} [${entries.join(exports.LITERAL_SEPARATOR)}]`;
856
864
  }
857
865
  if (literals.layout === 'shaped') {
858
866
  if (operands.length !== 2)
@@ -862,7 +870,7 @@ function renderBufferInstruction(opcode, operands, literals) {
862
870
  const keys = shape && literals.objectKeys(shape.keyOffset, shape.count);
863
871
  const values = shape && literals.objectValues(valueOffset, shape.count);
864
872
  if (!shape || !keys || !values) {
865
- return `n=${shape?.count ?? '?'} {<undecodable@shape${shapeIndex}/${valueOffset}>}`;
873
+ throw new Error(`undecodable object literal at shape ${shapeIndex}/${valueOffset}`);
866
874
  }
867
875
  const pairs = keys.map((k, i) => `${k}: ${values[i]}`);
868
876
  return `n=${shape.count} {${pairs.join(exports.LITERAL_SEPARATOR)}}`;
@@ -872,7 +880,7 @@ function renderBufferInstruction(opcode, operands, literals) {
872
880
  const keys = literals.objectKeys(operands[2], count);
873
881
  const values = literals.objectValues(operands[3], count);
874
882
  if (!keys || !values) {
875
- return `size=${sizeHint} n=${count} {<undecodable@${operands[2]}/${operands[3]}>}`;
883
+ throw new Error(`undecodable object literal at ${operands[2]}/${operands[3]}`);
876
884
  }
877
885
  const pairs = keys.map((k, i) => `${k}: ${values[i]}`);
878
886
  return `size=${sizeHint} n=${count} {${pairs.join(exports.LITERAL_SEPARATOR)}}`;
@@ -904,21 +912,26 @@ function normalizeDisassemblyLine(line, strings, literals) {
904
912
  const rendered = renderBufferInstruction(m[1].trim(), nums.map(Number), literals);
905
913
  if (rendered)
906
914
  return `${op} ${regs} ${rendered}`;
915
+ throw new Error(`unsupported literal operands: ${line.trim()}`);
907
916
  }
908
917
  // no binary buffers: only the size hint survives; the buffer content
909
- // is compared as a whole instead (compareBuffers)
918
+ // is compared as a whole for diagnostics only (never accepted as equivalent)
910
919
  return `${op} ${regs} sizes=${nums.slice(0, 1).join(',')}`;
911
920
  }
912
921
  }
913
922
  if (opcode.charCodeAt(0) === 0x4a /* J */) {
914
923
  m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
915
924
  if (m)
916
- return `${m[1]} <tgt>${m[4]}`;
925
+ return `${m[1]} ${m[3]}${normalizeOperandSpacing(m[4])}`;
917
926
  }
918
927
  if (opcode.startsWith('DefineOwnById')) {
919
928
  m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
920
- if (m)
921
- line = `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
929
+ if (m) {
930
+ const text = strings.get(Number(m[2]));
931
+ if (text === undefined)
932
+ throw new Error(`unresolved string id ${m[2]}`);
933
+ line = `${m[1]}${JSON.stringify(text)}`;
934
+ }
922
935
  }
923
936
  // Operand-width variants of one instruction (GetByIdShort/GetById/GetByIdLong,
924
937
  // LoadConstString/LoadConstStringLongIndex, ...) only differ by how wide a
@@ -928,12 +941,12 @@ function normalizeDisassemblyLine(line, strings, literals) {
928
941
  if (opEnd > indent &&
929
942
  (opEnd === line.length || isSpace(line.charCodeAt(opEnd)))) {
930
943
  const folded = foldWidthSuffix(opcode);
931
- line = `${line.slice(0, indent)}${folded}${line.slice(opEnd).replace(/\s+/g, ' ')}`;
944
+ line = `${line.slice(0, indent)}${folded}${normalizeOperandSpacing(line.slice(opEnd))}`;
932
945
  // Switch jump tables sit after the instructions; their relative offset (and
933
946
  // the table header hermesc prints for them) moves with instruction widths.
934
947
  // The two switch instructions carry that offset in different operands:
935
948
  // StringSwitchImm rX, <id>, <jtOffset>, <defaultLabel>, <count>
936
- // UIntSwitchImm rX, <jtOffset>, <defaultLabel>, <min>, <max>
949
+ // UIntSwitchImm (classic: SwitchImm) rX, <jtOffset>, <defaultLabel>, <min>, <max>
937
950
  // Folding only the first shape let a shifted UIntSwitchImm offset read as a
938
951
  // real difference and drop an otherwise good delta build.
939
952
  if (folded === 'StringSwitchImm') {
@@ -941,8 +954,8 @@ function normalizeDisassemblyLine(line, strings, literals) {
941
954
  if (m)
942
955
  line = `${m[1]}<jt>${m[2]}`;
943
956
  }
944
- else if (folded === 'UIntSwitchImm') {
945
- m = /^(\s*UIntSwitchImm r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
957
+ else if (folded === 'UIntSwitchImm' || folded === 'SwitchImm') {
958
+ m = /^(\s*(?:UIntSwitchImm|SwitchImm) r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
946
959
  if (m)
947
960
  line = `${m[1]}<jt>${m[2]}`;
948
961
  }
@@ -952,6 +965,46 @@ function normalizeDisassemblyLine(line, strings, literals) {
952
965
  }
953
966
  return line;
954
967
  }
968
+ /**
969
+ * Collapse formatting outside quoted operands without altering literal code units.
970
+ * ASCII dump spacing takes the char-code fast path; uncommon Unicode characters
971
+ * retain the complete runtime `\s` semantics instead of a narrower space list.
972
+ */
973
+ function normalizeOperandSpacing(text) {
974
+ let result = '';
975
+ let quoted = false;
976
+ let escaped = false;
977
+ let spacing = false;
978
+ for (let i = 0; i < text.length; i++) {
979
+ const char = text[i];
980
+ if (quoted) {
981
+ result += char;
982
+ if (escaped)
983
+ escaped = false;
984
+ else if (char === '\\')
985
+ escaped = true;
986
+ else if (char === '"')
987
+ quoted = false;
988
+ continue;
989
+ }
990
+ const code = text.charCodeAt(i);
991
+ const whitespace = code <= 0x7f
992
+ ? isSpace(code) || (code >= 0x0a && code <= 0x0c)
993
+ : /\s/.test(char);
994
+ if (whitespace) {
995
+ if (!spacing)
996
+ result += ' ';
997
+ spacing = true;
998
+ }
999
+ else {
1000
+ result += char;
1001
+ spacing = false;
1002
+ if (char === '"')
1003
+ quoted = true;
1004
+ }
1005
+ }
1006
+ return result;
1007
+ }
955
1008
  function isSpace(code) {
956
1009
  return code === 0x20 || code === 0x09 || code === 0x0d;
957
1010
  }
@@ -969,9 +1022,10 @@ function foldWidthSuffix(opcode) {
969
1022
  }
970
1023
  /** Split a readable stream into lines without readline (Bun's readline async iterator misbehaves when pulled manually). */
971
1024
  async function* streamLines(stream) {
1025
+ const decoder = new node_string_decoder_1.StringDecoder('utf8');
972
1026
  let rest = '';
973
1027
  for await (const chunk of stream) {
974
- rest += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
1028
+ rest += typeof chunk === 'string' ? chunk : decoder.write(chunk);
975
1029
  let index = rest.indexOf('\n');
976
1030
  while (index >= 0) {
977
1031
  yield rest.slice(0, index);
@@ -979,6 +1033,7 @@ async function* streamLines(stream) {
979
1033
  index = rest.indexOf('\n');
980
1034
  }
981
1035
  }
1036
+ rest += decoder.end();
982
1037
  if (rest)
983
1038
  yield rest;
984
1039
  }
@@ -993,7 +1048,7 @@ const DUMP_STDERR_KEEP = 4 * 1024;
993
1048
  /** a diagnostic line is cut to this many characters */
994
1049
  const DETAIL_LINE_MAX = 120;
995
1050
  function isFunctionHeader(line) {
996
- return line.startsWith('Function<') || line.startsWith('NCFunction<');
1051
+ return /^(?:Function|NCFunction|Constructor)</.test(line);
997
1052
  }
998
1053
  /**
999
1054
  * Structured reader over one `hermesc -dump-bytecode -pretty-disassemble`
@@ -1004,6 +1059,7 @@ function isFunctionHeader(line) {
1004
1059
  */
1005
1060
  class DumpReader {
1006
1061
  proc;
1062
+ binaryStrings;
1007
1063
  iterator;
1008
1064
  strings = new Map();
1009
1065
  /** literal buffers by section name, entries with string ids resolved */
@@ -1015,30 +1071,58 @@ class DumpReader {
1015
1071
  finished = false;
1016
1072
  /** set when the binary literal buffers of this side could be read */
1017
1073
  literals;
1018
- constructor(proc, dumpTo, buffers) {
1074
+ dumpError;
1075
+ debugOutput;
1076
+ debugFinished = Promise.resolve();
1077
+ pass;
1078
+ constructor(proc, dumpTo, buffers, binaryStrings) {
1019
1079
  this.proc = proc;
1080
+ this.binaryStrings = binaryStrings;
1020
1081
  // the string table is filled while the preamble streams by, before the
1021
1082
  // first instruction needs it
1083
+ if (binaryStrings) {
1084
+ for (const [id, value] of binaryStrings)
1085
+ this.strings.set(id, value);
1086
+ }
1022
1087
  if (buffers)
1023
1088
  this.literals = new hermes_literals_1.LiteralResolver(buffers, this.strings);
1024
- const pass = new stream_1.PassThrough();
1089
+ const pass = (this.pass = new stream_1.PassThrough());
1025
1090
  proc.stdout.pipe(pass);
1026
- if (dumpTo)
1027
- proc.stdout.pipe(fs_extra_1.default.createWriteStream(dumpTo));
1091
+ if (dumpTo) {
1092
+ const output = (this.debugOutput = fs_extra_1.default.createWriteStream(dumpTo));
1093
+ this.debugFinished = new Promise((resolve) => {
1094
+ output.once('finish', resolve);
1095
+ output.once('error', (error) => {
1096
+ this.dumpError = error;
1097
+ proc.kill('SIGKILL');
1098
+ resolve();
1099
+ });
1100
+ });
1101
+ proc.stdout.pipe(output);
1102
+ }
1028
1103
  this.iterator = streamLines(pass);
1029
1104
  let stderr = '';
1030
1105
  proc.stderr?.on('data', (chunk) => {
1031
1106
  stderr = (stderr + chunk.toString()).slice(-DUMP_STDERR_KEEP);
1032
1107
  });
1033
1108
  this.exit = new Promise((resolve) => {
1109
+ let processError;
1034
1110
  // a spawn failure (ENOENT) may leave stdout open and never 'close'
1035
1111
  proc.on('error', (error) => {
1112
+ // destroy() need not emit end, so pipe() will not finish its sinks.
1113
+ // End the debug file here: finish() awaits it before finally/kill().
1114
+ proc.stdout?.unpipe();
1115
+ proc.stdout?.destroy();
1036
1116
  pass.end();
1037
- resolve({ code: null, signal: null, error, stderr });
1117
+ this.debugOutput?.end();
1118
+ processError = error;
1119
+ if (!proc.pid)
1120
+ resolve({ code: null, signal: null, error, stderr });
1038
1121
  });
1039
- proc.on('close', (code, signal) => resolve({ code, signal, stderr }));
1122
+ proc.on('close', (code, signal) => resolve({ code, signal, error: processError, stderr }));
1040
1123
  });
1041
1124
  }
1125
+ /** Consume lookahead first, then the stream; null is reserved for EOF. */
1042
1126
  async nextLine() {
1043
1127
  if (this.pending !== null) {
1044
1128
  const line = this.pending;
@@ -1073,10 +1157,12 @@ class DumpReader {
1073
1157
  }
1074
1158
  if (this.section === 'Global String Table') {
1075
1159
  const m = STRING_TABLE_LINE.exec(line);
1076
- if (m)
1160
+ if (m && !this.binaryStrings)
1077
1161
  this.strings.set(Number(m[1]), m[2]);
1078
1162
  }
1079
- else if (this.section?.endsWith('Buffer') && line.trim() !== '') {
1163
+ else if (!this.literals &&
1164
+ this.section?.endsWith('Buffer') &&
1165
+ line.trim() !== '') {
1080
1166
  const entry = line.trim();
1081
1167
  const ref = BUFFER_STRING_ENTRY.exec(entry);
1082
1168
  const text = ref ? this.strings.get(Number(ref[1])) : undefined;
@@ -1118,10 +1204,17 @@ class DumpReader {
1118
1204
  /** drain whatever is left and report how the process ended */
1119
1205
  async finish() {
1120
1206
  while ((await this.nextLine()) !== null) { }
1121
- return this.exit;
1122
- }
1123
- kill() {
1124
- this.proc.kill();
1207
+ const exit = await this.exit;
1208
+ await this.debugFinished;
1209
+ return this.dumpError ? { ...exit, error: this.dumpError } : exit;
1210
+ }
1211
+ async kill() {
1212
+ this.proc.stdout?.unpipe();
1213
+ this.pass.destroy();
1214
+ this.proc.stdout?.destroy();
1215
+ this.proc.kill('SIGKILL');
1216
+ this.debugOutput?.end();
1217
+ await Promise.all([this.exit, this.debugFinished]);
1125
1218
  }
1126
1219
  }
1127
1220
  function describeExit(exit) {
@@ -1190,8 +1283,8 @@ function compareFunctions(a, b) {
1190
1283
  return null;
1191
1284
  }
1192
1285
  /**
1193
- * Compare two HBC files by disassembly (see normalizeDisassemblyLine): the
1194
- * literal buffers by content, then function by function. `-b` forces hermesc
1286
+ * Compare two HBC files by pretty disassembly, then audit the raw operands
1287
+ * against full binary strings, literals, function identities and addresses. `-b` forces hermesc
1195
1288
  * to treat inputs as bytecode whatever their extension. Both dumps are
1196
1289
  * consumed as streams so the ~100 MB of text never touches the disk (unless
1197
1290
  * `dumpTo` asks for it). A dump process that fails or ends early is reported
@@ -1200,19 +1293,34 @@ function compareFunctions(a, b) {
1200
1293
  * turned into a normalization rule or a bug report.
1201
1294
  */
1202
1295
  async function compareHermesBytecode(hermesCommand, withBase, plain, options = {}) {
1203
- const spawnDump = (file) => (0, child_process_1.spawn)(hermesCommand, ['-b', '-dump-bytecode', '-pretty-disassemble', file], { stdio: ['ignore', 'pipe', 'pipe'] });
1296
+ const controller = new AbortController();
1297
+ const timeoutMs = (0, hermes_timeout_1.hermesTimeout)(options.timeoutMs ?? process.env.PUSHY_HERMES_VERIFY_TIMEOUT_MS, 120_000);
1298
+ const abort = () => controller.abort(options.signal?.reason);
1299
+ if (options.signal?.aborted)
1300
+ abort();
1301
+ else
1302
+ options.signal?.addEventListener('abort', abort, { once: true });
1303
+ const timer = setTimeout(() => controller.abort(new Error(`Hermes verification timed out after ${timeoutMs}ms`)), timeoutMs);
1304
+ timer.unref();
1305
+ const spawnDump = (file) => (0, child_process_1.spawn)(hermesCommand, ['-b', '-dump-bytecode', '-pretty-disassemble', file], {
1306
+ stdio: ['ignore', 'pipe', 'pipe'],
1307
+ signal: controller.signal,
1308
+ killSignal: 'SIGKILL',
1309
+ });
1204
1310
  // The literal buffers are read from both files up front (header + three
1205
1311
  // byte ranges). Only when both sides can be read do the instructions
1206
1312
  // compare decoded literals; otherwise both fall back to the dumped buffers
1207
1313
  // as a whole, so the two sides always normalize the same way.
1208
- const [buffersA, buffersB] = await Promise.all([
1314
+ const [buffersA, buffersB, dataA, dataB] = await Promise.all([
1209
1315
  (0, hermes_literals_1.readLiteralBuffers)(withBase).catch(() => null),
1210
1316
  (0, hermes_literals_1.readLiteralBuffers)(plain).catch(() => null),
1317
+ (0, hermes_raw_1.readHermesSemanticData)(withBase).catch(() => null),
1318
+ (0, hermes_raw_1.readHermesSemanticData)(plain).catch(() => null),
1211
1319
  ]);
1212
1320
  const binary = buffersA && buffersB && buffersA.version === buffersB.version;
1213
1321
  const literals = binary ? 'instruction' : 'buffer';
1214
- const a = new DumpReader(spawnDump(withBase), options.dumpTo?.withBase, binary ? buffersA : null);
1215
- const b = new DumpReader(spawnDump(plain), options.dumpTo?.plain, binary ? buffersB : null);
1322
+ const a = new DumpReader(spawnDump(withBase), options.dumpTo?.withBase, binary ? buffersA : null, dataA?.strings);
1323
+ const b = new DumpReader(spawnDump(plain), options.dumpTo?.plain, binary ? buffersB : null, dataB?.strings);
1216
1324
  let functions = 0;
1217
1325
  const different = (detail) => ({
1218
1326
  status: 'different',
@@ -1253,7 +1361,16 @@ async function compareHermesBytecode(hermesCommand, withBase, plain, options = {
1253
1361
  literals,
1254
1362
  };
1255
1363
  }
1256
- return { status: 'equivalent', functions, literals };
1364
+ if (!binary || !dataA || !dataB) {
1365
+ return {
1366
+ status: 'dump-failed',
1367
+ detail: 'unsupported or unreadable HBC layout; text-only comparison cannot verify equivalence',
1368
+ functions,
1369
+ literals,
1370
+ };
1371
+ }
1372
+ const audit = await (0, hermes_raw_1.auditRawHermesBytecode)(hermesCommand, [withBase, plain], [dataA, dataB], [buffersA, buffersB], controller.signal);
1373
+ return { ...audit, functions, literals };
1257
1374
  }
1258
1375
  if (functions === 0 && !binary) {
1259
1376
  // buffers precede the functions, so both are complete by now. This
@@ -1270,9 +1387,18 @@ async function compareHermesBytecode(hermesCommand, withBase, plain, options = {
1270
1387
  functions++;
1271
1388
  }
1272
1389
  }
1390
+ catch (error) {
1391
+ return {
1392
+ status: 'dump-failed',
1393
+ detail: error instanceof Error ? error.message : String(error),
1394
+ functions,
1395
+ literals,
1396
+ };
1397
+ }
1273
1398
  finally {
1274
- a.kill();
1275
- b.kill();
1399
+ clearTimeout(timer);
1400
+ options.signal?.removeEventListener('abort', abort);
1401
+ await Promise.all([a.kill(), b.kill()]);
1276
1402
  }
1277
1403
  }
1278
1404
  /** Resolves true when equivalent; see compareHermesBytecode for the details. */
@@ -33,13 +33,13 @@ export declare function readLiteralBuffers(file: string): Promise<LiteralBuffers
33
33
  /**
34
34
  * Decode `count` literal values starting at byte `offset`. Null when the
35
35
  * offset or a run reaches outside the buffer or a tag type is unknown; the
36
- * caller reports that as a difference rather than guessing. `layout` decides
36
+ * caller fails verification rather than treating two failures as equivalent. `layout` decides
37
37
  * what type 6 means (see the file comment).
38
38
  */
39
39
  export declare function decodeSerializedLiterals(buffer: Buffer, offset: number, count: number, layout?: LiteralBuffers['layout']): LiteralValue[] | null;
40
40
  /**
41
41
  * One literal as text, string ids resolved through the dump's string table
42
- * (an unknown id stays visible as `?id`). Doubles keep their exact bits in
42
+ * (an unknown id fails closed). Doubles keep their exact bits in
43
43
  * the text so -0 and 0, or two NaNs, never collide by accident.
44
44
  */
45
45
  export declare function renderLiteral(value: LiteralValue, strings: Map<number, string>): string;
@@ -115,10 +115,16 @@ async function readLiteralBuffers(file) {
115
115
  /**
116
116
  * Decode `count` literal values starting at byte `offset`. Null when the
117
117
  * offset or a run reaches outside the buffer or a tag type is unknown; the
118
- * caller reports that as a difference rather than guessing. `layout` decides
118
+ * caller fails verification rather than treating two failures as equivalent. `layout` decides
119
119
  * what type 6 means (see the file comment).
120
120
  */
121
121
  function decodeSerializedLiterals(buffer, offset, count, layout = 'split') {
122
+ if (!Number.isSafeInteger(offset) ||
123
+ !Number.isSafeInteger(count) ||
124
+ offset < 0 ||
125
+ count < 0 ||
126
+ count > 1_000_000)
127
+ return null;
122
128
  const values = [];
123
129
  let pos = offset;
124
130
  while (values.length < count) {
@@ -131,6 +137,8 @@ function decodeSerializedLiterals(buffer, offset, count, layout = 'split') {
131
137
  return null;
132
138
  length = (length << 8) | buffer[pos++];
133
139
  }
140
+ if (length === 0)
141
+ return null;
134
142
  const type = tag & TAG_TYPE_MASK;
135
143
  for (let i = 0; i < length && values.length < count; i++) {
136
144
  switch (type) {
@@ -186,7 +194,7 @@ function decodeSerializedLiterals(buffer, offset, count, layout = 'split') {
186
194
  }
187
195
  /**
188
196
  * One literal as text, string ids resolved through the dump's string table
189
- * (an unknown id stays visible as `?id`). Doubles keep their exact bits in
197
+ * (an unknown id fails closed). Doubles keep their exact bits in
190
198
  * the text so -0 and 0, or two NaNs, never collide by accident.
191
199
  */
192
200
  function renderLiteral(value, strings) {
@@ -205,7 +213,9 @@ function renderLiteral(value, strings) {
205
213
  }
206
214
  case 'string': {
207
215
  const text = strings.get(value.id);
208
- return `[String ${text === undefined ? `?${value.id}` : JSON.stringify(text)}]`;
216
+ if (text === undefined)
217
+ throw new Error(`unresolved string id ${value.id}`);
218
+ return `[String ${JSON.stringify(text)}]`;
209
219
  }
210
220
  }
211
221
  }
@@ -241,7 +251,7 @@ class LiteralResolver {
241
251
  /** Shape table entry (HBC v98); null out of range or in the split layout. */
242
252
  shape(index) {
243
253
  const b = this.buffers;
244
- if (b.layout !== 'shaped' || index < 0)
254
+ if (b.layout !== 'shaped' || !Number.isSafeInteger(index) || index < 0)
245
255
  return null;
246
256
  const at = index * SHAPE_ENTRY_SIZE;
247
257
  if (at + SHAPE_ENTRY_SIZE > b.shapes.length)
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Lossless operand audit accompanying the human-readable Hermes comparison.
3
+ * Pretty disassembly truncates strings and BigInts, prints function names in
4
+ * place of IDs, and renders -0 as 0. Never use those spellings as identities.
5
+ *
6
+ * The raw dump supplies instruction/operand boundaries; referenced data and
7
+ * doubles come from the HBC itself. Bytecode layouts are intentionally bounded
8
+ * to the layouts already supported by hbcTransform. Unknown data fails closed.
9
+ */
10
+ import { type LiteralBuffers } from './hermes-literals';
11
+ export declare class UnverifiableHermesBytecode extends Error {
12
+ }
13
+ interface FunctionData {
14
+ offset: number;
15
+ size: number;
16
+ metadata: string;
17
+ }
18
+ export interface HermesSemanticData {
19
+ bytes: Buffer;
20
+ version: number;
21
+ strings: Map<number, string>;
22
+ functions: FunctionData[];
23
+ bigints: Buffer[];
24
+ regexps: Buffer[];
25
+ metadata: string;
26
+ }
27
+ /** Read exact strings (including UTF-16 code units) and function identities. */
28
+ export declare function readHermesSemanticData(file: string): Promise<HermesSemanticData>;
29
+ /** Canonicalize one complete function; addresses become instruction ordinals. */
30
+ export declare function normalizeRawHermesFunction(lines: string[], data: HermesSemanticData, functionIndex: number, buffers: LiteralBuffers): string[];
31
+ export interface RawAuditResult {
32
+ status: 'equivalent' | 'different' | 'dump-failed';
33
+ detail?: string;
34
+ }
35
+ /**
36
+ * Audit a pair of raw dumps while retaining one function per side plus HBC data.
37
+ * Cancellation/errors fail closed; both subprocesses are terminated and reaped.
38
+ */
39
+ export declare function auditRawHermesBytecode(command: string, files: [string, string], data: [HermesSemanticData, HermesSemanticData], buffers: [LiteralBuffers, LiteralBuffers], signal: AbortSignal): Promise<RawAuditResult>;
40
+ export {};
@@ -0,0 +1,486 @@
1
+ "use strict";
2
+ /**
3
+ * Lossless operand audit accompanying the human-readable Hermes comparison.
4
+ * Pretty disassembly truncates strings and BigInts, prints function names in
5
+ * place of IDs, and renders -0 as 0. Never use those spellings as identities.
6
+ *
7
+ * The raw dump supplies instruction/operand boundaries; referenced data and
8
+ * doubles come from the HBC itself. Bytecode layouts are intentionally bounded
9
+ * to the layouts already supported by hbcTransform. Unknown data fails closed.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.UnverifiableHermesBytecode = void 0;
13
+ exports.readHermesSemanticData = readHermesSemanticData;
14
+ exports.normalizeRawHermesFunction = normalizeRawHermesFunction;
15
+ exports.auditRawHermesBytecode = auditRawHermesBytecode;
16
+ const promises_1 = require("node:fs/promises");
17
+ const node_string_decoder_1 = require("node:string_decoder");
18
+ const child_process_1 = require("child_process");
19
+ const hbcTransform_1 = require("./hbcTransform");
20
+ const hermes_literals_1 = require("./hermes-literals");
21
+ class UnverifiableHermesBytecode extends Error {
22
+ }
23
+ exports.UnverifiableHermesBytecode = UnverifiableHermesBytecode;
24
+ /** Fail closed on missing references rather than comparing equal placeholders. */
25
+ function requireValue(value, what) {
26
+ if (value === null || value === undefined) {
27
+ throw new UnverifiableHermesBytecode(what);
28
+ }
29
+ return value;
30
+ }
31
+ /** Bound a reference to its owning section before creating a zero-copy view. */
32
+ function checkedSlice(data, start, length) {
33
+ if (!Number.isSafeInteger(start) ||
34
+ !Number.isSafeInteger(length) ||
35
+ start < 0 ||
36
+ length < 0 ||
37
+ start + length > data.length) {
38
+ throw new UnverifiableHermesBytecode('HBC reference outside its section');
39
+ }
40
+ return data.subarray(start, start + length);
41
+ }
42
+ /** Read exact strings (including UTF-16 code units) and function identities. */
43
+ async function readHermesSemanticData(file) {
44
+ const bytes = await (0, promises_1.readFile)(file);
45
+ const resolved = requireValue((0, hbcTransform_1.resolveHbcSections)(bytes, bytes.length), 'unsupported or unreadable HBC layout');
46
+ // A newly added diff-transform layout must not silently opt into semantic
47
+ // parsing: function header and operand schemas need an independent review.
48
+ if (!((resolved.version >= 87 && resolved.version <= 96) ||
49
+ resolved.version === 98)) {
50
+ throw new UnverifiableHermesBytecode('unsupported semantic HBC version');
51
+ }
52
+ const layout = requireValue((0, hbcTransform_1.pickLayout)(bytes), 'unknown HBC layout');
53
+ const section = (name) => {
54
+ const r = requireValue(resolved.sections.get(name), `missing ${name}`);
55
+ return checkedSlice(bytes, r.start, r.size);
56
+ };
57
+ const strings = new Map();
58
+ const small = section('smallStringTable');
59
+ const overflow = section('overflowStringTable');
60
+ const storage = section('stringStorage');
61
+ for (let at = 0; at < small.length; at += 4) {
62
+ const word = small.readUInt32LE(at);
63
+ const utf16 = (word & 1) !== 0;
64
+ let offset = (word >>> 1) & 0x7fffff;
65
+ let length = word >>> 24;
66
+ if (length === 255) {
67
+ const entry = checkedSlice(overflow, offset * 8, 8);
68
+ offset = entry.readUInt32LE(0);
69
+ length = entry.readUInt32LE(4);
70
+ }
71
+ const value = checkedSlice(storage, offset, length * (utf16 ? 2 : 1));
72
+ strings.set(at / 4, value.toString(utf16 ? 'utf16le' : 'latin1'));
73
+ }
74
+ const string = (id) => requireValue(strings.get(id), `unresolved string id ${id}`);
75
+ // Audited v98 function schema: hermes-compiler 250829098.0.16/.17
76
+ // (250829098 stable snapshot), NOT every static_h build reporting HBC 98.
77
+ // Large headers: 37 bytes, flags[36]; small cache bits: 6/1/1. Upstream
78
+ // 7193d4485beeb87cd7a3b6ca8b6b5d97a1a433c4 removed NumCacheNewObject
79
+ // without immediately bumping HBC: 36 bytes/flags[35], cache bits 7/1.
80
+ // hbcTransform's file-header variants do not distinguish that function
81
+ // schema change. A compiler upgrade needs independent large/small fixtures;
82
+ // do not infer either schema from numStringSwitchImms or HBC version alone.
83
+ const shaped = resolved.version === 98;
84
+ const entrySize = shaped ? 12 : 16;
85
+ const headers = section('functionHeaders');
86
+ const functions = [];
87
+ for (let at = 0; at < headers.length; at += entrySize) {
88
+ const word0 = headers.readUInt32LE(at);
89
+ const word1 = headers.readUInt32LE(at + 4);
90
+ let flags = headers[at + entrySize - 1];
91
+ let offset = word0 & 0x1ffffff;
92
+ let size;
93
+ let name;
94
+ let fields;
95
+ if (flags & 0x20) {
96
+ // SmallFuncHeader::getLargeHeaderOffset, classic and Static Hermes.
97
+ const largeOffset = shaped
98
+ ? ((word1 >>> 14) & 0xff) * 0x1000000 + offset
99
+ : (headers.readUInt32LE(at + 8) & 0x1ffffff) * 0x10000 + offset;
100
+ const large = checkedSlice(bytes, largeOffset, shaped ? 37 : 31);
101
+ offset = large.readUInt32LE(0);
102
+ size = large.readUInt32LE(shaped ? 12 : 8);
103
+ name = large.readUInt32LE(shaped ? 16 : 12);
104
+ flags = large[shaped ? 36 : 30];
105
+ fields = shaped
106
+ ? [4, 8, 20, 24, 28].map((p) => large.readUInt32LE(p))
107
+ : [4, 20, 24].map((p) => large.readUInt32LE(p));
108
+ fields.push(...large.subarray(shaped ? 32 : 28, shaped ? 36 : 30));
109
+ }
110
+ else if (shaped) {
111
+ size = word1 & 0x3fff;
112
+ name = (word1 >>> 14) & 0xff;
113
+ fields = [
114
+ (word0 >>> 25) & 31,
115
+ word0 >>> 30,
116
+ (word1 >>> 22) & 31,
117
+ word1 >>> 27,
118
+ headers[at + 8],
119
+ headers[at + 9],
120
+ headers[at + 10] & 63,
121
+ (headers[at + 10] >>> 6) & 1,
122
+ headers[at + 10] >>> 7,
123
+ ];
124
+ }
125
+ else {
126
+ size = word1 & 0x7fff;
127
+ name = word1 >>> 15;
128
+ fields = [
129
+ word0 >>> 25,
130
+ headers.readUInt32LE(at + 8) >>> 25,
131
+ headers[at + 12],
132
+ headers[at + 13],
133
+ headers[at + 14],
134
+ ];
135
+ }
136
+ checkedSlice(bytes, offset, size);
137
+ functions.push({
138
+ offset,
139
+ size,
140
+ // Debug presence and compact/overflow encoding are not runtime semantics.
141
+ metadata: JSON.stringify([string(name), flags & ~0x30, fields]),
142
+ });
143
+ }
144
+ const pairedStorage = (tableName, storageName) => {
145
+ const table = section(tableName);
146
+ const data = section(storageName);
147
+ const entries = [];
148
+ for (let at = 0; at < table.length; at += 8) {
149
+ entries.push(checkedSlice(data, table.readUInt32LE(at), table.readUInt32LE(at + 4)));
150
+ }
151
+ return entries;
152
+ };
153
+ const counts = Object.fromEntries(layout.headerFields.map((name, i) => [
154
+ name,
155
+ bytes.readUInt32LE(32 + i * 4),
156
+ ]));
157
+ const options = bytes[32 + layout.headerFields.length * 4];
158
+ const moduleTable = section('cjsModuleTable');
159
+ const modules = [];
160
+ for (let at = 0; at < moduleTable.length; at += 8) {
161
+ const id = moduleTable.readUInt32LE(at);
162
+ modules.push([
163
+ options & 2 ? id : string(id),
164
+ moduleTable.readUInt32LE(at + 4),
165
+ ]);
166
+ }
167
+ const sourceTable = section('functionSourceTable');
168
+ const sources = [];
169
+ for (let at = 0; at < sourceTable.length; at += 8) {
170
+ sources.push([
171
+ sourceTable.readUInt32LE(at),
172
+ string(sourceTable.readUInt32LE(at + 4)),
173
+ ]);
174
+ }
175
+ return {
176
+ bytes,
177
+ version: resolved.version,
178
+ strings,
179
+ functions,
180
+ bigints: pairedStorage('bigIntTable', 'bigIntStorage'),
181
+ regexps: pairedStorage('regExpTable', 'regExpStorage'),
182
+ metadata: JSON.stringify([
183
+ resolved.version,
184
+ counts.globalCodeIndex,
185
+ counts.segmentID,
186
+ options,
187
+ modules,
188
+ sources,
189
+ ]),
190
+ };
191
+ }
192
+ const OPERAND_BYTES = {
193
+ Reg8: 1,
194
+ Reg32: 4,
195
+ UInt8: 1,
196
+ UInt16: 2,
197
+ UInt32: 4,
198
+ Addr8: 1,
199
+ Addr32: 4,
200
+ Imm32: 4,
201
+ Double: 8,
202
+ };
203
+ // Zero-based string operand positions from BytecodeList.def, with the missing
204
+ // DefineOwnById annotation supplied explicitly. Keep classic and v98 variants.
205
+ const STRING_OPERANDS = {
206
+ DeclareGlobalVar: [0],
207
+ ThrowIfHasRestrictedGlobalProperty: [0],
208
+ GetById: [3],
209
+ GetByIdWithReceiver: [4],
210
+ TryGetById: [3],
211
+ PutById: [3],
212
+ TryPutById: [3],
213
+ PutNewOwnById: [2],
214
+ PutNewOwnNEById: [2],
215
+ PutByIdLoose: [3],
216
+ PutByIdStrict: [3],
217
+ TryPutByIdLoose: [3],
218
+ TryPutByIdStrict: [3],
219
+ DefineOwnById: [3],
220
+ DelById: [2],
221
+ LoadConstString: [1],
222
+ CreatePrivateName: [1],
223
+ CreateRegExp: [1, 2],
224
+ };
225
+ /** Remove encoding-width suffixes; operand values remain part of the audit. */
226
+ function foldWidth(opcode) {
227
+ return opcode.replace(/(?:LongIndex|Long|Short)$/, '');
228
+ }
229
+ /**
230
+ * Read raw operand boundaries and verify integer values against the HBC bytes.
231
+ * Doubles use their exact bits, not the rounded number printed by hermesc.
232
+ */
233
+ function parseRawInstruction(line, data, fn) {
234
+ const m = /^\[@ (\d+)\] ([A-Za-z][A-Za-z0-9]*)(.*)$/.exec(line);
235
+ if (!m)
236
+ throw new UnverifiableHermesBytecode(`unrecognized raw instruction: ${line.slice(0, 100)}`);
237
+ const offset = Number(m[1]);
238
+ let size = 1;
239
+ const operands = m[3].trim() === ''
240
+ ? []
241
+ : m[3]
242
+ .trim()
243
+ .split(/,\s*/)
244
+ .map((text) => {
245
+ const operand = /^([^<>]+)<([A-Za-z0-9]+)>$/.exec(text);
246
+ if (!operand || !Object.hasOwn(OPERAND_BYTES, operand[2])) {
247
+ throw new UnverifiableHermesBytecode(`unknown raw operand: ${text}`);
248
+ }
249
+ const type = operand[2];
250
+ const width = OPERAND_BYTES[type];
251
+ const raw = checkedSlice(checkedSlice(data.bytes, fn.offset, fn.size), offset + size, width);
252
+ size += width;
253
+ // Raw dump doubles are also rounded! Compare the actual IEEE-754 bits.
254
+ if (type === 'Double')
255
+ return { type, value: 0, bits: raw.toString('hex') };
256
+ const value = Number(operand[1]);
257
+ const binaryValue = type === 'Addr8'
258
+ ? raw.readInt8(0)
259
+ : type === 'Addr32' || type === 'Imm32'
260
+ ? raw.readInt32LE(0)
261
+ : width === 1
262
+ ? raw.readUInt8(0)
263
+ : width === 2
264
+ ? raw.readUInt16LE(0)
265
+ : raw.readUInt32LE(0);
266
+ if (!Number.isSafeInteger(value) || value !== binaryValue) {
267
+ throw new UnverifiableHermesBytecode('raw operand does not match the HBC bytes');
268
+ }
269
+ return { type, value };
270
+ });
271
+ return { offset, opcode: m[2], operands, size };
272
+ }
273
+ /** Canonicalize one complete function; addresses become instruction ordinals. */
274
+ function normalizeRawHermesFunction(lines, data, functionIndex, buffers) {
275
+ const fn = requireValue(data.functions[functionIndex], 'function index outside HBC table');
276
+ const instructions = lines
277
+ .filter((line) => line.startsWith('[@ '))
278
+ .map((line) => parseRawInstruction(line, data, fn));
279
+ const targets = new Map();
280
+ let end = 0;
281
+ for (const [index, inst] of instructions.entries()) {
282
+ if (inst.offset !== end)
283
+ throw new UnverifiableHermesBytecode('incomplete or unordered raw instruction stream');
284
+ targets.set(inst.offset, index);
285
+ end += inst.size;
286
+ }
287
+ // Static Hermes retains legal zero-byte (dead) functions in the table.
288
+ // Their metadata is still audited, and the raw reader still requires every
289
+ // function header. Only a body shorter/longer than its declared size fails.
290
+ if (end !== fn.size) {
291
+ throw new UnverifiableHermesBytecode('raw dump ended before the function body');
292
+ }
293
+ const target = (offset) => requireValue(targets.get(offset), `branch target ${offset} is not an instruction`);
294
+ const string = (id) => requireValue(data.strings.get(id), `unresolved string id ${id}`);
295
+ const literal = new hermes_literals_1.LiteralResolver(buffers, data.strings);
296
+ const output = [fn.metadata];
297
+ for (const inst of instructions) {
298
+ const op = foldWidth(inst.opcode);
299
+ const values = inst.operands.map((o) => o.value);
300
+ const refs = STRING_OPERANDS[op] ?? [];
301
+ const operands = inst.operands.map((operand, i) => {
302
+ if (refs.includes(i))
303
+ return ['string', string(operand.value)];
304
+ if (operand.type.startsWith('Addr'))
305
+ return ['target', target(inst.offset + operand.value)];
306
+ if (operand.type === 'Double')
307
+ return ['double', operand.bits];
308
+ return [
309
+ operand.type.startsWith('Reg') ? 'register' : 'integer',
310
+ operand.value,
311
+ ];
312
+ });
313
+ if (op === 'LoadConstBigInt') {
314
+ operands[1] = [
315
+ 'bigint',
316
+ requireValue(data.bigints[values[1]], 'unresolved BigInt').toString('hex'),
317
+ ];
318
+ }
319
+ else if (op === 'CreateRegExp') {
320
+ operands[3] = [
321
+ 'regexp',
322
+ requireValue(data.regexps[values[3]], 'unresolved RegExp').toString('hex'),
323
+ ];
324
+ }
325
+ else if (op === 'NewArrayWithBuffer') {
326
+ if (values.length !== 4)
327
+ throw new UnverifiableHermesBytecode('unknown array buffer operands');
328
+ operands[3] = requireValue(literal.array(values[3], values[2]), 'undecodable array literal');
329
+ }
330
+ else if (op === 'NewObjectWithBuffer' ||
331
+ op === 'NewObjectWithBufferAndParent') {
332
+ if (buffers.layout === 'split') {
333
+ if (values.length !== 5 || op !== 'NewObjectWithBuffer')
334
+ throw new UnverifiableHermesBytecode('unknown split object operands');
335
+ operands[3] = requireValue(literal.objectKeys(values[3], values[2]), 'undecodable object keys');
336
+ operands[4] = requireValue(literal.objectValues(values[4], values[2]), 'undecodable object values');
337
+ }
338
+ else {
339
+ const shapeAt = op === 'NewObjectWithBufferAndParent' ? 2 : 1;
340
+ if (values.length !== shapeAt + 2)
341
+ throw new UnverifiableHermesBytecode('unknown shaped object operands');
342
+ const shape = requireValue(literal.shape(values[shapeAt]), 'unknown object shape');
343
+ operands[shapeAt] = requireValue(literal.objectKeys(shape.keyOffset, shape.count), 'undecodable shape keys');
344
+ operands[shapeAt + 1] = requireValue(literal.objectValues(values[shapeAt + 1], shape.count), 'undecodable shape values');
345
+ }
346
+ }
347
+ else if (op === 'CacheNewObject') {
348
+ if (buffers.layout !== 'shaped' || values.length !== 4) {
349
+ throw new UnverifiableHermesBytecode('unknown cached object operands');
350
+ }
351
+ const shape = requireValue(literal.shape(values[2]), 'unknown cached object shape');
352
+ operands[2] = requireValue(literal.objectKeys(shape.keyOffset, shape.count), 'undecodable cached object keys');
353
+ }
354
+ else if (op === 'UIntSwitchImm' ||
355
+ op === 'SwitchImm' ||
356
+ op === 'StringSwitchImm') {
357
+ const strings = op === 'StringSwitchImm';
358
+ const tableAt = strings ? 2 : 1;
359
+ const count = strings ? values[4] : values[4] - values[3] + 1;
360
+ // The table offset is relative to the instruction, rounded up to 4-byte alignment.
361
+ const start = Math.ceil((fn.offset + inst.offset + values[tableAt]) / 4) * 4;
362
+ const table = checkedSlice(data.bytes, start, count * (strings ? 8 : 4));
363
+ const entries = [];
364
+ for (let i = 0; i < count; i++) {
365
+ const at = i * (strings ? 8 : 4);
366
+ entries.push([
367
+ strings ? string(table.readUInt32LE(at)) : values[3] + i,
368
+ target(inst.offset + table.readInt32LE(at + (strings ? 4 : 0))),
369
+ ]);
370
+ }
371
+ operands[tableAt] = entries;
372
+ }
373
+ output.push(JSON.stringify([op, operands]));
374
+ }
375
+ return output;
376
+ }
377
+ /** Decode split UTF-8 sequences without buffering the whole raw dump. */
378
+ async function* linesOf(stream) {
379
+ const decoder = new node_string_decoder_1.StringDecoder('utf8');
380
+ let rest = '';
381
+ for await (const chunk of stream) {
382
+ rest += decoder.write(chunk);
383
+ let at = rest.indexOf('\n');
384
+ while (at >= 0) {
385
+ yield rest.slice(0, at).replace(/\r$/, '');
386
+ rest = rest.slice(at + 1);
387
+ at = rest.indexOf('\n');
388
+ }
389
+ }
390
+ rest += decoder.end();
391
+ if (rest)
392
+ yield rest;
393
+ }
394
+ /**
395
+ * Audit a pair of raw dumps while retaining one function per side plus HBC data.
396
+ * Cancellation/errors fail closed; both subprocesses are terminated and reaped.
397
+ */
398
+ async function auditRawHermesBytecode(command, files, data, buffers, signal) {
399
+ if (data[0].metadata !== data[1].metadata)
400
+ return { status: 'different', detail: 'HBC runtime metadata differs' };
401
+ const children = files.map((file) => (0, child_process_1.spawn)(command, ['-b', '-dump-bytecode', '-pretty-disassemble=false', file], {
402
+ stdio: ['ignore', 'pipe', 'pipe'],
403
+ signal,
404
+ killSignal: 'SIGKILL',
405
+ }));
406
+ const exits = children.map((child) => new Promise((resolve) => {
407
+ let stderr = '';
408
+ let processError;
409
+ child.stderr?.on('data', (chunk) => {
410
+ stderr = (stderr + chunk.toString()).slice(-4096);
411
+ });
412
+ child.once('error', (error) => {
413
+ child.stdout?.destroy();
414
+ processError = error;
415
+ if (!child.pid)
416
+ resolve(error.message);
417
+ });
418
+ child.once('close', (code, reason) => resolve(processError
419
+ ? processError.message
420
+ : code === 0
421
+ ? null
422
+ : `${reason ?? `exit ${code}`}: ${stderr.trim().slice(-300)}`));
423
+ }));
424
+ const functions = async function* (side) {
425
+ let lines = null;
426
+ let index = 0;
427
+ for await (const line of linesOf(children[side].stdout)) {
428
+ if (/^(?:Function|NCFunction|Constructor)</.test(line)) {
429
+ if (lines)
430
+ yield normalizeRawHermesFunction(lines, data[side], index++, buffers[side]);
431
+ lines = [];
432
+ }
433
+ else if (/^(?:RegExp Bytecodes:|Debug |Textified callees table)/.test(line)) {
434
+ if (lines)
435
+ yield normalizeRawHermesFunction(lines, data[side], index++, buffers[side]);
436
+ lines = null;
437
+ }
438
+ else if (lines) {
439
+ lines.push(line);
440
+ }
441
+ }
442
+ if (lines)
443
+ yield normalizeRawHermesFunction(lines, data[side], index++, buffers[side]);
444
+ const error = await exits[side];
445
+ if (error)
446
+ throw new UnverifiableHermesBytecode(`${side === 0 ? 'base' : 'plain'} raw dump: ${error}`);
447
+ if (index !== data[side].functions.length)
448
+ throw new UnverifiableHermesBytecode('raw dump function count does not match HBC header');
449
+ };
450
+ const a = functions(0);
451
+ const b = functions(1);
452
+ let index = 0;
453
+ try {
454
+ for (;;) {
455
+ const [left, right] = await Promise.all([a.next(), b.next()]);
456
+ if (left.done || right.done) {
457
+ return left.done && right.done
458
+ ? { status: 'equivalent' }
459
+ : { status: 'different', detail: 'raw function counts differ' };
460
+ }
461
+ const length = Math.max(left.value.length, right.value.length);
462
+ for (let i = 0; i < length; i++) {
463
+ if (left.value[i] !== right.value[i]) {
464
+ return {
465
+ status: 'different',
466
+ detail: `function #${index}, raw instruction ${i}: ${left.value[i]?.slice(0, 150)} vs ${right.value[i]?.slice(0, 150)}`,
467
+ };
468
+ }
469
+ }
470
+ index++;
471
+ }
472
+ }
473
+ catch (error) {
474
+ return {
475
+ status: 'dump-failed',
476
+ detail: error instanceof Error ? error.message : String(error),
477
+ };
478
+ }
479
+ finally {
480
+ for (const child of children) {
481
+ child.stdout?.destroy();
482
+ child.kill('SIGKILL');
483
+ }
484
+ await Promise.all(exits);
485
+ }
486
+ }
@@ -0,0 +1,2 @@
1
+ /** Reject invalid/overflowing timer values instead of turning them into 1ms. */
2
+ export declare function hermesTimeout(value: unknown, fallback: number): number;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hermesTimeout = hermesTimeout;
4
+ /** Reject invalid/overflowing timer values instead of turning them into 1ms. */
5
+ function hermesTimeout(value, fallback) {
6
+ const parsed = Number(value);
7
+ return Number.isSafeInteger(parsed) && parsed > 0 && parsed <= 0x7fffffff
8
+ ? parsed
9
+ : fallback;
10
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.26.1",
3
+ "version": "2.26.2",
4
4
  "description": "command line tool for react-native-update (remote updates for react native)",
5
5
  "main": "lib/exports.js",
6
6
  "types": "lib/exports.d.ts",