forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathVM.cpp
More file actions
3586 lines (3261 loc) · 163 KB
/
Copy pathVM.cpp
File metadata and controls
3586 lines (3261 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008-2025 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "VM.h"
#include "ConcurrentButterfly.h"
#include "PropertyTable.h"
#include "VMLiteInlines.h" // UNGIL §E.1/I11 (U-T9): per-lite microtask enqueue/drain reroute.
#include "VMLiteShared.h"
#include "AbortReason.h"
#include "AccessCase.h"
#include "AggregateError.h"
#include "ArgList.h"
#include "BuiltinExecutables.h"
#include "BytecodeIntrinsicRegistry.h"
#include "CallMode.h"
#include "CheckpointOSRExitSideState.h"
#include "CodeBlock.h"
#include "CodeCache.h"
#include "CommonIdentifiers.h"
#include "ControlFlowProfiler.h"
#include "CrossTaskToken.h"
#include "CustomGetterSetterInlines.h"
#include "DOMAttributeGetterSetterInlines.h"
#include "Debugger.h"
#include "DeferredWorkTimer.h"
#include "Disassembler.h"
#include "DoublePredictionFuzzerAgent.h"
#include "ErrorInstance.h"
#include "EvalCodeBlockInlines.h"
#include "EvalExecutableInlines.h"
#include "Exception.h"
#include "FTLThunks.h"
#include "FileBasedFuzzerAgent.h"
#include "FunctionCodeBlockInlines.h"
#include "FunctionExecutableInlines.h"
#include "GetterSetterInlines.h"
#include "GigacageAlignedMemoryAllocator.h"
#include "GlobalObjectMethodTable.h"
#include "HasOwnPropertyCache.h"
#include "Heap.h"
#include "HeapInlines.h"
#include "HeapProfiler.h"
#include "IncrementalSweeper.h"
#include "Interpreter.h"
#include "IntlCache.h"
#include "IntlObject.h"
#include "JITCode.h"
#include "JITOperationList.h"
#include "JITSizeStatistics.h"
#include "JITThunks.h"
#include "JITWorklist.h"
#include "JSAPIValueWrapper.h"
#include "JSBigInt.h"
#include "JSCellButterflyInlines.h"
#include "JSGlobalObject.h"
#include "JSIterator.h"
#include "JSLock.h"
#include "JSMap.h"
#include "JSMicrotask.h"
#include "JSMicrotaskDispatcher.h"
#include "JSModuleLoaderInlines.h"
#include "JSPromise.h"
#include "JSPromiseCombinatorsContextInlines.h"
#include "JSPromiseCombinatorsGlobalContext.h"
#include "JSPromiseConstructor.h"
#include "JSPromiseReaction.h"
#include "JSPropertyNameEnumeratorInlines.h"
#include "JSSentinelInlines.h"
#include "JSSet.h"
#include "JSSourceCodeInlines.h"
#include "JSTemplateObjectDescriptorInlines.h"
#include "JSToWasm.h"
#include "LLIntData.h"
#include "LLIntExceptions.h"
#include "MarkedBlockInlines.h"
#include "MegamorphicCache.h"
#include "MicrotaskQueueInlines.h"
#include "MinimumReservedZoneSize.h"
#include "ModuleGraphLoadingStateInlines.h"
#include "ModuleLoadingContextInlines.h"
#include "ModuleLoaderPayloadInlines.h"
#include "ModuleProgramCodeBlockInlines.h"
#include "ModuleProgramExecutableInlines.h"
#include "ModuleRegistryEntryInlines.h"
#include "NarrowingNumberPredictionFuzzerAgent.h"
#include "NativeExecutable.h"
#include "NumberObject.h"
#include "PinballCompletion.h"
#include "PredictionFileCreatingFuzzerAgent.h"
#include "ProfilerDatabase.h"
#include "ProgramCodeBlockInlines.h"
#include "RaceAmplifier.h"
#include "ProgramExecutableInlines.h"
#include "PropertyInlineCache.h"
#include "PropertyTableInlines.h"
#include "RandomizingFuzzerAgent.h"
#include "RegExpCache.h"
#include "RegExpInlines.h"
#include "ResourceExhaustion.h"
#include "SamplingProfiler.h"
#include "ScopedArguments.h"
#include "ShadowChicken.h"
#include "SharedJITStubSet.h"
#include "SideDataRepository.h"
#include "SimpleTypedArrayController.h"
#include "SourceProviderCache.h"
#include "StrongInlines.h"
#include "StructureChainInlines.h"
#include "StructureInlines.h"
#include "SubspaceInlines.h"
#include "SymbolInlines.h"
#include "SymbolTableInlines.h"
#include "TestRunnerUtils.h"
#include "ThreadManager.h"
#include "ThunkGenerators.h"
#include "TypeProfiler.h"
#include "TypeProfilerLog.h"
#include "UnlinkedEvalCodeBlockInlines.h"
#include "UnlinkedFunctionCodeBlockInlines.h"
#include "UnlinkedFunctionExecutableInlines.h"
#include "UnlinkedModuleProgramCodeBlockInlines.h"
#include "UnlinkedProgramCodeBlockInlines.h"
#include "VMEntryScopeInlines.h"
#include "VMInlines.h"
#include "VMManager.h"
#include "VMTrapsInlines.h"
#include "VariableEnvironment.h"
#include "WaiterListManager.h"
#include "WasmDebugServerUtilities.h"
#include "WasmExecutionHandler.h"
#include "WasmWorklist.h"
#include "Watchdog.h"
#include "WeakGCMapInlines.h"
#include "WideningNumberPredictionFuzzerAgent.h"
#include <wtf/CryptographicallyRandomNumber.h>
#include <wtf/MainThread.h>
#include <wtf/MemoryPressureHandler.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/ProcessID.h>
#include <wtf/ReadWriteLock.h>
#include <wtf/SimpleStats.h>
#include <wtf/StackTrace.h>
#include <wtf/StringPrintStream.h>
#include <wtf/SystemTracing.h>
#include <wtf/Threading.h>
#include <wtf/text/AtomStringTable.h>
#include <wtf/text/StringToIntegerConversion.h>
#if ENABLE(DFG_JIT) || ENABLE(WEBASSEMBLY)
#include "ConservativeRoots.h"
#endif
#if ENABLE(REGEXP_TRACING)
#include "RegExp.h"
#endif
#if ENABLE(WEBASSEMBLY)
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyStreamingContextInlines.h"
#endif
#if PLATFORM(COCOA)
#include <notify.h>
#include <wtf/darwin/DispatchExtras.h>
#endif
#if ENABLE(WEBASSEMBLY_DEBUGGER)
#include "WasmDebugServerUtilities.h"
#endif
#include <span>
namespace JSC {
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(VM);
// UNGIL §E.1b.4/SD15 (U-T8e) — forward declarations for the rejection-tracker
// carrier-handoff machinery defined ahead of VM::callPromiseRejectionCallback
// below; ~VM (purge) and the non-static seams are consumed before that point.
void enqueuePromiseRejectionTrackerHandoffRecord(VM&, JSPromise*, JSPromiseRejectionOperation);
void flushPromiseRejectionTrackerHandoffRecords(VM&);
void notifyPromiseRejectionTrackerCrossThreadAware(JSGlobalObject*, JSPromise*, JSPromiseRejectionOperation);
static void purgePromiseRejectionHandoffRecordsAtVMDestruction(VM&);
// UNGIL §E.7.3 (U-T9): jsThreadsPurgeCrossThreadDeferredWorkAtVMDestruction
// (DeferredWorkTimer.cpp) is consumed in ~VM below via its ThreadManager.h
// declaration (already included by this TU).
// ===========================================================================
// UNGIL §A.1.1 (U-T3): g_jscCurrentVMLite — the JIT/LLInt-visible mirror of
// vmstate L4's `t_currentVMLite` (runtime/VMLite.cpp). The L4 freeze keeps
// the C++ accessors (VMLite::current/currentIfExists/setCurrent) backed by
// the plain thread_local in VMLite.cpp; generated code instead reads THIS
// symbol, per SPEC-jit annex App. R5 mechanics (the g_jscButterflyTIDTag
// precedent, jit/ConcurrentButterflyOperations.cpp):
//
// - ELF (Linux glibc+musl): initial-exec model => the symbol's TPOFF is
// link-time thread-invariant. The JIT-tier read is LANDED (the
// loadVMLite free-function emitter in jit/AssemblyHelpers.cpp; the
// member surface follows with the emission slice). The LLInt side —
// the `loadVMLite` offlineasm macro reading this symbol with
// initial-exec relocations (x86-64 `movq %fs:g_jscCurrentVMLite@TPOFF`;
// arm64 mrs + :tprel_hi12:/:tprel_lo12_nc:) plus the per-Group-3-site
// two-level selection and the JSCConfig `gilOffProcess` byte — is NOT
// YET LANDED: llint/ and runtime/JSCConfig.h are outside this slice's
// writable file set (OPEN U-T3 obligation, INTEGRATE-ungil.md 9b;
// escalated at the U-T3 amendment — the licensed flag-off golden-disasm
// re-baseline for the LLInt Group-3 branches happens when those branches
// land, not before). The symbol is extern "C" (unmangled
// asm-referenceable name) and defined OUTSIDE any ENABLE(JIT) region so
// that LLInt slice can bind to it unchanged.
// - Darwin: Mach-O TLV has no constant offset; the JIT-visible copy lives in
// a pthread TSD slot whose key is to be published through the M4a-style
// JSCConfig slot (vmLiteTLSKey, beside butterflyTIDTagTLSKey). That slot,
// its key creation, and the per-thread pthread_setspecific are NOT YET
// LANDED (same writable-set constraint; see the Darwin arm in
// jit/AssemblyHelpers.cpp). This thread_local still exists there
// (harmless; generated code will read the TSD slot, not this symbol).
//
// COHERENCE CONTRACT (the App. R5 CS3 discipline, applied to the lite
// pointer): VMLite::setCurrent — the SOLE writer of t_currentVMLite — must
// mirror every TLS write here (and, on Darwin, pthread_setspecific the same
// value into the vmLiteTLSKey slot), immediately after the t_currentVMLite
// store and before its TID-tag hook fires — INCLUDING the null/uninstall
// writes (carrier teardown, thread exit): an unmirrored clear would leave a
// reused thread's generated code reading a stale/freed lite. STATUS: the
// mirror store is NOT YET IMPLEMENTED (runtime/VMLite.cpp is outside this
// slice's writable set), and NO existing INTEGRATE-ungil.md obligation row
// covers it — obligation 9b covers only the Config byte / LLInt selection /
// loadVMLite emitter / VMEntryRecord slot. A dedicated IU obligation row
// (owner: the VMLite.cpp slice) must be added before any task emits live
// reads of this symbol; escalated at the U-T3 amendment. Until the mirror
// lands, this symbol stays null on every thread — dark-safe: only
// gilOff-mode compilations (§A.1.3 COMPILED-FOR-VM-mode rule) emit reads of
// it, and no shipping configuration constructs a gilOff VM.
// ===========================================================================
#if OS(LINUX)
extern "C" __attribute__((tls_model("initial-exec"))) thread_local VMLite* g_jscCurrentVMLite = nullptr;
#else
extern "C" thread_local VMLite* g_jscCurrentVMLite = nullptr;
#endif
MicrotaskQueue& VM::defaultMicrotaskQueue() { return m_defaultMicrotaskQueue.get(); }
#if ENABLE(GC_VALIDATION)
// Per-thread (see the VM.h declaration comment): GIL-off N mutators share a
// VM, and an object initialization is one thread's stack property.
thread_local const ClassInfo* VM::s_initializingObjectClass { nullptr };
#endif
// UNGIL §F.2 (U-T8): defined in JSLock.cpp (the token machinery's home);
// same-library linkage, deliberately not declared in any header — the
// predicate split is an implementation detail of the two functions below.
bool currentThreadHoldsEntryToken(const VM&);
bool VM::currentThreadIsHoldingAPILock() const
{
// UNGIL §F.2 (U-T8), the predicate split: GIL-off this predicate is
// REDEFINED as "the current thread holds an entry token for this VM" —
// the host-call assert meaning (DWT §E.7.2; U12/U13). Spawned threads
// never touch JSLock::m_lock (§F.1) and main/embedder m_lock holders
// ALSO hold a token (F1B), so the token question subsumes the mutex one.
// JSLock::currentThreadIsHoldingLock() stays MUTEX-LITERAL — §F.4's DAL
// handling + the m_lockDropDepth LIFO depend on it; consumers needing
// the mutex meaning ask the JSLock directly (IU table rows 19/22/26/36,
// JSLock.cpp). GIL-on (m_gilOff == 0 — every shipping configuration):
// bit-identical to the landed mutex forward.
if (m_gilOff) [[unlikely]]
return currentThreadHoldsEntryToken(*this);
return m_apiLock->currentThreadIsHoldingLock();
}
JSLock& VM::apiLock() { return m_apiLock.get(); }
// Note: Platform.h will enforce that ENABLE(ASSEMBLER) is true if either
// ENABLE(JIT) or ENABLE(YARR_JIT) or both are enabled. The code below
// just checks for ENABLE(JIT) or ENABLE(YARR_JIT) with this premise in mind.
#if ENABLE(ASSEMBLER)
static bool enableAssembler()
{
if (!Options::useJIT())
return false;
auto canUseJITString = unsafeSpan(getenv("JavaScriptCoreUseJIT"));
if (canUseJITString.data() && !parseInteger<int>(canUseJITString).value_or(0))
return false;
ExecutableAllocator::initializeUnderlyingAllocator();
if (!ExecutableAllocator::singleton().isValid()) {
if (Options::crashIfCantAllocateJITMemory())
CRASH();
return false;
}
return true;
}
#endif // ENABLE(!ASSEMBLER)
bool VM::canUseAssembler()
{
#if ENABLE(ASSEMBLER)
static std::once_flag onceKey;
static bool enabled = false;
std::call_once(onceKey, [] {
enabled = enableAssembler();
});
return enabled;
#else
return false; // interpreter only
#endif
}
void VM::computeCanUseJIT()
{
#if ENABLE(JIT)
#if ASSERT_ENABLED
RELEASE_ASSERT(!g_jscConfig.vm.canUseJITIsSet);
g_jscConfig.vm.canUseJITIsSet = true;
#endif
g_jscConfig.vm.canUseJIT = VM::canUseAssembler() && Options::useJIT();
#endif
}
static bool vmCreationShouldCrash = false;
VM::VM(VMType vmType, HeapType heapType, WTF::RunLoop* runLoop, bool* success)
: topCallFrame(CallFrame::noCaller())
, m_identifier(VMIdentifier::generate())
, m_apiLock(adoptRef(*new JSLock(this)))
, m_runLoop(runLoop ? *runLoop : WTF::RunLoop::currentSingleton())
, m_random(Options::seedOfVMRandomForFuzzer() ? Options::seedOfVMRandomForFuzzer() : cryptographicallyRandomNumber<uint32_t>())
, m_heapRandom(Options::seedOfVMRandomForFuzzer() ? Options::seedOfVMRandomForFuzzer() : cryptographicallyRandomNumber<uint32_t>())
, m_integrityRandom(*this)
, heap(*this, heapType)
, clientHeap(heap)
, vmType(vmType)
, deferredWorkTimer(DeferredWorkTimer::create(*this))
, m_atomStringTable(vmType == VMType::Default ? Thread::currentSingleton().atomStringTable() : new AtomStringTable)
, m_symbolRegistry(makeUniqueRef<SymbolRegistry>())
, m_privateSymbolRegistry(makeUniqueRef<SymbolRegistry>(SymbolRegistry::Type::PrivateSymbol))
, emptyList(new ArgList)
, machineCodeBytesPerBytecodeWordForBaselineJIT(makeUnique<SimpleStats>())
// These per-VM WeakGCMap caches are mutated from every JS thread when
// useJSThreads is on (one shared VM under VMLite), so they opt into
// WeakGCMap's internal leaf lock (SPEC-ungil §H / §LK.7). With
// useJSThreads off they stay lock-free, exactly as before.
, symbolImplToSymbolMap(*this, Options::useJSThreads() ? WeakGCMapLocking::Yes : WeakGCMapLocking::No)
, atomStringToJSStringMap(*this, Options::useJSThreads() ? WeakGCMapLocking::Yes : WeakGCMapLocking::No)
#if ENABLE(WEBASSEMBLY)
, wasmGCStructureMap(*this, Options::useJSThreads() ? WeakGCMapLocking::Yes : WeakGCMapLocking::No)
#endif
, m_regExpCache(makeUnique<RegExpCache>())
, m_compactVariableMap(adoptRef(*new CompactTDZEnvironmentMap))
, m_codeCache(makeUnique<CodeCache>())
, m_intlCache(makeUnique<IntlCache>())
, m_builtinExecutables(makeUnique<BuiltinExecutables>(*this))
, m_defaultMicrotaskQueue(MicrotaskQueue::create(*this))
, m_syncWaiter(adoptRef(*new Waiter(this)))
{
if (vmCreationShouldCrash || g_jscConfig.vmCreationDisallowed) [[unlikely]]
CRASH_WITH_EXTRA_SECURITY_IMPLICATION_AND_INFO(VMCreationDisallowed, "VM creation disallowed"_s, 0x4242424220202020, 0xbadbeef0badbeef, 0x1234123412341234, 0x1337133713371337);
// ANNEX A36 (UNGIL U-T1): process-monotonic epoch for the per-thread
// VM->carrier TLS maps (stale-epoch detection; never 0).
{
static std::atomic<uint64_t> s_nextVMEpoch { 1 };
m_vmEpoch = s_nextVMEpoch.fetch_add(1, std::memory_order_relaxed);
}
// UNGIL §0 U0c (ANNEX U0C, BINDING): m_gilOff is computed ONCE, here —
// BEFORE m_mainVMLite registration (end of this ctor), any entry
// (including this ctor's own JSLockHolder below), and any codegen
// (including the JIT thunk initialization below) — and is IMMUTABLE for
// the VM's lifetime. Under gilOffProcess every VM ctor races the
// designation CAS (Heap::tryDesignateStickySharedServer — won/lost, NO
// assert): the WINNER is the one m_gilOff VM per process (U0b) and
// eagerly flips sticky-ISS at clientSet()==1 (quiescence trivial at
// birth; noteSharedServerSticky's inner CAS sees previous==this, so I13
// stands textually unchanged and never fires on this path). A LOSER
// keeps m_gilOff=0 and the GIL-on single-migrating-client protocol; U0b
// spawn-refusal keeps its clientSet()<=1, so the HeapClientSet::add
// trigger never runs for it.
// AB17g item 2 (F1): latch the Config gilOffProcess byte BEFORE the
// m_gilOff designation below, so gilOffWithProcessGate()'s process-byte
// test alone is sufficient in every reachable state (the VM.h fallback
// term is dropped). Options are finalized strictly before any VM ctor
// (InitializeThreading), so the latch's isFinalized assert cannot fire
// here. The Config::finalize() call later in this ctor is unchanged:
// its latch call is a spent-call_once no-op, and the forceFencedBarrier
// options store just before it keeps its required position BEFORE the
// WTF::Config::finalize() freeze (M8/GT#7).
Config::latchGILOffProcess();
if (VM::isGILOffProcess()) [[unlikely]] {
// AB17g amendment (d): designation must never precede the latch.
ASSERT(g_jscConfig.gilOffProcess);
if (heap.tryDesignateStickySharedServer()) {
m_gilOff = true;
// AB17c F4: re-stamp the HandleSet's cached §F.3 mode byte. The
// HandleSet was constructed in this ctor's INIT LIST (Heap
// member), i.e. before m_gilOff above was computed, so its ctor
// stamp is always false; without this re-stamp every Strong
// allocate/free/barrier takes the UNLOCKED inline arm GIL-off
// and two threads race m_freeList (observed: double-allocated
// Strong slot under counter-lock.js — a spawned thread's
// property-wait Strong clobbered the carrier's in-flight
// UnlinkedCodeBlockGenerator codeBlock handle). Still
// single-threaded and unpublished here, so the write is
// pre-publication (see noteOwnerVMDesignatedGILOff()).
heap.handleSet()->noteOwnerVMDesignatedGILOff();
// U0c invariant check immediately before EVERY in-scope
// noteSharedServerSticky() trigger (annex U0C). The second
// trigger family — HeapClientSet::add's second-client site
// (HeapClientSet.cpp:69) — is OUTSIDE this slice's writable set
// and remains UNWIRED; see the declaration comment in
// heap/Heap.h and INTEGRATE-ungil.md ledger row 6 (still open).
heap.verifyStickySharedServerDesignation();
heap.noteSharedServerSticky();
}
}
// Arm the race amplifier (no-op unless --randomYieldPeriod is set).
// Idempotent across VM constructions; see runtime/RaceAmplifier.h.
RaceAmplifier::initialize();
// Set up lazy initializers.
{
m_hasOwnPropertyCache.initLater([](VM&, auto& ref) {
ref.set(HasOwnPropertyCache::create());
});
m_megamorphicCache.initLater([](VM&, auto& ref) {
ref.set(makeUniqueRef<MegamorphicCache>());
});
m_shadowChicken.initLater([](VM&, auto& ref) {
ref.set(makeUniqueRef<ShadowChicken>());
});
m_heapProfiler.initLater([](VM& vm, auto& ref) {
ref.set(makeUniqueRef<HeapProfiler>(vm));
});
m_stringSearcherTables.initLater([](VM&, auto& ref) {
ref.set(makeUniqueRef<AdaptiveStringSearcherTables>());
});
m_watchdog.initLater([](VM& vm, auto& ref) {
ref.set(adoptRef(*new Watchdog(&vm)));
vm.ensureTerminationException();
vm.requestEntryScopeService(EntryScopeService::Watchdog);
});
}
updateSoftReservedZoneSize(Options::softReservedZoneSize());
setLastStackTop(Thread::currentSingleton());
stringSplitIndice.reserveInitialCapacity(256);
JSRunLoopTimer::Manager::singleton().registerVM(*this);
// Need to be careful to keep everything consistent here
JSLockHolder lock(this);
AtomStringTable* existingEntryAtomStringTable = Thread::currentSingleton().setCurrentAtomStringTable(m_atomStringTable);
structureStructure.setWithoutWriteBarrier(Structure::createStructure(*this));
structureRareDataStructure.setWithoutWriteBarrier(StructureRareData::createStructure(*this, nullptr, jsNull()));
stringStructure.setWithoutWriteBarrier(JSString::createStructure(*this, nullptr, jsNull()));
smallStrings.initializeCommonStrings(*this);
numericStrings.initializeSmallIntCache(*this);
propertyNames = new CommonIdentifiers(*this);
propertyNameEnumeratorStructure.setWithoutWriteBarrier(JSPropertyNameEnumerator::createStructure(*this, nullptr, jsNull()));
getterSetterStructure.setWithoutWriteBarrier(GetterSetter::createStructure(*this, nullptr, jsNull()));
customGetterSetterStructure.setWithoutWriteBarrier(CustomGetterSetter::createStructure(*this, nullptr, jsNull()));
domAttributeGetterSetterStructure.setWithoutWriteBarrier(DOMAttributeGetterSetter::createStructure(*this, nullptr, jsNull()));
scopedArgumentsTableStructure.setWithoutWriteBarrier(ScopedArgumentsTable::createStructure(*this, nullptr, jsNull()));
apiWrapperStructure.setWithoutWriteBarrier(JSAPIValueWrapper::createStructure(*this, nullptr, jsNull()));
nativeExecutableStructure.setWithoutWriteBarrier(NativeExecutable::createStructure(*this, nullptr, jsNull()));
evalExecutableStructure.setWithoutWriteBarrier(EvalExecutable::createStructure(*this, nullptr, jsNull()));
programExecutableStructure.setWithoutWriteBarrier(ProgramExecutable::createStructure(*this, nullptr, jsNull()));
functionExecutableStructure.setWithoutWriteBarrier(FunctionExecutable::createStructure(*this, nullptr, jsNull()));
#if ENABLE(WEBASSEMBLY)
pinballCompletionStructure.setWithoutWriteBarrier(PinballCompletion::createStructure(*this, nullptr, jsNull()));
webAssemblyStreamingContextStructure.setWithoutWriteBarrier(JSWebAssemblyStreamingContext::createStructure(*this, nullptr, jsNull()));
#endif
moduleProgramExecutableStructure.setWithoutWriteBarrier(ModuleProgramExecutable::createStructure(*this, nullptr, jsNull()));
slimPromiseReactionStructure.setWithoutWriteBarrier(JSSlimPromiseReaction::createStructure(*this, nullptr, jsNull()));
fullPromiseReactionStructure.setWithoutWriteBarrier(JSFullPromiseReaction::createStructure(*this, nullptr, jsNull()));
jsMicrotaskDispatcherStructure.setWithoutWriteBarrier(JSMicrotaskDispatcher::createStructure(*this, nullptr, jsNull()));
moduleLoaderStructure.setWithoutWriteBarrier(JSModuleLoader::createStructure(*this, nullptr, jsNull()));
moduleRegistryEntryStructure.setWithoutWriteBarrier(ModuleRegistryEntry::createStructure(*this, nullptr, jsNull()));
moduleLoadingContextStructure.setWithoutWriteBarrier(ModuleLoadingContext::createStructure(*this, nullptr, jsNull()));
moduleLoaderPayloadStructure.setWithoutWriteBarrier(ModuleLoaderPayload::createStructure(*this, nullptr, jsNull()));
moduleGraphLoadingStateStructure.setWithoutWriteBarrier(ModuleGraphLoadingState::createStructure(*this, nullptr, jsNull()));
promiseCombinatorsContextStructure.setWithoutWriteBarrier(JSPromiseCombinatorsContext::createStructure(*this, nullptr, jsNull()));
promiseCombinatorsGlobalContextStructure.setWithoutWriteBarrier(JSPromiseCombinatorsGlobalContext::createStructure(*this, nullptr, jsNull()));
regExpStructure.setWithoutWriteBarrier(RegExp::createStructure(*this, nullptr, jsNull()));
symbolStructure.setWithoutWriteBarrier(Symbol::createStructure(*this, nullptr, jsNull()));
symbolTableStructure.setWithoutWriteBarrier(SymbolTable::createStructure(*this, nullptr, jsNull()));
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
rawImmutableButterflyStructure(CopyOnWriteArrayWithInt32).setWithoutWriteBarrier(JSCellButterfly::createStructure(*this, nullptr, jsNull(), CopyOnWriteArrayWithInt32));
Structure* copyOnWriteArrayWithContiguousStructure = JSCellButterfly::createStructure(*this, nullptr, jsNull(), CopyOnWriteArrayWithContiguous);
rawImmutableButterflyStructure(CopyOnWriteArrayWithDouble).setWithoutWriteBarrier(Options::allowDoubleShape() ? JSCellButterfly::createStructure(*this, nullptr, jsNull(), CopyOnWriteArrayWithDouble) : copyOnWriteArrayWithContiguousStructure);
rawImmutableButterflyStructure(CopyOnWriteArrayWithContiguous).setWithoutWriteBarrier(copyOnWriteArrayWithContiguousStructure);
WTF_ALLOW_UNSAFE_BUFFER_USAGE_END
// This is only for JSCellButterfly filled with atom strings.
cellButterflyOnlyAtomStringsStructure.setWithoutWriteBarrier(JSCellButterfly::createStructure(*this, nullptr, jsNull(), CopyOnWriteArrayWithContiguous));
sourceCodeStructure.setWithoutWriteBarrier(JSSourceCode::createStructure(*this, nullptr, jsNull()));
structureChainStructure.setWithoutWriteBarrier(StructureChain::createStructure(*this, nullptr, jsNull()));
sparseArrayValueMapStructure.setWithoutWriteBarrier(SparseArrayValueMap::createStructure(*this, nullptr, jsNull()));
templateObjectDescriptorStructure.setWithoutWriteBarrier(JSTemplateObjectDescriptor::createStructure(*this, nullptr, jsNull()));
unlinkedFunctionExecutableStructure.setWithoutWriteBarrier(UnlinkedFunctionExecutable::createStructure(*this, nullptr, jsNull()));
unlinkedProgramCodeBlockStructure.setWithoutWriteBarrier(UnlinkedProgramCodeBlock::createStructure(*this, nullptr, jsNull()));
unlinkedEvalCodeBlockStructure.setWithoutWriteBarrier(UnlinkedEvalCodeBlock::createStructure(*this, nullptr, jsNull()));
unlinkedFunctionCodeBlockStructure.setWithoutWriteBarrier(UnlinkedFunctionCodeBlock::createStructure(*this, nullptr, jsNull()));
unlinkedModuleProgramCodeBlockStructure.setWithoutWriteBarrier(UnlinkedModuleProgramCodeBlock::createStructure(*this, nullptr, jsNull()));
propertyTableStructure.setWithoutWriteBarrier(PropertyTable::createStructure(*this, nullptr, jsNull()));
functionRareDataStructure.setWithoutWriteBarrier(FunctionRareData::createStructure(*this, nullptr, jsNull()));
exceptionStructure.setWithoutWriteBarrier(Exception::createStructure(*this, nullptr, jsNull()));
programCodeBlockStructure.setWithoutWriteBarrier(ProgramCodeBlock::createStructure(*this, nullptr, jsNull()));
moduleProgramCodeBlockStructure.setWithoutWriteBarrier(ModuleProgramCodeBlock::createStructure(*this, nullptr, jsNull()));
evalCodeBlockStructure.setWithoutWriteBarrier(EvalCodeBlock::createStructure(*this, nullptr, jsNull()));
functionCodeBlockStructure.setWithoutWriteBarrier(FunctionCodeBlock::createStructure(*this, nullptr, jsNull()));
bigIntStructure.setWithoutWriteBarrier(JSBigInt::createStructure(*this, nullptr, jsNull()));
m_orderedHashTableDeletedValue.setWithoutWriteBarrier(JSOrderedHashMap::createDeletedValue(*this));
m_orderedHashTableSentinel.setWithoutWriteBarrier(JSOrderedHashMap::createSentinel(*this));
m_sortScratchSentinel.setWithoutWriteBarrier(JSCellButterfly::create(*this, CopyOnWriteArrayWithContiguous, 0));
{
Structure* sentinelStructure = JSSentinel::createStructure(*this, nullptr, jsNull());
m_sentinelStructure.setWithoutWriteBarrier(sentinelStructure);
m_fastArrayValuesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastArrayKeysSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastArrayEntriesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastMapKeysSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastMapValuesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastMapEntriesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastSetValuesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastSetEntriesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
m_fastStringValuesSentinel.setWithoutWriteBarrier(JSSentinel::create(*this, sentinelStructure));
}
// Eagerly initialize constant cells since the concurrent compiler can access them.
if (Options::useJIT()) {
emptyPropertyNameEnumerator();
ensureMegamorphicCache();
}
{
auto* bigInt = JSBigInt::tryCreateFrom(*this, 1);
if (bigInt)
heapBigIntConstantOne.setWithoutWriteBarrier(bigInt);
else {
if (success)
*success = false;
else
RELEASE_ASSERT_RESOURCE_AVAILABLE(bigInt, MemoryExhaustion, "Crash intentionally because memory is exhausted.");
}
}
{
auto* bigInt = JSBigInt::tryCreateWithLength(*this, 0);
if (bigInt)
heapBigIntConstantZero.setWithoutWriteBarrier(bigInt);
else {
if (success)
*success = false;
else
RELEASE_ASSERT_RESOURCE_AVAILABLE(bigInt, MemoryExhaustion, "Crash intentionally because memory is exhausted.");
}
}
Thread::currentSingleton().setCurrentAtomStringTable(existingEntryAtomStringTable);
Gigacage::addPrimitiveDisableCallback(primitiveGigacageDisabledCallback, this);
heap.notifyIsSafeToCollect();
if (Options::useProfiler()) [[unlikely]] {
m_perBytecodeProfiler = makeUnique<Profiler::Database>(*this);
StringPrintStream pathOut;
const char* profilerPath = getenv("JSC_PROFILER_PATH");
if (profilerPath)
pathOut.print(profilerPath, "/");
else
pathOut.print("/tmp/");
pathOut.print("JSCProfile-", getCurrentProcessID(), "-", m_perBytecodeProfiler->databaseID(), ".json");
static NeverDestroyed<CString> pathOutString = pathOut.toCString();
#if PLATFORM(COCOA)
static std::once_flag registerFlag;
std::call_once(registerFlag, [this]() {
int pid = getpid();
const char* key = "com.apple.WebKit.bytecode.profiler";
dataLogLn("<BYTECODE.STAT><", pid, "> Registering callback for dumping profiles, dumping to ", pathOutString.get(), ".");
dataLogLn("<BYTECODE.STAT><", pid, "> Use `notifyutil -v -p ", key, "` to dump statistics.");
int token;
notify_register_dispatch(key, &token, mainDispatchQueueSingleton(), ^(int) {
dataLogLn("<BYTECODE.STAT><", pid, "> Dumping");
if (!m_perBytecodeProfiler->save(pathOutString->data()))
dataLogLn("<BYTECODE.STAT><", pid, "> Failed to dump to ", pathOutString.get(), ". Do you need to add a sandbox extension? ((allow file-write* (subpath \"/private/tmp/\")) in WebProcess.sb.in");
else
dataLogLn("<BYTECODE.STAT><", pid, "> Dumped to ", pathOutString.get());
dataLogLn("<BYTECODE.STAT><", pid, "> Dumping finished");
});
});
#endif
if (Options::dumpProfilerDataAtExit()) [[unlikely]]
m_perBytecodeProfiler->registerToSaveAtExit(pathOutString->data());
}
// Initialize this last, as a free way of asserting that VM initialization itself
// won't use this.
m_typedArrayController = adoptRef(new SimpleTypedArrayController());
m_bytecodeIntrinsicRegistry = makeUnique<BytecodeIntrinsicRegistry>(*this);
if (Options::useTypeProfiler())
enableTypeProfiler();
if (Options::useControlFlowProfiler())
enableControlFlowProfiler();
#if ENABLE(SAMPLING_PROFILER)
if (Options::useSamplingProfiler()) {
setShouldBuildPCToCodeOriginMapping();
Ref<Stopwatch> stopwatch = Stopwatch::create();
stopwatch->start();
ensureSamplingProfiler(WTF::move(stopwatch));
if (Options::samplingProfilerPath())
m_samplingProfiler->registerForReportAtExit();
m_samplingProfiler->start();
}
#endif // ENABLE(SAMPLING_PROFILER)
if (Options::useRandomizingFuzzerAgent())
setFuzzerAgent(makeUnique<RandomizingFuzzerAgent>(*this));
if (Options::useDoublePredictionFuzzerAgent())
setFuzzerAgent(makeUnique<DoublePredictionFuzzerAgent>(*this));
if (Options::useFileBasedFuzzerAgent())
setFuzzerAgent(makeUnique<FileBasedFuzzerAgent>(*this));
if (Options::usePredictionFileCreatingFuzzerAgent())
setFuzzerAgent(makeUnique<PredictionFileCreatingFuzzerAgent>(*this));
if (Options::useNarrowingNumberPredictionFuzzerAgent())
setFuzzerAgent(makeUnique<NarrowingNumberPredictionFuzzerAgent>(*this));
if (Options::useWideningNumberPredictionFuzzerAgent())
setFuzzerAgent(makeUnique<WideningNumberPredictionFuzzerAgent>(*this));
if (Options::alwaysGeneratePCToCodeOriginMap())
setShouldBuildPCToCodeOriginMapping();
if (Options::watchdog()) {
Ref watchdog = ensureWatchdog();
watchdog->setTimeLimit(Seconds::fromMilliseconds(Options::watchdog()));
}
if (Options::useTracePoints())
requestEntryScopeService(EntryScopeService::TracePoints);
#if ENABLE(WEBASSEMBLY_DEBUGGER)
if (Options::enableWasmDebugger()) [[unlikely]]
m_debugState = makeUnique<Wasm::DebugState>();
#endif
#if ENABLE(JIT)
// Make sure that any stubs that the JIT is going to use are initialized in non-compilation threads.
if (Options::useJIT()) {
jitStubs = makeUnique<JITThunks>();
jitStubs->initialize(*this);
#if ENABLE(FTL_JIT)
ftlThunks = makeUnique<FTL::Thunks>();
#endif // ENABLE(FTL_JIT)
m_sharedJITStubs = makeUnique<SharedJITStubSet>();
getBoundFunction(/* isJSFunction */ true, SourceTaintedOrigin::Untainted);
}
#endif // ENABLE(JIT)
if (Options::forceDebuggerBytecodeGeneration() || Options::alwaysUseShadowChicken())
ensureShadowChicken();
#if ENABLE(JIT)
if (Options::dumpBaselineJITSizeStatistics() || Options::dumpDFGJITSizeStatistics())
jitSizeStatistics = makeUnique<JITSizeStatistics>();
#endif
// SPEC-objectmodel §10 manifest entry 4b / M8 (GT#7): flag-on, the fenced
// nuke/publication order must be the ONLY branch (see the flag-on block
// below). The Options write must happen BEFORE Config::finalize()
// write-protects the options storage. Skip the store when the option is
// already set: Config::finalize() freezes the options page once per
// process, so a second VM constructed afterwards must not write to it
// (even a same-value store to a read-only page faults). The first flag-on
// VM forces the option before the freeze, so later VMs always observe
// true here and skip. THREADS-INTEGRATE(objectmodel)
if (Options::useJSThreads() && !Options::forceFencedBarrier()) [[unlikely]]
Options::forceFencedBarrier() = true;
Config::finalize();
// Intentionally do NOT eagerly resolve the host timezone / IANA timezone data
// here. ucal_open() + the IANA timezone enumeration + ICU likely-subtags load
// is one of the single largest contributors to interpreter startup CPU, and a
// large fraction of short-lived processes never touch Date/Intl/toLocaleString.
// DateCache::timeZoneCache() (via timeZoneCacheSlow()) and intlAvailableTimeZones()
// are both guarded by their own one-time initialization, so the work is performed
// lazily on first use instead. process.env.TZ is still honored eagerly because
// WTF::setTimeZoneOverride() only records the timezone id string (cheap) and the
// ICU calendar/likely-subtags resolution is deferred to first use anyway.
if (Options::useVMLite()) [[unlikely]] {
// SPEC-vmstate §6.4.4: main carrier (tid 0), created at the END of
// the ctor. registerLite is the sole writer of VMLite::vm. The ctor
// NEVER calls setCurrent — JSLock::didAcquireLock installs the
// carrier at the outermost acquisition (M4).
m_mainVMLite = makeUnique<VMLite>();
// UNGIL §A.1.3 level-2 byte: copied from vm.m_gilOff AT lite
// registration. Set BEFORE registerLite publishes the lite to
// registry walkers. (A36: GIL-off entry never INSTALLS m_mainVMLite
// — every thread, the main one included, uses a per-(thread,VM)
// carrier from JSLock's TLS map — but the byte is stamped uniformly
// at every registration site.)
m_mainVMLite->gilOff = m_gilOff ? 1 : 0;
VMLiteRegistry::singleton().registerLite(*m_mainVMLite, *this);
}
// SPEC-objectmodel §10 manifest entry 4b / M8 (GT#7): in-place butterfly
// reallocs must stay disabled for the HEAP LIFETIME. Heap::endMarking
// restores the fence from Options::forceFencedBarrier() (Heap.cpp), which
// was forced above, before Config::finalize(). THREADS-INTEGRATE(objectmodel)
if (Options::useJSThreads()) [[unlikely]]
heap.setMutatorShouldBeFenced(true);
// SPEC-objectmodel §9.2/I32 + Task 1 self-test (manifest entry 4a).
if (Options::useJSThreads()) [[unlikely]] {
alignas(16) static uint64_t sampleCell[2];
RELEASE_ASSERT(concurrentButterflyAtomicsAreLockFree(&sampleCell));
concurrentButterflySelfTestIfNeeded(); // runs iff Options::verifyConcurrentButterfly()
}
// SPEC-objectmodel §6 / §10 manifest entry 4c (Task 9): register the
// per-server-heap butterfly-quarantine epoch bump. The adapter runs
// world-stopped once per collection of THIS server heap (legacy AND
// shared protocols, heap CR §13.10d) and bumps ONLY that heap's slot in
// the owned ButterflyQuarantineEpochs registry — NEVER a process-global
// counter (r13). Idempotent per heap; registration must precede client #2.
if (Options::useJSThreads()) [[unlikely]]
registerButterflyQuarantineEpochHook(heap);
// We must set this at the end only after the VM is fully initialized.
WTF::storeStoreFence();
m_isInService = true;
// Register after all VM state is initialized so that a stop-the-world triggered
// immediately on registration sees a fully constructed VM.
VMManager::singleton().notifyVMConstruction(*this);
}
static ReadWriteLock s_destructionLock;
void waitForVMDestruction()
{
Locker locker { s_destructionLock.write() };
}
void VM::setCrossTaskToken(RefPtr<CrossTaskToken>&& token)
{
m_crossTaskToken = WTF::move(token);
}
#if USE(BUN_JSC_ADDITIONS)
void VM::queueMicrotask(QueuedTask&& task)
{
// UNGIL §E.1/I11 (U-T9): GIL-off, enqueue re-routes to the CURRENT
// lite's queue on spawned/non-main-carrier threads — the VM default
// queue is the MAIN carrier's (vmstate §6.6). MAIN-CARRIER KEY
// (GIL-removal review round): GIL-off, m_mainVMLite is NEVER installed
// (A36 — every thread gets a per-(thread,VM) carrier, the main thread
// included), so `lite != m_mainVMLite.get()` alone was constantly true
// and the default queue became an undrained sink. The gilOff main
// carrier is the MAIN THREAD's carrier — exactly the
// ownerHasNoTlsDtor==true lite (A36 r32, fixed at registration; it also
// borrows &vm.clientHeap, F1B) — and it keeps the default queue, paired
// with the same key in drainMicrotasks. Flag-off/GIL-on: the landed
// single-queue enqueue, byte-identical.
if (m_gilOff) [[unlikely]] {
VMLite* lite = VMLite::currentIfExists();
if (lite && lite->vm == this && lite != m_mainVMLite.get() && !lite->ownerHasNoTlsDtor) {
lite->enqueueMicrotaskToDefaultQueue(WTF::move(task));
return;
}
// UNGIL §E.1/§E.4 (TSAN family 30, microtask-queue): the AB-25
// interim fail-stop (RELEASE_ASSERT(isMainThread())) is RETIRED for
// the enqueue arm — this IS the AB-20/AB-23/AB-25 service-request
// word for cross-thread enqueues. GIL-off the VM default queue is
// OWNED by the main thread's carrier (the AB-23 re-key above); a
// no-lite-window/foreign-VM-lite enqueue from any OTHER thread must
// not touch the owner's plain Deque (that was the corruption-grade
// unsynchronized write racing the carrier's drain). Instead it is
// handed off through the queue's lock-guarded foreign inbox and
// serviced at the owner's next drain: the inbox lock
// release(enqueuer)/acquire(carrier drain splice) establishes the
// happens-before that publishes the task's words before the carrier
// dequeues/runs/frees them. The main thread (its own carrier, or
// the pre-carrier no-lite window — ownerHasNoTlsDtor is fixed from
// WTF::isMainThread() at registration, JSLock.cpp) is the owner and
// keeps the landed plain enqueue below. Flag-off/GIL-on: branch not
// taken, landed single-queue enqueue byte-identical.
if (!WTF::isMainThread()) [[unlikely]] {
m_defaultMicrotaskQueue->enqueueFromForeignThread(WTF::move(task));
return;
}
}
m_defaultMicrotaskQueue->enqueue(WTF::move(task));
}
#endif
// UNGIL U-T6 seam (defined in JSLock.cpp, same-library linkage — see the
// banner there): the calling thread's carrier lite for `vm`, or null.
VMLite* carrierLiteOfCurrentThreadIfExists(VM&);
// ============================================================================
// UNGIL ANNEX A36 (as AMENDED r32) + EXIT1.9 (U-T6): the ~VM foreign-carrier
// collection walk — step (2) of the §6.4.4 ~VM order. Runs only for the
// m_gilOff VM (flag-off/GIL-on ~VM is bit-identical to the landed shape).
//
// Under registry-lock holds, each of this VM's carrier lites (the
// ThreadManager carrier TID range — spawned lites are covered by the
// EXIT1.9 step-(3) wait instead) that is not marked TEARDOWN is
// token-free-asserted (proxy: its client holds no heap access; the
// destroying thread's OWN carrier is exempt — its token survives until the
// final m_lock drop, §F.2 IU row 21), marked COLLECTED — the lock-published
// discriminator the owner's TLS destructor keys on — and physically
// unregistered via the notifying wrapper. TEARDOWN lites are SKIPPED (owner
// mid-live-detach, still registered; the step-(3) wait covers them).
//
// The lock is then RELEASED and the walk performs the FULL server-side
// detach of each COLLECTED client lock-free (it acquires MSPL and can park
// in the access bracket — holding the registry lock across it is ILLEGAL,
// LK.6/I7). RECORDED REFINEMENT (this implementation vs the A36 letter):
// the detach is `delete client` — the live GCClient::Heap dtor body IS
// "everything in ~GCClient::Heap that names m_server" (access bracket,
// lastChanceToFinalize's MSPL relinquishment, clientSet().remove), and its
// member destruction (TLC tables, LocalAllocator unlinks — all structural
// no-ops after the relinquishment) also runs against the STILL-ALIVE
// server. A36 defers "client + lite destruction" to the owner's deferred
// dtor; deferring the CLIENT is impossible within U-T6's file ownership —
// ~GCThreadLocalCache (GCThreadLocalCache.cpp, unowned) unconditionally
// constructs a MutatorSlowPathLocker against m_server, so a post-VM-death
// client destruction would UAF the freed server no matter what the dtor
// body skips. Destroying the client INSIDE the walk (server alive; the
// owner is excluded — it is either pre-COLLECTED-wait or token-free and
// never touches the client again, and the degenerate dtor path never
// dereferences lite->clientHeap) preserves every invariant the deferral
// argued for: no double clientSet().remove, no concurrent MSPL section on
// the same client, no owner-side UAF; and the LITE (with its state byte) is
// still freed only by the party that observed DETACHED (the owner's dtor
// for bit-CLEAR; the walk itself, post-flip, for bit-SET) — the byte is
// never read after free. The main-thread carrier's client is BORROWED
// (&vm.clientHeap, F1B) and is never destroyed here — it dies with the VM
// as today.
//
// After each client's detach the walk re-acquires the registry lock, flips
// COLLECTED->DETACHED, notifyAll()s vmTeardownCondition, drops the lock
// (short hold, acquires nothing) and never touches that lite/client again —
// EXCEPT (r32) a bit-SET (ownerHasNoTlsDtor) lite, which the walk itself
// degenerately frees right after its flip: no destructor is ever installed
// over the main-thread slot on any platform, so no competing dtor exists BY
// CONSTRUCTION. A bit-CLEAR lite is NEVER walk-freed.
//
// RECORDED DEVIATION (EXIT1.9 step (2) "one registry-lock hold"): the
// COLLECTED mark and the physical unregistration run in SEPARATE holds
// because VMLiteRegistry::unregisterLite (VMLiteShared.cpp, outside U-T6's
// owned set) takes the non-recursive registry lock itself. Sound: a
// COLLECTED-but-still-registered lite counts EXITED to every conductor
// (EXIT1.4(a)) and the owner's dtor keys ONLY on the state byte, never on
// registration; the whole walk still strictly precedes the step-(3) wait,
// so the wait never counts a carrier.
// ============================================================================
// Returns the DESTROYING THREAD's own collected carrier when its client is
// OWNED (a non-main destroyer) — that client's detach is DEFERRED to
// detachDeferredOwnCarrierClientForVMDestruction, called later in ~VM right
// before heap.lastChanceToFinalize(): the destroying thread's client access
// must survive the access-requiring mid-~VM steps (Strong-clearing teardown
// such as the SD15 purge and DWT shutdown mutate the HandleSet, which
// requires an entered thread WITH access — GIL-on the destroyer holds
// access through all of ~VM for the same reason). Null for a main-thread
// destroyer (borrowed client, flipped in the walk) and when this thread has
// no carrier.
static VMLite* collectForeignCarriersForVMDestruction(VM& vm)
{
ASSERT(vm.gilOff());
auto& registry = VMLiteRegistry::singleton();
VMLite* ownCarrier = carrierLiteOfCurrentThreadIfExists(vm);
VMLite* deferredOwnCarrier = nullptr;
Vector<VMLite*, 4> collected;
{
Locker locker { registry.lock };
for (VMLite* lite : registry.lites) {
if (lite->vm != &vm || lite == vm.mainVMLite())
continue;
if (!ThreadManager::isCarrierTID(lite->tid))
continue; // spawned lite mid-T5: the EXIT1.9 step-(3) wait covers it
if (lite->state == VMLite::State::Teardown)
continue; // owner mid-live-detach: SKIPPED; step (3) covers it
RELEASE_ASSERT(lite->state == VMLite::State::Live); // Collected/Detached lites were unregistered in the hold that marked them
// Token-free assert (A36): an entered carrier holds client heap
// access (F1B acquires on every lock()); an embedder thread
// still entered at ~VM is a §F.6 contract violation. The
// destroying thread's own carrier is exempt (IU row 21).
if (lite != ownCarrier && lite->clientHeap)
RELEASE_ASSERT(!lite->clientHeap->hasHeapAccess());
lite->state = VMLite::State::Collected;
collected.append(lite);
}
}
for (VMLite* lite : collected)
unregisterVMLiteAndNotifyTeardown(*lite); // U20 r31: EVERY physical removal is the notifying call
for (VMLite* lite : collected) {
// The destroying thread's own carrier with an OWNED client: detach
// deferred (see above) — it stays COLLECTED until the deferred
// detach flips it; its owner is THIS thread, so no TLS destructor
// can race the deferral, and the EXIT1.9 wait does not count it
// (already unregistered).
if (lite == ownCarrier && lite->clientHeap && lite->clientHeap != &vm.clientHeap) {
deferredOwnCarrier = lite;
continue;
}
RaceAmplifier::perturb(); // EXIT1.8 CARRIER-TLS-DEATH-DURING-DETACH stall point: post-unregister, pre-detach.
// Lock-free full server-side detach (see the banner). Borrowed
// (main-thread) clients are the VM's own — skipped.
GCClient::Heap* client = lite->clientHeap;
if (client && client != &vm.clientHeap)
delete client; // the live dtor against the still-alive server; may park in the access bracket
RaceAmplifier::perturb(); // EXIT1.8 stall point: post-detach, pre-flip (incl. mid-lastChanceToFinalize via the dtor's own hooks).
bool walkFrees = false;
uint16_t tid = lite->tid;
{
Locker locker { registry.lock };
RELEASE_ASSERT(lite->state == VMLite::State::Collected); // terminal-state machine: no other transition is legal
lite->state = VMLite::State::Detached;
walkFrees = lite->ownerHasNoTlsDtor; // r32: registration-time-fixed; read under the lock like the state byte
vmLiteTeardownCondition().notifyAll(); // wake the owner's COLLECTED wait (short re-hold; acquires nothing)
}
if (walkFrees) {
RaceAmplifier::perturb(); // EXIT1.8 r32 WALK-FREE stall point: between the flip and the degenerate free.
// r32: the walk runs the degenerate free for the bit-SET lite —
// exactly once; no destructor ever visits it (destructor-free
// main-thread map). The owner's TLS-map unique_ptr dangles —
// never consulted (lock() compares the VM epoch BEFORE the
// cached carrier; the stale-epoch eviction release()s it).
delete lite;
releaseCarrierTIDIfHooked(tid);
}
// bit-CLEAR: NEVER walk-freed — the owner's TLS destructor (or the
// stale-epoch eviction on re-entry) runs the degenerate free after
// observing DETACHED and retires the TID there.
}
return deferredOwnCarrier;
}
// The deferred half of the own-carrier disposition (see
// collectForeignCarriersForVMDestruction): runs on the destroying thread
// right before heap.lastChanceToFinalize() — the last point at which the
// server is fully alive and the latest the destroyer may keep client
// access. Deletes the owned client (releasing this thread's access inside
// the dtor) and flips the lite COLLECTED->DETACHED so this thread's own
// eventual TLS destructor (or a stale-epoch eviction) takes the degenerate
// path. Never called for a main-thread destroyer (borrowed client).
static void detachDeferredOwnCarrierClientForVMDestruction(VM& vm, VMLite* lite)
{
if (!lite)