react-nitro-hermes 0.0.1-alpha.8 → 0.0.1-alpha.9

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.
Files changed (181) hide show
  1. package/hermes/CMakeLists.txt +874 -0
  2. package/hermes/android/HostObjectJniTest.cpp +178 -0
  3. package/hermes/android/build-logic/build.gradle.kts +31 -0
  4. package/hermes/android/build-logic/settings.gradle.kts +17 -0
  5. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/helpers/internal/SerializeHermesCompilerPackageJson.kt +33 -0
  6. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/plugins/internal/TestUtilsPlugin.kt +80 -0
  7. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/tasks/internal/CustomExecTask.kt +46 -0
  8. package/hermes/android/build-logic/src/main/kotlin/publish.gradle.kts +82 -0
  9. package/hermes/android/build.gradle.kts +332 -0
  10. package/hermes/android/cppruntime/build.gradle +72 -0
  11. package/hermes/android/cppruntime/src/main/AndroidManifest.xml +2 -0
  12. package/hermes/android/cppruntime/src/main/cpp/CMakeLists.txt +8 -0
  13. package/hermes/android/cppruntime/src/main/cpp/stub.cpp +12 -0
  14. package/hermes/android/cross-compile/swift-libicu.patch +13 -0
  15. package/hermes/android/cross-compile/toolchain-android-arm-api13-gnustl.cmake +13 -0
  16. package/hermes/android/cross-compile/toolchain-android-arm-api15-gnustl.cmake +14 -0
  17. package/hermes/android/gradle/libs.versions.toml +30 -0
  18. package/hermes/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  19. package/hermes/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  20. package/hermes/android/gradle.properties +3 -0
  21. package/hermes/android/gradlew +248 -0
  22. package/hermes/android/gradlew.bat +93 -0
  23. package/hermes/android/intltest/build.gradle +147 -0
  24. package/hermes/android/intltest/java/com/facebook/hermes/test/CMakeLists.txt +45 -0
  25. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.cpp +68 -0
  26. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.h +44 -0
  27. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.java +45 -0
  28. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogueTestData.java +32 -0
  29. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesInstrumentationTest.java +150 -0
  30. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlAndroidTest.java +147 -0
  31. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlTest262.java +470 -0
  32. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesRuntimeFactory.cpp +73 -0
  33. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.cpp +90 -0
  34. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.h +62 -0
  35. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.java +155 -0
  36. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.cpp +48 -0
  37. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.h +36 -0
  38. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoad.cpp +13 -0
  39. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoadEpilogue.cpp +13 -0
  40. package/hermes/android/intltest/src/main/AndroidManifest.xml +2 -0
  41. package/hermes/android/ios-artifacts/build.gradle.kts +65 -0
  42. package/hermes/android/settings.gradle.kts +27 -0
  43. package/hermes/cmake/modules/Hermes.cmake +481 -0
  44. package/hermes/cmake/modules/Lit.cmake +96 -0
  45. package/hermes/doc/Branches.md +38 -0
  46. package/hermes/doc/BuildingAndRunning.md +121 -0
  47. package/hermes/doc/CodingStandards.md +112 -0
  48. package/hermes/doc/CrossCompilation.md +79 -0
  49. package/hermes/doc/Design.md +217 -0
  50. package/hermes/doc/Emscripten.md +156 -0
  51. package/hermes/doc/Features.md +143 -0
  52. package/hermes/doc/GCSafeCoding.md +563 -0
  53. package/hermes/doc/GenGC.md +300 -0
  54. package/hermes/doc/Hades.md +344 -0
  55. package/hermes/doc/HighLevelOptimizations.md +37 -0
  56. package/hermes/doc/IR.md +1306 -0
  57. package/hermes/doc/IntlAPIs.md +196 -0
  58. package/hermes/doc/JIT.md +999 -0
  59. package/hermes/doc/LazyEvalCompilation.md +84 -0
  60. package/hermes/doc/MemoryProfilers.md +316 -0
  61. package/hermes/doc/Modules.md +144 -0
  62. package/hermes/doc/Optimizer.md +83 -0
  63. package/hermes/doc/PerfProfiling.md +29 -0
  64. package/hermes/doc/ProhibitInvoke.md +329 -0
  65. package/hermes/doc/ReactNative.md +40 -0
  66. package/hermes/doc/ReactNativeIntegration.md +94 -0
  67. package/hermes/doc/RegExp.md +24 -0
  68. package/hermes/doc/SpecIncompat.md +85 -0
  69. package/hermes/doc/Strings.md +140 -0
  70. package/hermes/doc/TypedLanguage.md +432 -0
  71. package/hermes/doc/VM.md +174 -0
  72. package/hermes/doc/blog/2024-11-09-octane-benchmark-jit-progress.md +17 -0
  73. package/hermes/doc/blog/2024-12-19-static-hermes-update-dec-2024.md +47 -0
  74. package/hermes/doc/blog/2024-12-23-compiling-javascript-to-wasm.md +267 -0
  75. package/hermes/doc/blog/2025-06-09-jsi-runtime-data-apis.md +23 -0
  76. package/hermes/doc/blog/2025-07-15-static-h-performance-june-2025.md +18 -0
  77. package/hermes/doc/blog/2025-11-02-hermes-compilation-runtime-modes.md +23 -0
  78. package/hermes/doc/blog/2025-11-06-hermes-memory-modes.md +35 -0
  79. package/hermes/doc/blog/2025-11-24-json-parsing-performance.md +17 -0
  80. package/hermes/doc/blog/2025-12-02-iserialization.md +11 -0
  81. package/hermes/doc/blog/2025-12-12-new-way-to-contribute.md +68 -0
  82. package/hermes/doc/blog/2026-06-05-new-hermes-stable-release.md +51 -0
  83. package/hermes/doc/blog/README.md +25 -0
  84. package/hermes/doc/blog/images/2024-11-09-octane-pi3.jpeg +0 -0
  85. package/hermes/doc/blog/images/2024-11-09-octane-pi5.jpeg +0 -0
  86. package/hermes/doc/blog/images/2025-07-15-perf-hv32-interpreter.jpeg +0 -0
  87. package/hermes/doc/blog/images/2025-07-15-perf-hv32-jit.jpeg +0 -0
  88. package/hermes/doc/icu_license.txt +420 -0
  89. package/hermes/doc/img/heap_snapshot_retainers.png +0 -0
  90. package/hermes/doc/img/logo.svg +1 -0
  91. package/hermes/doc/img/object_captured_by_environment.png +0 -0
  92. package/hermes/doc/img/root_categories.png +0 -0
  93. package/hermes/doc/plans/ir-type/flow-type-system.md +324 -0
  94. package/hermes/doc/plans/ir-type/ir-type-system-v2-design.md +652 -0
  95. package/hermes/doc/plans/ir-type/ir-type-system.md +220 -0
  96. package/hermes/doc/plans/ir-type/ir-type-v2-implementation.md +1187 -0
  97. package/hermes/doc/plans/ir-type/memory.md +48 -0
  98. package/hermes/doc/plans/ir-type/phase1-steps.md +512 -0
  99. package/hermes/doc/plans/ir-type/progress.md +239 -0
  100. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-design.md +203 -0
  101. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-results.md +71 -0
  102. package/hermes/doc/superpowers/plans/2026-07-28-worker-arraybuffer-input.md +597 -0
  103. package/hermes/doc/superpowers/plans/2026-08-18-jitemitter-split.md +1149 -0
  104. package/hermes/doc/superpowers/plans/2026-08-20-jit-type-asserts.md +969 -0
  105. package/hermes/doc/superpowers/plans/2026-08-23-jit-shared-compiler-driver.md +478 -0
  106. package/hermes/doc/superpowers/plans/2026-08-23-x86-64-jit-skeleton.md +797 -0
  107. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-arith.md +444 -0
  108. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-calls.md +261 -0
  109. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-props.md +240 -0
  110. package/hermes/doc/superpowers/plans/2026-10-26-regexp-bytecode-sharing.md +2197 -0
  111. package/hermes/doc/superpowers/plans/2026-10-28-regexp-start-filter-and-exec-fast-paths.md +3981 -0
  112. package/hermes/doc/superpowers/specs/2026-07-28-worker-arraybuffer-input-design.md +206 -0
  113. package/hermes/doc/superpowers/specs/2026-08-18-jitemitter-split-design.md +530 -0
  114. package/hermes/doc/superpowers/specs/2026-08-20-jit-type-asserts-design.md +360 -0
  115. package/hermes/doc/superpowers/specs/2026-08-23-x86-64-jit-design.md +246 -0
  116. package/hermes/doc/superpowers/specs/2026-08-26-icu-free-normalize-design.md +355 -0
  117. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-convert-to-case-design.md +305 -0
  118. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-locale-compare-design.md +429 -0
  119. package/hermes/doc/superpowers/specs/2026-08-29-icu-free-date-format-design.md +297 -0
  120. package/hermes/doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md +605 -0
  121. package/hermes/doc/superpowers/specs/2026-10-28-regexp-start-filter-and-exec-fast-paths-design.md +551 -0
  122. package/hermes/doc/typescript-stripping.md +90 -0
  123. package/hermes/external/CMakeLists.txt +20 -0
  124. package/hermes/utils/IntlGen/IntlGen.java +531 -0
  125. package/hermes/utils/bench_with_stats.py +827 -0
  126. package/hermes/utils/build-apple-framework.sh +323 -0
  127. package/hermes/utils/chrome_snapshot_parser.py +210 -0
  128. package/hermes/utils/cmake-dev-build.sh +18 -0
  129. package/hermes/utils/commons.sh +55 -0
  130. package/hermes/utils/dump-cpp-funcs.sh +3 -0
  131. package/hermes/utils/es5objects.js +198 -0
  132. package/hermes/utils/format.sh +145 -0
  133. package/hermes/utils/gen-promise-internal-bc.sh +66 -0
  134. package/hermes/utils/genUnicodeTable.py +2503 -0
  135. package/hermes/utils/hermes-lit/CMakeLists.txt +22 -0
  136. package/hermes/utils/hermes-lit/hermes-lit.in +15 -0
  137. package/hermes/utils/jit/README.md +134 -0
  138. package/hermes/utils/jit/jit-diff.sh +160 -0
  139. package/hermes/utils/jit/jit-dump.sh +193 -0
  140. package/hermes/utils/lit-expect-gen/generate.py +217 -0
  141. package/hermes/utils/promise/index.js +15 -0
  142. package/hermes/utils/promise/package.json +13 -0
  143. package/hermes/utils/promise/rollup.config.js +19 -0
  144. package/hermes/utils/promise/yarn.lock +247 -0
  145. package/hermes/utils/scripts/hermes/consts.js +26 -0
  146. package/hermes/utils/scripts/hermes/create-tarball.js +75 -0
  147. package/hermes/utils/scripts/hermes/get-hermes-version.js +57 -0
  148. package/hermes/utils/scripts/hermes/hermes-utils.js +122 -0
  149. package/hermes/utils/scripts/hermes/package.json +6 -0
  150. package/hermes/utils/scripts/hermes/prepare-artifacts.js +113 -0
  151. package/hermes/utils/scripts/hermes/publish-artifacts.js +109 -0
  152. package/hermes/utils/scripts/hermes/publish-npm.js +96 -0
  153. package/hermes/utils/scripts/hermes/scm-utils.js +41 -0
  154. package/hermes/utils/scripts/hermes/set-artifacts-version.js +64 -0
  155. package/hermes/utils/scripts/hermes/version-utils.js +98 -0
  156. package/hermes/utils/scripts/hermes/yarn.lock +240 -0
  157. package/hermes/utils/summarize_sizes.py +184 -0
  158. package/hermes/utils/symbolicate-nativecall-stats.py +112 -0
  159. package/hermes/utils/test_runner.py +13 -0
  160. package/hermes/utils/testsuite/README.facebook +3 -0
  161. package/hermes/utils/testsuite/README.md +69 -0
  162. package/hermes/utils/testsuite/cli.py +547 -0
  163. package/hermes/utils/testsuite/es_ast.py +337 -0
  164. package/hermes/utils/testsuite/external/LICENSE +28 -0
  165. package/hermes/utils/testsuite/external/README.facebook +8 -0
  166. package/hermes/utils/testsuite/external/__init__.py +0 -0
  167. package/hermes/utils/testsuite/external/_monkeyYaml.py +164 -0
  168. package/hermes/utils/testsuite/external/parse_test262.py +141 -0
  169. package/hermes/utils/testsuite/hermes.py +522 -0
  170. package/hermes/utils/testsuite/preprocess.py +365 -0
  171. package/hermes/utils/testsuite/progress.py +377 -0
  172. package/hermes/utils/testsuite/skiplist.json +4356 -0
  173. package/hermes/utils/testsuite/skiplist.py +270 -0
  174. package/hermes/utils/testsuite/test_run_defs.py +435 -0
  175. package/hermes/utils/testsuite/typing_defs.py +52 -0
  176. package/hermes/utils/testsuite/utils.py +214 -0
  177. package/hermes/utils/tidy.sh +22 -0
  178. package/hermes/utils/update-fbcode-hermes.sh +53 -0
  179. package/hermes/utils/updateErrorTest.py +193 -0
  180. package/hermes/utils/wasm-compile.sh +65 -0
  181. package/package.json +1 -1
@@ -0,0 +1,2197 @@
1
+ # Shared RegExp Bytecode Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use
4
+ > superpowers:subagent-driven-development (recommended) or
5
+ > superpowers:executing-plans to implement this plan task-by-task. Steps
6
+ > use checkbox (`- [ ]`) syntax for tracking.
7
+
8
+ **Goal:** Materialize each regex literal's bytecode at most once per
9
+ `RuntimeModule` or `SHUnit` and share it among every `JSRegExp` created
10
+ from it. Make Static Hermes compile regex literals ahead of time.
11
+
12
+ **Architecture:** A new immutable, intrusively and atomically
13
+ refcounted `vm::RegExpBytecode` holds one regexp's bytecode in a single
14
+ malloc. It carries an ownership kind:
15
+ - `Exclusive`: held by exactly one `JSRegExp`, which reports its memory;
16
+ - `Cached`: held by a literal cache, which reports it.
17
+
18
+ Each `RuntimeModule` and each `SHUnitExt` keeps a lazily filled vector
19
+ of `Cached` entries indexed by literal ID. SH codegen emits the
20
+ literals' bytecode into the generated C, and `_sh_ljs_create_regexp`
21
+ reads it from the unit instead of parsing.
22
+
23
+ **Tech Stack:** C++17, C (SH-generated code), lit/FileCheck, GoogleTest,
24
+ ASan/TSan.
25
+
26
+ **Spec:** `doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md`
27
+ (Codex-reviewed over 3 rounds; binding). Read it in full before Task 1,
28
+ and read `DESIGN-PRINCIPLES.md` (repo root). Where this plan resolves an
29
+ ambiguity in the spec, it says so in the task ("Spec resolution"). The
30
+ last section lists them all.
31
+
32
+ ## Global Constraints
33
+
34
+ - **Repository.** The repository is the worktree
35
+ `/home/tmikov/work/hermes-regex-jit` (branch `regexp-bytecode-sharing`).
36
+ The shell's working directory is a DIFFERENT checkout
37
+ (`/home/tmikov/work/hermes`): every path, `git` and `cmake` command uses
38
+ `R=/home/tmikov/work/hermes-regex-jit` explicitly (`git -C $R ...`).
39
+ Never bare `cd`; use `( cd dir; cmd; )` if unavoidable.
40
+ - **Scope.**
41
+ - Regex *literals* only: `CreateRegExp` in HBC, `CreateRegExpInst` in
42
+ SH.
43
+ - Non-goals, from the spec:
44
+ - caching `new RegExp(str)` or `new RegExp(re)`;
45
+ - weak references or eviction;
46
+ - borrowing module storage;
47
+ - matcher costs;
48
+ - an SH heap-snapshot node (filed as a dz issue in Task 6).
49
+ - **Names** (spec-fixed):
50
+ - `vm::RegExpBytecode` in `include/hermes/VM/RegExpBytecode.h`, with
51
+ `enum class Ownership : uint8_t { Exclusive, Cached }`;
52
+ - `RuntimeModule::getRegExpBytecode(uint32_t)` and
53
+ `RuntimeModule::regExpCacheMemorySize()`;
54
+ - `JSRegExp::getBytecode()`;
55
+ - SH ABI: `SHRegExpTableEntry {offset, length}` and `SHUnit` fields
56
+ `regexp_storage`, `regexp_table`, `num_regexps`;
57
+ - `_sh_ljs_create_regexp(shr, unit, pattern, flags, regexp_id)`;
58
+ - generated C arrays `s_regexp_storage` and `s_regexp_table`.
59
+ - **GC-safe coding.** Every C++ change under `lib/VM/`,
60
+ `include/hermes/VM/` or `unittests/VMRuntime/` is written after
61
+ invoking the `gc-safe-coding` skill.
62
+ - Hermes throws by longjmp, so no `LocalsRAII` or `GCScope` may span a
63
+ call that can throw.
64
+ - Never compare raw pointers across a GC point. Compare bytecode
65
+ pointers only between objects that are both rooted.
66
+ - **Style.**
67
+ - 80 columns, 2-space indent.
68
+ - A doc comment on every declaration.
69
+ - Only trivial one-line methods inside a class body.
70
+ - New files start with the Meta copyright header (CLAUDE.md).
71
+ - **Build trees** (configured: clang, Debug, `-O1`):
72
+ - `$R/cmake-build-asan`: ASan, `HERMESVM_ALLOW_JIT=2`; the reference
73
+ tree;
74
+ - `$R/cmake-build-tsan`: TSan;
75
+ - `$R/cmake-build-hsan`: ASan, MallocGC, `HERMESVM_SANITIZE_HANDLES`;
76
+ - `$R/cmake-build-hv32`: ASan, `HERMESVM_HEAP_HV_MODE=HEAP_HV_PREFER32`.
77
+
78
+ Rebuild a tree before running its tests and after every mutation and
79
+ restore:
80
+
81
+ ```bash
82
+ cmake --build $R/cmake-build-<t> --target hermes hermesc shermes \
83
+ HermesVMRuntimeTests
84
+ ```
85
+ - **Tests.**
86
+ - Unit tests:
87
+ `$R/cmake-build-<t>/unittests/VMRuntime/HermesVMRuntimeTests
88
+ --gtest_filter='<pattern>'`.
89
+ - Full suite: `cmake --build $R/cmake-build-<t> --target check-hermes`.
90
+ Baseline on `cmake-build-asan` at the spec commit: 4473 expected
91
+ passes, 6 expected failures, 162 unsupported, 0 failures.
92
+ - Filtered lit: prefix with `LIT_FILTER='<regex>'`.
93
+ - **Prove-can-fail.** Show every new test FAILING with the code it pins
94
+ disabled, using the mutation named in the task. Then restore the code,
95
+ REBUILD the tree, and re-run the test green.
96
+ - A test labelled "regression guard" passes before the change. It is
97
+ still shown to fail under its named mutation.
98
+ - **Scratch files.** `S` below is your session scratchpad directory (the
99
+ harness gives its path). Put every temporary file there, never in the
100
+ repo.
101
+ - **Commits.**
102
+ - One commit per task. The subject is given in the task. Every message
103
+ ends with exactly:
104
+ ```
105
+ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
106
+ Claude-Session: https://claude.ai/code/session_019iPixSEVBGc2qFmM3Mq1Js
107
+ ```
108
+ - Stage by explicit path only: never `git add -A`, never
109
+ `git add dz/issues`.
110
+ - Never push.
111
+ - **Reporting.** Each task's report lists:
112
+ - the commit hash;
113
+ - the trees built;
114
+ - every suite run, with its pass/unsupported/fail counts;
115
+ - each mutation, with the failure it produced.
116
+
117
+ Task 6 copies these into the spec's "Delivered" section.
118
+ - **BASE.** The spec is commit `fb22f7c1f`, and this plan is committed on
119
+ top of it. BASE for the final code review is the plan commit; Task 1's
120
+ report records it (`git -C $R rev-parse HEAD` before Task 1).
121
+
122
+ ## Review Focus
123
+
124
+ These are inputs the spec implies but its test list does not name, with
125
+ the behavior a person would expect. Each has a test in the owning task.
126
+
127
+ 1. **Per-object state on shared bytecode.** Two live regexps from the
128
+ same literal keep independent `lastIndex`, `exec` progress and named
129
+ groups, and a regexp used as a `split` separator keeps its own
130
+ `lastIndex` and `sticky`. Tested on the interpreter, `-O0`, lazy and
131
+ the JIT by `test/hermes/regexp-literal-shared.js` and
132
+ `test/jit/regexp-literal-shared.js` (Task 2).
133
+ 2. **Literals in different modules with the same ID.** Two modules whose
134
+ only literals are `/one/` and `/two/` both use regexp ID 0. Each must
135
+ evaluate its own pattern (Task 2, `LiteralCachesArePerModule`).
136
+ 3. **A moving GC.** On the MallocGC `cmake-build-hsan` tree with
137
+ sanitize rate 1.0, every allocation moves the heap, and with it the
138
+ `JSRegExp` cell holding the refcounted pointer. Matches must still be
139
+ right, with no double-release and no ASan report. The default rate is
140
+ only 0.01 (`include/hermes/VM/RuntimeFlags.h:44-56`,
141
+ `unittests/VMRuntime/VMRuntimeTestHelpers.h:41`), so:
142
+ - `RegExpBytecodeTest` uses a fixture with rate 1.0;
143
+ - `regexp-literal-shared.js` has a `-gc-sanitize-handles=1` RUN line.
144
+ The option is accepted, and inert, in trees without handle
145
+ sanitization.
146
+
147
+ Both run on `cmake-build-hsan` in Task 2.
148
+ 4. **Compressed pointers (HV32).** The `JSRegExp` layout changes, which
149
+ affects the 8-byte alignment comment at `JSRegExp.h:145-148`. The full
150
+ suite must pass on `cmake-build-hv32` (Task 6).
151
+ 5. **A non-ASCII, `u`-flag literal in SH AOT.** Its pattern symbol is
152
+ UTF-16, and its bytecode was compiled from the compiler's UTF-8 form.
153
+ `source` and matching must agree with the interpreter (Task 4,
154
+ `test/shermes/regexp-aot.js`).
155
+
156
+ ---
157
+
158
+ ## File Structure
159
+
160
+ - `include/hermes/VM/RegExpBytecode.h`, `lib/VM/RegExpBytecode.cpp`
161
+ (new), `lib/VM/CMakeLists.txt`: the shared bytecode object.
162
+ - `include/hermes/VM/JSRegExp.h`, `lib/VM/JSRegExp.cpp`: hold an
163
+ `IntrusiveRefCntPtr`, the ownership-aware fast copy and memory
164
+ reporting.
165
+ - `lib/VM/Interpreter-slowpaths.cpp`: `Interpreter::createRegExp`.
166
+ - `include/hermes/VM/RuntimeModule.h`, `lib/VM/RuntimeModule.cpp`,
167
+ `lib/VM/Domain.cpp`: the module literal cache, its snapshot nodes and
168
+ its malloc size.
169
+ - `include/hermes/VM/static_h.h`, `lib/VM/StaticH.cpp`,
170
+ `lib/VM/SHUnitExt.h`, `lib/VM/StaticHUnit.cpp`: the SH ABI and the unit
171
+ cache.
172
+ - `lib/BCGen/SH/SH.cpp`: SH emission.
173
+ - Tests:
174
+ - `unittests/VMRuntime/RegExpBytecodeTest.cpp` (new),
175
+ `unittests/VMRuntime/CMakeLists.txt`,
176
+ `unittests/VMRuntime/HeapSnapshotTest.cpp`;
177
+ - `test/hermes/regexp-literal-shared.js`,
178
+ `test/jit/regexp-literal-shared.js`, `test/shermes/regexp-aot.js`
179
+ (new).
180
+ - The spec's "Delivered" section, and one dz issue.
181
+
182
+ ---
183
+
184
+ ### Task 1: `RegExpBytecode` and `JSRegExp` on top of it
185
+
186
+ A refactor with no sharing yet. Every `JSRegExp` gets an `Exclusive`
187
+ entry. The interpreter copies its literal's bytes into a fresh entry,
188
+ exactly as it copies them into a malloc today.
189
+
190
+ **Files:**
191
+ - Create: `include/hermes/VM/RegExpBytecode.h`, `lib/VM/RegExpBytecode.cpp`
192
+ - Modify: `lib/VM/CMakeLists.txt` (source list; `JSRegExp.cpp` is at
193
+ line 39)
194
+ - Modify: `include/hermes/VM/JSRegExp.h:11-18`, `:50-58`, `:133-156`
195
+ - Modify: `lib/VM/JSRegExp.cpp:101-166`, `:192-203`, `:264-275`,
196
+ `:324-392`, `:400-425`
197
+ - Modify: `lib/VM/Interpreter-slowpaths.cpp:618-619`
198
+ - Create: `unittests/VMRuntime/RegExpBytecodeTest.cpp`
199
+ - Modify: `unittests/VMRuntime/CMakeLists.txt:11-79`
200
+
201
+ **Interfaces:**
202
+ - **Produces:**
203
+ - `RegExpBytecode::create(llvh::ArrayRef<uint8_t>, Ownership)`,
204
+ returning `llvh::IntrusiveRefCntPtr<RegExpBytecode>`;
205
+ - `bytecode()`, `header()`, `ownership()` and `mallocSize()`;
206
+ - `JSRegExp::initialize(self, runtime, pattern, flags,
207
+ llvh::IntrusiveRefCntPtr<RegExpBytecode>)`, which replaces the
208
+ `ArrayRef` overload;
209
+ - `llvh::ArrayRef<uint8_t> JSRegExp::getBytecode() const`;
210
+ - `const RegExpBytecode *JSRegExp::getBytecodeEntry() const`.
211
+ - **Spec resolution:** the spec names only `getBytecode()`.
212
+ `getBytecodeEntry()` is added because the tests in Tasks 2-4 must read
213
+ the entry's ownership and `mallocSize()`.
214
+ - **Spec resolution:** an `Exclusive` `JSRegExp` now reports
215
+ `mallocSize()`, which includes the entry's header, instead of
216
+ `bytecodeSize_`. This is the entry's real malloc size.
217
+
218
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
219
+
220
+ - [ ] **Step 2: Write the tests**
221
+
222
+ Create `unittests/VMRuntime/RegExpBytecodeTest.cpp`:
223
+
224
+ ```cpp
225
+ /*
226
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
227
+ *
228
+ * This source code is licensed under the MIT license found in the
229
+ * LICENSE file in the root directory of this source tree.
230
+ */
231
+
232
+ #include "TestHelpers1.h"
233
+ #include "VMRuntimeTestHelpers.h"
234
+
235
+ #include "hermes/BCGen/HBC/HBC.h"
236
+ #include "hermes/Regex/RegexSerialization.h"
237
+ #include "hermes/VM/Callable.h"
238
+ #include "hermes/VM/JSArray.h"
239
+ #include "hermes/VM/JSRegExp.h"
240
+ #include "hermes/VM/RegExpBytecode.h"
241
+ #include "hermes/VM/StringPrimitive.h"
242
+
243
+ #include "gtest/gtest.h"
244
+
245
+ #include <cstddef>
246
+
247
+ using namespace hermes::vm;
248
+
249
+ namespace hermes {
250
+ namespace unittest {
251
+ namespace regexpbytecodetest {
252
+ namespace {
253
+
254
+ /// Runs every test with handle sanitization at every allocation. On a
255
+ /// HERMESVM_SANITIZE_HANDLES build with MallocGC, each allocation then
256
+ /// moves the heap (Hades instead collects the young generation); without
257
+ /// HERMESVM_SANITIZE_HANDLES the rate has no effect.
258
+ class RegExpBytecodeTest : public RuntimeTestFixtureBase {
259
+ public:
260
+ RegExpBytecodeTest()
261
+ : RuntimeTestFixtureBase(
262
+ RuntimeConfig::Builder()
263
+ .withGCConfig(
264
+ GCConfig::Builder(kTestGCConfigBuilder)
265
+ .withSanitizeConfig(vm::GCSanitizeConfig::Builder()
266
+ .withSanitizeRate(1.0)
267
+ .build())
268
+ .build())
269
+ .build()) {}
270
+ };
271
+
272
+ /// \return element \p index of \p arr, which must be a JSRegExp.
273
+ JSRegExp *regExpAt(Runtime &runtime, Handle<JSArray> arr, uint32_t index) {
274
+ return vmcast<JSRegExp>(arr->at(runtime, index).unboxToHV(runtime));
275
+ }
276
+
277
+ /// Run \p code in a new module and \return its completion value, which
278
+ /// must be an array.
279
+ Handle<JSArray> runForArray(Runtime &runtime, const char *code) {
280
+ CallResult<HermesValue> res =
281
+ runtime.run(code, "test.js", hbc::CompileFlags{});
282
+ EXPECT_NE(ExecutionStatus::EXCEPTION, res.getStatus());
283
+ return runtime.makeHandle(vmcast<JSArray>(*res));
284
+ }
285
+
286
+ TEST(RegExpBytecodeObjectTest, CreateCopiesBytes) {
287
+ auto compiled = CompiledRegExp::tryCompile("a(b)c", "gy");
288
+ ASSERT_TRUE(compiled.hasValue());
289
+ llvh::ArrayRef<uint8_t> src = compiled->getBytecode();
290
+
291
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> entry =
292
+ RegExpBytecode::create(src, RegExpBytecode::Ownership::Exclusive);
293
+ EXPECT_NE(src.data(), entry->bytecode().data());
294
+ EXPECT_TRUE(src.equals(entry->bytecode()));
295
+ EXPECT_TRUE(
296
+ regex::SyntaxFlags::fromByte(entry->header().syntaxFlags).sticky);
297
+ EXPECT_EQ(RegExpBytecode::Ownership::Exclusive, entry->ownership());
298
+ // The bytes follow the object, aligned like a malloc result.
299
+ EXPECT_EQ(
300
+ 0u,
301
+ reinterpret_cast<uintptr_t>(entry->bytecode().data()) %
302
+ alignof(std::max_align_t));
303
+ EXPECT_GE(entry->mallocSize(), sizeof(RegExpBytecode) + src.size());
304
+ EXPECT_LT(
305
+ entry->mallocSize(),
306
+ sizeof(RegExpBytecode) + alignof(std::max_align_t) + src.size());
307
+
308
+ // A second reference keeps the bytes alive after the first is dropped
309
+ // (ASan checks the read).
310
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> second = entry;
311
+ entry.reset();
312
+ EXPECT_TRUE(src.equals(second->bytecode()));
313
+ }
314
+
315
+ TEST_F(RegExpBytecodeTest, DynamicRegExpsAreExclusive) {
316
+ Handle<JSArray> arr = runForArray(
317
+ runtime, "[new RegExp('abc', 'g'), new RegExp('abc', 'g')]");
318
+ JSRegExp *r0 = regExpAt(runtime, arr, 0);
319
+ JSRegExp *r1 = regExpAt(runtime, arr, 1);
320
+ EXPECT_NE(r0->getBytecode().data(), r1->getBytecode().data());
321
+ EXPECT_TRUE(r0->getBytecode().equals(r1->getBytecode()));
322
+ EXPECT_EQ(
323
+ RegExpBytecode::Ownership::Exclusive,
324
+ r0->getBytecodeEntry()->ownership());
325
+ // The sole holder reports the entry.
326
+ EXPECT_EQ(
327
+ r0->getBytecodeEntry()->mallocSize(), r0->getVT()->getMallocSize(r0));
328
+ }
329
+
330
+ TEST_F(RegExpBytecodeTest, SplitDoesNotClearStickyOfItsArgument) {
331
+ // split() makes a sticky-cleared copy of its separator
332
+ // (lib/VM/JSLib/RegExp.cpp:2436-2439); the separator itself must stay
333
+ // sticky.
334
+ CallResult<HermesValue> res = runtime.run(
335
+ "var r = /a/y; 'bab'.split(r); r.lastIndex = 0;"
336
+ "r.exec('ba') === null && r.sticky",
337
+ "test.js",
338
+ hbc::CompileFlags{});
339
+ ASSERT_FALSE(isException(res));
340
+ EXPECT_TRUE(res->getBool());
341
+ }
342
+
343
+ } // namespace
344
+ } // namespace regexpbytecodetest
345
+ } // namespace unittest
346
+ } // namespace hermes
347
+ ```
348
+
349
+ In `unittests/VMRuntime/CMakeLists.txt`, add `RegExpBytecodeTest.cpp` to
350
+ `RTSources` on its own line, immediately before `RuntimeConfigTest.cpp`
351
+ (line 60).
352
+
353
+ - [ ] **Step 3: See it fail**
354
+
355
+ ```bash
356
+ cmake --build $R/cmake-build-asan --target HermesVMRuntimeTests
357
+ ```
358
+
359
+ Expected: a compile error, `hermes/VM/RegExpBytecode.h` not found.
360
+
361
+ - [ ] **Step 4: Write `RegExpBytecode`**
362
+
363
+ `include/hermes/VM/RegExpBytecode.h`:
364
+
365
+ ```cpp
366
+ /*
367
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
368
+ *
369
+ * This source code is licensed under the MIT license found in the
370
+ * LICENSE file in the root directory of this source tree.
371
+ */
372
+
373
+ #ifndef HERMES_VM_REGEXPBYTECODE_H
374
+ #define HERMES_VM_REGEXPBYTECODE_H
375
+
376
+ #include "hermes/Regex/RegexBytecode.h"
377
+
378
+ #include "llvh/ADT/ArrayRef.h"
379
+ #include "llvh/ADT/IntrusiveRefCntPtr.h"
380
+
381
+ #include <cstddef>
382
+ #include <cstdint>
383
+ #include <cstdlib>
384
+
385
+ namespace hermes {
386
+ namespace vm {
387
+
388
+ /// The bytecode of one compiled regexp. It is immutable after create() and
389
+ /// shared through llvh::IntrusiveRefCntPtr. The count is atomic because the
390
+ /// last reference may be dropped by a JSRegExp finalizer on the Hades
391
+ /// background thread. The object and its bytes are one malloc.
392
+ class RegExpBytecode final
393
+ : public llvh::ThreadSafeRefCountedBase<RegExpBytecode> {
394
+ public:
395
+ /// Who is responsible for reporting this object's memory.
396
+ enum class Ownership : uint8_t {
397
+ /// Owned by exactly one JSRegExp; that JSRegExp reports it.
398
+ Exclusive,
399
+ /// Held by a literal cache (RuntimeModule or SHUnitExt) and shared by
400
+ /// any number of JSRegExps; the cache reports it.
401
+ Cached,
402
+ };
403
+
404
+ /// \return a new object holding a copy of \p bytecode, which must start
405
+ /// with a regex::RegexBytecodeHeader.
406
+ static llvh::IntrusiveRefCntPtr<RegExpBytecode> create(
407
+ llvh::ArrayRef<uint8_t> bytecode,
408
+ Ownership ownership);
409
+
410
+ /// \return the bytecode.
411
+ llvh::ArrayRef<uint8_t> bytecode() const {
412
+ return {bytes(), size_};
413
+ }
414
+
415
+ /// \return the header at the start of the bytecode.
416
+ const regex::RegexBytecodeHeader &header() const {
417
+ return *reinterpret_cast<const regex::RegexBytecodeHeader *>(bytes());
418
+ }
419
+
420
+ /// \return who reports this object's memory.
421
+ Ownership ownership() const {
422
+ return ownership_;
423
+ }
424
+
425
+ /// \return the bytes of malloc'd memory, including this header.
426
+ size_t mallocSize() const;
427
+
428
+ /// Free the single allocation made by create(); called through the
429
+ /// delete in ThreadSafeRefCountedBase::Release().
430
+ static void operator delete(void *p) {
431
+ free(p);
432
+ }
433
+
434
+ private:
435
+ /// Construct the header; create() copies the bytes after it.
436
+ RegExpBytecode(uint32_t size, Ownership ownership)
437
+ : size_(size), ownership_(ownership) {}
438
+
439
+ /// \return the offset of the bytes from the start of the allocation:
440
+ /// the object size rounded up to malloc alignment.
441
+ static constexpr size_t bytesOffset();
442
+
443
+ /// \return the start of the bytes.
444
+ inline const uint8_t *bytes() const;
445
+
446
+ /// \return the start of the bytes.
447
+ inline uint8_t *bytes();
448
+
449
+ /// Number of bytes of bytecode.
450
+ uint32_t size_;
451
+
452
+ /// Who reports this object's memory.
453
+ Ownership ownership_;
454
+ };
455
+
456
+ constexpr size_t RegExpBytecode::bytesOffset() {
457
+ return (sizeof(RegExpBytecode) + alignof(std::max_align_t) - 1) /
458
+ alignof(std::max_align_t) * alignof(std::max_align_t);
459
+ }
460
+
461
+ inline const uint8_t *RegExpBytecode::bytes() const {
462
+ return reinterpret_cast<const uint8_t *>(this) + bytesOffset();
463
+ }
464
+
465
+ inline uint8_t *RegExpBytecode::bytes() {
466
+ return reinterpret_cast<uint8_t *>(this) + bytesOffset();
467
+ }
468
+
469
+ } // namespace vm
470
+ } // namespace hermes
471
+
472
+ #endif // HERMES_VM_REGEXPBYTECODE_H
473
+ ```
474
+
475
+ `lib/VM/RegExpBytecode.cpp`:
476
+
477
+ ```cpp
478
+ /*
479
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
480
+ *
481
+ * This source code is licensed under the MIT license found in the
482
+ * LICENSE file in the root directory of this source tree.
483
+ */
484
+
485
+ #include "hermes/VM/RegExpBytecode.h"
486
+
487
+ #include "hermes/Support/CheckedMalloc.h"
488
+
489
+ #include <cassert>
490
+ #include <cstring>
491
+ #include <limits>
492
+ #include <new>
493
+
494
+ namespace hermes {
495
+ namespace vm {
496
+
497
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> RegExpBytecode::create(
498
+ llvh::ArrayRef<uint8_t> bytecode,
499
+ Ownership ownership) {
500
+ assert(
501
+ bytecode.size() >= sizeof(regex::RegexBytecodeHeader) &&
502
+ "regexp bytecode must start with a header");
503
+ assert(
504
+ bytecode.size() <= std::numeric_limits<uint32_t>::max() &&
505
+ "Bytecode size cannot exceed 32 bits");
506
+ void *mem = checkedMalloc(bytesOffset() + bytecode.size());
507
+ auto *self = new (mem) RegExpBytecode((uint32_t)bytecode.size(), ownership);
508
+ memcpy(self->bytes(), bytecode.data(), bytecode.size());
509
+ return llvh::IntrusiveRefCntPtr<RegExpBytecode>(self);
510
+ }
511
+
512
+ size_t RegExpBytecode::mallocSize() const {
513
+ return bytesOffset() + size_;
514
+ }
515
+
516
+ } // namespace vm
517
+ } // namespace hermes
518
+ ```
519
+
520
+ Add `RegExpBytecode.cpp` to the source list in `lib/VM/CMakeLists.txt`,
521
+ next to `JSRegExp.cpp`, keeping the list's order style. Check
522
+ `grep -n checkedMalloc $R/include/hermes/Support/CheckedMalloc.h` for
523
+ the function's namespace. If it is not reachable unqualified inside
524
+ `hermes::vm`, qualify it as `hermes::checkedMalloc`, the way
525
+ `JSRegExp.cpp:273` reaches it.
526
+
527
+ - [ ] **Step 5: Convert `JSRegExp`**
528
+
529
+ `include/hermes/VM/JSRegExp.h`:
530
+ - Add `#include "hermes/VM/RegExpBytecode.h"` after the
531
+ `hermes/VM/JSObject.h` include (line 13).
532
+ - Replace the `ArrayRef` `initialize` (lines 50-58) with:
533
+
534
+ ```cpp
535
+ /// Initializes RegExp with existing bytecode. Populates fields for the
536
+ /// pattern and flags, but performs no validation on them. It is assumed that
537
+ /// the bytecode is correct and corresponds to the given pattern/flags.
538
+ /// \p bytecode is shared, not copied. The regexp must not have been
539
+ /// initialized before.
540
+ static void initialize(
541
+ Handle<JSRegExp> selfHandle,
542
+ Runtime &runtime,
543
+ Handle<StringPrimitive> pattern,
544
+ Handle<StringPrimitive> flags,
545
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> bytecode);
546
+ ```
547
+
548
+ - After `setSyntaxFlags` (line 101), add:
549
+
550
+ ```cpp
551
+ /// \return the bytecode. The regexp must have been initialized.
552
+ llvh::ArrayRef<uint8_t> getBytecode() const {
553
+ return bytecode_->bytecode();
554
+ }
555
+
556
+ /// \return the object holding the bytecode, or null before
557
+ /// initialization.
558
+ const RegExpBytecode *getBytecodeEntry() const {
559
+ return bytecode_.get();
560
+ }
561
+ ```
562
+
563
+ - Replace `initializeBytecode` (lines 136-137) with:
564
+
565
+ ```cpp
566
+ /// Take the reference \p bytecode and set syntaxFlags_ from its header.
567
+ void setBytecode(llvh::IntrusiveRefCntPtr<RegExpBytecode> bytecode);
568
+
569
+ /// \return the bytecode object if this regexp owns it exclusively and so
570
+ /// reports its memory, otherwise null.
571
+ const RegExpBytecode *exclusiveBytecode() const;
572
+ ```
573
+
574
+ - Replace lines 151-152 (`bytecode_`, `bytecodeSize_`) with the
575
+ following. Keep the comment at lines 145-148, which still applies: the
576
+ pointer is 8 bytes.
577
+
578
+ ```cpp
579
+ /// The bytecode, owned exclusively or shared with a literal cache. One
580
+ /// pointer, so the GC may relocate the cell by copying it.
581
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> bytecode_{};
582
+ ```
583
+
584
+ `lib/VM/JSRegExp.cpp`:
585
+ - In the bytecode `initialize` (lines 101-128), change the parameter to
586
+ `llvh::IntrusiveRefCntPtr<RegExpBytecode> bytecode`. Change the last
587
+ line to `selfHandle->setBytecode(std::move(bytecode));`.
588
+ - Fast copy (lines 150-163). Replace the `initialize(...)` call at
589
+ 152-158 with:
590
+
591
+ ```cpp
592
+ // A Cached entry is shared. An Exclusive entry has exactly one holder,
593
+ // which reports its memory, so it is copied.
594
+ const RegExpBytecode *other = otherHandle->bytecode_.get();
595
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> bytecode =
596
+ other->ownership() == RegExpBytecode::Ownership::Cached
597
+ ? otherHandle->bytecode_
598
+ : RegExpBytecode::create(
599
+ other->bytecode(), RegExpBytecode::Ownership::Exclusive);
600
+ initialize(selfHandle, runtime, lv.pattern, flags, std::move(bytecode));
601
+ ```
602
+
603
+ The entry pointer is read before `initialize`, which may allocate, and
604
+ is not used after it. In this task every entry is `Exclusive`, so the
605
+ shared branch is dead until Task 2.
606
+ - Dynamic path (line 202): replace the call with
607
+
608
+ ```cpp
609
+ initialize(
610
+ selfHandle,
611
+ runtime,
612
+ pattern,
613
+ flags,
614
+ RegExpBytecode::create(bytecode, RegExpBytecode::Ownership::Exclusive));
615
+ ```
616
+
617
+ - Replace `initializeBytecode` (lines 264-275) with:
618
+
619
+ ```cpp
620
+ void JSRegExp::setBytecode(llvh::IntrusiveRefCntPtr<RegExpBytecode> bytecode) {
621
+ assert(!bytecode_ && "a JSRegExp's bytecode is set only once");
622
+ syntaxFlags_ = regex::SyntaxFlags::fromByte(bytecode->header().syntaxFlags);
623
+ bytecode_ = std::move(bytecode);
624
+ }
625
+
626
+ const RegExpBytecode *JSRegExp::exclusiveBytecode() const {
627
+ const RegExpBytecode *bytecode = bytecode_.get();
628
+ return bytecode &&
629
+ bytecode->ownership() == RegExpBytecode::Ownership::Exclusive
630
+ ? bytecode
631
+ : nullptr;
632
+ }
633
+ ```
634
+
635
+ - `search`:
636
+ - Line 329: keep the assert (`selfHandle->bytecode_` converts to bool).
637
+ - Lines 351 and 359: `llvh::makeArrayRef(selfHandle->bytecode_,
638
+ selfHandle->bytecodeSize_)` becomes `selfHandle->getBytecode()`. The
639
+ entry is kept alive by the rooted `selfHandle` for the whole search.
640
+ - `~JSRegExp` (377-379) becomes `JSRegExp::~JSRegExp() = default;`.
641
+ Releasing the pointer drops the reference.
642
+ - `_finalizeImpl` (381-387):
643
+
644
+ ```cpp
645
+ void JSRegExp::_finalizeImpl(GCCell *cell, GC &gc) {
646
+ JSRegExp *self = vmcast<JSRegExp>(cell);
647
+ // A Cached entry's native ID belongs to its cache.
648
+ if (const RegExpBytecode *bytecode = self->exclusiveBytecode())
649
+ gc.getIDTracker().untrackNative(bytecode);
650
+ self->~JSRegExp();
651
+ }
652
+ ```
653
+
654
+ - `_mallocSizeImpl` (389-392):
655
+
656
+ ```cpp
657
+ size_t JSRegExp::_mallocSizeImpl(GCCell *cell) {
658
+ // A Cached entry is reported by its cache.
659
+ const RegExpBytecode *bytecode = vmcast<JSRegExp>(cell)->exclusiveBytecode();
660
+ return bytecode ? bytecode->mallocSize() : 0;
661
+ }
662
+ ```
663
+
664
+ - `_snapshotAddEdgesImpl` (404-409) and `_snapshotAddNodesImpl`
665
+ (414-424). Guard on `const RegExpBytecode *bytecode =
666
+ self->exclusiveBytecode()` instead of `self->bytecode_`. Use
667
+ `gc.getNativeID(bytecode)` and size `bytecode->mallocSize()` in place
668
+ of `self->bytecode_` / `self->bytecodeSize_`.
669
+
670
+ `lib/VM/Interpreter-slowpaths.cpp` lines 618-619 become:
671
+
672
+ ```cpp
673
+ JSRegExp::initialize(
674
+ lv.re,
675
+ runtime,
676
+ lv.pattern,
677
+ lv.flags,
678
+ RegExpBytecode::create(
679
+ runtimeModule->getRegExpBytecodeFromRegExpID(regexpID),
680
+ RegExpBytecode::Ownership::Exclusive));
681
+ ```
682
+
683
+ Finally, grep the whole tree, excluding `cmake-build-*` and
684
+ `API/hermes_sandbox`, for `bytecodeSize_`, `initializeBytecode` and the
685
+ old `initialize` overload taking an `ArrayRef`. Callers per the spec:
686
+ - `Interpreter-slowpaths.cpp:613-619`;
687
+ - `StaticH.cpp:1795-1801`;
688
+ - `JSLib/RegExp.cpp:484` and `:667-669`;
689
+ - `JSRegExp.cpp`.
690
+
691
+ Every hit must be converted.
692
+
693
+ - [ ] **Step 6: Build and run**
694
+
695
+ ```bash
696
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes \
697
+ HermesVMRuntimeTests
698
+ $R/cmake-build-asan/unittests/VMRuntime/HermesVMRuntimeTests \
699
+ --gtest_filter='RegExpBytecode*'
700
+ ```
701
+
702
+ Expected: 4 tests pass.
703
+
704
+ - [ ] **Step 7: Prove each test can fail** (rebuild after each mutation
705
+ and after each restore)
706
+ - `CreateCopiesBytes`: make `mallocSize()` return `size_`. The
707
+ `EXPECT_GE` fails.
708
+ - `DynamicRegExpsAreExclusive` (regression guard for T3): create the
709
+ dynamic path's entry with `Ownership::Cached`. The ownership and
710
+ malloc-size expectations fail.
711
+ - `SplitDoesNotClearStickyOfItsArgument` (regression guard for T5):
712
+ 1. In `search`, read sticky from
713
+ `regex::SyntaxFlags::fromByte(selfHandle->bytecode_->header()
714
+ .syntaxFlags)`.
715
+ 2. In `setSyntaxFlags`, also write `flags.toByte()` into the header
716
+ through a `const_cast` (shared-state leakage).
717
+ 3. Turn the fast copy's condition into `true` for every entry, so the
718
+ splitter shares.
719
+
720
+ The test FAILS (`false`). This combination is what the test exists
721
+ to catch.
722
+
723
+ - [ ] **Step 8: Full suite**
724
+
725
+ ```bash
726
+ cmake --build $R/cmake-build-asan --target check-hermes
727
+ ```
728
+
729
+ Expected: the baseline numbers, 0 failures.
730
+
731
+ - [ ] **Step 9: Commit**
732
+
733
+ ```bash
734
+ git -C $R add include/hermes/VM/RegExpBytecode.h lib/VM/RegExpBytecode.cpp \
735
+ lib/VM/CMakeLists.txt include/hermes/VM/JSRegExp.h lib/VM/JSRegExp.cpp \
736
+ lib/VM/Interpreter-slowpaths.cpp unittests/VMRuntime/RegExpBytecodeTest.cpp \
737
+ unittests/VMRuntime/CMakeLists.txt
738
+ git -C $R commit # "VM: hold JSRegExp bytecode in a refcounted RegExpBytecode"
739
+ ```
740
+
741
+ ---
742
+
743
+ ### Task 2: Per-module literal cache and fast-copy sharing
744
+
745
+ **Files:**
746
+ - Modify: `include/hermes/VM/RuntimeModule.h:278-280` and the private
747
+ members (`:104-182`)
748
+ - Modify: `lib/VM/RuntimeModule.cpp:290-296`
749
+ - Modify: `lib/VM/Interpreter-slowpaths.cpp` (the Task 1 call)
750
+ - Modify: `unittests/VMRuntime/RegExpBytecodeTest.cpp`
751
+ - Create: `test/hermes/regexp-literal-shared.js`,
752
+ `test/jit/regexp-literal-shared.js`
753
+
754
+ **Interfaces:**
755
+ - **Consumes:** Task 1's `RegExpBytecode` and `JSRegExp` API.
756
+ - **Produces:**
757
+ `llvh::IntrusiveRefCntPtr<RegExpBytecode>
758
+ RuntimeModule::getRegExpBytecode(uint32_t regExpID)`, and the private
759
+ member
760
+ `std::vector<llvh::IntrusiveRefCntPtr<RegExpBytecode>> regExpCache_`.
761
+ Task 3 reads that member.
762
+
763
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
764
+
765
+ - [ ] **Step 2: Write the tests**
766
+
767
+ Add these includes to `RegExpBytecodeTest.cpp`: `hermes/BCGen/HBC/BCProvider.h`,
768
+ `hermes/Support/MemoryBuffer.h`, `hermes/VM/RuntimeModule.h`,
769
+ `llvh/Support/MemoryBuffer.h` and `<memory>`. In the anonymous namespace,
770
+ after `runForArray`, add:
771
+
772
+ ```cpp
773
+ /// Run \p code in a new module, compiled with \p flags, and \return its
774
+ /// completion value, which must be a function.
775
+ Handle<JSFunction> runForFunction(
776
+ Runtime &runtime,
777
+ const char *code,
778
+ const hbc::CompileFlags &flags = hbc::CompileFlags{}) {
779
+ CallResult<HermesValue> res = runtime.run(code, "test.js", flags);
780
+ EXPECT_NE(ExecutionStatus::EXCEPTION, res.getStatus());
781
+ return runtime.makeHandle(vmcast<JSFunction>(*res));
782
+ }
783
+
784
+ /// Call \p fn with no arguments and \return its result, which must be a
785
+ /// JSRegExp.
786
+ Handle<JSRegExp> callForRegExp(Runtime &runtime, Handle<JSFunction> fn) {
787
+ CallResult<PseudoHandle<>> res =
788
+ Callable::executeCall0(fn, runtime, Runtime::getUndefinedValue());
789
+ EXPECT_NE(ExecutionStatus::EXCEPTION, res.getStatus());
790
+ return runtime.makeHandle(vmcast<JSRegExp>(res->get()));
791
+ }
792
+
793
+ /// \return whether \p re matches the ASCII string \p str, searching from 0.
794
+ bool matches(Runtime &runtime, Handle<JSRegExp> re, const char *str) {
795
+ CallResult<RegExpMatch> m = JSRegExp::search(
796
+ re, runtime, StringPrimitive::createNoThrow(runtime, str), 0);
797
+ EXPECT_NE(ExecutionStatus::EXCEPTION, m.getStatus());
798
+ return !m->empty();
799
+ }
800
+ ```
801
+
802
+ Then add the tests:
803
+
804
+ ```cpp
805
+ TEST_F(RegExpBytecodeTest, LiteralIsSharedAcrossEvaluations) {
806
+ Handle<JSArray> arr = runForArray(
807
+ runtime,
808
+ "(function () { function f() { return /a(b)c/g; }"
809
+ " return [f(), f()]; })()");
810
+ JSRegExp *r0 = regExpAt(runtime, arr, 0);
811
+ JSRegExp *r1 = regExpAt(runtime, arr, 1);
812
+ EXPECT_NE(r0, r1);
813
+ EXPECT_EQ(r0->getBytecode().data(), r1->getBytecode().data());
814
+ EXPECT_EQ(
815
+ RegExpBytecode::Ownership::Cached, r0->getBytecodeEntry()->ownership());
816
+ // The cache, not the JSRegExp, reports a Cached entry.
817
+ EXPECT_EQ(0u, r0->getVT()->getMallocSize(r0));
818
+ }
819
+
820
+ TEST_F(RegExpBytecodeTest, LiteralCachesArePerModule) {
821
+ // Each module's only literal has regexp ID 0.
822
+ Handle<JSFunction> one =
823
+ runForFunction(runtime, "(function () { return /one/; })");
824
+ Handle<JSFunction> two =
825
+ runForFunction(runtime, "(function () { return /two/; })");
826
+ Handle<JSRegExp> r1 = callForRegExp(runtime, one);
827
+ Handle<JSRegExp> r2 = callForRegExp(runtime, two);
828
+ EXPECT_NE(r1->getBytecode().data(), r2->getBytecode().data());
829
+ EXPECT_TRUE(matches(runtime, r1, "one"));
830
+ EXPECT_FALSE(matches(runtime, r1, "two"));
831
+ EXPECT_TRUE(matches(runtime, r2, "two"));
832
+ EXPECT_FALSE(matches(runtime, r2, "one"));
833
+ }
834
+
835
+ TEST_F(RegExpBytecodeTest, LazilyCompiledLiteralGrowsTheCache) {
836
+ hbc::CompileFlags flags;
837
+ flags.lazy = true;
838
+ flags.preemptiveFileCompilationThreshold = 0;
839
+ flags.preemptiveFunctionCompilationThreshold = 0;
840
+ Handle<JSFunction> f = runForFunction(
841
+ runtime,
842
+ "(function () { return function () { return /lazy(re)/g; }; })()",
843
+ flags);
844
+ RuntimeModule *rm = f->getRuntimeModule();
845
+ // Precondition: the literal is not in the table until its function is
846
+ // compiled, so its ID is past the table size at module load.
847
+ ASSERT_EQ(0u, rm->getBytecode()->getRegExpTable().size());
848
+ Handle<JSRegExp> r0 = callForRegExp(runtime, f);
849
+ ASSERT_EQ(1u, rm->getBytecode()->getRegExpTable().size());
850
+ Handle<JSRegExp> r1 = callForRegExp(runtime, f);
851
+ EXPECT_EQ(r0->getBytecode().data(), r1->getBytecode().data());
852
+ EXPECT_TRUE(matches(runtime, r1, "xlazyre"));
853
+ }
854
+
855
+ TEST_F(RegExpBytecodeTest, FastCopySharesOnlyCachedBytecode) {
856
+ Handle<JSArray> arr =
857
+ runForArray(runtime, "[/a(b)c/g, new RegExp('a(b)c', 'g')]");
858
+ Handle<JSRegExp> lit = runtime.makeHandle(regExpAt(runtime, arr, 0));
859
+ Handle<JSRegExp> dyn = runtime.makeHandle(regExpAt(runtime, arr, 1));
860
+ ASSERT_EQ(
861
+ RegExpBytecode::Ownership::Cached, lit->getBytecodeEntry()->ownership());
862
+ ASSERT_EQ(
863
+ RegExpBytecode::Ownership::Exclusive,
864
+ dyn->getBytecodeEntry()->ownership());
865
+
866
+ // The fast copy used by matchAll and split.
867
+ auto copy = [&](Handle<JSRegExp> other, const char *flags) {
868
+ Handle<JSRegExp> self = runtime.makeHandle(JSRegExp::create(runtime));
869
+ EXPECT_EQ(
870
+ ExecutionStatus::RETURNED,
871
+ JSRegExp::initialize(
872
+ self,
873
+ runtime,
874
+ other,
875
+ StringPrimitive::createNoThrow(runtime, flags)));
876
+ return self;
877
+ };
878
+
879
+ Handle<JSRegExp> litSame = copy(lit, "g");
880
+ EXPECT_EQ(lit->getBytecode().data(), litSame->getBytecode().data());
881
+
882
+ Handle<JSRegExp> litOther = copy(lit, "gy");
883
+ EXPECT_NE(lit->getBytecode().data(), litOther->getBytecode().data());
884
+ EXPECT_EQ(
885
+ RegExpBytecode::Ownership::Exclusive,
886
+ litOther->getBytecodeEntry()->ownership());
887
+ EXPECT_TRUE(JSRegExp::getSyntaxFlags(*litOther).sticky);
888
+
889
+ Handle<JSRegExp> dynSame = copy(dyn, "g");
890
+ EXPECT_NE(dyn->getBytecode().data(), dynSame->getBytecode().data());
891
+ EXPECT_TRUE(dyn->getBytecode().equals(dynSame->getBytecode()));
892
+ EXPECT_EQ(
893
+ RegExpBytecode::Ownership::Exclusive,
894
+ dynSame->getBytecodeEntry()->ownership());
895
+ }
896
+
897
+ TEST_F(RegExpBytecodeTest, LiteralOutlivesItsModule) {
898
+ // runtime.run() would load the module as persistent, and the runtime
899
+ // would keep its storage. Instead, run from an owning buffer, held only
900
+ // by the provider, with persistent = false.
901
+ std::weak_ptr<hbc::BCProvider> weakProvider;
902
+ Handle<JSRegExp> re;
903
+ {
904
+ std::vector<uint8_t> bc =
905
+ bytecodeForSource("(function () { return /a(b)c/g; })()");
906
+ auto buffer = std::make_unique<OwnedMemoryBuffer>(
907
+ llvh::MemoryBuffer::getMemBufferCopy(
908
+ llvh::StringRef((const char *)bc.data(), bc.size())));
909
+ std::shared_ptr<hbc::BCProvider> provider =
910
+ hbc::BCProviderFromBuffer::createBCProviderFromBuffer(std::move(buffer))
911
+ .first;
912
+ ASSERT_TRUE(provider);
913
+ weakProvider = provider;
914
+ RuntimeModuleFlags rmFlags;
915
+ rmFlags.persistent = false;
916
+ CallResult<HermesValue> res = runtime.runBytecode(
917
+ std::move(provider),
918
+ rmFlags,
919
+ "test.js",
920
+ Runtime::makeNullHandle<Environment>());
921
+ ASSERT_FALSE(isException(res));
922
+ re = runtime.makeHandle(vmcast<JSRegExp>(*res));
923
+ }
924
+ for (int i = 0; i < 3 && !weakProvider.expired(); ++i)
925
+ runtime.collect("test");
926
+ // Precondition: the module and its storage are gone.
927
+ ASSERT_TRUE(weakProvider.expired());
928
+ EXPECT_TRUE(matches(runtime, re, "xabcx"));
929
+ }
930
+ ```
931
+
932
+ `re` is assigned inside the block. If `Handle<JSRegExp> re;` does not
933
+ compile (no default constructor), declare
934
+ `MutableHandle<JSRegExp> re{runtime};` and assign with `re = ...`. Pass
935
+ it to `matches` as `re` (it converts to `Handle<JSRegExp>`).
936
+
937
+ Create `test/hermes/regexp-literal-shared.js`:
938
+
939
+ ```js
940
+ /**
941
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
942
+ *
943
+ * This source code is licensed under the MIT license found in the
944
+ * LICENSE file in the root directory of this source tree.
945
+ */
946
+
947
+ // RUN: %hermes -O %s | %FileCheck --match-full-lines %s
948
+ // RUN: %hermes -O0 %s | %FileCheck --match-full-lines %s
949
+ // RUN: %hermes -lazy %s | %FileCheck --match-full-lines %s
950
+ // RUN: %hermes -gc-sanitize-handles=1 %s | %FileCheck --match-full-lines %s
951
+
952
+ // Regexps from one literal share bytecode but nothing else: lastIndex,
953
+ // match progress and named groups stay per object.
954
+
955
+ function main() {
956
+ function mk() { return /a(?<n>\d)/g; }
957
+ var a = mk(), b = mk();
958
+ print(a === b);
959
+ // CHECK: false
960
+ print(a.exec("a1a2")[0], a.lastIndex, b.lastIndex);
961
+ // CHECK-NEXT: a1 2 0
962
+ print(b.exec("xa3")[0], b.lastIndex, a.lastIndex);
963
+ // CHECK-NEXT: a3 3 2
964
+ print(a.exec("a1a2").groups.n, a.lastIndex);
965
+ // CHECK-NEXT: 2 4
966
+ print(mk().test("a5"), mk().lastIndex);
967
+ // CHECK-NEXT: true 0
968
+ var s = /b/y;
969
+ print("abc".split(s).length, s.sticky, s.lastIndex);
970
+ // CHECK-NEXT: 2 true 0
971
+ // split() cleared sticky on its private copy only.
972
+ print(s.exec("ab") === null);
973
+ // CHECK-NEXT: true
974
+ }
975
+ main();
976
+ ```
977
+
978
+ Create `test/jit/regexp-literal-shared.js`:
979
+
980
+ ```js
981
+ /**
982
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
983
+ *
984
+ * This source code is licensed under the MIT license found in the
985
+ * LICENSE file in the root directory of this source tree.
986
+ */
987
+
988
+ // RUN: %hermes -Xjit=force -Xjit-crash-on-error %S/../hermes/regexp-literal-shared.js | %FileCheck --match-full-lines %S/../hermes/regexp-literal-shared.js
989
+ // REQUIRES: jit
990
+
991
+ // The JIT reaches the same Interpreter::createRegExp; run the shared
992
+ // literal test through it.
993
+ ```
994
+
995
+ If `-lazy` is not a `hermes` option (`$R/cmake-build-asan/bin/hermes
996
+ --help | grep -i lazy`), use the option the help text names for lazy
997
+ compilation, and say so in the report.
998
+
999
+ - [ ] **Step 3: See them fail**
1000
+
1001
+ Build and run `--gtest_filter='RegExpBytecode*'` on `cmake-build-asan`.
1002
+
1003
+ Expected:
1004
+ - `LiteralIsSharedAcrossEvaluations`, `LazilyCompiledLiteralGrowsTheCache`
1005
+ and `FastCopySharesOnlyCachedBytecode` FAIL: there are distinct
1006
+ copies, and the ownership is `Exclusive`.
1007
+ - `LiteralCachesArePerModule` and `LiteralOutlivesItsModule` pass. They
1008
+ are regression guards.
1009
+ - The two lit tests pass, also guards:
1010
+
1011
+ ```bash
1012
+ LIT_FILTER='regexp-literal-shared' cmake --build $R/cmake-build-asan \
1013
+ --target check-hermes
1014
+ ```
1015
+
1016
+ - [ ] **Step 4: Implement the cache**
1017
+
1018
+ `include/hermes/VM/RuntimeModule.h`:
1019
+ - Add `#include "hermes/VM/RegExpBytecode.h"` with the other VM
1020
+ includes.
1021
+ - After `moduleExports_` (line 181), add:
1022
+
1023
+ ```cpp
1024
+ /// The shared bytecode of each regexp literal, indexed by regexp ID and
1025
+ /// created on first use. Grows with the regexp table under lazy
1026
+ /// compilation. Mutator thread only.
1027
+ std::vector<llvh::IntrusiveRefCntPtr<RegExpBytecode>> regExpCache_{};
1028
+ ```
1029
+
1030
+ - After `getRegExpBytecodeFromRegExpID` (line 280), add:
1031
+
1032
+ ```cpp
1033
+ /// \return the shared bytecode of regexp literal \p regExpID, creating
1034
+ /// it from the module's bytecode on first use. Mutator thread only.
1035
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> getRegExpBytecode(
1036
+ uint32_t regExpID);
1037
+ ```
1038
+
1039
+ `lib/VM/RuntimeModule.cpp`, after `getRegExpBytecodeFromRegExpID`
1040
+ (line 296):
1041
+
1042
+ ```cpp
1043
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> RuntimeModule::getRegExpBytecode(
1044
+ uint32_t regExpID) {
1045
+ if (LLVM_UNLIKELY(regExpID >= regExpCache_.size())) {
1046
+ // Lazy compilation adds regexps to the table as functions compile.
1047
+ size_t tableSize = bcProvider_->getRegExpTable().size();
1048
+ assert(regExpID < tableSize && "Invalid regexp id");
1049
+ regExpCache_.resize(tableSize);
1050
+ }
1051
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> &entry = regExpCache_[regExpID];
1052
+ if (LLVM_UNLIKELY(!entry)) {
1053
+ entry = RegExpBytecode::create(
1054
+ getRegExpBytecodeFromRegExpID(regExpID),
1055
+ RegExpBytecode::Ownership::Cached);
1056
+ }
1057
+ return entry;
1058
+ }
1059
+ ```
1060
+
1061
+ `lib/VM/Interpreter-slowpaths.cpp`: the `RegExpBytecode::create(...)`
1062
+ argument from Task 1 becomes
1063
+ `runtimeModule->getRegExpBytecode(regexpID)`.
1064
+
1065
+ - [ ] **Step 5: Build and run**
1066
+
1067
+ On `cmake-build-asan`, run:
1068
+ - `--gtest_filter='RegExpBytecode*'`: all pass;
1069
+ - `LIT_FILTER='regexp'`: all pass.
1070
+
1071
+ - [ ] **Step 6: Moving GC (Review Focus 3)**
1072
+
1073
+ ```bash
1074
+ cmake --build $R/cmake-build-hsan --target hermes hermesc shermes \
1075
+ HermesVMRuntimeTests
1076
+ $R/cmake-build-hsan/unittests/VMRuntime/HermesVMRuntimeTests \
1077
+ --gtest_filter='RegExpBytecode*'
1078
+ LIT_FILTER='regexp' cmake --build $R/cmake-build-hsan --target check-hermes
1079
+ ```
1080
+
1081
+ Expected: all pass, with no ASan report.
1082
+
1083
+ - [ ] **Step 7: Prove each test can fail** (on `cmake-build-asan`;
1084
+ rebuild after each change)
1085
+ - `LiteralIsSharedAcrossEvaluations`: in `getRegExpBytecode`, return a
1086
+ new `Cached` entry without storing it. FAILS (distinct data).
1087
+ - `LazilyCompiledLiteralGrowsTheCache`: delete the resize branch.
1088
+ FAILS: an ASan or assertion failure indexing past the vector.
1089
+ - `FastCopySharesOnlyCachedBytecode`: in the fast copy, always take the
1090
+ `create` branch. FAILS at `litSame`.
1091
+ - `LiteralCachesArePerModule` (guard): make `regExpCache_` a
1092
+ function-local `static` vector inside `getRegExpBytecode`. It is then
1093
+ shared by every module, and the test FAILS (`r2` matches `one`).
1094
+ - `LiteralOutlivesItsModule` (guard): temporarily build a borrowing
1095
+ variant.
1096
+ 1. Add `const uint8_t *borrowed_ = nullptr;` to `RegExpBytecode`.
1097
+ 2. Make `bytecode()` and `header()` read from `borrowed_` when it is
1098
+ set.
1099
+ 3. Add a temporary factory `createBorrowed(llvh::ArrayRef<uint8_t>)`.
1100
+ It allocates only the header, keeps the real `size_`, sets
1101
+ `borrowed_ = bytecode.data()`, and uses `Ownership::Cached`. Do
1102
+ not route it through `create` with an empty array: `create`'s
1103
+ header-size assertion would fire first.
1104
+ 4. Have `RuntimeModule::getRegExpBytecode` use
1105
+ `createBorrowed(getRegExpBytecodeFromRegExpID(regExpID))`.
1106
+
1107
+ The weak-pointer precondition still passes, and `matches` then FAILS
1108
+ under ASan (heap-use-after-free on the provider's freed buffer).
1109
+ Restore, rebuild, green.
1110
+ - The lit tests (guards). Use Task 1's shared-state mutation:
1111
+ - `search` reads sticky from the shared header;
1112
+ - `setSyntaxFlags` writes the header through a `const_cast`.
1113
+
1114
+ After the split, `s.exec("ab")` no longer returns `null`, so the last
1115
+ `CHECK-NEXT: true` FAILS on every RUN line, the JIT one included.
1116
+ `lastIndex` and `groups` are JS properties of each object and cannot
1117
+ leak through the bytecode. The test pins them only as behaviour.
1118
+
1119
+ - [ ] **Step 8: Full suite** on `cmake-build-asan`: baseline numbers plus
1120
+ the two new lit tests, 0 failures.
1121
+
1122
+ - [ ] **Step 9: Commit**
1123
+
1124
+ ```bash
1125
+ git -C $R add include/hermes/VM/RuntimeModule.h lib/VM/RuntimeModule.cpp \
1126
+ lib/VM/Interpreter-slowpaths.cpp unittests/VMRuntime/RegExpBytecodeTest.cpp \
1127
+ test/hermes/regexp-literal-shared.js test/jit/regexp-literal-shared.js
1128
+ git -C $R commit # "VM: share regexp literal bytecode per RuntimeModule"
1129
+ ```
1130
+
1131
+ ---
1132
+
1133
+ ### Task 3: Memory accounting and heap snapshots for cached entries
1134
+
1135
+ **Files:**
1136
+ - Modify: `include/hermes/VM/RuntimeModule.h` (next to
1137
+ `additionalMemorySize`, `:411-413`)
1138
+ - Modify: `lib/VM/RuntimeModule.cpp:66-76` (destructor), `:412-417`,
1139
+ `:454-499` (snapshot)
1140
+ - Modify: `lib/VM/Domain.cpp:62-71`
1141
+ - Modify: `unittests/VMRuntime/HeapSnapshotTest.cpp`
1142
+
1143
+ **Interfaces:**
1144
+ - **Consumes:** `regExpCache_` from Task 2, and
1145
+ `JSRegExp::getBytecodeEntry()`.
1146
+ - **Produces:** `size_t RuntimeModule::regExpCacheMemorySize() const`.
1147
+ - **Spec resolution:** T8 lives in `HeapSnapshotTest.cpp`, to reuse its
1148
+ snapshot parsers (`Node`, `Edge`, `TAKE_SNAPSHOT`,
1149
+ `FIND_NODE_AND_EDGES_FOR_ID`), rather than in `RegExpBytecodeTest.cpp`.
1150
+
1151
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
1152
+
1153
+ - [ ] **Step 2: Write the test**
1154
+
1155
+ In `unittests/VMRuntime/HeapSnapshotTest.cpp`:
1156
+ - add the includes `hermes/VM/Callable.h`, `hermes/VM/JSRegExp.h`,
1157
+ `hermes/VM/RegExpBytecode.h` and `hermes/VM/RuntimeModule.h`, where
1158
+ they are missing;
1159
+ - after `FIND_NODE_AND_EDGES_FOR_ID` (line 364), add:
1160
+
1161
+ ```cpp
1162
+ /// \return every node named \p name.
1163
+ static std::vector<Node> findNodesNamed(
1164
+ const std::string &name,
1165
+ const JSONArray &nodes,
1166
+ const JSONArray &strings) {
1167
+ std::vector<Node> found;
1168
+ for (auto it = nodes.begin(), e = nodes.end(); it != e;
1169
+ it += HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT) {
1170
+ Node node = Node::parse(it, strings);
1171
+ if (node.name == name)
1172
+ found.push_back(std::move(node));
1173
+ }
1174
+ return found;
1175
+ }
1176
+ ```
1177
+
1178
+ After `TEST_F(HeapSnapshotRuntimeTest, FunctionLocationForLazyCode)`,
1179
+ add:
1180
+
1181
+ ```cpp
1182
+ TEST_F(HeapSnapshotRuntimeTest, RegExpBytecodeReportedByItsModule) {
1183
+ JSONFactory::Allocator alloc;
1184
+ JSONFactory jsonFactory{alloc};
1185
+
1186
+ CallResult<HermesValue> res = runtime.run(
1187
+ "(function () { return function () { return /a(b)c/g; }; })()",
1188
+ "file:///fake.js",
1189
+ hbc::CompileFlags{});
1190
+ ASSERT_FALSE(isException(res));
1191
+ Handle<JSFunction> f = runtime.makeHandle(vmcast<JSFunction>(*res));
1192
+ RuntimeModule *rm = f->getRuntimeModule();
1193
+ const size_t numRegExps = rm->getBytecode()->getRegExpTable().size();
1194
+ ASSERT_EQ(1u, numRegExps);
1195
+ // Precondition: nothing is cached yet.
1196
+ ASSERT_EQ(0u, rm->regExpCacheMemorySize());
1197
+ const auto rmID = runtime.getHeap().getNativeID(rm);
1198
+
1199
+ size_t rmSizeBefore;
1200
+ {
1201
+ JSONObject *root = TAKE_SNAPSHOT(runtime.getHeap(), jsonFactory, false);
1202
+ ASSERT_TRUE(root != nullptr);
1203
+ const JSONArray &nodes = *llvh::cast<JSONArray>(root->at("nodes"));
1204
+ const JSONArray &strings = *llvh::cast<JSONArray>(root->at("strings"));
1205
+ // Precondition: no other regexp bytecode is reported.
1206
+ ASSERT_EQ(0u, findNodesNamed("RegExpBytecode", nodes, strings).size());
1207
+ rmSizeBefore = FIND_NODE_FOR_ID(rmID, nodes, strings).selfSize;
1208
+ }
1209
+
1210
+ auto call = [&]() {
1211
+ CallResult<PseudoHandle<>> r =
1212
+ Callable::executeCall0(f, runtime, Runtime::getUndefinedValue());
1213
+ EXPECT_FALSE(isException(r));
1214
+ return runtime.makeHandle(vmcast<JSRegExp>(r->get()));
1215
+ };
1216
+
1217
+ Handle<JSRegExp> r0 = call();
1218
+ const RegExpBytecode *entry = r0->getBytecodeEntry();
1219
+ ASSERT_EQ(RegExpBytecode::Ownership::Cached, entry->ownership());
1220
+ EXPECT_EQ(0u, r0->getVT()->getMallocSize(r0.get()));
1221
+ const size_t sizeAfterFirst = rm->regExpCacheMemorySize();
1222
+
1223
+ Handle<JSRegExp> r1 = call();
1224
+ EXPECT_EQ(entry, r1->getBytecodeEntry());
1225
+ EXPECT_EQ(0u, r1->getVT()->getMallocSize(r1.get()));
1226
+ // The second evaluation adds nothing.
1227
+ EXPECT_EQ(sizeAfterFirst, rm->regExpCacheMemorySize());
1228
+
1229
+ JSONObject *root = TAKE_SNAPSHOT(runtime.getHeap(), jsonFactory, false);
1230
+ ASSERT_TRUE(root != nullptr);
1231
+ const JSONArray &nodes = *llvh::cast<JSONArray>(root->at("nodes"));
1232
+ const JSONArray &edges = *llvh::cast<JSONArray>(root->at("edges"));
1233
+ const JSONArray &strings = *llvh::cast<JSONArray>(root->at("strings"));
1234
+
1235
+ // Exactly one node for the shared bytecode, sized by its allocation.
1236
+ const auto entryID = runtime.getHeap().getNativeID(entry);
1237
+ std::vector<Node> bytecodeNodes =
1238
+ findNodesNamed("RegExpBytecode", nodes, strings);
1239
+ ASSERT_EQ(1u, bytecodeNodes.size());
1240
+ EXPECT_EQ(entryID, bytecodeNodes[0].id);
1241
+ EXPECT_EQ(entry->mallocSize(), bytecodeNodes[0].selfSize);
1242
+
1243
+ // The module node keeps its size and points at its cache vector. Every
1244
+ // module emits a vector node (the runtime's internal module too), so the
1245
+ // vector is found through this module's edge.
1246
+ auto rmNodeAndEdges =
1247
+ FIND_NODE_AND_EDGES_FOR_ID(rmID, nodes, edges, strings);
1248
+ EXPECT_EQ(rmSizeBefore, rmNodeAndEdges.first.selfSize);
1249
+ auto cacheEdgeIt = std::find_if(
1250
+ rmNodeAndEdges.second.begin(),
1251
+ rmNodeAndEdges.second.end(),
1252
+ [](const Edge &edge) {
1253
+ return edge.type == HeapSnapshot::EdgeType::Internal &&
1254
+ edge.name == "regExpCache";
1255
+ });
1256
+ ASSERT_NE(rmNodeAndEdges.second.end(), cacheEdgeIt);
1257
+
1258
+ // The vector node: named, sized by its capacity, with an indexed edge
1259
+ // to the entry.
1260
+ auto vectorNodeAndEdges =
1261
+ FIND_NODE_AND_EDGES_FOR_ID(cacheEdgeIt->toNode, nodes, edges, strings);
1262
+ EXPECT_EQ("std::vector<RegExpBytecode *>", vectorNodeAndEdges.first.name);
1263
+ const size_t slotSize = sizeof(llvh::IntrusiveRefCntPtr<RegExpBytecode>);
1264
+ const size_t vectorBytes = vectorNodeAndEdges.first.selfSize;
1265
+ EXPECT_GE(vectorBytes, numRegExps * slotSize);
1266
+ EXPECT_EQ(0u, vectorBytes % slotSize);
1267
+ EXPECT_EQ(
1268
+ std::vector<Edge>{Edge(HeapSnapshot::EdgeType::Element, 0, entryID)},
1269
+ vectorNodeAndEdges.second);
1270
+
1271
+ // The malloc estimate agrees with the snapshot: the vector plus the
1272
+ // entry.
1273
+ EXPECT_EQ(vectorBytes + entry->mallocSize(), sizeAfterFirst);
1274
+ }
1275
+ ```
1276
+
1277
+ When the fixture tears the runtime down, it asserts that every native ID
1278
+ was untracked (`lib/VM/Runtime.cpp:522-528`). The test's
1279
+ `getNativeID(entry)` and the snapshot's calls make the module
1280
+ responsible for untracking.
1281
+
1282
+ - [ ] **Step 3: See it fail**
1283
+
1284
+ Build and run `--gtest_filter='HeapSnapshotRuntimeTest.RegExp*'`.
1285
+
1286
+ Expected: a compile error, `regExpCacheMemorySize` is not a member.
1287
+
1288
+ - [ ] **Step 4: Implement**
1289
+
1290
+ `RuntimeModule.h`, after `additionalMemorySize()` (line 413):
1291
+
1292
+ ```cpp
1293
+ /// \return the malloc'd bytes held by the regexp literal cache: its
1294
+ /// vector and the entries in it. Reported by the Domain separately from
1295
+ /// additionalMemorySize(), because the entries have their own snapshot
1296
+ /// nodes.
1297
+ size_t regExpCacheMemorySize() const;
1298
+ ```
1299
+
1300
+ `RuntimeModule.cpp`:
1301
+ - After `additionalMemorySize()` (line 417):
1302
+
1303
+ ```cpp
1304
+ size_t RuntimeModule::regExpCacheMemorySize() const {
1305
+ size_t size = regExpCache_.capacity() * sizeof(regExpCache_[0]);
1306
+ for (const auto &entry : regExpCache_) {
1307
+ if (entry)
1308
+ size += entry->mallocSize();
1309
+ }
1310
+ return size;
1311
+ }
1312
+ ```
1313
+
1314
+ - In `~RuntimeModule`, after line 75:
1315
+
1316
+ ```cpp
1317
+ // Entries may outlive the module, held by JSRegExps, but only the module
1318
+ // reports them.
1319
+ for (const auto &entry : regExpCache_) {
1320
+ if (entry)
1321
+ runtime_.getHeap().getIDTracker().untrackNative(entry.get());
1322
+ }
1323
+ runtime_.getHeap().getIDTracker().untrackNative(&regExpCache_);
1324
+ ```
1325
+
1326
+ - In `snapshotAddNodes`, after the `functionMap_` node (line 490):
1327
+
1328
+ ```cpp
1329
+
1330
+ // Create a native node for each cached regexp bytecode entry.
1331
+ for (const auto &entry : regExpCache_) {
1332
+ if (entry) {
1333
+ snap.beginNode();
1334
+ snap.endNode(
1335
+ HeapSnapshot::NodeType::Native,
1336
+ "RegExpBytecode",
1337
+ gc.getNativeID(entry.get()),
1338
+ entry->mallocSize(),
1339
+ 0);
1340
+ }
1341
+ }
1342
+
1343
+ // Create a node for regExpCache_, with an edge to each entry.
1344
+ snap.beginNode();
1345
+ for (int i = 0, e = regExpCache_.size(); i < e; i++) {
1346
+ if (const RegExpBytecode *entry = regExpCache_[i].get()) {
1347
+ snap.addIndexedEdge(
1348
+ HeapSnapshot::EdgeType::Element, i, gc.getNativeID(entry));
1349
+ }
1350
+ }
1351
+ snap.endNode(
1352
+ HeapSnapshot::NodeType::Native,
1353
+ "std::vector<RegExpBytecode *>",
1354
+ gc.getNativeID(&regExpCache_),
1355
+ regExpCache_.capacity() * sizeof(regExpCache_[0]),
1356
+ 0);
1357
+ ```
1358
+
1359
+ - In `snapshotAddEdges`, after the `functionMap` edge:
1360
+
1361
+ ```cpp
1362
+ snap.addNamedEdge(
1363
+ HeapSnapshot::EdgeType::Internal,
1364
+ "regExpCache",
1365
+ gc.getNativeID(&regExpCache_));
1366
+ ```
1367
+
1368
+ `lib/VM/Domain.cpp:66` becomes:
1369
+
1370
+ ```cpp
1371
+ rmSize += sizeof(RuntimeModule) + rm->additionalMemorySize() +
1372
+ rm->regExpCacheMemorySize();
1373
+ ```
1374
+
1375
+ `additionalMemorySize()` and the `RuntimeModule` node size
1376
+ (`Domain.cpp:92`) stay unchanged.
1377
+
1378
+ - [ ] **Step 5: Build and run**
1379
+
1380
+ Run `--gtest_filter='HeapSnapshot*:RegExpBytecode*'` on `cmake-build-asan`.
1381
+
1382
+ Expected: all pass.
1383
+
1384
+ - [ ] **Step 6: Prove it can fail**
1385
+ - In `JSRegExp::_mallocSizeImpl`, return `mallocSize()` for every
1386
+ entry. FAILS (`getMallocSize` is not 0).
1387
+ - Remove the per-entry node loop. FAILS (no `RegExpBytecode` node).
1388
+ - Remove the per-entry `untrackNative` loop from `~RuntimeModule`. The
1389
+ test binary FAILS at fixture teardown with "A pointer is left in the
1390
+ ID tracker".
1391
+ - Remove the `regExpCache` edge. FAILS (`cacheEdge` not found).
1392
+
1393
+ - [ ] **Step 7: Full suite** on `cmake-build-asan`: 0 failures.
1394
+
1395
+ - [ ] **Step 8: Commit**
1396
+
1397
+ ```bash
1398
+ git -C $R add include/hermes/VM/RuntimeModule.h lib/VM/RuntimeModule.cpp \
1399
+ lib/VM/Domain.cpp unittests/VMRuntime/HeapSnapshotTest.cpp
1400
+ git -C $R commit # "VM: report cached regexp bytecode from its RuntimeModule"
1401
+ ```
1402
+
1403
+ ---
1404
+
1405
+ ### Task 4: Static Hermes ahead-of-time regexp bytecode
1406
+
1407
+ The ABI, the runtime and the compiler change together: generated C
1408
+ compiled against the new header must use the new call.
1409
+
1410
+ **Files:**
1411
+ - Modify: `include/hermes/VM/static_h.h:31-38` (new entry type), `:133-142`
1412
+ (`SHUnit` fields) and `:891-892` (declaration)
1413
+ - Modify: `lib/VM/SHUnitExt.h`, `lib/VM/StaticHUnit.cpp:117`, `:206-210`
1414
+ - Modify: `lib/VM/StaticH.cpp:1788-1810`
1415
+ - Modify: `lib/BCGen/SH/SH.cpp:177-246`, `:429-447`, `:1798-1826`,
1416
+ `:3169-3216`
1417
+ - Modify: `unittests/VMRuntime/RegExpBytecodeTest.cpp`
1418
+ - Create: `test/shermes/regexp-aot.js`
1419
+
1420
+ **Interfaces:**
1421
+ - **Consumes:** `RegExpBytecode` (Task 1);
1422
+ `CompiledRegExp &Context::getCompiledRegExp(UniqueString *, UniqueString *)`
1423
+ (`include/hermes/AST/Context.h:351-357`); and `UniquingRegExpTable`
1424
+ (`include/hermes/Regex/RegexSerialization.h:90-162`).
1425
+ - **Produces:**
1426
+ - `explicit SHUnitExt::SHUnitExt(uint32_t numRegExps)`;
1427
+ - `SHUnitExt::regExpCache`;
1428
+ - `hermes::vm::sh_unit_get_regexp_bytecode(SHUnit *, uint32_t)`.
1429
+ - **Spec resolution:** the spec sizes the cache "when the unit is
1430
+ attached". This is done through the `SHUnitExt` constructor argument,
1431
+ and lookup goes through `sh_unit_get_regexp_bytecode`, mirroring
1432
+ `RuntimeModule::getRegExpBytecode`.
1433
+ - **Spec resolution:** the new `SHUnit` fields go right after
1434
+ `object_literal_class_cache`, with the other literal data. The
1435
+ generated initializer uses designated initializers, so the position
1436
+ does not matter to it.
1437
+
1438
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
1439
+
1440
+ - [ ] **Step 2: Write the tests**
1441
+
1442
+ Unit test (T7b). Add these includes to `RegExpBytecodeTest.cpp`:
1443
+ - `"../../lib/VM/SHUnitExt.h"`, following the precedent of
1444
+ `unittests/VMRuntime/JitChainWalkTest.cpp:12`;
1445
+ - `"hermes/VM/StaticHUtils.h"`;
1446
+ - `"hermes/VM/static_h.h"`.
1447
+
1448
+ Then add the test:
1449
+
1450
+ ```cpp
1451
+ TEST_F(RegExpBytecodeTest, SHUnitSharesPrecompiledBytecode) {
1452
+ auto compiled = CompiledRegExp::tryCompile("a(b)c", "g");
1453
+ ASSERT_TRUE(compiled.hasValue());
1454
+ llvh::ArrayRef<uint8_t> bc = compiled->getBytecode();
1455
+ const SHRegExpTableEntry table[] = {{0, (uint32_t)bc.size()}};
1456
+
1457
+ // Only the regexp fields matter to _sh_ljs_create_regexp.
1458
+ SHUnit unit{};
1459
+ unit.regexp_storage = bc.data();
1460
+ unit.regexp_table = table;
1461
+ unit.num_regexps = 1;
1462
+ unit.runtime_ext = new SHUnitExt{unit.num_regexps};
1463
+
1464
+ auto symbol = [&](const char *str) {
1465
+ CallResult<Handle<SymbolID>> sym =
1466
+ runtime.getIdentifierTable().getSymbolHandle(
1467
+ runtime, createASCIIRef(str));
1468
+ EXPECT_NE(ExecutionStatus::EXCEPTION, sym.getStatus());
1469
+ return sym->get().unsafeGetRaw();
1470
+ };
1471
+ const SHSymbolID pattern = symbol("a(b)c");
1472
+ const SHSymbolID flags = symbol("g");
1473
+
1474
+ const size_t sizeBefore = sh_unit_additional_memory_size(&unit);
1475
+ auto create = [&]() {
1476
+ SHLegacyValue v = _sh_ljs_create_regexp(
1477
+ getSHRuntime(runtime), &unit, pattern, flags, 0);
1478
+ return runtime.makeHandle(vmcast<JSRegExp>(HermesValue::fromRaw(v.raw)));
1479
+ };
1480
+ Handle<JSRegExp> r0 = create();
1481
+ Handle<JSRegExp> r1 = create();
1482
+ EXPECT_EQ(r0->getBytecode().data(), r1->getBytecode().data());
1483
+ EXPECT_TRUE(bc.equals(r0->getBytecode()));
1484
+ EXPECT_EQ(
1485
+ RegExpBytecode::Ownership::Cached, r0->getBytecodeEntry()->ownership());
1486
+ // The vector was sized when the unit was attached; only the entry is
1487
+ // new.
1488
+ EXPECT_EQ(
1489
+ sizeBefore + r0->getBytecodeEntry()->mallocSize(),
1490
+ sh_unit_additional_memory_size(&unit));
1491
+ EXPECT_TRUE(matches(runtime, r1, "xabc"));
1492
+
1493
+ // The regexps keep the entry alive after the unit's cache is gone.
1494
+ delete unit.runtime_ext;
1495
+ EXPECT_TRUE(matches(runtime, r0, "abc"));
1496
+ }
1497
+ ```
1498
+
1499
+ The pattern symbol and the regexp handles are rooted: the symbols by the
1500
+ identifier table and the `Handle`s, the regexps by the fixture's
1501
+ `GCScope`. `createASCIIRef` is in `include/hermes/VM/StringRefUtils.h:32`.
1502
+ Include that header if it is not reached transitively.
1503
+
1504
+ Add `#include <algorithm>` to `HeapSnapshotTest.cpp` in Task 3 if it is
1505
+ missing (`std::find`).
1506
+
1507
+ Lit test (T7a, T7c, Review Focus 5). Create `test/shermes/regexp-aot.js`:
1508
+
1509
+ ```js
1510
+ /**
1511
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1512
+ *
1513
+ * This source code is licensed under the MIT license found in the
1514
+ * LICENSE file in the root directory of this source tree.
1515
+ */
1516
+
1517
+ // RUN: %shermes -O0 -emit-c -o - %s | %FileCheck %s
1518
+ // RUN: %shermes -O -emit-c -o - %s | %FileCheck %s
1519
+ // RUN: %shermes -exec %s | %FileCheck --check-prefix=EXEC --match-full-lines %s
1520
+
1521
+ // SH compiles regexp literals ahead of time: each distinct literal gets one
1522
+ // entry in s_regexp_table, and _sh_ljs_create_regexp takes its index.
1523
+
1524
+ function main() {
1525
+ function mk() { return /(?<y>\d{4})-(?<m>\d\d)/gy; }
1526
+ function same() { return /(?<y>\d{4})-(?<m>\d\d)/gy; }
1527
+ function uni() { return /é|\u{1F600}/u; }
1528
+ var prev = null;
1529
+ for (var i = 0; i < 3; ++i) {
1530
+ var r = i == 1 ? same() : mk();
1531
+ print(r === prev, r.flags, r.sticky, r.lastIndex);
1532
+ var m = r.exec("2024-10 rest");
1533
+ print(m.groups.y, m.groups.m, r.lastIndex);
1534
+ prev = r;
1535
+ }
1536
+ var u = uni();
1537
+ print(u.source, u.test("\u{1F600}"), u.test("é"), u.test("e"));
1538
+ }
1539
+ main();
1540
+
1541
+ // CHECK: _sh_ljs_create_regexp(shr, shUnit, get_symbols(shUnit)[{{[0-9]+}}], get_symbols(shUnit)[{{[0-9]+}}], 0);
1542
+ // CHECK: _sh_ljs_create_regexp(shr, shUnit, get_symbols(shUnit)[{{[0-9]+}}], get_symbols(shUnit)[{{[0-9]+}}], 0);
1543
+ // CHECK: _sh_ljs_create_regexp(shr, shUnit, get_symbols(shUnit)[{{[0-9]+}}], get_symbols(shUnit)[{{[0-9]+}}], 1);
1544
+ // CHECK: static unsigned char s_regexp_storage[{{[0-9]+}}] = {
1545
+ // CHECK-NEXT: static const SHRegExpTableEntry s_regexp_table[] = {
1546
+ // CHECK-NEXT: { .offset = 0, .length = [[LEN:[0-9]+]] },
1547
+ // CHECK-NEXT: { .offset = [[LEN]], .length = {{[0-9]+}} },
1548
+ // CHECK-NEXT: };
1549
+ // CHECK: .regexp_storage = s_regexp_storage, .regexp_table = s_regexp_table, .num_regexps = 2,
1550
+
1551
+ // EXEC: false gy true 0
1552
+ // EXEC-NEXT: 2024 10 7
1553
+ // EXEC-NEXT: false gy true 0
1554
+ // EXEC-NEXT: 2024 10 7
1555
+ // EXEC-NEXT: false gy true 0
1556
+ // EXEC-NEXT: 2024 10 7
1557
+ // EXEC-NEXT: é|\u{1F600} true true false
1558
+ ```
1559
+
1560
+ The three CHECK call lines assume that `mk`, `same` and `uni` are emitted
1561
+ in source order, and that the optimizer neither inlines nor reorders
1562
+ them.
1563
+ - If `-O` inlines or reorders them, keep the `-O` RUN line. Give it a
1564
+ separate `--check-prefix` whose call checks still require two calls
1565
+ with the same id and one with a different id. For example, use
1566
+ `CHECK-DAG` lines `, 0);` (twice) and `, 1);`.
1567
+ - Keep the table checks identical for both RUN lines.
1568
+
1569
+ Report any such adjustment.
1570
+
1571
+ - [ ] **Step 3: See them fail**
1572
+
1573
+ ```bash
1574
+ cmake --build $R/cmake-build-asan --target HermesVMRuntimeTests shermes
1575
+ LIT_FILTER='regexp-aot' cmake --build $R/cmake-build-asan --target check-hermes
1576
+ ```
1577
+
1578
+ Expected:
1579
+ - The unit test does not compile: no `SHRegExpTableEntry`, and the
1580
+ `SHUnitExt` constructor takes no argument.
1581
+ - The two `-emit-c` RUN lines FAIL: no `s_regexp_table`, and the old call
1582
+ has three arguments.
1583
+ - The `-exec` part passes. It is a regression guard.
1584
+
1585
+ - [ ] **Step 4: ABI** (`include/hermes/VM/static_h.h`)
1586
+
1587
+ After `SHShapeTableEntry` (line 38):
1588
+
1589
+ ```c
1590
+
1591
+ /// Locates the bytecode of one regexp literal in SHUnit::regexp_storage.
1592
+ typedef struct SHRegExpTableEntry {
1593
+ /// Offset of the bytecode in regexp_storage, in bytes.
1594
+ uint32_t offset;
1595
+ /// Length of the bytecode, in bytes.
1596
+ uint32_t length;
1597
+ } SHRegExpTableEntry;
1598
+ ```
1599
+
1600
+ In `SHUnit`, after `object_literal_class_cache` (line 142):
1601
+
1602
+ ```c
1603
+
1604
+ /// Concatenated bytecode of the unit's regexp literals, compiled ahead of
1605
+ /// time.
1606
+ const unsigned char *regexp_storage;
1607
+ /// One entry per regexp literal, indexed by the id passed to
1608
+ /// _sh_ljs_create_regexp.
1609
+ const SHRegExpTableEntry *regexp_table;
1610
+ /// Number of entries in regexp_table.
1611
+ uint32_t num_regexps;
1612
+ ```
1613
+
1614
+ Replace the declaration at lines 891-892 with:
1615
+
1616
+ ```c
1617
+ /// Create a regexp from literal \p regexp_id of \p unit, whose pattern and
1618
+ /// flags are the symbols \p pattern and \p flags. The bytecode was compiled
1619
+ /// ahead of time and is shared by every evaluation of the literal.
1620
+ SHERMES_EXPORT SHLegacyValue _sh_ljs_create_regexp(
1621
+ SHRuntime *shr,
1622
+ SHUnit *unit,
1623
+ SHSymbolID pattern,
1624
+ SHSymbolID flags,
1625
+ uint32_t regexp_id);
1626
+ ```
1627
+
1628
+ - [ ] **Step 5: Runtime**
1629
+
1630
+ `lib/VM/SHUnitExt.h`:
1631
+ - Add the includes `"hermes/VM/RegExpBytecode.h"` and `<vector>`.
1632
+ - In `SHUnitExt`, after `addCacheEntries`, add the member below, and
1633
+ replace the constructor:
1634
+
1635
+ ```cpp
1636
+ /// The shared bytecode of each regexp literal, indexed like
1637
+ /// SHUnit::regexp_table and created on first use. Mutator thread only.
1638
+ std::vector<llvh::IntrusiveRefCntPtr<hermes::vm::RegExpBytecode>>
1639
+ regExpCache;
1640
+
1641
+ /// Create the data for a unit with \p numRegExps regexp literals.
1642
+ explicit SHUnitExt(uint32_t numRegExps) : regExpCache(numRegExps) {
1643
+ // Reserve entry 0.
1644
+ addCacheEntries.emplace_back();
1645
+ }
1646
+ ```
1647
+
1648
+ - After `sh_unit_get_add_cache_entry`, add:
1649
+
1650
+ ```cpp
1651
+ /// \return the shared bytecode of regexp literal \p regExpID of \p unit,
1652
+ /// creating it from the unit's precompiled bytecode on first use. Mutator
1653
+ /// thread only.
1654
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> sh_unit_get_regexp_bytecode(
1655
+ SHUnit *unit,
1656
+ uint32_t regExpID);
1657
+ ```
1658
+
1659
+ `lib/VM/StaticHUnit.cpp`:
1660
+ - Line 117 becomes `unit->runtime_ext = new SHUnitExt{unit->num_regexps};`.
1661
+ Grep `lib/` and `API/` (excluding `API/hermes_sandbox`) for any other
1662
+ `new SHUnitExt` and convert it the same way.
1663
+ - `sh_unit_additional_memory_size` (lines 206-210) becomes:
1664
+
1665
+ ```cpp
1666
+ size_t hermes::vm::sh_unit_additional_memory_size(const SHUnit *unit) {
1667
+ const SHUnitExt *ext = unit->runtime_ext;
1668
+ size_t regExpSize = ext->regExpCache.capacity() * sizeof(ext->regExpCache[0]);
1669
+ for (const auto &entry : ext->regExpCache) {
1670
+ if (entry)
1671
+ regExpSize += entry->mallocSize();
1672
+ }
1673
+ return sizeof(unit->runtime_ext) + ext->templateMap.getMemorySize() +
1674
+ ext->addCacheEntries.capacity_in_bytes() + regExpSize;
1675
+ }
1676
+ ```
1677
+
1678
+ - Add, after it:
1679
+
1680
+ ```cpp
1681
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> hermes::vm::sh_unit_get_regexp_bytecode(
1682
+ SHUnit *unit,
1683
+ uint32_t regExpID) {
1684
+ auto &cache = unit->runtime_ext->regExpCache;
1685
+ assert(regExpID < cache.size() && "Invalid regexp id");
1686
+ llvh::IntrusiveRefCntPtr<RegExpBytecode> &entry = cache[regExpID];
1687
+ if (LLVM_UNLIKELY(!entry)) {
1688
+ const SHRegExpTableEntry &te = unit->regexp_table[regExpID];
1689
+ entry = RegExpBytecode::create(
1690
+ {unit->regexp_storage + te.offset, te.length},
1691
+ RegExpBytecode::Ownership::Cached);
1692
+ }
1693
+ return entry;
1694
+ }
1695
+ ```
1696
+
1697
+ `lib/VM/StaticH.cpp`: replace `_sh_ljs_create_regexp` (lines 1788-1810)
1698
+ with the following. Nothing in it can throw, so the `LocalsRAII` is
1699
+ safe. Its structure is `Interpreter::createRegExp`'s
1700
+ (`Interpreter-slowpaths.cpp:597-622`).
1701
+
1702
+ ```cpp
1703
+ LLVM_ATTRIBUTE_NOINLINE
1704
+ extern "C" SHLegacyValue _sh_ljs_create_regexp(
1705
+ SHRuntime *shr,
1706
+ SHUnit *unit,
1707
+ SHSymbolID pattern,
1708
+ SHSymbolID flags,
1709
+ uint32_t regexp_id) {
1710
+ Runtime &runtime = getRuntime(shr);
1711
+ GCScopeMarkerRAII marker{runtime};
1712
+ struct : public Locals {
1713
+ PinnedValue<JSRegExp> re;
1714
+ PinnedValue<StringPrimitive> pattern;
1715
+ PinnedValue<StringPrimitive> flags;
1716
+ } lv;
1717
+ LocalsRAII lraii{runtime, &lv};
1718
+
1719
+ lv.re = JSRegExp::create(runtime);
1720
+ lv.pattern =
1721
+ runtime.getStringPrimFromSymbolID(SymbolID::unsafeCreate(pattern));
1722
+ lv.flags = runtime.getStringPrimFromSymbolID(SymbolID::unsafeCreate(flags));
1723
+ // The bytecode was compiled ahead of time; nothing is parsed here.
1724
+ JSRegExp::initialize(
1725
+ lv.re,
1726
+ runtime,
1727
+ lv.pattern,
1728
+ lv.flags,
1729
+ sh_unit_get_regexp_bytecode(unit, regexp_id));
1730
+ return lv.re.getHermesValue();
1731
+ }
1732
+ ```
1733
+
1734
+ `StaticH.cpp` already includes `SHUnitExt.h` (line 8). If
1735
+ `lv.re.getHermesValue()` does not convert to `SHLegacyValue`, write
1736
+ `HermesValue res = lv.re.getHermesValue(); return res;`, which is what
1737
+ the old code's `return *cr;` relied on.
1738
+
1739
+ - [ ] **Step 6: Compiler** (`lib/BCGen/SH/SH.cpp`)
1740
+
1741
+ - Add `#include "hermes/Regex/RegexSerialization.h"` to the includes.
1742
+ - Move `generateBuffer` out of `SHLiteralBuffers` (lines 235-245). Put it
1743
+ before the class, as a free function, and delete the `private:`
1744
+ section:
1745
+
1746
+ ```cpp
1747
+ /// Emit \p buf as a C array of unsigned char named \p name.
1748
+ static void generateBuffer(
1749
+ llvh::raw_ostream &os,
1750
+ llvh::StringRef name,
1751
+ llvh::ArrayRef<unsigned char> buf) {
1752
+ os << "static unsigned char " << name << "[" << buf.size() << "] = {";
1753
+ for (unsigned char c : buf) {
1754
+ os << (int)c << ",";
1755
+ }
1756
+ os << "};\n";
1757
+ }
1758
+
1759
+ /// Emit the regexp bytecode storage and the table that locates each
1760
+ /// regexp in it.
1761
+ static void generateRegExpTable(
1762
+ llvh::raw_ostream &os,
1763
+ const UniquingRegExpTable &table) {
1764
+ generateBuffer(os, "s_regexp_storage", table.getBytecodeBuffer());
1765
+ os << "static const SHRegExpTableEntry s_regexp_table[] = {\n";
1766
+ for (const RegExpTableEntry &entry : table.getEntryList()) {
1767
+ os.indent(2);
1768
+ os << "{ .offset = " << entry.offset << ", .length = " << entry.length
1769
+ << " },\n";
1770
+ }
1771
+ os << "};\n";
1772
+ }
1773
+ ```
1774
+
1775
+ An empty table emits `[] = {\n};`, exactly as `s_obj_shape_table`
1776
+ already does for a module with no object literals (lines 226-232).
1777
+ - In `ModuleGen` (lines 429-447), after `nativeFunctionTable`, add:
1778
+
1779
+ ```cpp
1780
+
1781
+ /// Uniqued table of the module's regexp literals and their bytecode.
1782
+ UniquingRegExpTable regExpTable{};
1783
+ ```
1784
+
1785
+ - Replace `generateCreateRegExpInst` (lines 1798-1826) with:
1786
+
1787
+ ```cpp
1788
+ void generateCreateRegExpInst(CreateRegExpInst &inst) {
1789
+ os_.indent(2);
1790
+
1791
+ uint32_t patternStrID =
1792
+ moduleGen_.stringTable.add(inst.getPattern()->getValue().str());
1793
+ uint32_t flagsStrID =
1794
+ moduleGen_.stringTable.add(inst.getFlags()->getValue().str());
1795
+ // Semantic resolution compiled every regexp literal into the Context.
1796
+ CompiledRegExp &regexp = F_.getContext().getCompiledRegExp(
1797
+ inst.getPattern()->getValue().getUnderlyingPointer(),
1798
+ inst.getFlags()->getValue().getUnderlyingPointer());
1799
+ uint32_t regExpID = moduleGen_.regExpTable.addRegExp(&regexp);
1800
+
1801
+ generateValue(inst);
1802
+ os_ << " = ";
1803
+ os_ << "_sh_ljs_create_regexp(shr, shUnit, ";
1804
+ os_ << llvh::format("get_symbols(shUnit)[%u]", patternStrID);
1805
+ os_ << ", ";
1806
+ os_ << llvh::format("get_symbols(shUnit)[%u]", flagsStrID);
1807
+ os_ << ", " << regExpID << ");\n";
1808
+ }
1809
+ ```
1810
+
1811
+ - In the unit emission (line 3170), after
1812
+ `moduleGen.literalBuffers.generate(OS);`, add
1813
+ `generateRegExpTable(OS, moduleGen.regExpTable);`.
1814
+ - In the `CREATE_THIS_UNIT` initializer, after line 3211
1815
+ (`.object_literal_class_cache = ...`), add:
1816
+
1817
+ ```cpp
1818
+ << ".regexp_storage = s_regexp_storage, "
1819
+ << ".regexp_table = s_regexp_table, "
1820
+ << ".num_regexps = " << moduleGen.regExpTable.getEntryList().size()
1821
+ << ", "
1822
+ ```
1823
+
1824
+ - [ ] **Step 7: Build and run**
1825
+
1826
+ ```bash
1827
+ cmake --build $R/cmake-build-asan --target hermes hermesc shermes \
1828
+ HermesVMRuntimeTests
1829
+ $R/cmake-build-asan/unittests/VMRuntime/HermesVMRuntimeTests \
1830
+ --gtest_filter='RegExpBytecode*'
1831
+ LIT_FILTER='shermes' cmake --build $R/cmake-build-asan --target check-hermes
1832
+ ```
1833
+
1834
+ Expected:
1835
+ - Everything passes.
1836
+ - Every existing `test/shermes` test passes. They all have zero or more
1837
+ regexps, and the ones with zero exercise the empty table.
1838
+
1839
+ - [ ] **Step 8: Prove each test can fail**
1840
+ - `SHUnitSharesPrecompiledBytecode`: in `sh_unit_get_regexp_bytecode`,
1841
+ return a new entry without storing it. FAILS (distinct data, and the
1842
+ memory size is wrong).
1843
+ - `regexp-aot.js` CHECK lines:
1844
+ - Emit `0` instead of `regExpID` in the call. The third call CHECK
1845
+ (`, 1);`) fails.
1846
+ - Separately, to pin uniquing: temporarily delete the early-return
1847
+ lookup in `UniquingRegExpTable::addRegExp`
1848
+ (`include/hermes/Regex/RegexSerialization.h:122-124`). The keys
1849
+ still reference Context-owned `CompiledRegExp`s. The table gets
1850
+ three entries, and the second call CHECK (`, 0);`, now `1`) and
1851
+ `.num_regexps = 2` fail. Restore it, and rebuild `hermesc` and
1852
+ `shermes` too.
1853
+ - `regexp-aot.js` EXEC (guard): in `_sh_ljs_create_regexp`, pass
1854
+ `regexp_id ^ 1` to `sh_unit_get_regexp_bytecode`. `mk` gets `uni`'s
1855
+ bytecode, and EXEC FAILS.
1856
+
1857
+ - [ ] **Step 9: Full suite** on `cmake-build-asan`: 0 failures.
1858
+
1859
+ - [ ] **Step 10: Code-review note for the report**
1860
+
1861
+ The spec states that no test proves the runtime parse is gone. Quote,
1862
+ in the report, the final `_sh_ljs_create_regexp` and
1863
+ `sh_unit_get_regexp_bytecode`. Confirm that neither calls
1864
+ `JSRegExp::initialize(self, runtime, pattern, flags)` (the compiling
1865
+ overload) nor `regex::Regex`.
1866
+
1867
+ - [ ] **Step 11: Commit**
1868
+
1869
+ ```bash
1870
+ git -C $R add include/hermes/VM/static_h.h lib/VM/SHUnitExt.h \
1871
+ lib/VM/StaticHUnit.cpp lib/VM/StaticH.cpp lib/BCGen/SH/SH.cpp \
1872
+ unittests/VMRuntime/RegExpBytecodeTest.cpp test/shermes/regexp-aot.js
1873
+ git -C $R commit # "SH: compile regexp literals ahead of time"
1874
+ ```
1875
+
1876
+ ---
1877
+
1878
+ ### Task 5: Concurrency guards under TSan
1879
+
1880
+ Spec "TSan" cases 1 and 2. These are regression guards.
1881
+ - **Case 1.** Old-gen-sweep finalizers on the Hades background thread
1882
+ decrement a `Cached` entry's count while the mutator increments it by
1883
+ evaluating the same literal. The module's cache keeps the count above
1884
+ zero.
1885
+ - The sweep runs under `gcMutex_` on the executor thread
1886
+ (`lib/VM/gcs/HadesGC.cpp:1641`, `:1717`, `:1168`).
1887
+ - The mutator's cache lookup and pointer copy hold no such lock
1888
+ (`include/hermes/VM/HadesGC.h:1684`, `lib/VM/gcs/HadesGC.cpp:2339`).
1889
+
1890
+ So a non-atomic count is a real race, which TSan can observe subject
1891
+ to scheduling.
1892
+ - **Case 2.** A lifetime guard. The module dies first, and the
1893
+ finalizers of the promoted regexps then release the entry's last
1894
+ references.
1895
+
1896
+ **Files:**
1897
+ - Modify: `unittests/VMRuntime/RegExpBytecodeTest.cpp`
1898
+
1899
+ **Interfaces:**
1900
+ - **Consumes:** everything above;
1901
+ `GCBase::collectWithOptions(std::string &&, const GCOptions &)`
1902
+ (`include/hermes/VM/GCBase.h:1092-1094`);
1903
+ `GCBase::inYoungGen(const GCCell *)` (`:1101`); and `kConcurrentGC`
1904
+ (`include/hermes/VM/GCConcurrency.h:25`).
1905
+
1906
+ - [ ] **Step 1: Invoke the gc-safe-coding skill.**
1907
+
1908
+ - [ ] **Step 2: Write the tests**
1909
+
1910
+ - Add the includes `"hermes/VM/GCConcurrency.h"` and `<thread>`.
1911
+ - Look up `Callable::executeCall1`'s exact signature in
1912
+ `include/hermes/VM/Callable.h` before writing the calls below. Adapt
1913
+ the argument (`HermesValue` or `Handle<>`) to it.
1914
+ - Add these helpers to the anonymous namespace:
1915
+
1916
+ ```cpp
1917
+ /// Run \p code, which evaluates to [mk, fill]: mk() returns a regexp
1918
+ /// literal, fill(n) returns an array of n results of mk().
1919
+ void runFactory(
1920
+ Runtime &runtime,
1921
+ std::shared_ptr<hbc::BCProvider> provider,
1922
+ MutableHandle<JSFunction> &mk,
1923
+ MutableHandle<JSFunction> &fill) {
1924
+ RuntimeModuleFlags rmFlags;
1925
+ rmFlags.persistent = false;
1926
+ CallResult<HermesValue> res = runtime.runBytecode(
1927
+ std::move(provider),
1928
+ rmFlags,
1929
+ "test.js",
1930
+ Runtime::makeNullHandle<Environment>());
1931
+ ASSERT_NE(ExecutionStatus::EXCEPTION, res.getStatus());
1932
+ Handle<JSArray> arr = runtime.makeHandle(vmcast<JSArray>(*res));
1933
+ mk = vmcast<JSFunction>(arr->at(runtime, 0).unboxToHV(runtime));
1934
+ fill = vmcast<JSFunction>(arr->at(runtime, 1).unboxToHV(runtime));
1935
+ }
1936
+
1937
+ /// The source run by runFactory.
1938
+ const char *const kFactorySource =
1939
+ "(function () {"
1940
+ " function mk() { return /c(o)n/g; }"
1941
+ " function fill(n) {"
1942
+ " var a = new Array(n);"
1943
+ " for (var i = 0; i < n; ++i) a[i] = mk();"
1944
+ " return a;"
1945
+ " }"
1946
+ " return [mk, fill];"
1947
+ "})()";
1948
+
1949
+ /// \return a provider for kFactorySource that is owned only by the
1950
+ /// returned pointer, and set \p weak to observe it.
1951
+ std::shared_ptr<hbc::BCProvider> factoryProvider(
1952
+ std::weak_ptr<hbc::BCProvider> &weak) {
1953
+ std::vector<uint8_t> bc = bytecodeForSource(kFactorySource);
1954
+ std::shared_ptr<hbc::BCProvider> provider =
1955
+ hbc::BCProviderFromBuffer::createBCProviderFromBuffer(
1956
+ std::make_unique<OwnedMemoryBuffer>(
1957
+ llvh::MemoryBuffer::getMemBufferCopy(
1958
+ llvh::StringRef((const char *)bc.data(), bc.size()))))
1959
+ .first;
1960
+ weak = provider;
1961
+ return provider;
1962
+ }
1963
+
1964
+ /// Collect young generations until every element of \p arr is in the old
1965
+ /// generation, so that its finalizer runs in an old-gen sweep.
1966
+ ::testing::AssertionResult promoteAll(Runtime &runtime, Handle<JSArray> arr) {
1967
+ for (int round = 0; round < 4; ++round) {
1968
+ bool allOld = true;
1969
+ for (uint32_t i = 0, e = JSArray::getLength(*arr, runtime); i < e; ++i) {
1970
+ if (runtime.getHeap().inYoungGen(
1971
+ vmcast<GCCell>(arr->at(runtime, i).unboxToHV(runtime))))
1972
+ allOld = false;
1973
+ }
1974
+ if (allOld && runtime.getHeap().inYoungGen(*arr) == false)
1975
+ return ::testing::AssertionSuccess();
1976
+ runtime.getHeap().collectWithOptions("test", GCBase::GCOptions{});
1977
+ }
1978
+ return ::testing::AssertionFailure() << "regexps were not promoted";
1979
+ }
1980
+
1981
+ /// Request asynchronous old-generation collections while running \p work
1982
+ /// for \p iterations, then finish with a synchronous full collection.
1983
+ template <typename Work>
1984
+ void driveAsyncMajor(Runtime &runtime, int iterations, Work work) {
1985
+ const GCBase::GCOptions async{
1986
+ GCBase::GCType::Major, GCBase::GCExecutionPolicy::Async};
1987
+ for (int i = 0; i < iterations; ++i) {
1988
+ if (i % 64 == 0)
1989
+ runtime.getHeap().collectWithOptions("test", async);
1990
+ GCScopeMarkerRAII marker{runtime};
1991
+ work();
1992
+ std::this_thread::yield();
1993
+ }
1994
+ runtime.collect("test");
1995
+ }
1996
+ ```
1997
+
1998
+ - Add the tests:
1999
+
2000
+ ```cpp
2001
+ TEST_F(RegExpBytecodeTest, ConcurrentReleaseWhileAcquiring) {
2002
+ if (!kConcurrentGC)
2003
+ GTEST_SKIP() << "needs the Hades background thread";
2004
+ std::weak_ptr<hbc::BCProvider> weak;
2005
+ MutableHandle<JSFunction> mk{runtime}, fill{runtime};
2006
+ runFactory(runtime, factoryProvider(weak), mk, fill);
2007
+
2008
+ CallResult<PseudoHandle<>> filled = Callable::executeCall1(
2009
+ fill,
2010
+ runtime,
2011
+ Runtime::getUndefinedValue(),
2012
+ HermesValue::encodeTrustedNumberValue(256));
2013
+ ASSERT_NE(ExecutionStatus::EXCEPTION, filled.getStatus());
2014
+ MutableHandle<JSArray> arr{runtime, vmcast<JSArray>(filled->get())};
2015
+ ASSERT_TRUE(promoteAll(runtime, arr));
2016
+
2017
+ // Drop the promoted regexps; their old-gen sweep releases the shared
2018
+ // entry while the mutator keeps acquiring it.
2019
+ arr = nullptr;
2020
+ driveAsyncMajor(runtime, 4096, [&]() { callForRegExp(runtime, mk); });
2021
+ EXPECT_TRUE(matches(runtime, callForRegExp(runtime, mk), "con"));
2022
+ }
2023
+
2024
+ TEST_F(RegExpBytecodeTest, ConcurrentReleaseAfterModuleDeath) {
2025
+ if (!kConcurrentGC)
2026
+ GTEST_SKIP() << "needs the Hades background thread";
2027
+ std::weak_ptr<hbc::BCProvider> weak;
2028
+ MutableHandle<JSArray> arr{runtime};
2029
+ {
2030
+ // Handles live until their GCScope ends, not their C++ scope. This
2031
+ // scope frees the factory's handles; arr belongs to the fixture's.
2032
+ GCScope factoryScope{runtime};
2033
+ MutableHandle<JSFunction> mk{runtime}, fill{runtime};
2034
+ runFactory(runtime, factoryProvider(weak), mk, fill);
2035
+ CallResult<PseudoHandle<>> filled = Callable::executeCall1(
2036
+ fill,
2037
+ runtime,
2038
+ Runtime::getUndefinedValue(),
2039
+ HermesValue::encodeTrustedNumberValue(256));
2040
+ ASSERT_NE(ExecutionStatus::EXCEPTION, filled.getStatus());
2041
+ arr = vmcast<JSArray>(filled->get());
2042
+ // Release the factory: a callable function keeps its Domain alive.
2043
+ }
2044
+ ASSERT_TRUE(promoteAll(runtime, arr));
2045
+ for (int i = 0; i < 3 && !weak.expired(); ++i)
2046
+ runtime.collect("test");
2047
+ // Precondition: the module is gone; only the regexps hold the entry.
2048
+ ASSERT_TRUE(weak.expired());
2049
+
2050
+ arr = nullptr;
2051
+ driveAsyncMajor(runtime, 4096, [&]() {
2052
+ // Unrelated allocation keeps the mutator busy.
2053
+ JSObject::create(runtime);
2054
+ });
2055
+ }
2056
+ ```
2057
+
2058
+ `MutableHandle` assignment from a raw pointer and from `nullptr` exists
2059
+ in `include/hermes/VM/Handle.h`. Check it, and use `.set(...)` if
2060
+ `operator=` takes a different type. In `promoteAll`, pass `arr.get()`,
2061
+ not `*arr`, to `inYoungGen`. The `weak.expired()` precondition fails if
2062
+ anything still roots the factory: fix the rooting, never the
2063
+ assertion.
2064
+
2065
+ - [ ] **Step 3: Run on the TSan tree**
2066
+
2067
+ ```bash
2068
+ cmake --build $R/cmake-build-tsan --target HermesVMRuntimeTests
2069
+ TSAN_OPTIONS=halt_on_error=1 \
2070
+ $R/cmake-build-tsan/unittests/VMRuntime/HermesVMRuntimeTests \
2071
+ --gtest_filter='RegExpBytecode*'
2072
+ ```
2073
+
2074
+ Expected: everything passes with no TSan report. Both concurrency tests
2075
+ RUN, not skip. If they skip, `kConcurrentGC` is false in this tree:
2076
+ report `grep HERMESVM_ALLOW_CONCURRENT_GC
2077
+ $R/cmake-build-tsan/CMakeCache.txt` and STOP.
2078
+
2079
+ Also run the same filter on `cmake-build-asan`, which has the concurrent
2080
+ GC too.
2081
+
2082
+ - [ ] **Step 4: Prove the guards can fail**
2083
+
2084
+ - **Case 1** (`ConcurrentReleaseWhileAcquiring`), on
2085
+ `cmake-build-tsan`:
2086
+ 1. Derive `RegExpBytecode` from `llvh::RefCountedBase<RegExpBytecode>`,
2087
+ whose count is not atomic.
2088
+ 2. Rebuild, and run the test up to 10 times. Expected: TSan reports a
2089
+ data race on `RefCount`.
2090
+ 3. Restore, rebuild, green.
2091
+
2092
+ If no run reports a race, say so plainly in the report, with the
2093
+ iteration counts tried. Do not change the test to force an outcome. A
2094
+ TSan guard that cannot be shown to fire is reported as such.
2095
+ - **Case 2** (`ConcurrentReleaseAfterModuleDeath`), on
2096
+ `cmake-build-asan`:
2097
+ 1. In `~RuntimeModule`, call `entry->Release()` once more per non-null
2098
+ entry (an over-release).
2099
+ 2. With 256 holders, the count starts at 257. After the extra release
2100
+ and the cache's own, 255 references remain for 256 holders, so the
2101
+ 255th finalizer frees the entry and the 256th touches freed memory.
2102
+ Expected: ASan reports a heap-use-after-free.
2103
+ 3. Restore, rebuild, green.
2104
+
2105
+ This shows the guard catches a lifetime error. It does not by itself
2106
+ show which thread ran the finalizer.
2107
+
2108
+ - [ ] **Step 5: Commit**
2109
+
2110
+ ```bash
2111
+ git -C $R add unittests/VMRuntime/RegExpBytecodeTest.cpp
2112
+ git -C $R commit # "VM: TSan guards for cached regexp bytecode release"
2113
+ ```
2114
+
2115
+ ---
2116
+
2117
+ ### Task 6: Cross-configuration verification, Delivered section, follow-up issue
2118
+
2119
+ **Files:**
2120
+ - Modify: `doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md`
2121
+ (append "Delivered")
2122
+ - Create: one `dz/issues/*.md` file, via `dz`
2123
+
2124
+ - [ ] **Step 1: Full suites**
2125
+
2126
+ ```bash
2127
+ for t in asan hsan hv32; do
2128
+ cmake --build $R/cmake-build-$t --target check-hermes
2129
+ done
2130
+ LIT_FILTER='jit/' cmake --build $R/cmake-build-asan --target check-hermes
2131
+ TSAN_OPTIONS=halt_on_error=1 \
2132
+ $R/cmake-build-tsan/unittests/VMRuntime/HermesVMRuntimeTests \
2133
+ --gtest_filter='RegExpBytecode*:HeapSnapshot*'
2134
+ ```
2135
+
2136
+ Expected: 0 failures everywhere (Review Focus 3 and 4). Record each
2137
+ tree's counts.
2138
+
2139
+ - [ ] **Step 2: File the follow-up**
2140
+
2141
+ Run `dz help agents` first. If `dz` is not on `PATH`, STOP and report;
2142
+ do not install it. Then create an issue:
2143
+ - **Title:** `SH units have no heap-snapshot node for their regexp cache`
2144
+ - **Body:** `sh_unit_additional_memory_size` counts the
2145
+ `SHUnitExt::regExpCache` vector and its entries. Because SH units have
2146
+ no native snapshot node, the entries appear in no heap snapshot. A unit
2147
+ node, with child nodes like `RuntimeModule::snapshotAddNodes`, would
2148
+ fix this. Cite `lib/VM/StaticHUnit.cpp` (the memory size function) and
2149
+ the spec's accounting section.
2150
+
2151
+ Add a component only if `dz` requires one (`dz component add` per
2152
+ CLAUDE.md).
2153
+
2154
+ - [ ] **Step 3: Delivered section**
2155
+
2156
+ Append `## Delivered (2026-10-26)` to the spec. It lists:
2157
+ - the commits of Tasks 1-5;
2158
+ - the per-tree suite counts;
2159
+ - each mutation and the failure it produced, including any TSan guard
2160
+ that could not be shown to fire;
2161
+ - every spec resolution taken (from the list below, plus any made during
2162
+ implementation);
2163
+ - the dz issue id.
2164
+
2165
+ - [ ] **Step 4: Commit**
2166
+
2167
+ ```bash
2168
+ git -C $R add doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md \
2169
+ dz/issues/<the new issue file>.md
2170
+ git -C $R commit # "Spec: record delivery of shared regexp bytecode"
2171
+ ```
2172
+
2173
+ ---
2174
+
2175
+ ## Spec resolutions (summary)
2176
+
2177
+ 1. `JSRegExp::getBytecodeEntry()` is added beside the spec's
2178
+ `getBytecode()`. Tests need the entry's ownership and `mallocSize()`
2179
+ (Task 1).
2180
+ 2. An `Exclusive` `JSRegExp` reports `mallocSize()`, which includes the
2181
+ entry header, where it previously reported the bare bytecode size
2182
+ (Task 1).
2183
+ 3. The trailing bytes are aligned to `alignof(std::max_align_t)`, as a
2184
+ malloc'd buffer is today (Task 1).
2185
+ 4. The SH cache is sized by `SHUnitExt(uint32_t numRegExps)` and read
2186
+ through `sh_unit_get_regexp_bytecode` (Task 4).
2187
+ 5. The new `SHUnit` fields follow `object_literal_class_cache` (Task 4).
2188
+ 6. T8 lives in `HeapSnapshotTest.cpp` to reuse its snapshot parsers
2189
+ (Task 3).
2190
+ 7. T6's mutation is a temporary borrowing variant of `RegExpBytecode`.
2191
+ It fails under ASan after the provider has expired (Task 2).
2192
+ 8. T8 reads the cache vector's capacity from its snapshot node, reached
2193
+ through the module's `regExpCache` edge, and checks the malloc
2194
+ estimate against it rather than assuming an exact capacity (Task 3).
2195
+ 9. Task 5's case 1 races the mutator's increments against concurrent
2196
+ finalizer decrements, and case 2 guards the last release after the
2197
+ module destructor. Each has its own mutation (Task 5).