Repository navigation
Expand file tree
/
Copy pathVMManagerStopTheWorldTest.cpp
More file actions
1407 lines (1196 loc) · 54.5 KB
/
Copy pathVMManagerStopTheWorldTest.cpp
File metadata and controls
1407 lines (1196 loc) · 54.5 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) 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. 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 INC. 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 "VMManagerStopTheWorldTest.h"
#include "JavaScript.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/InitializeThreading.h>
#include <JavaScriptCore/JSCConfig.h>
#include <JavaScriptCore/JSStringRefCPP.h>
#include <JavaScriptCore/Options.h>
#include <JavaScriptCore/VMManager.h>
#include <string>
#include <thread>
#include <vector>
#include <wtf/Condition.h>
#include <wtf/DataLog.h>
#include <wtf/Forward.h>
#include <wtf/HashSet.h>
#include <wtf/Lock.h>
#include <wtf/MainThread.h>
#include <wtf/MonotonicTime.h>
#include <wtf/Scope.h>
#include <wtf/Threading.h>
#include <wtf/Vector.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringBuilder.h>
namespace VMManagerStopTheWorldTest {
using JSC::JSGlobalObject;
using JSC::Options;
using JSC::StopTheWorldEvent;
using JSC::StopTheWorldStatus;
using JSC::VM;
using JSC::VMManager;
/*
The Stop the World (STW) feature basically involves multiple threads:
1. Mutator threads running VMs
2. An optional agent thread (like GC or a Debugger)
The Actors
==========
This test exercises the Stop the World feature using the following VMs / threads:
1. main thread
- this is the conductor that orchesrates the test.
- see test().
2. worker threads
- there are numberOfTestVMs of these, and they each run a VM.
- each worker will run through a series of checkpoints, which will serve as
synchronization points for the test.
- see checkpointCallback(), scriptString(), and inactiveWorkerScriptString().
3. inactiveVM thread
- this is a thread with a VM that is not executing some of the time
i.e. the thread is executing code outside of the VM
a.k.a. the thread has not entered the VM
a.k.a. the VM is not activated, hence "inactive".
- the purpose of having this inactiveVM is to ensure that the existence
of an deactivated VM does not block active VMs from reaching world stopped mode.
- we also the scenario where this inactiveVM gets activate while the world is
already stopped. In such a case, the inactiveVM should block on VM entry and
not actually execute any code in the VM.
4. extraVM thread
- this is a thread that creates a new VM after we've in Stop the World.
This tests that the new VM will block on VM construction. We need this because
GlobalGC needs heap activity to stop while the world is stopped. During VM
construction, a lot of JS objects are allocated (i.e. heap activity). Hence,
we need to test that VM construction is blocked while the world is stopped.
The Timeline and Script
=======================
All the test scenarios are outlined in the STEPs below. The way to think of the
STEPs is that each STEP represents a point in time. The orchestration of the test
may bounce around between the different threads above, and sometimes, more than
one thread may be running at the same time. However, the execution of all the
threads are structured so that they obey the STEPS. Depending on the current STEP,
each thread will perform different work / tests (as outlined below).
Lastly, this test employs 2 agents: a WasmDebugger and a MemoryDebugger. These are
only in debuggers in name. We're using them because VMManager provide hooks to
customize the callbacks for these debuggers.
- see wasmDebuggerTestCallback() and memoryDebuggerTestCallback().
In this test, the test WasmDebugger will exercise STW feature like the real
WasmDebugger would. This include allowing a single VM to run in RunOne mode while
all other VMs (and their threads) are stopped.
In this test, the test MemoryDebugger will behave like the GlobalGC agent. The key
scenario we want to test with it is one where the WasmDebugger has a VM running in
RunOne mode, and a GC is triggered. This means that the test MemoryDebugger
(representing GlobalGC) needs to be able to Stop the World while we're in RunOne
mode, and after it is done, it can resume automatically back in RunOne mode allowing
the WasmDebugger to continue.
We will run through the STEPS numberOfIterationsToRun times to ensure that the same
STW operations can be performed more than once, and that there are no residual state
that interferes with subsequent operation.
Outline of the STEPs (test script)
==================================
Setup and Initialization
STEP 0000 Record VMs pre-existing before this test
STEP 0001 Start and count inactive workers
STEP 0001 Start workers
STEP 0003 Wait till worker threads arrive @ checkpoint 0, and are ready to run tests
STEP 0004 All workers arrived at Checkpoint 0.
STEP 0005 Record worker VMs
Run tests
STEP 1000 Start test iteration
STEP 1000.1 Wake all workers
STEP 1000.2 Wait for workers to arrive at Checkpoint 1
// Test 1: Stop the World.
STEP 1100 All workers arrived at Checkpoint 1
STEP 1100.1 Wake all workers
STEP 1100.2 Request Stop the World
STEP 1100.3 Wait for WasmDebugger to stop at Checkpoint 1
STEP 1190 Success: Stopped in WasmDebugger
// Test 2: While in StopTheWorld, test that new VM will stop at VM construction.
STEP 1200 Start Test 2
STEP 1200.1 All workers have stopped in WasmDebugger
STEP 1200.2 Start a new thread and confirm that it stops at VM construction
STEP 1250 Wait for WasmDebugger to detect new thread
STEP 1290 Success: Found new stopped VM / thread
// Test 3: While in StopTheWorld, activating the inactive thread should stop at entry.
STEP 1300 Start Test 3
STEP 1300.1 Activate the inactive VM
STEP 1350 Wait for WasmDebugger to detect new thread
STEP 1390 Success: Found new stopped VM / thread
// Test 4: Context switch between VMs.
STEP 1400 Start Test 4
STEP 1400.1 Switching to a targetVM
STEP 1490 Success: Context switched thru all test VMs
// Test 5: RunOne mode in a targetVM thread.
STEP 1500 Start Test 5
STEP 1510 RunOne mode initiated
STEP 1590 Success: TargetVM reached Checkpoint2
// Test 6: While in RunOne mode, another STW request (MemoryDebugger) should succeed.
STEP 1500 Start Test 6
STEP 1690 Success: TargetVM reached MemoryDebugger
// Test 7: MemoryDebugger's Resume should return to RunOne mode.
STEP 1700 Start Test 7
STEP 1710 Resumed from MemoryDebugger
STEP 1790 Success: MemoryDebugger resumed RunOne mode
// Test 8: While in StopTheWorld, thread completion should ResumeAll
STEP 1800 Start Test 8
STEP 1810 RunOne thread breaks out of Checkpoint2
STEP 1820 RunOne thread will exit imminently
STEP 1830 World has automatically resumed RunAll mode
STEP 1890 Success: all threads parked after resuming RunAll
// Test 9: VM deactivation on RunOne thread should automatically ResumeAll.
STEP 1900 Start Test 9
STEP 1910 Request Stop the World
STEP 1920 Stopped in WasmDebugger
STEP 1930 RunOne in the inactiveVM worker and get it to exit
STEP 1940 Wait for VM deactivation to resume RunAll from RunOne
STEP 1990 Success: All workers auro-resumed RunOne VM deactivated
To find out what each of the test actors are doing for each STEP, search for the
corresponding 4 digit STEP number in the code below.
*/
// Debugging options
constexpr int verboseLevel = 0; // 0 = most quiet, 1 = print SET_STEP, 2 = print all.
constexpr bool crashOnAbort = false; // Crash on first failure if true.
constexpr bool logVMManagerInfoOnEachStep = false; // print VMManager::info() on each STEP if true.
constexpr double timeoutIfTestIsUnresponsive = true;
// Test configuration
constexpr unsigned numberOfInactiveVMs = 1; // Must be 1. Do not change.
constexpr unsigned numberOfTestVMs = 5;
constexpr unsigned numberOfIterationsToRun = 3;
// Test runtime state
unsigned step = 0;
bool needAbort = false;
int failuresFound = 0;
Lock lock;
Condition mainThreadConditionVariable;
Condition extraVMConditionVariable;
Condition workersConditionVariable;
Condition inactiveWorkersTerminationConditionVariable;
bool needToNotifyVMDestruction = false;
bool mainIsWaitingForVMDestruction = false;
Condition okToNotifyVMDestructionConditionVariable;
Condition vmDestructionConditionVariable;
Atomic<unsigned> inactiveVMsCreated;
Vector<VM*>* testVMsPtr = nullptr;
bool isCreatingInactiveVM = false;
Atomic<unsigned> totalNumberOfVMs = 0;
unsigned totalNumberOfActiveVMs = 0;
Atomic<unsigned> numberOfThreadsStarted = 0;
namespace Test0 {
Atomic<unsigned> totalNumberOfVMsReady = 0;
}
namespace Test1 {
Atomic<unsigned> numberOfVMsReady = 0;
}
namespace Test2 {
bool reachedCheckpoint0 = false;
unsigned numberOfStoppedVMsAtStart = 0;
VM* extraVM = nullptr;
}
namespace Test3 {
bool reachedCheckpoint5 = false;
unsigned numberOfStoppedVMsAtStart = 0;
}
namespace Test4 {
unsigned numberOfContextSwitches = 0;
VM* targetVM = nullptr;
}
namespace Test5 {
VM* targetVM = nullptr;
}
namespace Test8 {
VM* targetVM = nullptr;
Atomic<unsigned> numberOfRunningThreads = 0;
Atomic<unsigned> numberOfWaitingThreads = 0;
}
namespace Test9 {
VM* targetVM = nullptr;
Atomic<unsigned> numberOfWaitingThreads = 0;
}
namespace TestEnd {
bool doneTesting = false;
}
#undef TID
#undef DLOG
#undef PAD
#undef LOG_STEP_IMPL
#undef LOG_STEP
#undef LOG_INFO
#undef SET_STEP
#undef CHECK
#undef EXPECT_EQ
#undef EXPECT_NE
#undef VMID
#undef WAIT_TIMEOUT_S
#define TID "t", Thread::currentSingleton().uid()
#define DLOG(threadNameOrLabel, ...) \
dataLogLnIf(verboseLevel >= 2, "<", TID, "> " #threadNameOrLabel " @ ", __LINE__, ": ", __VA_ARGS__)
#define PAD(__step) (verboseLevel > 1 && sizeof(#__step) == 5 ? " " : "")
#define LOG_STEP_IMPL(__doPrint, __step, threadNameOrLabel, ...) do { \
dataLogLnIf((__doPrint), "STEP ", #__step, PAD(__step), " <", TID, "> " #threadNameOrLabel, " @ ", __LINE__, ": ", __VA_ARGS__); \
} while (false)
#define LOG_STEP(__step, threadNameOrLabel, ...) do { \
LOG_STEP_IMPL(verboseLevel >= 2, __step, threadNameOrLabel, __VA_ARGS__); \
} while (false)
#define LOG_INFO(__step, threadNameOrLabel) do { \
auto info = VMManager::info(); \
LOG_STEP_IMPL(logVMManagerInfoOnEachStep, __step, threadNameOrLabel, "-- info VMs: ", info.numberOfVMs, ", ActiveVMs: ", info.numberOfActiveVMs, ", StoppedVMs ", info.numberOfStoppedVMs, ", mode: ", info.worldMode); \
} while (false)
#define SET_STEP(__step, threadNameOrLabel, ...) do { \
LOG_STEP_IMPL(verboseLevel >= 1, __step, threadNameOrLabel, __VA_ARGS__); \
LOG_INFO(__step, threadNameOrLabel); \
step = (unsigned)__step; \
} while (false)
#define CHECK(condition, ...) do { \
if (!(condition)) { \
dataLogLn("FAIL: ", #condition, " @ thread<", TID, ">: ", __VA_ARGS__); \
dataLogLn(" @ " __FILE__, ":", __LINE__); \
failuresFound++; \
} \
} while (false)
#define EXPECT_EQ(actual, expected, ...) do { \
auto expectedValue = expected; \
decltype(expectedValue) actualValue = actual; \
if (expectedValue != actualValue) { \
dataLogLn("FAIL: EXPECT_EQ(", #actual, ", ", #expected, ", ... @ thread<", TID, ">: ", __VA_ARGS__); \
dataLogLn(" @ " __FILE__, ":", __LINE__); \
dataLogLn(" actual: ", actual); \
dataLogLn(" expected: ", expected); \
failuresFound++; \
} \
} while (false)
#define EXPECT_NE(actual, expected, ...) do { \
auto expectedValue = expected; \
decltype(expectedValue) actualValue = actual; \
if (expectedValue == actualValue) { \
dataLogLn("FAIL: EXPECT_NE(", #actual, ", ", #expected, ", ... @ thread<", TID, ">: ", __VA_ARGS__); \
dataLogLn(" @ " __FILE__, ":", __LINE__); \
dataLogLn(" actual: ", actual); \
dataLogLn(" expected: !", expected); \
failuresFound++; \
} \
} while (false)
#define VMID(__vm) \
"vm<", (__vm).identifier(), ">:", RawPointer(&(__vm))
#define WAIT_TIMEOUT_S (timeoutIfTestIsUnresponsive ? Seconds(1.0) : Seconds(std::numeric_limits<double>::infinity()))
class APIString {
WTF_MAKE_NONCOPYABLE(APIString);
public:
APIString(const char* string)
: m_string(JSStringCreateWithUTF8CString(string))
{
}
APIString(JSGlobalContextRef context, JSValueRef value)
: m_string(JSValueToStringCopy(context, value, nullptr))
{
}
~APIString()
{
if (m_string)
SUPPRESS_UNCOUNTED_ARG JSStringRelease(m_string);
}
operator JSStringRef() { return m_string; }
private:
SUPPRESS_UNCOUNTED_MEMBER JSStringRef m_string;
};
static int abortTest(Locker<Lock>&)
{
needAbort = true;
DLOG(abort, "abortTest");
mainThreadConditionVariable.notifyAll();
workersConditionVariable.notifyAll();
inactiveWorkersTerminationConditionVariable.notifyAll();
VMManager::requestResumeAll(VMManager::StopReason::WasmDebugger);
VMManager::requestResumeAll(VMManager::StopReason::MemoryDebugger);
RELEASE_ASSERT(!crashOnAbort || !needAbort);
return -1;
}
static int abortTest()
{
Locker locker { lock };
return abortTest(locker);
}
static std::vector<std::thread>& threadsList()
{
static std::vector<std::thread>* list;
static std::once_flag flag;
std::call_once(flag, [] () {
list = new std::vector<std::thread>();
});
return *list;
}
static JSValueRef checkpointCallback(JSContextRef ctx, JSObjectRef functionObject, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
JSGlobalObject* globalObject = toJS(ctx);
VM& vm = globalObject->vm();
UNUSED_PARAM(functionObject);
UNUSED_PARAM(thisObject);
RELEASE_ASSERT(argumentCount == 1);
RELEASE_ASSERT(!*exception);
unsigned checkpointID = JSValueToInt32(ctx, arguments[0], exception);
RELEASE_ASSERT(!*exception);
if (needAbort)
*exception = JSValueMakeNumber(ctx, 42);
JSValueRef result = nullptr;
switch (checkpointID) {
case 0: { // Checkpoint 0
if (step >= 1820) {
// Later tests should rendezvous at later checkpoints.
result = JSValueMakeBoolean(ctx, false);
break;
}
Locker locker { lock };
if (step >= 1200 && step <= 1290)
Test2::reachedCheckpoint0 = true;
// Have all worker threads wait till the main thread is ready before proceeding.
auto previous = Test0::totalNumberOfVMsReady.exchangeAdd(1);
if (previous + 1 == numberOfTestVMs) {
mainThreadConditionVariable.notifyAll();
SET_STEP(0004, worker, "All workers arrived at Checkpoint 0");
}
workersConditionVariable.wait(lock);
result = JSValueMakeUndefined(ctx);
break;
}
case 1: { // Checkpoint 1
if (step == 1000) {
Locker locker { lock };
// Make sure all threads have reached checkpoint 1.
auto previous = Test1::numberOfVMsReady.exchangeAdd(1);
if (previous + 1 == numberOfTestVMs) {
mainThreadConditionVariable.notifyAll();
SET_STEP(1100, worker, "All workers arrived at Checkpoint 1");
}
workersConditionVariable.wait(lock);
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step <= 1290) {
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step <= 1490) {
LOG_STEP(1490, worker, "Checkpoint 1: Worker should not run while world is stopped in Test 4");
abortTest();
break;
}
if (step >= 1510) {
// Later tests should rendezvous at later checkpoints.
result = JSValueMakeBoolean(ctx, false);
break;
}
LOG_STEP(9999, worker, "Checkpoint 1: should not reach here");
abortTest(); // Should not reach here.
break;
}
case 2: { // Checkpoint 2
if (step == 1510) {
EXPECT_EQ(Test5::targetVM, &vm, "Checkpoint2 reached from the wrong VM thread");
if (failuresFound) {
abortTest();
break;
}
}
if (step < 1590) {
Locker locker { lock };
mainThreadConditionVariable.notifyAll();
SET_STEP(1590, worker, "Success: TargetVM reached Checkpoint2");
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step == 1710) {
Locker locker { lock };
EXPECT_EQ(VMManager::info().worldMode, VMManager::Mode::RunOne, "Should be RunOne");
mainThreadConditionVariable.notifyAll();
SET_STEP(1720, worker, "Confirmed transitioned to RunOne mode at Checkpoint2");
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step == 1800) {
SET_STEP(1810, worker, "RunOne thread breaks out of Checkpoint2");
Test8::targetVM = &vm;
result = JSValueMakeBoolean(ctx, false);
break;
}
if (step >= 1820) {
// Later tests should rendezvous at later checkpoints.
result = JSValueMakeBoolean(ctx, false);
break;
}
result = JSValueMakeBoolean(ctx, true);
break;
}
case 3: { // Checkpoint 3
if (step == 1810) {
ASSERT(Test8::targetVM == &vm);
// This VM is imminently exiting and its thread is terminating. Hence, we need to
// decrement the expected number of VMs and active VMs by 1.
totalNumberOfActiveVMs--;
SET_STEP(1820, worker, "RunOne thread will exit imminently");
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step >= 1820) {
// Later tests should rendezvous at later checkpoints.
result = JSValueMakeBoolean(ctx, false);
break;
}
LOG_STEP(9999, worker, "Checkpoint 1: should not reach here");
abortTest(); // Should not reach here.
break;
}
case 4: { // Checkpoint 4
// Fall through to Checkpoint 5's code intentionally so that Checkpoint 4
// will do the equivalent work of Checkpoint 5 because:
// 1. the regular worker VMs will execute the regular script that goes through
// Checkpoint 4.
// 2. the inactive worker VM will never go through Checkpoint 3, but will end up
// here in Checkpoint 5.
//
// Test 8 and Test 9 will rely on this same checkpoint behavior.
[[fallthrough]];
}
case 5: { // Checkpoint 5
// This part is only for Checkpoint 5. When Checkpoint 4 code falls through to here,
// step will be at least 1820, and will skip this part.
if (step >= 1300 && step <= 1390) {
LOG_STEP(1388.5, worker, "@ Checkpoint 5: Test3::reachedCheckpoint5");
Test3::reachedCheckpoint5 = true;
abortTest();
break;
}
// The following is common to Checkpoint 4 and 5.
if (step == 1820) {
auto previous = Test8::numberOfRunningThreads.exchangeAdd(1);
if (previous + 1 == totalNumberOfActiveVMs) {
SET_STEP(1830, worker, "Success: World automatically resumed RunAll mode");
WTF::storeLoadFence();
}
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step == 1830) {
Locker locker { lock };
auto previous = Test8::numberOfWaitingThreads.exchangeAdd(1);
if (previous + 1 == totalNumberOfActiveVMs) {
SET_STEP(1890, worker, "Success: all threads parked after resuming RunAll");
mainThreadConditionVariable.notifyAll();
}
workersConditionVariable.wait(lock);
result = JSValueMakeBoolean(ctx, true);
break;
}
if (step == 1940) {
if (checkpointID == 5) {
// Get the "inactiveVM" worker to exit its script and deactivate its VM.
result = JSValueMakeBoolean(ctx, false);
break;
}
Locker locker { lock };
auto previous = Test9::numberOfWaitingThreads.exchangeAdd(1);
if (previous + 1 == totalNumberOfActiveVMs) {
mainThreadConditionVariable.notifyAll();
SET_STEP(1990, worker, "Success: All workers auro-resumed RunOne VM deactivated");
}
workersConditionVariable.wait(lock);
break;
}
// The "inactiveVM" may end up stuck in the Checkpoint 5 loop. So, make it
// return false (i.e.stop looping) if we're done.
result = JSValueMakeBoolean(ctx, !TestEnd::doneTesting);
break;
}
case 6: { // Checkpoint 6
result = JSValueMakeBoolean(ctx, TestEnd::doneTesting);
break;
}
} // end switch (checkpointID)
if (needAbort)
*exception = JSValueMakeNumber(ctx, 42);
return result;
}
// This function is just to act as a sink for JS variables to make sure that the JITs don't
// optimize them away.
static JSValueRef ensureAliveCallback(JSContextRef ctx, JSObjectRef functionObject, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
UNUSED_PARAM(functionObject);
UNUSED_PARAM(thisObject);
UNUSED_PARAM(argumentCount);
UNUSED_PARAM(arguments);
UNUSED_PARAM(exception);
return JSValueMakeUndefined(ctx);
}
static StopTheWorldStatus wasmDebuggerTestCallback(VM& vm, StopTheWorldEvent)
{
if (step == 1100) {
// Test 1: Stop the World test.
Locker locker { lock };
SET_STEP(1190, wasmDebugger, "Success: Stopped in WasmDebugger");
mainThreadConditionVariable.notifyAll();
return STW_CONTINUE();
}
// Test 2: While in StopTheWorld, test that new VM will stop at construction.
if (step <= 1200) {
std::this_thread::yield();
return STW_CONTINUE();
}
if (step == 1250) {
auto info = VMManager::info();
if (info.numberOfStoppedVMs <= Test2::numberOfStoppedVMsAtStart) {
std::this_thread::yield();
return STW_CONTINUE();
}
Locker locker { lock };
SET_STEP(1290, wasmDebugger, "Success: Found new stopped VM / thread");
mainThreadConditionVariable.notifyAll();
return STW_CONTINUE();
}
// Test 3: Activated VM should stop.
if (step < 1300) {
std::this_thread::yield();
return STW_CONTINUE();
}
if (step == 1350) {
auto info = VMManager::info();
if (info.numberOfStoppedVMs <= Test3::numberOfStoppedVMsAtStart) {
std::this_thread::yield();
return STW_CONTINUE();
}
Locker locker { lock };
SET_STEP(1390, wasmDebugger, "Success: Found new stopped VM / thread");
mainThreadConditionVariable.notifyAll();
return STW_CONTINUE();
}
// Test 4: Context switch test.
if (step < 1400) {
std::this_thread::yield();
return STW_CONTINUE();
}
if (step < 1490) {
if (Test4::targetVM) {
if (&vm != Test4::targetVM) {
SET_STEP(9999, wasmDebugger, "Failed: Context switched did not reach targetVM");
abortTest();
return STW_RESUME_ALL();
}
}
if (Test4::numberOfContextSwitches < testVMsPtr->size()) {
RELEASE_ASSERT(!Test4::numberOfContextSwitches || &vm == Test4::targetVM);
Test4::targetVM = testVMsPtr->at(Test4::numberOfContextSwitches);
LOG_STEP(1400.1, wasmDebugger, "Switch [", Test4::numberOfContextSwitches, "] from ", VMID(vm), " to targetVM ", VMID(*Test4::targetVM));
Test4::numberOfContextSwitches++;
return STW_CONTEXT_SWITCH(Test4::targetVM);
}
RELEASE_ASSERT(&vm == Test4::targetVM);
Locker locker { lock };
SET_STEP(1490, wasmDebugger, "Success: All context switches succeeded");
mainThreadConditionVariable.notifyAll();
return STW_CONTINUE();
}
// Test 5: RunOne mode in a targetVM thread.
if (step < 1500) {
std::this_thread::yield();
return STW_CONTINUE();
}
if (step < 1510) {
SET_STEP(1510, wasmDebugger, "RunOne mode initiated targetting ", VMID(*Test5::targetVM));
return STW_RESUME_ONE(Test5::targetVM);
}
RELEASE_ASSERT(step != 1510);
if (step < 1590) {
std::this_thread::yield();
return STW_CONTINUE();
}
// Test 9: VM deactivation on RunOne thread should automatically ResumeAll.
if (step < 1900) {
SET_STEP(9999, wasmDebugger, "Failed: Should not have stopped in the WasmDebugger");
abortTest();
return STW_RESUME_ALL();
}
if (step == 1910) {
Locker locker { lock };
SET_STEP(1920, wasmDebugger, "Stopped in WasmDebugger");
mainThreadConditionVariable.notifyAll();
return STW_CONTINUE();
}
if (step == 1930) {
SET_STEP(1940, wasmDebugger, "Wait for VM deactivation to resume RunAll from RunOne");
return STW_RESUME_ONE(Test9::targetVM);
}
if (step < 1990) {
std::this_thread::yield();
return STW_CONTINUE();
}
return STW_RESUME_ALL();
}
static StopTheWorldStatus memoryDebuggerTestCallback(VM&, StopTheWorldEvent)
{
// Test 6: While in RunOne mode, another STW request (MemoryDebugger) should succeed.
if (step == 1600) {
Locker locker { lock };
SET_STEP(1690, memoryDebugger, "Success: Stopped in MemoryDebugger");
mainThreadConditionVariable.notifyAll();
return STW_CONTINUE();
}
if (step < 1700) {
std::this_thread::yield();
return STW_CONTINUE();
}
if (step == 1700) {
Locker locker { lock };
SET_STEP(1710, memoryDebugger, "Resumed from MemoryDebugger");
return STW_RESUME();
}
SET_STEP(9999, memoryDebugger, "Failed: Should not have stopped in the MemoryDebugger");
abortTest();
return STW_RESUME_ALL();
}
static void notifyVMDestruction()
{
Locker locker { lock };
// Either the main thread reaches the rendezvous first or the worker does.
//
// If the main thread is first, then the worker's only job is to tell the
// main thread that they have sync'ed up and both can move forward.
//
// If the worker is first, then it needs to give the main thread time to
// catch up. Hence, the worker should wait for the main thread in that case.
if (!mainIsWaitingForVMDestruction) {
// Worker is first. So, wait.
okToNotifyVMDestructionConditionVariable.wait(lock);
}
vmDestructionConditionVariable.notifyAll();
needToNotifyVMDestruction = false;
}
static void waitForVMDestruction() WTF_REQUIRES_LOCK(lock)
{
mainIsWaitingForVMDestruction = true;
okToNotifyVMDestructionConditionVariable.notifyAll();
vmDestructionConditionVariable.wait(lock);
WTF::compilerFence();
mainIsWaitingForVMDestruction = false;
WTF::storeLoadFence();
}
static int test()
{
// Flush any output from previous tests before starting this one. This will make
// test output read a lot more sensibly since this test uses dataLog which prints
// to stderr while other tests tend to use stdout.
fflush(stdout);
fflush(stderr);
JSC::Config::configureForTesting();
WTF::initializeMainThread();
JSC::initialize();
auto startTime = MonotonicTime::now();
dataLogLn("");
dataLogLn("Starting VMManager StopTheWorld Test");
auto* originalWasmDebugger = g_jscConfig.wasmDebuggerOnStop;
auto* originalWasmDebuggerOnResume = g_jscConfig.wasmDebuggerOnResume;
auto* originalMemoryDebugger = g_jscConfig.memoryDebuggerStopTheWorld;
VMManager::setWasmDebuggerOnStop(wasmDebuggerTestCallback);
VMManager::setWasmDebuggerOnResume([] { /* no-op for test */ });
VMManager::setMemoryDebuggerCallback(memoryDebuggerTestCallback);
// FIXME: for now, VMTraps doesn't completely work on JIT runs yet. Once we fix that, we'll need
// to upgrade these tests to explicitly trigger and test JIT cases.
StringBuilder savedOptionsBuilder;
Options::dumpAllOptionsInALine(savedOptionsBuilder);
Options::setOptions("--useBaselineJIT=false");
auto resetSettings = makeScopeExit([&] {
Options::setOptions(savedOptionsBuilder.toString().ascii().data());
VMManager::setWasmDebuggerOnStop(originalWasmDebugger);
VMManager::setWasmDebuggerOnResume(originalWasmDebuggerOnResume);
VMManager::setMemoryDebuggerCallback(originalMemoryDebugger);
});
#define ABORT_IF_FAILED(__locker) do { \
if (failuresFound) { \
abortTest(__locker); \
return true; \
} \
} while (false)
// Code for worker threads.
auto task = [] (VM** addressOfVMToExport) {
int ret = 0;
// Script for regular worker.
std::string scriptString = R"script({
// For active VM workers.
function foo() { return 1; }
function bar() { return 2; }
function baz() { return 3; }
checkpoint(0);
// Run the whole thing more than once (controlled by checkpoint(3)) so that we can verify
// that there's no stuck state between all the stop and resumes.
for (;;) {
var x = 0;
while (checkpoint(1))
x += foo();
while (checkpoint(2))
x += bar();
if (checkpoint(3))
break;
while (checkpoint(4))
x += baz();
if (checkpoint(6))
break;
}
ensureAlive(x);
})script";
// Test 8: The inactive worker creates the worker and then just waits.
// Script for the "inactiveVM" worker.
std::string inactiveWorkerScriptString = R"script({
// For the inactive VM which we later activate.
function foo() { return 1; }
var x = 0;
while (checkpoint(5))
x += foo();
ensureAlive(x);
})script";
bool isInactiveWorker = isCreatingInactiveVM;
if (isInactiveWorker)
LOG_STEP(0001.1, worker, "START thread");
else {
numberOfThreadsStarted.exchangeAdd(1);
LOG_STEP(0002.1, worker, "START thread");
}
totalNumberOfVMs.exchangeAdd(1); // JSGlobalContextCreateInGroup will create a VM.
JSGlobalContextRef context = JSGlobalContextCreateInGroup(nullptr, nullptr);
JSObjectRef globalObject = JSContextGetGlobalObject(context);
RELEASE_ASSERT(JSValueIsObject(context, globalObject));
VM& vm = toJS(context)->vm();
if (addressOfVMToExport)
*addressOfVMToExport = &vm;
if (isInactiveWorker)
LOG_STEP(0001.2, worker, "Created ", VMID(vm));
else
LOG_STEP(0002.2, worker, "Created ", VMID(vm));
auto installGlobalFunction = [&] (const char* name, auto callback) {
APIString nameStr(name);
JSObjectRef function = JSObjectMakeFunctionWithCallback(context, nameStr, callback);
SUPPRESS_UNCOUNTED_ARG JSObjectSetProperty(context, globalObject, nameStr, function, kJSPropertyAttributeNone, nullptr);
};
installGlobalFunction("checkpoint", checkpointCallback);
installGlobalFunction("ensureAlive", ensureAliveCallback);
while (!TestEnd::doneTesting) {
if (isInactiveWorker) {
// Initially, the inactive worker creates the worker and then just waits.
Locker locker { lock };
auto previous = inactiveVMsCreated.exchangeAdd(1);
LOG_STEP(0001.3, worker, "previous ", previous, " inactiveVMsCreated ", inactiveVMsCreated.loadRelaxed());
if (previous + 1 == numberOfInactiveVMs)
mainThreadConditionVariable.notifyAll();
if (TestEnd::doneTesting)
break;
inactiveWorkersTerminationConditionVariable.wait(lock);
}
std::string* scriptStringToEvaluate = isInactiveWorker ? &inactiveWorkerScriptString : &scriptString;
APIString jsScriptString(scriptStringToEvaluate->c_str());
CHECK(jsScriptString, "script C string to jsString");
JSValueRef exception = nullptr;
SUPPRESS_UNCOUNTED_ARG JSValueRef jsScript = JSEvaluateScript(context, jsScriptString, nullptr, nullptr, 0, &exception);
CHECK(!exception, "unexpected exception from script evaluation");
if (exception) {
APIString string(context, exception);
if (string) {
SUPPRESS_UNCOUNTED_ARG dataLogLn("FAIL: thread<", TID, "> ", __FILE__, ":", __LINE__, ": ", utf8CString(string));
} else
dataLogLn("FAIL: thread<", TID, "> ", __FILE__, ":", __LINE__, ": stringifying exception failed");
}
CHECK(jsScript, "script evaluation");
if (step >= 1800 && step < 1890) {
// In Test 8, the RunOne thread should terminate.
break; // Don't loop again.
}
}
JSGlobalContextRelease(context);
totalNumberOfVMs.exchangeSub(1); // JSGlobalContextRelease will destroy the VM.
if (needToNotifyVMDestruction)
notifyVMDestruction();
return ret;
};
UncheckedKeyHashSet<VM*> preexistingVMs;
Vector<VM*> testVMs;
VM* inactiveVM = nullptr;
// === Set up and prepare for testing ===================================================
// Setup initial conditions.
// If we ever want to run this test more than once (for some internal debugging),
// explicitly re-initializing to their expected default values will be essential.
inactiveVMsCreated.exchange(0);
testVMsPtr = &testVMs; // Hack so that STW callbacks can access this list.
isCreatingInactiveVM = false;
numberOfThreadsStarted.exchange(0);
Test0::totalNumberOfVMsReady.exchange(0);
Test1::numberOfVMsReady.exchange(0);
Test2::reachedCheckpoint0 = false;
TestEnd::doneTesting = false;
// We should ideally run this test in its own process so that we're in full control of
// the number of VMs in play. However, for this first cut, we're going to piggy back
// off of testapi. So, we need to account for pre-existing VMs that may be left over
// from other tests that testapi runs. We need to track and discount those VMs.
SET_STEP(0000, main, "Record VMs pre-existing before this test");
auto error = VMManager::forEachVMWithTimeout(WAIT_TIMEOUT_S, [&] (VM& vm) {
preexistingVMs.add(&vm);
return IterationStatus::Continue;
});
EXPECT_EQ(error, VMManager::Error::None, "Failed to collect pre-existing VMs.");
// We expect that no other tests are running concurrently while this test is executing.
// Hence, the only VMs added/removed should be from this test, and we can track them
// with some tricks.
totalNumberOfVMs.exchange(preexistingVMs.size());
// Start our worker threads.
SET_STEP(0001, main, "Start and count inactive workers");
// Start our inactive worker threads.
isCreatingInactiveVM = true;
WTF::storeLoadFence();
for (unsigned t = 0; t < numberOfInactiveVMs; ++t)
threadsList().push_back(std::thread(task, &inactiveVM));
if (numberOfInactiveVMs) {
Locker locker { lock };