@oxc-minify/binding-wasm32-wasi 0.151.0 → 0.153.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/minify.wasi-browser.js +450 -12
- package/minify.wasi.cjs +812 -15
- package/minify.wasi.d.cts +34 -1
- package/minify.wasm32-wasi.wasm +0 -0
- package/package.json +2 -2
- package/wasi-worker-browser.mjs +24 -0
- package/wasi-worker.mjs +167 -63
package/minify.wasi.cjs
CHANGED
|
@@ -139,7 +139,13 @@ function __createWasiWorker(filename) {
|
|
|
139
139
|
return new Worker(filename, {
|
|
140
140
|
env: process.env,
|
|
141
141
|
execArgv: __workerExecArgv,
|
|
142
|
-
workerData: {
|
|
142
|
+
workerData: {
|
|
143
|
+
hostRoot: __hostRoot,
|
|
144
|
+
rootDir: __rootDir,
|
|
145
|
+
crashFlag: __wasiThreadCrashFlag,
|
|
146
|
+
crashReport: __wasiThreadCrashReport,
|
|
147
|
+
addonCrashFlag: __wasiAddonCrashFlag,
|
|
148
|
+
},
|
|
143
149
|
})
|
|
144
150
|
} catch (error) {
|
|
145
151
|
if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
|
|
@@ -155,6 +161,300 @@ function __createWasiWorker(filename) {
|
|
|
155
161
|
}
|
|
156
162
|
}
|
|
157
163
|
|
|
164
|
+
// Set to 1 by a pool worker (see wasi-worker.mjs) right before it reports that
|
|
165
|
+
// its wasm thread died. Shared memory, so this thread reads it synchronously even
|
|
166
|
+
// while the worker's 'error' event is still queued behind the code that is
|
|
167
|
+
// exiting right now.
|
|
168
|
+
const __wasiThreadCrashFlag = new Int32Array(new SharedArrayBuffer(4))
|
|
169
|
+
// Written by the first pool worker whose wasm thread dies, before it raises the
|
|
170
|
+
// flag: its error and `threadId` (layout in wasi-worker.mjs). Read without
|
|
171
|
+
// waiting for any event, see `__readWasiThreadCrashReport`.
|
|
172
|
+
const __wasiThreadCrashReport = new SharedArrayBuffer(4096)
|
|
173
|
+
let __wasiThreadCrashReportRead
|
|
174
|
+
// The first error a pool worker reported through its 'error' event, and that
|
|
175
|
+
// worker's `threadId`. See `__getWasiThreadCrashError`.
|
|
176
|
+
let __wasiThreadCrashWorkerError
|
|
177
|
+
let __wasiThreadCrashWorkerId
|
|
178
|
+
let __wasiThreadCrashError
|
|
179
|
+
// Raised while `__runWasiInitializationRollbackSteps` runs, so its polls and
|
|
180
|
+
// steps stop after a crash the way a public disposal's do.
|
|
181
|
+
let __wasiInitializationRollbackActive = false
|
|
182
|
+
let __wasiThreadCrashed = false
|
|
183
|
+
|
|
184
|
+
// A view of the addon's crash flag, one word of the shared wasm memory, for the
|
|
185
|
+
// pool workers: they raise it when their wasm thread dies, and the shutdown
|
|
186
|
+
// waits inside the cleanup calls on this thread then trap instead of waiting on
|
|
187
|
+
// the dead thread for good. Undefined for an addon built with an older napi.
|
|
188
|
+
let __wasiAddonCrashFlag
|
|
189
|
+
|
|
190
|
+
function __captureWasiAddonCrashFlag(instance) {
|
|
191
|
+
try {
|
|
192
|
+
const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
|
|
193
|
+
if (typeof getAddress !== 'function') {
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
const address = getAddress() >>> 0
|
|
197
|
+
const buffer = __sharedMemory.buffer
|
|
198
|
+
if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
__wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
|
|
202
|
+
} catch {}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Whether any wasm thread of this binding has died: a trap or an uncaught error
|
|
207
|
+
* in a pool worker, including one that failed to load after its thread spawn
|
|
208
|
+
* had already been reported as started.
|
|
209
|
+
*
|
|
210
|
+
* After that the shared wasm state cannot be trusted: a lock the dead thread
|
|
211
|
+
* held stays held, and a join or park that waits on it — the async runtime's
|
|
212
|
+
* `finish_shutdown` waiting for the dead thread's work to go idle — blocks
|
|
213
|
+
* this thread forever in a raw `memory.atomic.wait32`, which neither
|
|
214
|
+
* emnapi's crash check nor a signal can interrupt.
|
|
215
|
+
*/
|
|
216
|
+
function __hasWasiThreadCrashed() {
|
|
217
|
+
if (__wasiThreadCrashed || Atomics.load(__wasiThreadCrashFlag, 0) !== 0) {
|
|
218
|
+
return true
|
|
219
|
+
}
|
|
220
|
+
const manager = __getWasiThreadManager()
|
|
221
|
+
return Boolean(manager && manager._fatalError)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
let __wasiThreadCrashDisposePromise
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Stores the first error a pool worker reported, with the worker's id. Called
|
|
228
|
+
* from the loader's own 'error' listener, which runs before emnapi's.
|
|
229
|
+
*/
|
|
230
|
+
function __recordWasiThreadCrashError(error, workerId) {
|
|
231
|
+
if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
|
|
232
|
+
return
|
|
233
|
+
}
|
|
234
|
+
__wasiThreadCrashWorkerError = error
|
|
235
|
+
__wasiThreadCrashWorkerId = workerId
|
|
236
|
+
__fillWasiThreadCrashError()
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The error in the shared crash report, rebuilt once it is complete: the
|
|
241
|
+
* worker writes it before it raises the flag, so it is there as soon as the
|
|
242
|
+
* crash is seen. Plain JavaScript over shared memory; never enters wasm.
|
|
243
|
+
*/
|
|
244
|
+
function __readWasiThreadCrashReport() {
|
|
245
|
+
if (__wasiThreadCrashReportRead !== undefined) {
|
|
246
|
+
return __wasiThreadCrashReportRead
|
|
247
|
+
}
|
|
248
|
+
try {
|
|
249
|
+
const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
|
|
250
|
+
if (Atomics.load(header, 0) !== 2) {
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
const length = Atomics.load(header, 1)
|
|
254
|
+
const threadId = Atomics.load(header, 2)
|
|
255
|
+
let error
|
|
256
|
+
if (length > 0) {
|
|
257
|
+
// Copied out of shared memory: TextDecoder does not take a shared view.
|
|
258
|
+
const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
|
|
259
|
+
const report = JSON.parse(new TextDecoder().decode(bytes))
|
|
260
|
+
error = new Error(String(report.message))
|
|
261
|
+
if (typeof report.name === 'string') {
|
|
262
|
+
error.name = report.name
|
|
263
|
+
}
|
|
264
|
+
if (typeof report.stack === 'string') {
|
|
265
|
+
error.stack = report.stack
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
__wasiThreadCrashReportRead = { error, threadId }
|
|
269
|
+
} catch {
|
|
270
|
+
__wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
|
|
271
|
+
}
|
|
272
|
+
return __wasiThreadCrashReportRead
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The one error every crash path of this binding reports, created on first
|
|
277
|
+
* use.
|
|
278
|
+
*
|
|
279
|
+
* The shared flag is raised before this thread has processed the worker's
|
|
280
|
+
* 'error' event, and once the workers are terminated that event is often
|
|
281
|
+
* never delivered, so neither it nor emnapi's `_fatalError` can be counted
|
|
282
|
+
* on. The cause is filled in from the first source that has it: the error the
|
|
283
|
+
* 'error' listener kept, else the worker's shared crash report, else
|
|
284
|
+
* `_fatalError` — here, and again from the 'error' listener when it arrives
|
|
285
|
+
* later. Until then the error carries only its message.
|
|
286
|
+
*/
|
|
287
|
+
function __getWasiThreadCrashError() {
|
|
288
|
+
if (__wasiThreadCrashError === undefined) {
|
|
289
|
+
__wasiThreadCrashError = new Error(
|
|
290
|
+
'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
|
|
291
|
+
)
|
|
292
|
+
}
|
|
293
|
+
__fillWasiThreadCrashError()
|
|
294
|
+
return __wasiThreadCrashError
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function __fillWasiThreadCrashError() {
|
|
298
|
+
const crashError = __wasiThreadCrashError
|
|
299
|
+
if (crashError === undefined) {
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
if (crashError.cause === undefined) {
|
|
304
|
+
let cause = __wasiThreadCrashWorkerError
|
|
305
|
+
if (cause === undefined) {
|
|
306
|
+
const report = __readWasiThreadCrashReport()
|
|
307
|
+
cause = report ? report.error : undefined
|
|
308
|
+
}
|
|
309
|
+
if (cause === undefined) {
|
|
310
|
+
const manager = __getWasiThreadManager()
|
|
311
|
+
cause = manager ? manager._fatalError : undefined
|
|
312
|
+
}
|
|
313
|
+
if (cause !== undefined && cause !== null) {
|
|
314
|
+
crashError.cause = cause
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (crashError.workerThreadId === undefined) {
|
|
318
|
+
let workerId = __wasiThreadCrashWorkerId
|
|
319
|
+
if (workerId === undefined) {
|
|
320
|
+
const report = __readWasiThreadCrashReport()
|
|
321
|
+
workerId = report && report.threadId > 0 ? report.threadId : undefined
|
|
322
|
+
}
|
|
323
|
+
if (workerId !== undefined) {
|
|
324
|
+
crashError.workerThreadId = workerId
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
} catch {}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Let the event loop drain after a wasm thread died, without entering wasm.
|
|
332
|
+
*
|
|
333
|
+
* emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
|
|
334
|
+
* `MessagePort` (`refCounter.refHandle`) that it refs when the count of
|
|
335
|
+
* in-flight async work and threadsafe-function requests leaves zero and unrefs
|
|
336
|
+
* when it comes back. The requests the dead thread held never complete, so the
|
|
337
|
+
* count never returns to zero and the port holds the process open for good.
|
|
338
|
+
* `Context.destroy()` would not release it either — and it runs cleanup
|
|
339
|
+
* hooks, which is exactly what must not happen now. So unref the port directly.
|
|
340
|
+
* The count is left as is: it stays above zero, so a later request never refs
|
|
341
|
+
* the port again.
|
|
342
|
+
*
|
|
343
|
+
* The field is private in emnapi's typings, so read it defensively; a context
|
|
344
|
+
* without it (a non-Node host, a future emnapi) is left alone.
|
|
345
|
+
*/
|
|
346
|
+
function __releaseEmnapiWaitingRequestHandle() {
|
|
347
|
+
try {
|
|
348
|
+
const refCounter = __emnapiContext && __emnapiContext.refCounter
|
|
349
|
+
const refHandle = refCounter && refCounter.refHandle
|
|
350
|
+
if (refHandle && typeof refHandle.unref === 'function') {
|
|
351
|
+
refHandle.unref()
|
|
352
|
+
}
|
|
353
|
+
} catch {}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* The public disposer after a wasm thread died. The normal chain drains async
|
|
358
|
+
* work, runs the environment cleanup barrier and destroys the context — every
|
|
359
|
+
* one of those re-enters wasm, and the barrier's shutdown waits for the dead
|
|
360
|
+
* thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
|
|
361
|
+
* avoids. An app that handled the worker's error and then disposes would block
|
|
362
|
+
* there for good. Only stop the workers, then reject: the binding was not
|
|
363
|
+
* cleaned up and cannot be, so reporting success would be a lie. The context
|
|
364
|
+
* is not destroyed — only its waiting-request port is unrefed, so the process
|
|
365
|
+
* can exit on its own — and the 'exit' listener takes its short path too.
|
|
366
|
+
*
|
|
367
|
+
* Latched: every later call returns the same promise.
|
|
368
|
+
*/
|
|
369
|
+
function __disposeWasiBindingAfterThreadCrash() {
|
|
370
|
+
if (__wasiThreadCrashDisposePromise) {
|
|
371
|
+
return __wasiThreadCrashDisposePromise
|
|
372
|
+
}
|
|
373
|
+
__releaseEmnapiWaitingRequestHandle()
|
|
374
|
+
let workerResult
|
|
375
|
+
try {
|
|
376
|
+
workerResult = __terminateWasiWorkers()
|
|
377
|
+
} catch (terminateError) {
|
|
378
|
+
workerResult = Promise.reject(terminateError)
|
|
379
|
+
}
|
|
380
|
+
// Built at settlement, after the workers stopped: by then the 'error' event
|
|
381
|
+
// has usually delivered the worker's error.
|
|
382
|
+
__wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
|
|
383
|
+
() => {
|
|
384
|
+
throw __getWasiThreadCrashError()
|
|
385
|
+
},
|
|
386
|
+
(terminateError) => {
|
|
387
|
+
throw __attachCleanupErrors(__getWasiThreadCrashError(), [
|
|
388
|
+
terminateError,
|
|
389
|
+
])
|
|
390
|
+
},
|
|
391
|
+
)
|
|
392
|
+
return __wasiThreadCrashDisposePromise
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Stops a public disposal that a thread crash overtook.
|
|
397
|
+
*
|
|
398
|
+
* The check at the top of `__disposeWasiBinding` only sees a crash that came
|
|
399
|
+
* first. A thread that dies once the chain is running leaves it polling for
|
|
400
|
+
* work the dead thread still counts — the async-work drain for
|
|
401
|
+
* `napi_wasm_async_work_pending`, the barrier's poll for
|
|
402
|
+
* `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
|
|
403
|
+
* the poll's referenced timers keep the process alive forever with the
|
|
404
|
+
* disposal promise pending. Each poll turn and each step boundary calls this,
|
|
405
|
+
* and the throw ends the chain before anything re-enters wasm again; the
|
|
406
|
+
* disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
|
|
407
|
+
*
|
|
408
|
+
* The initialization rollback runs the same polls and steps, so they stop while
|
|
409
|
+
* it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
|
|
410
|
+
* through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
|
|
411
|
+
* neither in flight is left alone.
|
|
412
|
+
*/
|
|
413
|
+
function __abortWasiDisposalIfThreadCrashed() {
|
|
414
|
+
if (
|
|
415
|
+
(__wasiDisposePromise !== undefined ||
|
|
416
|
+
__wasiInitializationRollbackActive) &&
|
|
417
|
+
__hasWasiThreadCrashed()
|
|
418
|
+
) {
|
|
419
|
+
throw new Error(
|
|
420
|
+
'napi-rs: WASI disposal stopped because a worker thread crashed',
|
|
421
|
+
)
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Settles an in-flight public disposal whose chain failed after a thread
|
|
427
|
+
* died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
|
|
428
|
+
* way — through the crash disposal: it releases the waiting-request port,
|
|
429
|
+
* terminates the workers and rejects with the same error an entry-time crash
|
|
430
|
+
* gets. `__wasiDisposePromise` stays set, so this caller, every caller that
|
|
431
|
+
* joined it and every later one hold the same promise. Returns false when no
|
|
432
|
+
* thread died, leaving the ordinary failure handling alone.
|
|
433
|
+
*/
|
|
434
|
+
function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
|
|
435
|
+
if (!__hasWasiThreadCrashed()) {
|
|
436
|
+
return false
|
|
437
|
+
}
|
|
438
|
+
__disposeWasiBindingAfterThreadCrash().then(resolve, reject)
|
|
439
|
+
return true
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Ends an initialization rollback after a wasm thread died, without entering
|
|
444
|
+
* wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
|
|
445
|
+
* crash disposal releases the waiting-request port and terminates the workers,
|
|
446
|
+
* once. The initialization error itself is left to propagate: the crash error
|
|
447
|
+
* is returned as the rollback's cleanup error, so
|
|
448
|
+
* `__completeWasiInitializationRollback` attaches it — as the cause when the
|
|
449
|
+
* error has none — and keeps the record, since the context was not destroyed.
|
|
450
|
+
*/
|
|
451
|
+
function __rollbackWasiInitializationAfterThreadCrash() {
|
|
452
|
+
const crashError = __getWasiThreadCrashError()
|
|
453
|
+
// Its rejection is `crashError` itself, which the caller reports.
|
|
454
|
+
void __disposeWasiBindingAfterThreadCrash().catch(() => {})
|
|
455
|
+
return [crashError]
|
|
456
|
+
}
|
|
457
|
+
|
|
158
458
|
const __cwd = process.cwd()
|
|
159
459
|
const __rootDir = __nodePath.parse(__cwd).root
|
|
160
460
|
const __hostRoot =
|
|
@@ -233,6 +533,20 @@ let __emnapiContextDestroyed = false
|
|
|
233
533
|
let __emnapiContextDestroyPromise
|
|
234
534
|
let __emnapiWasmEnvCleanupPrepared = false
|
|
235
535
|
let __emnapiWasmEnvCleanupPreparing = false
|
|
536
|
+
// The closer for a barrier that is parked between `…_begin` and `…_finish`,
|
|
537
|
+
// set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
|
|
538
|
+
// tell those two apart on its own: it is raised both for a purely synchronous
|
|
539
|
+
// frame — which must not be re-entered, and which nothing outside it can
|
|
540
|
+
// finish — and across this window, which spans real event-loop turns, so a
|
|
541
|
+
// caller that cannot yield can land in the middle of one. That caller can close
|
|
542
|
+
// this window, because `…_finish` is idempotent and joins, which is exactly
|
|
543
|
+
// what the single call does. See `__prepareWasmEnvCleanup`.
|
|
544
|
+
let __finishParkedWasmEnvCleanup
|
|
545
|
+
// Raised while a caller that can still yield is driving the barrier, so the
|
|
546
|
+
// queue it leaves behind is expected rather than lost. See
|
|
547
|
+
// `__reportUnreachedWasmEnvSettlements`.
|
|
548
|
+
let __emnapiWasmEnvCleanupYielding = false
|
|
549
|
+
let __emnapiWasmEnvSettlementLossReported = false
|
|
236
550
|
let __emnapiWasmEnvCleanupRan = false
|
|
237
551
|
let __emnapiWasmEnvCleanupDrained = false
|
|
238
552
|
let __emnapiWasmEnvCleanupDrainPromise
|
|
@@ -345,7 +659,24 @@ function __isPreparingWasmEnvCleanup() {
|
|
|
345
659
|
}
|
|
346
660
|
|
|
347
661
|
function __prepareWasmEnvCleanup() {
|
|
348
|
-
if (__emnapiWasmEnvCleanupPrepared
|
|
662
|
+
if (__emnapiWasmEnvCleanupPrepared) {
|
|
663
|
+
return
|
|
664
|
+
}
|
|
665
|
+
// A handshake parked between its two halves is one this frame can close, and
|
|
666
|
+
// must: every caller of this function is about to destroy the context, and
|
|
667
|
+
// the turns the poll is waiting for will not come — an 'exit' teardown is
|
|
668
|
+
// the last thing the process runs, and `Context.destroy()` takes the
|
|
669
|
+
// environment away. Closing it here runs `…_finish`, which is the call that joins, so
|
|
670
|
+
// this degrades to exactly the single call below. Leaving it open instead
|
|
671
|
+
// destroys the context with the barrier still raised, the runtime never
|
|
672
|
+
// joined and the workers never drained.
|
|
673
|
+
const finishParked = __finishParkedWasmEnvCleanup
|
|
674
|
+
if (finishParked !== undefined) {
|
|
675
|
+
finishParked()
|
|
676
|
+
__reportUnreachedWasmEnvSettlements()
|
|
677
|
+
return
|
|
678
|
+
}
|
|
679
|
+
if (__emnapiWasmEnvCleanupPreparing) {
|
|
349
680
|
return
|
|
350
681
|
}
|
|
351
682
|
const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
|
|
@@ -360,10 +691,57 @@ function __prepareWasmEnvCleanup() {
|
|
|
360
691
|
__emnapiWasmEnvCleanupPreparing = false
|
|
361
692
|
}
|
|
362
693
|
__emnapiWasmEnvCleanupRan = true
|
|
694
|
+
__reportUnreachedWasmEnvSettlements()
|
|
363
695
|
}
|
|
364
696
|
__emnapiWasmEnvCleanupPrepared = true
|
|
365
697
|
}
|
|
366
698
|
|
|
699
|
+
/**
|
|
700
|
+
* Say so when the barrier leaves settlements queued and nothing is left that
|
|
701
|
+
* could deliver them.
|
|
702
|
+
*
|
|
703
|
+
* Only the disposal chain yields the event-loop turns @emnapi/core needs to
|
|
704
|
+
* dispatch its queue. Every other caller of the barrier destroys in the same
|
|
705
|
+
* turn — a raw `Context.destroy()`, the 'exit' teardown — and
|
|
706
|
+
* `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
|
|
707
|
+
* that queue with a null env and discards it. The promises those settlements
|
|
708
|
+
* were for then hang forever, silently.
|
|
709
|
+
*
|
|
710
|
+
* Loud, once, and never throwing: this runs from inside `Context.destroy()`,
|
|
711
|
+
* emnapi's own beforeExit destroy included, where throwing would take the whole
|
|
712
|
+
* teardown down with it. Destroying anyway is still the right trade — the queue
|
|
713
|
+
* is already unreachable by then.
|
|
714
|
+
*/
|
|
715
|
+
function __reportUnreachedWasmEnvSettlements() {
|
|
716
|
+
if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
|
|
717
|
+
return
|
|
718
|
+
}
|
|
719
|
+
const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
|
|
720
|
+
if (typeof pending !== 'function') {
|
|
721
|
+
return
|
|
722
|
+
}
|
|
723
|
+
let queued
|
|
724
|
+
try {
|
|
725
|
+
queued = pending()
|
|
726
|
+
} catch {
|
|
727
|
+
return
|
|
728
|
+
}
|
|
729
|
+
if (!queued) {
|
|
730
|
+
return
|
|
731
|
+
}
|
|
732
|
+
__emnapiWasmEnvSettlementLossReported = true
|
|
733
|
+
try {
|
|
734
|
+
const consoleHost = globalThis.console
|
|
735
|
+
if (consoleHost && typeof consoleHost.error === 'function') {
|
|
736
|
+
consoleHost.error(
|
|
737
|
+
"napi-rs: the wasm environment is being destroyed with " +
|
|
738
|
+
queued +
|
|
739
|
+
" queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.",
|
|
740
|
+
)
|
|
741
|
+
}
|
|
742
|
+
} catch {}
|
|
743
|
+
}
|
|
744
|
+
|
|
367
745
|
// Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
|
|
368
746
|
// on, so the drain turns below interleave with that dispatch instead of racing
|
|
369
747
|
// ahead of it on a faster queue.
|
|
@@ -413,6 +791,301 @@ function __scheduleTimer(callback, delay) {
|
|
|
413
791
|
}
|
|
414
792
|
}
|
|
415
793
|
|
|
794
|
+
// A real, referenced timer rather than a zero-delay macrotask, for the same
|
|
795
|
+
// reason the async-work drain uses one: this polls the addon instead of
|
|
796
|
+
// interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
|
|
797
|
+
// the loop instead of yielding it.
|
|
798
|
+
const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
|
|
799
|
+
// Arrivals it takes before the poll paces on the host's timers alone. One
|
|
800
|
+
// proves nothing: a timer armed before the host's timers stopped still fires.
|
|
801
|
+
const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
|
|
802
|
+
// How long a parked turn's own timer must already have been due before a
|
|
803
|
+
// backup that runs calls it dropped. Slack, not a deadline: a timer is due
|
|
804
|
+
// against the event loop's clock, which is read once per iteration, while
|
|
805
|
+
// these are `Date.now()` readings taken part-way through one, so the two
|
|
806
|
+
// drift apart by however long the loop has been inside the current iteration.
|
|
807
|
+
const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
|
|
808
|
+
// How long a backup itself waits. What is left of it after the slack and one
|
|
809
|
+
// interval — 149 ms — has to cover the *two* poll turns that can separate a
|
|
810
|
+
// parked turn from the last backup armed while the host's timers still
|
|
811
|
+
// worked, so the ceiling on a single turn is half of it. See the invariant on
|
|
812
|
+
// `__armWasmRuntimePollStallBackup`.
|
|
813
|
+
const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Pacing state for one runtime-work poll.
|
|
817
|
+
*
|
|
818
|
+
* Per poll, never per module: whether the host's timers arrive is not a
|
|
819
|
+
* property of the module. A host can lose its timers between two disposals,
|
|
820
|
+
* and in the deferred shape every instance shares this module — one healthy
|
|
821
|
+
* instance must not disarm the fallback for the next one.
|
|
822
|
+
*/
|
|
823
|
+
function __createWasmRuntimePollPace() {
|
|
824
|
+
return {
|
|
825
|
+
// Timers armed by *this* poll that have actually arrived.
|
|
826
|
+
arrivals: 0,
|
|
827
|
+
// The turn waiting on a timer alone *right now* — undefined whenever no
|
|
828
|
+
// turn is parked — and when that turn's own timer came due.
|
|
829
|
+
settleTurn: undefined,
|
|
830
|
+
turnTimerDueAt: 0,
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* The backup that ends a turn whose timer is never going to arrive.
|
|
836
|
+
*
|
|
837
|
+
* Once the poll paces on the timer alone it has nothing left to fall back on
|
|
838
|
+
* if the host's timers stop mid-poll: the turn that armed the dead timer is
|
|
839
|
+
* the turn that parks, and a parked poll schedules nothing that could notice.
|
|
840
|
+
* So every turn arms one of these before it yields, and each one compares due
|
|
841
|
+
* times instead of measuring how long the parked turn has been waiting.
|
|
842
|
+
*
|
|
843
|
+
* Invariant: a parked turn is ended by the newest backup that was armed while
|
|
844
|
+
* the host's timers still worked, and a backup ends a turn only when that
|
|
845
|
+
* turn's own timer was already due a whole window before the backup itself.
|
|
846
|
+
* Neither half turns on how far apart the arms happen to fall — what bounds
|
|
847
|
+
* the rescue is how far back that newest live backup is:
|
|
848
|
+
*
|
|
849
|
+
* - *Ends it.* Hosts run timers in due order, so a backup that runs while a
|
|
850
|
+
* turn due a whole window earlier is still parked proves that turn's timer
|
|
851
|
+
* was dropped rather than merely late. That same comparison is what leaves a
|
|
852
|
+
* healthy host alone: there the turn's timer has already run and cleared
|
|
853
|
+
* `settleTurn` before any backup due after it can look.
|
|
854
|
+
* - *Two turns back, not one.* A turn that ended does not prove its own timer
|
|
855
|
+
* arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
|
|
856
|
+
* primitives and the macrotask wins, so such a turn can end with its own
|
|
857
|
+
* timer — and the backup armed one line before it — already dead. The
|
|
858
|
+
* arrival that then flips the poll onto the timer alone can itself be a
|
|
859
|
+
* timer armed before the host's timers died. So the turn that parks can sit
|
|
860
|
+
* two turns past the last live arm, and the newest live backup is due
|
|
861
|
+
* `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
|
|
862
|
+
* Arming on every turn is what holds it to two, rather than however far back
|
|
863
|
+
* a throttle last let one through.
|
|
864
|
+
* - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
|
|
865
|
+
* inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
|
|
866
|
+
* per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
|
|
867
|
+
* Past that the turn stays parked and the disposal promise never settles.
|
|
868
|
+
* The bound is deliberate: reaching it takes a host that drops timers
|
|
869
|
+
* mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
|
|
870
|
+
* Node nor WebContainer — the hosts that run the threaded artifact — does
|
|
871
|
+
* the second.
|
|
872
|
+
*
|
|
873
|
+
* The poll then goes back to arming both primitives until two fresh arrivals
|
|
874
|
+
* prove the timers again. A host that stops running the timers it has
|
|
875
|
+
* *already* accepted leaves nothing to fire, and the disposal promise stays
|
|
876
|
+
* pending rather than wedging the thread — the same outcome as a blocking
|
|
877
|
+
* closure that never returns. Unreferenced wherever the host allows it: the
|
|
878
|
+
* poll's own turn timers are what keep the loop alive, never these.
|
|
879
|
+
*/
|
|
880
|
+
function __armWasmRuntimePollStallBackup(pace) {
|
|
881
|
+
const setTimer = globalThis.setTimeout
|
|
882
|
+
if (typeof setTimer !== 'function') {
|
|
883
|
+
// Nothing to back up: `__scheduleTimer` is on the macrotask channel
|
|
884
|
+
// already, and that one cannot park.
|
|
885
|
+
return
|
|
886
|
+
}
|
|
887
|
+
// Read before arming, so this never claims to be due earlier than the timer
|
|
888
|
+
// actually is: a backup ends a turn only when it is provably due after it.
|
|
889
|
+
const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
|
|
890
|
+
let handle
|
|
891
|
+
try {
|
|
892
|
+
handle = setTimer(() => {
|
|
893
|
+
const settleTurn = pace.settleTurn
|
|
894
|
+
if (
|
|
895
|
+
!settleTurn ||
|
|
896
|
+
pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
|
|
897
|
+
) {
|
|
898
|
+
// No turn is parked, or the parked one's timer came due too close to
|
|
899
|
+
// this backup to call it dropped — it may still arrive, and the turn
|
|
900
|
+
// that armed it armed a backup due a whole window after *that*.
|
|
901
|
+
return
|
|
902
|
+
}
|
|
903
|
+
pace.arrivals = 0
|
|
904
|
+
pace.settleTurn = undefined
|
|
905
|
+
settleTurn()
|
|
906
|
+
}, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
|
|
907
|
+
} catch {
|
|
908
|
+
return
|
|
909
|
+
}
|
|
910
|
+
if (handle && typeof handle.unref === 'function') {
|
|
911
|
+
try {
|
|
912
|
+
handle.unref()
|
|
913
|
+
} catch {}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* One turn of the runtime-work poll.
|
|
919
|
+
*
|
|
920
|
+
* `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
|
|
921
|
+
* missing or throws, but not when it is present, returns a handle and never
|
|
922
|
+
* fires — fake timers in a test suite that disposes from an `afterEach`, or a
|
|
923
|
+
* host whose timers belong to an IO context that is already gone. That host
|
|
924
|
+
* would park this poll forever, and the poll is unbounded, so nothing would
|
|
925
|
+
* ever call `…_finish`.
|
|
926
|
+
*
|
|
927
|
+
* Arm both primitives until timers armed by this poll have arrived twice, and
|
|
928
|
+
* let whichever lands first end the turn; the loser resolves nothing. A host
|
|
929
|
+
* with working timers therefore pays the double arming for the first turn or
|
|
930
|
+
* two — the macrotask wins the race, but the timers behind it still arrive and
|
|
931
|
+
* are counted — and paces on the timer alone from then on, instead of spinning
|
|
932
|
+
* the loop on a zero-delay queue. A host whose timers never arrive keeps both,
|
|
933
|
+
* and the macrotask is what keeps the poll moving. A host whose timers stop
|
|
934
|
+
* after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
|
|
935
|
+
* which ends the parked turn and puts this poll back on both.
|
|
936
|
+
*/
|
|
937
|
+
function __yieldWasmRuntimePollTurn(pace) {
|
|
938
|
+
// Armed before the turn yields, and by every turn: what rescues a parked
|
|
939
|
+
// turn has to have been armed while the host's timers still worked, and the
|
|
940
|
+
// turn that parks is the one whose own timer is already dead.
|
|
941
|
+
__armWasmRuntimePollStallBackup(pace)
|
|
942
|
+
return new Promise((resolve) => {
|
|
943
|
+
let settled = false
|
|
944
|
+
const settle = () => {
|
|
945
|
+
if (settled) {
|
|
946
|
+
return
|
|
947
|
+
}
|
|
948
|
+
settled = true
|
|
949
|
+
if (pace.settleTurn === settle) {
|
|
950
|
+
// Nothing is parked any more: a backup running later must not read a
|
|
951
|
+
// due time this turn has already answered.
|
|
952
|
+
pace.settleTurn = undefined
|
|
953
|
+
}
|
|
954
|
+
resolve()
|
|
955
|
+
}
|
|
956
|
+
__scheduleTimer(() => {
|
|
957
|
+
pace.arrivals++
|
|
958
|
+
settle()
|
|
959
|
+
}, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
|
|
960
|
+
// Read next to the arming it describes; see
|
|
961
|
+
// `__armWasmRuntimePollStallBackup` for what the two due times mean.
|
|
962
|
+
const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
|
|
963
|
+
if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
|
|
964
|
+
__scheduleMacrotask(settle)
|
|
965
|
+
return
|
|
966
|
+
}
|
|
967
|
+
// Paced by the timer alone from here; the backup is what ends this turn if
|
|
968
|
+
// the timer never arrives.
|
|
969
|
+
pace.settleTurn = settle
|
|
970
|
+
pace.turnTimerDueAt = turnTimerDueAt
|
|
971
|
+
})
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
|
|
976
|
+
* event-loop turns in the middle.
|
|
977
|
+
*
|
|
978
|
+
* `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
|
|
979
|
+
* async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
|
|
980
|
+
* waits on is this one, the only thread that can give a running blocking
|
|
981
|
+
* closure the JavaScript turn *it* is waiting for. A single call there can wait
|
|
982
|
+
* for work that can never finish. The addon's two-phase form splits that:
|
|
983
|
+
* `…_begin` stops the runtime without joining and reports whether anything is
|
|
984
|
+
* still live, `napi_wasm_runtime_work_pending` answers that question again
|
|
985
|
+
* without blocking, and `…_finish` joins. The turns yielded in between are the
|
|
986
|
+
* entire point.
|
|
987
|
+
*
|
|
988
|
+
* The poll has no deadline, for the same reason the async-work drain below has
|
|
989
|
+
* none: giving up means calling `…_finish`, which joins on this thread, and the
|
|
990
|
+
* work it would join is the work that is waiting for a turn from this thread —
|
|
991
|
+
* so a bound does not end the wait, it only moves it somewhere the JavaScript
|
|
992
|
+
* thread can no longer be reached. A blocking closure that never returns keeps
|
|
993
|
+
* the disposal promise pending instead, exactly as a task whose `execute` never
|
|
994
|
+
* returns already keeps an *undisposed* process alive. The host contract is in
|
|
995
|
+
* `crates/async-runtime/README.md`: a blocking closure must never wait on a
|
|
996
|
+
* JavaScript turn. The process-exit path still blocks in `…_finish`, because it
|
|
997
|
+
* has no turns left to give (see `__prepareWasmEnvCleanup`).
|
|
998
|
+
*
|
|
999
|
+
* Feature-detected like every other export in this teardown, so an addon built
|
|
1000
|
+
* against a napi crate that predates the split keeps the single blocking call.
|
|
1001
|
+
* Returns nothing whenever the handshake finished without yielding, which keeps
|
|
1002
|
+
* an idle disposal synchronous.
|
|
1003
|
+
*/
|
|
1004
|
+
function __prepareWasmEnvCleanupWithTurns() {
|
|
1005
|
+
if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
|
|
1006
|
+
return
|
|
1007
|
+
}
|
|
1008
|
+
const exports = __napiInstance?.exports
|
|
1009
|
+
const begin = exports?.napi_prepare_wasm_env_cleanup_begin
|
|
1010
|
+
const finish = exports?.napi_prepare_wasm_env_cleanup_finish
|
|
1011
|
+
if (typeof begin !== 'function' || typeof finish !== 'function') {
|
|
1012
|
+
// No split to use. The settlement drain still follows this, so the queue
|
|
1013
|
+
// the single call leaves behind is expected rather than lost.
|
|
1014
|
+
__emnapiWasmEnvCleanupYielding = true
|
|
1015
|
+
try {
|
|
1016
|
+
__prepareWasmEnvCleanup()
|
|
1017
|
+
} finally {
|
|
1018
|
+
__emnapiWasmEnvCleanupYielding = false
|
|
1019
|
+
}
|
|
1020
|
+
return
|
|
1021
|
+
}
|
|
1022
|
+
const workPending = exports?.napi_wasm_runtime_work_pending
|
|
1023
|
+
// The in-flight flag stays raised across the turns below, so a `destroy()`
|
|
1024
|
+
// from one of the JavaScript handlers they run is the same no-op it is inside
|
|
1025
|
+
// the single call: the barrier is up and the runtime is mid-teardown, and
|
|
1026
|
+
// destroying between the halves would strand exactly what this delivers.
|
|
1027
|
+
__emnapiWasmEnvCleanupPreparing = true
|
|
1028
|
+
let live
|
|
1029
|
+
try {
|
|
1030
|
+
live = begin()
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
__emnapiWasmEnvCleanupPreparing = false
|
|
1033
|
+
throw error
|
|
1034
|
+
}
|
|
1035
|
+
__emnapiWasmEnvCleanupRan = true
|
|
1036
|
+
const finishCleanup = () => {
|
|
1037
|
+
if (__emnapiWasmEnvCleanupPrepared) {
|
|
1038
|
+
// Already closed by a caller that could not yield — the 'exit' teardown
|
|
1039
|
+
// reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
|
|
1040
|
+
// is idempotent, but the flags it lowers are not: running it again here
|
|
1041
|
+
// would clear a `preparing` some later barrier had raised.
|
|
1042
|
+
return
|
|
1043
|
+
}
|
|
1044
|
+
__finishParkedWasmEnvCleanup = undefined
|
|
1045
|
+
try {
|
|
1046
|
+
finish()
|
|
1047
|
+
} finally {
|
|
1048
|
+
__emnapiWasmEnvCleanupPreparing = false
|
|
1049
|
+
}
|
|
1050
|
+
__emnapiWasmEnvCleanupPrepared = true
|
|
1051
|
+
}
|
|
1052
|
+
if (!live || typeof workPending !== 'function') {
|
|
1053
|
+
finishCleanup()
|
|
1054
|
+
return
|
|
1055
|
+
}
|
|
1056
|
+
// Publish the closer before yielding: from here until `finishCleanup` runs,
|
|
1057
|
+
// a caller that cannot yield is entitled to end this handshake itself.
|
|
1058
|
+
__finishParkedWasmEnvCleanup = finishCleanup
|
|
1059
|
+
const finishCleanupUnlessCrashed = () => {
|
|
1060
|
+
try {
|
|
1061
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
1062
|
+
} catch (error) {
|
|
1063
|
+
__finishParkedWasmEnvCleanup = undefined
|
|
1064
|
+
throw error
|
|
1065
|
+
}
|
|
1066
|
+
finishCleanup()
|
|
1067
|
+
}
|
|
1068
|
+
return (async () => {
|
|
1069
|
+
// Unbounded, exactly like the async-work drain below. The wait ends when
|
|
1070
|
+
// the addon reports its runtime work finished; the turns spent here are
|
|
1071
|
+
// what let that happen at all.
|
|
1072
|
+
const pace = __createWasmRuntimePollPace()
|
|
1073
|
+
for (;;) {
|
|
1074
|
+
await __yieldWasmRuntimePollTurn(pace)
|
|
1075
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
1076
|
+
try {
|
|
1077
|
+
if (!workPending()) {
|
|
1078
|
+
return
|
|
1079
|
+
}
|
|
1080
|
+
} catch {
|
|
1081
|
+
// A trap is the only way this fails, and a trapped instance has no
|
|
1082
|
+
// reachable work left. Stop polling and finish.
|
|
1083
|
+
return
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
})().then(finishCleanupUnlessCrashed, finishCleanupUnlessCrashed)
|
|
1087
|
+
}
|
|
1088
|
+
|
|
416
1089
|
// Turns to wait for while the addon still reports queued settlements. Reaching
|
|
417
1090
|
// zero is the only success. A counter still nonzero at this bound rejects the
|
|
418
1091
|
// disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
|
|
@@ -549,6 +1222,19 @@ function __destroyEmnapiContext() {
|
|
|
549
1222
|
}
|
|
550
1223
|
|
|
551
1224
|
__prepareWasmEnvCleanup()
|
|
1225
|
+
if (__isPreparingWasmEnvCleanup()) {
|
|
1226
|
+
// Reached from inside the synchronous barrier — a promise hook one of the
|
|
1227
|
+
// settlements above ran, which is the reentrancy the destroy wrapper
|
|
1228
|
+
// exists for. `Context.destroy()` below would hit that wrapper's in-flight
|
|
1229
|
+
// no-op and answer `undefined`, and recording that as a completed destroy
|
|
1230
|
+
// is what makes the frame that *did* start the barrier skip the real one
|
|
1231
|
+
// afterwards, leaving the context retained with its cleanup hooks unrun.
|
|
1232
|
+
// Refuse instead: nothing is flagged, and that frame destroys for real the
|
|
1233
|
+
// moment it returns. The deferred loader carries the same backstop. A
|
|
1234
|
+
// parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
|
|
1235
|
+
// rather than skipping it.
|
|
1236
|
+
return
|
|
1237
|
+
}
|
|
552
1238
|
const result = __emnapiContext.destroy()
|
|
553
1239
|
if (!__isThenable(result)) {
|
|
554
1240
|
__emnapiContextDestroyed = true
|
|
@@ -720,6 +1406,7 @@ function __drainWasiAsyncWork() {
|
|
|
720
1406
|
await new Promise((resolve) => {
|
|
721
1407
|
__scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
|
|
722
1408
|
})
|
|
1409
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
723
1410
|
}
|
|
724
1411
|
})(),
|
|
725
1412
|
).then(
|
|
@@ -815,6 +1502,7 @@ function __finishWasiDisposal() {
|
|
|
815
1502
|
}
|
|
816
1503
|
|
|
817
1504
|
function __continueWasiDisposal() {
|
|
1505
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
818
1506
|
const destroyResult = __destroyEmnapiContext()
|
|
819
1507
|
if (__isThenable(destroyResult)) {
|
|
820
1508
|
return Promise.resolve(destroyResult).then(__finishWasiDisposal)
|
|
@@ -822,11 +1510,8 @@ function __continueWasiDisposal() {
|
|
|
822
1510
|
return __finishWasiDisposal()
|
|
823
1511
|
}
|
|
824
1512
|
|
|
825
|
-
function
|
|
826
|
-
|
|
827
|
-
// reach JavaScript, and only then destroy the environment. Doing these two
|
|
828
|
-
// back to back is what strands them.
|
|
829
|
-
__prepareWasmEnvCleanup()
|
|
1513
|
+
function __drainWasmEnvForWasiDisposal() {
|
|
1514
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
830
1515
|
const drainResult = __drainWasmEnvCleanup()
|
|
831
1516
|
if (__isThenable(drainResult)) {
|
|
832
1517
|
return Promise.resolve(drainResult).then(__continueWasiDisposal)
|
|
@@ -834,6 +1519,19 @@ function __cleanUpWasmEnvForWasiDisposal() {
|
|
|
834
1519
|
return __continueWasiDisposal()
|
|
835
1520
|
}
|
|
836
1521
|
|
|
1522
|
+
function __cleanUpWasmEnvForWasiDisposal() {
|
|
1523
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
1524
|
+
// Run the pre-teardown barrier — yielding the turns its two-phase form asks
|
|
1525
|
+
// for, when the addon has one — then let the settlements it queued actually
|
|
1526
|
+
// reach JavaScript, and only then destroy the environment. Doing any two of
|
|
1527
|
+
// these back to back is what strands them.
|
|
1528
|
+
const prepareResult = __prepareWasmEnvCleanupWithTurns()
|
|
1529
|
+
if (__isThenable(prepareResult)) {
|
|
1530
|
+
return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
|
|
1531
|
+
}
|
|
1532
|
+
return __drainWasmEnvForWasiDisposal()
|
|
1533
|
+
}
|
|
1534
|
+
|
|
837
1535
|
function __startWasiDisposal() {
|
|
838
1536
|
// Outstanding `napi_async_work` goes first, while the environment is still
|
|
839
1537
|
// completely live: the completion callbacks run addon code, and everything
|
|
@@ -859,6 +1557,9 @@ function __disposeWasiBinding() {
|
|
|
859
1557
|
if (__wasiDisposePromise) {
|
|
860
1558
|
return __wasiDisposePromise
|
|
861
1559
|
}
|
|
1560
|
+
if (!__wasiDisposed && __hasWasiThreadCrashed()) {
|
|
1561
|
+
return __disposeWasiBindingAfterThreadCrash()
|
|
1562
|
+
}
|
|
862
1563
|
if (__wasiDisposed) {
|
|
863
1564
|
return Promise.resolve()
|
|
864
1565
|
}
|
|
@@ -875,6 +1576,9 @@ function __disposeWasiBinding() {
|
|
|
875
1576
|
try {
|
|
876
1577
|
result = __startWasiDisposal()
|
|
877
1578
|
} catch (error) {
|
|
1579
|
+
if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
|
|
1580
|
+
return disposePromise
|
|
1581
|
+
}
|
|
878
1582
|
__wasiDisposePromise = undefined
|
|
879
1583
|
rejectDispose(error)
|
|
880
1584
|
return disposePromise
|
|
@@ -886,6 +1590,9 @@ function __disposeWasiBinding() {
|
|
|
886
1590
|
resolveDispose(value)
|
|
887
1591
|
},
|
|
888
1592
|
(error) => {
|
|
1593
|
+
if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
|
|
1594
|
+
return
|
|
1595
|
+
}
|
|
889
1596
|
__wasiDisposePromise = undefined
|
|
890
1597
|
rejectDispose(error)
|
|
891
1598
|
},
|
|
@@ -921,6 +1628,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
|
|
|
921
1628
|
}
|
|
922
1629
|
|
|
923
1630
|
function __destroyContextForWasiRollback(cleanupErrors) {
|
|
1631
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
924
1632
|
let destroyResult
|
|
925
1633
|
try {
|
|
926
1634
|
destroyResult = __destroyEmnapiContext()
|
|
@@ -989,19 +1697,43 @@ function __retainFailedWasiRollback(cleanupErrors) {
|
|
|
989
1697
|
* goes away. That is the deliberate choice: a hung promise is a silent liveness
|
|
990
1698
|
* bug with no upper bound, while the retained bookkeeping is bounded by the page.
|
|
991
1699
|
*/
|
|
992
|
-
function
|
|
1700
|
+
function __runWasiInitializationRollbackSteps() {
|
|
993
1701
|
// The environment teardown this rollback performs, kept nested so it cannot
|
|
994
1702
|
// be reached without the async-work drain below running first.
|
|
995
1703
|
function __rollbackWasmEnvForWasiInitialization() {
|
|
1704
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
996
1705
|
const cleanupErrors = []
|
|
1706
|
+
let prepareResult
|
|
1707
|
+
try {
|
|
1708
|
+
prepareResult = __prepareWasmEnvCleanupWithTurns()
|
|
1709
|
+
} catch (cleanupError) {
|
|
1710
|
+
cleanupErrors.push(cleanupError)
|
|
1711
|
+
return __retainFailedWasiRollback(cleanupErrors)
|
|
1712
|
+
}
|
|
1713
|
+
if (__isThenable(prepareResult)) {
|
|
1714
|
+
return Promise.resolve(prepareResult).then(
|
|
1715
|
+
() => __drainWasmEnvForWasiRollback(cleanupErrors),
|
|
1716
|
+
(cleanupError) => {
|
|
1717
|
+
cleanupErrors.push(cleanupError)
|
|
1718
|
+
return __retainFailedWasiRollback(cleanupErrors)
|
|
1719
|
+
},
|
|
1720
|
+
)
|
|
1721
|
+
}
|
|
1722
|
+
return __drainWasmEnvForWasiRollback(cleanupErrors)
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// The settlement drain of the rollback above, reached either straight away or
|
|
1726
|
+
// after the barrier's two-phase form has yielded its turns. A barrier that
|
|
1727
|
+
// did not finish never gets here: it retains instead, exactly as a drain that
|
|
1728
|
+
// did not finish does.
|
|
1729
|
+
function __drainWasmEnvForWasiRollback(cleanupErrors) {
|
|
1730
|
+
__abortWasiDisposalIfThreadCrashed()
|
|
997
1731
|
let drainResult
|
|
998
|
-
let settlementsUnreached = false
|
|
999
1732
|
try {
|
|
1000
|
-
__prepareWasmEnvCleanup()
|
|
1001
1733
|
drainResult = __drainWasmEnvCleanup()
|
|
1002
1734
|
} catch (cleanupError) {
|
|
1003
1735
|
cleanupErrors.push(cleanupError)
|
|
1004
|
-
|
|
1736
|
+
return __retainFailedWasiRollback(cleanupErrors)
|
|
1005
1737
|
}
|
|
1006
1738
|
if (__isThenable(drainResult)) {
|
|
1007
1739
|
return Promise.resolve(drainResult).then(
|
|
@@ -1012,9 +1744,6 @@ function __rollbackWasiInitialization() {
|
|
|
1012
1744
|
},
|
|
1013
1745
|
)
|
|
1014
1746
|
}
|
|
1015
|
-
if (settlementsUnreached) {
|
|
1016
|
-
return __retainFailedWasiRollback(cleanupErrors)
|
|
1017
|
-
}
|
|
1018
1747
|
return __destroyContextForWasiRollback(cleanupErrors)
|
|
1019
1748
|
}
|
|
1020
1749
|
|
|
@@ -1046,6 +1775,55 @@ function __rollbackWasiInitialization() {
|
|
|
1046
1775
|
return __rollbackWasmEnvForWasiInitialization()
|
|
1047
1776
|
}
|
|
1048
1777
|
|
|
1778
|
+
/**
|
|
1779
|
+
* The rollback above, stopped when a wasm thread has died.
|
|
1780
|
+
*
|
|
1781
|
+
* Its polls wait for work the dead thread still counts, so they never end, and
|
|
1782
|
+
* the barrier's `…_finish` and `Context.destroy()` would re-enter wasm
|
|
1783
|
+
* and wait on that thread for good. While the rollback runs, the poll turns
|
|
1784
|
+
* and step boundaries stop it (`__abortWasiDisposalIfThreadCrashed`), and a
|
|
1785
|
+
* crash seen before, during or after it ends it through
|
|
1786
|
+
* `__rollbackWasiInitializationAfterThreadCrash`. Without a crash the
|
|
1787
|
+
* result — synchronous or not — is passed through unchanged.
|
|
1788
|
+
*/
|
|
1789
|
+
function __rollbackWasiInitialization() {
|
|
1790
|
+
if (__hasWasiThreadCrashed()) {
|
|
1791
|
+
return __rollbackWasiInitializationAfterThreadCrash()
|
|
1792
|
+
}
|
|
1793
|
+
__wasiInitializationRollbackActive = true
|
|
1794
|
+
let result
|
|
1795
|
+
try {
|
|
1796
|
+
result = __runWasiInitializationRollbackSteps()
|
|
1797
|
+
} catch (error) {
|
|
1798
|
+
__wasiInitializationRollbackActive = false
|
|
1799
|
+
if (__hasWasiThreadCrashed()) {
|
|
1800
|
+
return __rollbackWasiInitializationAfterThreadCrash()
|
|
1801
|
+
}
|
|
1802
|
+
throw error
|
|
1803
|
+
}
|
|
1804
|
+
if (!__isThenable(result)) {
|
|
1805
|
+
__wasiInitializationRollbackActive = false
|
|
1806
|
+
return __hasWasiThreadCrashed()
|
|
1807
|
+
? __rollbackWasiInitializationAfterThreadCrash()
|
|
1808
|
+
: result
|
|
1809
|
+
}
|
|
1810
|
+
return Promise.resolve(result).then(
|
|
1811
|
+
(cleanupErrors) => {
|
|
1812
|
+
__wasiInitializationRollbackActive = false
|
|
1813
|
+
return __hasWasiThreadCrashed()
|
|
1814
|
+
? __rollbackWasiInitializationAfterThreadCrash()
|
|
1815
|
+
: cleanupErrors
|
|
1816
|
+
},
|
|
1817
|
+
(error) => {
|
|
1818
|
+
__wasiInitializationRollbackActive = false
|
|
1819
|
+
if (__hasWasiThreadCrashed()) {
|
|
1820
|
+
return __rollbackWasiInitializationAfterThreadCrash()
|
|
1821
|
+
}
|
|
1822
|
+
throw error
|
|
1823
|
+
},
|
|
1824
|
+
)
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1049
1827
|
const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
|
|
1050
1828
|
const __wasiRollbackRegistryKey =
|
|
1051
1829
|
typeof __filename === 'string' ? __filename : __wasmFilePath
|
|
@@ -1149,11 +1927,24 @@ function __removeWasiExitListener() {
|
|
|
1149
1927
|
|
|
1150
1928
|
function __disposeWasiBindingAtExit() {
|
|
1151
1929
|
__wasiExitListenerRegistered = false
|
|
1930
|
+
if (__hasWasiThreadCrashed()) {
|
|
1931
|
+
// Never re-enter wasm after a thread died: the environment cleanup joins
|
|
1932
|
+
// the dead thread's work and would hang the exit forever — SIGTERM
|
|
1933
|
+
// included, since its JavaScript listener never gets a turn. Stop the
|
|
1934
|
+
// workers and leave.
|
|
1935
|
+
try {
|
|
1936
|
+
void Promise.resolve(__terminateWasiWorkers()).catch(() => {})
|
|
1937
|
+
} catch {}
|
|
1938
|
+
return
|
|
1939
|
+
}
|
|
1152
1940
|
// An 'exit' handler cannot yield, so it cannot wait for queued promise
|
|
1153
1941
|
// settlements the way __startWasiDisposal does — the process is leaving and
|
|
1154
1942
|
// those promises have no observer left anyway. Run the synchronous teardown
|
|
1155
1943
|
// directly. Every step is idempotent, which also makes this the synchronous
|
|
1156
|
-
// finish for a disposal that is still waiting for its drain
|
|
1944
|
+
// finish for a disposal that is still waiting for its drain — and, through
|
|
1945
|
+
// __prepareWasmEnvCleanup, for one still parked between the two halves of
|
|
1946
|
+
// the environment cleanup barrier: there are no turns left to poll with, so
|
|
1947
|
+
// this closes that handshake with `…_finish`, which joins.
|
|
1157
1948
|
try {
|
|
1158
1949
|
__destroyEmnapiContext()
|
|
1159
1950
|
} catch {}
|
|
@@ -1260,6 +2051,11 @@ try {
|
|
|
1260
2051
|
onCreateWorker() {
|
|
1261
2052
|
const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
|
|
1262
2053
|
__wasiWorkers.add(worker)
|
|
2054
|
+
// Registered before emnapi's own listeners, which rethrow the error.
|
|
2055
|
+
worker.on('error', (error) => {
|
|
2056
|
+
__wasiThreadCrashed = true
|
|
2057
|
+
__recordWasiThreadCrashError(error, worker.threadId)
|
|
2058
|
+
})
|
|
1263
2059
|
worker.onmessage = ({ data }) => {
|
|
1264
2060
|
__wasmCreateOnMessageForFsProxy(__nodeFs)(data)
|
|
1265
2061
|
}
|
|
@@ -1303,6 +2099,7 @@ try {
|
|
|
1303
2099
|
},
|
|
1304
2100
|
beforeInit({ instance }) {
|
|
1305
2101
|
__napiInstance = instance
|
|
2102
|
+
__captureWasiAddonCrashFlag(instance)
|
|
1306
2103
|
for (const name of Object.keys(instance.exports)) {
|
|
1307
2104
|
if (name.startsWith('__napi_register__')) {
|
|
1308
2105
|
instance.exports[name]()
|