-
Notifications
You must be signed in to change notification settings - Fork 15
/
Internal.hs
1424 lines (1268 loc) · 61 KB
/
Internal.hs
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
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTSyntax #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- incomplete uni patterns in 'schedule' (when interpreting 'StmTxCommitted')
-- and 'reschedule'.
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module Control.Monad.IOSim.Internal
( IOSim (..)
, SimM
, runIOSim
, runSimTraceST
, traceM
, traceSTM
, STM
, STMSim
, SimSTM
, setCurrentTime
, unshareClock
, TimeoutException (..)
, EventlogEvent (..)
, EventlogMarker (..)
, ThreadId
, ThreadLabel
, Labelled (..)
, SimTrace
, Trace.Trace (SimTrace, Trace, TraceMainReturn, TraceMainException, TraceDeadlock)
, SimEvent (..)
, SimResult (..)
, SimEventType (..)
, TraceEvent
, ppTrace
, ppTrace_
, ppSimEvent
, liftST
, execReadTVar
) where
import Prelude hiding (read)
import Data.Dynamic
import Data.Foldable (toList, traverse_, foldlM)
import Deque.Strict (Deque)
import qualified Deque.Strict as Deque
import qualified Data.List as List
import qualified Data.List.Trace as Trace
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (mapMaybe)
import Data.OrdPSQ (OrdPSQ)
import qualified Data.OrdPSQ as PSQ
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Time (UTCTime (..), fromGregorian)
import GHC.Exts (fromList)
import GHC.Conc (ThreadStatus(..), BlockReason(..))
import Control.Exception
(NonTermination (..), assert, throw, AsyncException (..))
import Control.Monad (join, when)
import Control.Monad.ST.Lazy
import Control.Monad.ST.Lazy.Unsafe (unsafeIOToST, unsafeInterleaveST)
import Data.STRef.Lazy
import Control.Concurrent.Class.MonadSTM.TVar hiding (TVar)
import Control.Monad.Class.MonadSTM hiding (STM)
import Control.Monad.Class.MonadThrow hiding (getMaskingState)
import Control.Monad.Class.MonadTime
import Control.Monad.Class.MonadTimer
import Control.Monad.IOSim.InternalTypes
import Control.Monad.IOSim.Types hiding (SimEvent (SimPOREvent),
Trace (SimPORTrace))
import Control.Monad.IOSim.Types (SimEvent)
--
-- Simulation interpreter
--
data Thread s a = Thread {
threadId :: !ThreadId,
threadControl :: !(ThreadControl s a),
threadBlocked :: !Bool,
threadMasking :: !MaskingState,
-- other threads blocked in a ThrowTo to us because we are or were masked
threadThrowTo :: ![(SomeException, Labelled ThreadId)],
threadClockId :: !ClockId,
threadLabel :: Maybe ThreadLabel,
threadNextTId :: !Int
}
labelledTVarId :: TVar s a -> ST s (Labelled TVarId)
labelledTVarId TVar { tvarId, tvarLabel } = (Labelled tvarId) <$> readSTRef tvarLabel
labelledThreads :: Map ThreadId (Thread s a) -> [Labelled ThreadId]
labelledThreads threadMap =
-- @Map.foldr'@ (and alikes) are not strict enough, to not ratain the
-- original thread map we need to evaluate the spine of the list.
-- TODO: https://github.com/haskell/containers/issues/749
Map.foldr'
(\Thread { threadId, threadLabel } !acc -> Labelled threadId threadLabel : acc)
[] threadMap
-- | Timers mutable variables. Supports 'newTimeout' api, the second
-- one 'registerDelay', the third one 'threadDelay'.
--
data TimerCompletionInfo s =
Timer !(TVar s TimeoutState)
| TimerRegisterDelay !(TVar s Bool)
| TimerThreadDelay !ThreadId
| TimerTimeout !ThreadId !TimeoutId !(STRef s IsLocked)
-- | Internal state.
--
data SimState s a = SimState {
runqueue :: !(Deque ThreadId),
-- | All threads other than the currently running thread: both running
-- and blocked threads.
threads :: !(Map ThreadId (Thread s a)),
-- | Keep track of the reason threads finished for 'threadStatus'
finished :: !(Map ThreadId FinishedReason),
-- | current time
curTime :: !Time,
-- | ordered list of timers and timeouts
timers :: !(OrdPSQ TimeoutId Time (TimerCompletionInfo s)),
-- | list of clocks
clocks :: !(Map ClockId UTCTime),
nextVid :: !TVarId, -- ^ next unused 'TVarId'
nextTmid :: !TimeoutId -- ^ next unused 'TimeoutId'
}
initialState :: SimState s a
initialState =
SimState {
runqueue = mempty,
threads = Map.empty,
finished = Map.empty,
curTime = Time 0,
timers = PSQ.empty,
clocks = Map.singleton (ClockId []) epoch1970,
nextVid = TVarId 0,
nextTmid = TimeoutId 0
}
where
epoch1970 = UTCTime (fromGregorian 1970 1 1) 0
invariant :: Maybe (Thread s a) -> SimState s a -> x -> x
invariant (Just running) simstate@SimState{runqueue,threads,clocks} =
assert (not (threadBlocked running))
. assert (threadId running `Map.notMember` threads)
. assert (threadId running `List.notElem` runqueue)
. assert (threadClockId running `Map.member` clocks)
. invariant Nothing simstate
invariant Nothing SimState{runqueue,threads,clocks} =
assert (all (`Map.member` threads) runqueue)
. assert (and [ threadBlocked t == (threadId t `notElem` runqueue)
| t <- Map.elems threads ])
. assert (toList runqueue == List.nub (toList runqueue))
. assert (and [ threadClockId t `Map.member` clocks
| t <- Map.elems threads ])
-- | Interpret the simulation monotonic time as a 'NominalDiffTime' since
-- the start.
timeSinceEpoch :: Time -> NominalDiffTime
timeSinceEpoch (Time t) = fromRational (toRational t)
-- | Schedule / run a thread.
--
schedule :: Thread s a -> SimState s a -> ST s (SimTrace a)
schedule !thread@Thread{
threadId = tid,
threadControl = ThreadControl action ctl,
threadMasking = maskst,
threadLabel = tlbl
}
!simstate@SimState {
runqueue,
threads,
finished,
timers,
clocks,
nextVid, nextTmid,
curTime = time
} =
invariant (Just thread) simstate $
case action of
Return x -> {-# SCC "schedule.Return" #-}
case ctl of
MainFrame ->
-- the main thread is done, so we're done
-- even if other threads are still running
return $ SimTrace time tid tlbl EventThreadFinished
$ TraceMainReturn time x (labelledThreads threads)
ForkFrame -> do
-- this thread is done
!trace <- deschedule (Terminated FinishedNormally) thread simstate
return $ SimTrace time tid tlbl EventThreadFinished
$ SimTrace time tid tlbl (EventDeschedule $ Terminated FinishedNormally)
$ trace
MaskFrame k maskst' ctl' -> do
-- pop the control stack, restore thread-local state
let thread' = thread { threadControl = ThreadControl (k x) ctl'
, threadMasking = maskst' }
-- but if we're now unmasked, check for any pending async exceptions
!trace <- deschedule Interruptable thread' simstate
return $ SimTrace time tid tlbl (EventMask maskst')
$ SimTrace time tid tlbl (EventDeschedule Interruptable)
$ trace
CatchFrame _handler k ctl' -> do
-- pop the control stack and continue
let thread' = thread { threadControl = ThreadControl (k x) ctl' }
schedule thread' simstate
TimeoutFrame tmid isLockedRef k ctl' -> do
-- There is a possible race between timeout action and the timeout expiration.
-- We use a lock to solve the race.
--
-- The lock starts 'NotLocked' and when the timeout fires the lock is
-- locked and asynchronously an assassin thread is coming to interrupt
-- it. If the lock is locked when the timeout is fired then nothing
-- happens.
--
-- Knowing this, if we reached this point in the code and the lock is
-- 'Locked', then it means that this thread still hasn't received the
-- 'TimeoutException', so we need to kill the thread that is responsible
-- for doing that (the assassin thread, we need to defend ourselves!)
-- and run our continuation successfully and peacefully. We will do that
-- by uninterruptibly-masking ourselves so we can not receive any
-- exception and kill the assassin thread behind its back.
-- If the lock is 'NotLocked' then it means we can just acquire it and
-- carry on with the success case.
locked <- readSTRef isLockedRef
case locked of
Locked etid -> do
let -- Kill the assassin throwing thread and carry on the
-- continuation
thread' =
thread { threadControl =
ThreadControl (ThrowTo (toException ThreadKilled)
etid
(k (Just x)))
ctl'
, threadMasking = MaskedUninterruptible
}
schedule thread' simstate
NotLocked -> do
-- Acquire lock
writeSTRef isLockedRef (Locked tid)
-- Remove the timer from the queue
let timers' = PSQ.delete tmid timers
-- Run the continuation
thread' = thread { threadControl = ThreadControl (k (Just x)) ctl' }
schedule thread' simstate { timers = timers'
}
Throw thrower e -> {-# SCC "schedule.Throw" #-}
case unwindControlStack e thread of
-- Found a CatchFrame
Right thread'@Thread { threadMasking = maskst' } -> do
-- We found a suitable exception handler, continue with that
trace <- schedule thread' simstate
return (SimTrace time tid tlbl (EventThrow e) $
SimTrace time tid tlbl (EventMask maskst') trace)
Left isMain
-- We unwound and did not find any suitable exception handler, so we
-- have an unhandled exception at the top level of the thread.
| isMain ->
-- An unhandled exception in the main thread terminates the program
return (SimTrace time tid tlbl (EventThrow e) $
SimTrace time tid tlbl (EventThreadUnhandled e) $
TraceMainException time e (labelledThreads threads))
| otherwise -> do
-- An unhandled exception in any other thread terminates the thread
let reason | ThrowSelf <- thrower = FinishedNormally
| otherwise = FinishedDied
!trace <- deschedule (Terminated reason) thread simstate
return $ SimTrace time tid tlbl (EventThrow e)
$ SimTrace time tid tlbl (EventThreadUnhandled e)
$ SimTrace time tid tlbl (EventDeschedule $ Terminated reason)
$ trace
Catch action' handler k ->
{-# SCC "schedule.Catch" #-} do
-- push the failure and success continuations onto the control stack
let thread' = thread { threadControl = ThreadControl action'
(CatchFrame handler k ctl) }
schedule thread' simstate
Evaluate expr k ->
{-# SCC "schedule.Evaulate" #-} do
mbWHNF <- unsafeIOToST $ try $ evaluate expr
case mbWHNF of
Left e -> do
-- schedule this thread to immediately raise the exception
let thread' = thread { threadControl = ThreadControl (Throw ThrowSelf e) ctl }
schedule thread' simstate
Right whnf -> do
-- continue with the resulting WHNF
let thread' = thread { threadControl = ThreadControl (k whnf) ctl }
schedule thread' simstate
Say msg k ->
{-# SCC "schedule.Say" #-} do
let thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate
return (SimTrace time tid tlbl (EventSay msg) trace)
Output x k ->
{-# SCC "schedule.Output" #-} do
let thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate
return (SimTrace time tid tlbl (EventLog x) trace)
LiftST st k ->
{-# SCC "schedule.LiftST" #-} do
x <- strictToLazyST st
let thread' = thread { threadControl = ThreadControl (k x) ctl }
schedule thread' simstate
GetMonoTime k ->
{-# SCC "schedule.GetMonoTime" #-} do
let thread' = thread { threadControl = ThreadControl (k time) ctl }
schedule thread' simstate
GetWallTime k ->
{-# SCC "schedule.GetWallTime" #-} do
let !clockid = threadClockId thread
!clockoff = clocks Map.! clockid
!walltime = timeSinceEpoch time `addUTCTime` clockoff
!thread' = thread { threadControl = ThreadControl (k walltime) ctl }
schedule thread' simstate
SetWallTime walltime' k ->
{-# SCC "schedule.SetWallTime" #-} do
let !clockid = threadClockId thread
!clockoff = clocks Map.! clockid
!walltime = timeSinceEpoch time `addUTCTime` clockoff
!clockoff' = addUTCTime (diffUTCTime walltime' walltime) clockoff
!thread' = thread { threadControl = ThreadControl k ctl }
!simstate' = simstate { clocks = Map.insert clockid clockoff' clocks }
schedule thread' simstate'
UnshareClock k ->
{-# SCC "schedule.UnshareClock" #-} do
let !clockid = threadClockId thread
!clockoff = clocks Map.! clockid
!clockid' = let ThreadId i = tid in ClockId i -- reuse the thread id
!thread' = thread { threadControl = ThreadControl k ctl
, threadClockId = clockid' }
!simstate' = simstate { clocks = Map.insert clockid' clockoff clocks }
schedule thread' simstate'
-- we treat negative timers as cancelled ones; for the record we put
-- `EventTimerCreated` and `EventTimerCancelled` in the trace; This differs
-- from `GHC.Event` behaviour.
NewTimeout d k | d < 0 ->
{-# SCC "schedule.NewTimeout.1" #-} do
let !t = NegativeTimeout nextTmid
!expiry = d `addTime` time
!thread' = thread { threadControl = ThreadControl (k t) ctl }
trace <- schedule thread' simstate { nextTmid = succ nextTmid }
return (SimTrace time tid tlbl (EventTimerCreated nextTmid nextVid expiry) $
SimTrace time tid tlbl (EventTimerCancelled nextTmid) $
trace)
NewTimeout d k ->
{-# SCC "schedule.NewTimeout.2" #-} do
!tvar <- execNewTVar nextVid
(Just $ "<<timeout-state " ++ show (unTimeoutId nextTmid) ++ ">>")
TimeoutPending
let !expiry = d `addTime` time
!t = Timeout tvar nextTmid
!timers' = PSQ.insert nextTmid expiry (Timer tvar) timers
!thread' = thread { threadControl = ThreadControl (k t) ctl }
trace <- schedule thread' simstate { timers = timers'
, nextVid = succ nextVid
, nextTmid = succ nextTmid }
return (SimTrace time tid tlbl (EventTimerCreated nextTmid nextVid expiry) trace)
-- This case is guarded by checks in 'timeout' itself.
StartTimeout d _ _ | d <= 0 ->
error "schedule: StartTimeout: Impossible happened"
StartTimeout d action' k ->
{-# SCC "schedule.StartTimeout" #-} do
isLockedRef <- newSTRef NotLocked
let !expiry = d `addTime` time
!timers' = PSQ.insert nextTmid expiry (TimerTimeout tid nextTmid isLockedRef) timers
!thread' = thread { threadControl =
ThreadControl action'
(TimeoutFrame nextTmid isLockedRef k ctl)
}
!trace <- deschedule Yield thread' simstate { timers = timers'
, nextTmid = succ nextTmid }
return (SimTrace time tid tlbl (EventTimeoutCreated nextTmid tid expiry) trace)
RegisterDelay d k | d < 0 ->
{-# SCC "schedule.NewRegisterDelay.1" #-} do
!tvar <- execNewTVar nextVid
(Just $ "<<timeout " ++ show (unTimeoutId nextTmid) ++ ">>")
True
let !expiry = d `addTime` time
!thread' = thread { threadControl = ThreadControl (k tvar) ctl }
trace <- schedule thread' simstate { nextVid = succ nextVid }
return (SimTrace time tid tlbl (EventRegisterDelayCreated nextTmid nextVid expiry) $
SimTrace time tid tlbl (EventRegisterDelayFired nextTmid) $
trace)
RegisterDelay d k ->
{-# SCC "schedule.NewRegisterDelay.2" #-} do
!tvar <- execNewTVar nextVid
(Just $ "<<timeout " ++ show (unTimeoutId nextTmid) ++ ">>")
False
let !expiry = d `addTime` time
!timers' = PSQ.insert nextTmid expiry (TimerRegisterDelay tvar) timers
!thread' = thread { threadControl = ThreadControl (k tvar) ctl }
trace <- schedule thread' simstate { timers = timers'
, nextVid = succ nextVid
, nextTmid = succ nextTmid }
return (SimTrace time tid tlbl
(EventRegisterDelayCreated nextTmid nextVid expiry) trace)
ThreadDelay d k | d < 0 ->
{-# SCC "schedule.NewThreadDelay" #-} do
let !expiry = d `addTime` time
!thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate
return (SimTrace time tid tlbl (EventThreadDelay expiry) $
SimTrace time tid tlbl EventThreadDelayFired $
trace)
ThreadDelay d k ->
{-# SCC "schedule.NewThreadDelay" #-} do
let !expiry = d `addTime` time
!timers' = PSQ.insert nextTmid expiry (TimerThreadDelay tid) timers
!thread' = thread { threadControl = ThreadControl k ctl }
!trace <- deschedule Blocked thread' simstate { timers = timers'
, nextTmid = succ nextTmid }
return (SimTrace time tid tlbl (EventThreadDelay expiry) trace)
-- we do not follow `GHC.Event` behaviour here; updating a timer to the past
-- effectively cancels it.
UpdateTimeout (Timeout _tvar tmid) d k | d < 0 ->
{-# SCC "schedule.UpdateTimeout" #-} do
let !timers' = PSQ.delete tmid timers
!thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate { timers = timers' }
return (SimTrace time tid tlbl (EventTimerCancelled tmid) trace)
UpdateTimeout (Timeout _tvar tmid) d k ->
{-# SCC "schedule.UpdateTimeout" #-} do
-- updating an expired timeout is a noop, so it is safe
-- to race using a timeout with updating or cancelling it
let updateTimeout_ Nothing = ((), Nothing)
updateTimeout_ (Just (_p, v)) = ((), Just (expiry, v))
!expiry = d `addTime` time
!timers' = snd (PSQ.alter updateTimeout_ tmid timers)
!thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate { timers = timers' }
return (SimTrace time tid tlbl (EventTimerUpdated tmid expiry) trace)
-- updating a negative timer is a no-op, unlike in `GHC.Event`.
UpdateTimeout (NegativeTimeout _tmid) _d k ->
{-# SCC "schedule.UpdateTimeout" #-} do
let thread' = thread { threadControl = ThreadControl k ctl }
schedule thread' simstate
CancelTimeout (Timeout tvar tmid) k ->
{-# SCC "schedule.CancelTimeout" #-} do
let !timers' = PSQ.delete tmid timers
!thread' = thread { threadControl = ThreadControl k ctl }
!written <- execAtomically' (runSTM $ writeTVar tvar TimeoutCancelled)
(wakeup, wokeby) <- threadsUnblockedByWrites written
mapM_ (\(SomeTVar var) -> unblockAllThreadsFromTVar var) written
let (unblocked,
simstate') = unblockThreads wakeup simstate
trace <- schedule thread' simstate' { timers = timers' }
return $ SimTrace time tid tlbl (EventTimerCancelled tmid)
$ traceMany
[ (time, tid', tlbl', EventTxWakeup vids)
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads
, let Just vids = Set.toList <$> Map.lookup tid' wokeby ]
$ trace
-- cancelling a negative timer is a no-op
CancelTimeout (NegativeTimeout _tmid) k ->
{-# SCC "schedule.CancelTimeout" #-} do
-- negative timers are promptly removed from the state
let thread' = thread { threadControl = ThreadControl k ctl }
schedule thread' simstate
Fork a k ->
{-# SCC "schedule.Fork" #-} do
let !nextId = threadNextTId thread
!tid' = childThreadId tid nextId
!thread' = thread { threadControl = ThreadControl (k tid') ctl
, threadNextTId = succ nextId }
!thread'' = Thread { threadId = tid'
, threadControl = ThreadControl (runIOSim a)
ForkFrame
, threadBlocked = False
, threadMasking = threadMasking thread
, threadThrowTo = []
, threadClockId = threadClockId thread
, threadLabel = Nothing
, threadNextTId = 1
}
!threads' = Map.insert tid' thread'' threads
trace <- schedule thread' simstate { runqueue = Deque.snoc tid' runqueue
, threads = threads' }
return (SimTrace time tid tlbl (EventThreadForked tid') trace)
Atomically a k ->
{-# SCC "schedule.Atomically" #-} execAtomically time tid tlbl nextVid (runSTM a) $ \res ->
case res of
StmTxCommitted x written _read created
tvarDynamicTraces tvarStringTraces nextVid' -> do
(!wakeup, wokeby) <- threadsUnblockedByWrites written
!_ <- mapM_ (\(SomeTVar tvar) -> unblockAllThreadsFromTVar tvar) written
let thread' = thread { threadControl = ThreadControl (k x) ctl }
(unblocked,
simstate') = unblockThreads wakeup simstate
written' <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) written
created' <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) created
-- We don't interrupt runnable threads to provide fairness
-- anywhere else. We do it here by putting the tx that committed
-- a transaction to the back of the runqueue, behind all other
-- runnable threads, and behind the unblocked threads.
-- For testing, we should have a more sophisticated policy to show
-- that algorithms are not sensitive to the exact policy, so long
-- as it is a fair policy (all runnable threads eventually run).
!trace <- deschedule Yield thread' simstate' { nextVid = nextVid' }
return $ SimTrace time tid tlbl (EventTxCommitted
written' created' Nothing)
$ traceMany
[ (time, tid', tlbl', EventTxWakeup vids')
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads
, let Just vids' = Set.toList <$> Map.lookup tid' wokeby ]
$ traceMany
[ (time, tid, tlbl, EventLog tr)
| tr <- tvarDynamicTraces ]
$ traceMany
[ (time, tid, tlbl, EventSay str)
| str <- tvarStringTraces ]
$ SimTrace time tid tlbl (EventUnblocked unblocked)
$ SimTrace time tid tlbl (EventDeschedule Yield)
$ trace
StmTxAborted _read e -> do
-- schedule this thread to immediately raise the exception
let thread' = thread { threadControl = ThreadControl (Throw ThrowSelf e) ctl }
!trace <- schedule thread' simstate
return $ SimTrace time tid tlbl (EventTxAborted Nothing) trace
StmTxBlocked read -> do
!_ <- mapM_ (\(SomeTVar tvar) -> blockThreadOnTVar tid tvar) read
vids <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) read
!trace <- deschedule Blocked thread simstate
return $ SimTrace time tid tlbl (EventTxBlocked vids Nothing)
$ SimTrace time tid tlbl (EventDeschedule Blocked)
$ trace
GetThreadId k ->
{-# SCC "schedule.GetThreadId" #-} do
let thread' = thread { threadControl = ThreadControl (k tid) ctl }
schedule thread' simstate
LabelThread tid' l k | tid' == tid ->
{-# SCC "schedule.LabelThread" #-} do
let thread' = thread { threadControl = ThreadControl k ctl
, threadLabel = Just l }
schedule thread' simstate
LabelThread tid' l k ->
{-# SCC "schedule.LabelThread" #-} do
let thread' = thread { threadControl = ThreadControl k ctl }
threads' = Map.adjust (\t -> t { threadLabel = Just l }) tid' threads
schedule thread' simstate { threads = threads' }
ThreadStatus tid' k ->
{-# SCC "schedule.ThreadStatus" #-} do
let result | Just r <- Map.lookup tid' finished = reasonToStatus r
| Just t <- Map.lookup tid' threads = threadStatus t
| otherwise = error "The impossible happened - tried to loookup thread in state."
reasonToStatus FinishedNormally = ThreadFinished
reasonToStatus FinishedDied = ThreadDied
threadStatus t | threadBlocked t = ThreadBlocked BlockedOnOther
| otherwise = ThreadRunning
thread' = thread { threadControl = ThreadControl (k result) ctl }
schedule thread' simstate
GetMaskState k ->
{-# SCC "schedule.GetMaskState" #-} do
let thread' = thread { threadControl = ThreadControl (k maskst) ctl }
schedule thread' simstate
SetMaskState maskst' action' k ->
{-# SCC "schedule.SetMaskState" #-} do
let thread' = thread { threadControl = ThreadControl
(runIOSim action')
(MaskFrame k maskst ctl)
, threadMasking = maskst' }
trace <-
case maskst' of
-- If we're now unmasked then check for any pending async exceptions
Unmasked -> SimTrace time tid tlbl (EventDeschedule Interruptable)
<$> deschedule Interruptable thread' simstate
_ -> schedule thread' simstate
return $ SimTrace time tid tlbl (EventMask maskst')
$ trace
ThrowTo e tid' _ | tid' == tid ->
{-# SCC "schedule.ThrowTo" #-} do
-- Throw to ourself is equivalent to a synchronous throw,
-- and works irrespective of masking state since it does not block.
let thread' = thread { threadControl = ThreadControl (Throw ThrowSelf e) ctl }
trace <- schedule thread' simstate
return (SimTrace time tid tlbl (EventThrowTo e tid) trace)
ThrowTo e tid' k ->
{-# SCC "schedule.ThrowTo" #-} do
let thread' = thread { threadControl = ThreadControl k ctl }
willBlock = case Map.lookup tid' threads of
Just t -> not (threadInterruptible t)
_ -> False
if willBlock
then do
-- The target thread has async exceptions masked so we add the
-- exception and the source thread id to the pending async exceptions.
let adjustTarget t = t { threadThrowTo = (e, Labelled tid tlbl) : threadThrowTo t }
threads' = Map.adjust adjustTarget tid' threads
!trace <- deschedule Blocked thread' simstate { threads = threads' }
return $ SimTrace time tid tlbl (EventThrowTo e tid')
$ SimTrace time tid tlbl EventThrowToBlocked
$ SimTrace time tid tlbl (EventDeschedule Blocked)
$ trace
else do
-- The target thread has async exceptions unmasked, or is masked but
-- is blocked (and all blocking operations are interruptible) then we
-- raise the exception in that thread immediately. This will either
-- cause it to terminate or enter an exception handler.
-- In the meantime the thread masks new async exceptions. This will
-- be resolved if the thread terminates or if it leaves the exception
-- handler (when restoring the masking state would trigger the any
-- new pending async exception).
let thrower = case threadMasking <$> Map.lookup tid' threads of
Just Unmasked -> ThrowOther
_ -> ThrowSelf
adjustTarget t@Thread{ threadControl = ThreadControl _ ctl' } =
t { threadControl = ThreadControl (Throw thrower e) ctl'
, threadBlocked = False
}
simstate'@SimState { threads = threads' }
= snd (unblockThreads [tid'] simstate)
threads'' = Map.adjust adjustTarget tid' threads'
simstate'' = simstate' { threads = threads'' }
trace <- schedule thread' simstate''
return $ SimTrace time tid tlbl (EventThrowTo e tid')
$ trace
YieldSim k -> do
let thread' = thread { threadControl = ThreadControl k ctl }
deschedule Yield thread' simstate
-- ExploreRaces is ignored by this simulator
ExploreRaces k ->
{-# SCC "schedule.ExploreRaces" #-}
schedule thread{ threadControl = ThreadControl k ctl } simstate
Fix f k ->
{-# SCC "schedule.Fix" #-} do
r <- newSTRef (throw NonTermination)
x <- unsafeInterleaveST $ readSTRef r
let k' = unIOSim (f x) $ \x' ->
LiftST (lazyToStrictST (writeSTRef r x')) (\() -> k x')
thread' = thread { threadControl = ThreadControl k' ctl }
schedule thread' simstate
threadInterruptible :: Thread s a -> Bool
threadInterruptible thread =
case threadMasking thread of
Unmasked -> True
MaskedInterruptible
| threadBlocked thread -> True -- blocking operations are interruptible
| otherwise -> False
MaskedUninterruptible -> False
deschedule :: Deschedule -> Thread s a -> SimState s a -> ST s (SimTrace a)
deschedule Yield !thread !simstate@SimState{runqueue, threads} =
-- We don't interrupt runnable threads to provide fairness anywhere else.
-- We do it here by putting the thread to the back of the runqueue, behind
-- all other runnable threads.
--
-- For testing, we should have a more sophisticated policy to show that
-- algorithms are not sensitive to the exact policy, so long as it is a
-- fair policy (all runnable threads eventually run).
{-# SCC "deschedule.Yield" #-}
let runqueue' = Deque.snoc (threadId thread) runqueue
threads' = Map.insert (threadId thread) thread threads in
reschedule simstate { runqueue = runqueue', threads = threads' }
deschedule Interruptable !thread@Thread {
threadId = tid,
threadControl = ThreadControl _ ctl,
threadMasking = Unmasked,
threadThrowTo = (e, tid') : etids,
threadLabel = tlbl
}
!simstate@SimState{ curTime = time, threads } =
-- We're unmasking, but there are pending blocked async exceptions.
-- So immediately raise the exception and unblock the blocked thread
-- if possible.
{-# SCC "deschedule.Interruptable.Unmasked" #-}
let thread' = thread { threadControl = ThreadControl (Throw ThrowSelf e) ctl
, threadMasking = MaskedInterruptible
, threadThrowTo = etids }
(unblocked,
simstate') = unblockThreads [l_labelled tid'] simstate
in do
trace <- schedule thread' simstate'
return $ SimTrace time tid tlbl (EventThrowToUnmasked tid')
$ traceMany [ (time, tid'', tlbl'', EventThrowToWakeup)
| tid'' <- unblocked
, let tlbl'' = lookupThreadLabel tid'' threads ]
trace
deschedule Interruptable !thread !simstate =
-- Either masked or unmasked but no pending async exceptions.
-- Either way, just carry on.
{-# SCC "deschedule.Interruptable.Masked" #-}
schedule thread simstate
deschedule Blocked !thread@Thread { threadThrowTo = _ : _
, threadMasking = maskst } !simstate
| maskst /= MaskedUninterruptible =
-- We're doing a blocking operation, which is an interrupt point even if
-- we have async exceptions masked, and there are pending blocked async
-- exceptions. So immediately raise the exception and unblock the blocked
-- thread if possible.
{-# SCC "deschedule.Interruptable.Blocked.1" #-}
deschedule Interruptable thread { threadMasking = Unmasked } simstate
deschedule Blocked !thread !simstate@SimState{threads} =
{-# SCC "deschedule.Interruptable.Blocked.2" #-}
let thread' = thread { threadBlocked = True }
threads' = Map.insert (threadId thread') thread' threads in
reschedule simstate { threads = threads' }
deschedule (Terminated reason) !thread !simstate@SimState{ curTime = time, threads } =
-- This thread is done. If there are other threads blocked in a
-- ThrowTo targeted at this thread then we can wake them up now.
{-# SCC "deschedule.Terminated" #-}
let !wakeup = map (l_labelled . snd) (reverse (threadThrowTo thread))
(unblocked,
!simstate') = unblockThreads wakeup
simstate { finished = Map.insert (threadId thread)
reason
(finished simstate) }
in do
!trace <- reschedule simstate'
return $ traceMany
[ (time, tid', tlbl', EventThrowToWakeup)
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads ]
trace
deschedule Sleep _thread _simstate =
error "IOSim: impossible happend"
-- When there is no current running thread but the runqueue is non-empty then
-- schedule the next one to run.
reschedule :: SimState s a -> ST s (SimTrace a)
reschedule !simstate@SimState{ runqueue, threads }
| Just (!tid, runqueue') <- Deque.uncons runqueue =
{-# SCC "reschedule.Just" #-}
invariant Nothing simstate $
let thread = threads Map.! tid in
schedule thread simstate { runqueue = runqueue'
, threads = Map.delete tid threads }
-- But when there are no runnable threads, we advance the time to the next
-- timer event, or stop.
reschedule !simstate@SimState{ threads, timers, curTime = time } =
{-# SCC "reschedule.Nothing" #-}
invariant Nothing simstate $
-- important to get all events that expire at this time
case removeMinimums timers of
Nothing -> return (TraceDeadlock time (labelledThreads threads))
Just (tmids, !time', !fired, !timers') -> assert (time' >= time) $ do
-- Reuse the STM functionality here to write all the timer TVars.
-- Simplify to a special case that only reads and writes TVars.
!written <- execAtomically' (runSTM $ mapM_ timeoutSTMAction fired)
(wakeupSTM, wokeby) <- threadsUnblockedByWrites written
!_ <- mapM_ (\(SomeTVar tvar) -> unblockAllThreadsFromTVar tvar) written
-- Check all fired threadDelays
let wakeupThreadDelay = [ tid | TimerThreadDelay tid <- fired ]
wakeup = wakeupThreadDelay ++ wakeupSTM
(_, !simstate') = unblockThreads wakeup simstate
-- For each 'timeout' action where the timeout has fired, start a
-- new thread to execute throwTo to interrupt the action.
!timeoutExpired = [ (tid, tmid, isLockedRef)
| TimerTimeout tid tmid isLockedRef <- fired ]
-- Get the isLockedRef values
!timeoutExpired' <- traverse (\(tid, tmid, isLockedRef) -> do
locked <- readSTRef isLockedRef
return (tid, tmid, isLockedRef, locked)
)
timeoutExpired
!simstate'' <- forkTimeoutInterruptThreads timeoutExpired' simstate'
!trace <- reschedule simstate'' { curTime = time'
, timers = timers' }
return $
traceMany ([ ( time', ThreadId [-1], Just "timer"
, EventTimerFired tmid)
| (tmid, Timer _) <- zip tmids fired ]
++ [ ( time', ThreadId [-1], Just "register delay timer"
, EventRegisterDelayFired tmid)
| (tmid, TimerRegisterDelay _) <- zip tmids fired ]
++ [ (time', tid', tlbl', EventTxWakeup vids)
| tid' <- wakeupSTM
, let tlbl' = lookupThreadLabel tid' threads
, let Just vids = Set.toList <$> Map.lookup tid' wokeby ]
++ [ ( time', tid, Just "thread delay timer"
, EventThreadDelayFired)
| tid <- wakeupThreadDelay ]
++ [ ( time', tid, Just "timeout timer"
, EventTimeoutFired tmid)
| (tid, tmid, _, _) <- timeoutExpired' ]
++ [ ( time', tid, Just "thread forked"
, EventThreadForked tid)
| (tid, _, _, _) <- timeoutExpired' ])
trace
where
timeoutSTMAction (Timer var) = do
x <- readTVar var
case x of
TimeoutPending -> writeTVar var TimeoutFired
TimeoutFired -> error "MonadTimer(Sim): invariant violation"
TimeoutCancelled -> return ()
timeoutSTMAction (TimerRegisterDelay var) = writeTVar var True
-- Note that 'threadDelay' is not handled via STM style wakeup, but rather
-- it's handled directly above with 'wakeupThreadDelay' and 'unblockThreads'
timeoutSTMAction TimerThreadDelay{} = return ()
timeoutSTMAction TimerTimeout{} = return ()
unblockThreads :: [ThreadId] -> SimState s a -> ([ThreadId], SimState s a)
unblockThreads !wakeup !simstate@SimState {runqueue, threads} =
-- To preserve our invariants (that threadBlocked is correct)
-- we update the runqueue and threads together here
(unblocked, simstate {
runqueue = runqueue <> fromList unblocked,
threads = threads'
})
where
-- can only unblock if the thread exists and is blocked (not running)
!unblocked = [ tid
| tid <- wakeup
, case Map.lookup tid threads of
Just Thread { threadBlocked = True } -> True
_ -> False
]
-- and in which case we mark them as now running
!threads' = List.foldl'
(flip (Map.adjust (\t -> t { threadBlocked = False })))
threads
unblocked
-- | This function receives a list of TimerTimeout values that represent threads
-- for which the timeout expired and kills the running thread if needed.
--
-- This function is responsible for the second part of the race condition issue
-- and relates to the 'schedule's 'TimeoutFrame' locking explanation (here is
-- where the assassin threads are launched. So, as explained previously, at this
-- point in code, the timeout expired so we need to interrupt the running
-- thread. If the running thread finished at the same time the timeout expired
-- we have a race condition. To deal with this race condition what we do is
-- look at the lock value. If it is 'Locked' this means that the running thread
-- already finished (or won the race) so we can safely do nothing. Otherwise, if
-- the lock value is 'NotLocked' we need to acquire the lock and launch an
-- assassin thread that is going to interrupt the running one. Note that we
-- should run this interrupting thread in an unmasked state since it might
-- receive a 'ThreadKilled' exception.
--
forkTimeoutInterruptThreads :: [(ThreadId, TimeoutId, STRef s IsLocked, IsLocked)]
-> SimState s a
-> ST s (SimState s a)
forkTimeoutInterruptThreads timeoutExpired simState@SimState {threads} =
foldlM (\st@SimState{ runqueue = runqueue,
threads = threads'
}
(t, isLockedRef)
-> do
let tid' = threadId t
threads'' = Map.insert tid' t threads'
runqueue' = Deque.snoc tid' runqueue
writeSTRef isLockedRef (Locked tid')
return st { runqueue = runqueue',
threads = threads''
})
simState
throwToThread
where
-- can only throw exception if the thread exists and if the mutually
-- exclusive lock exists and is still 'NotLocked'
toThrow = [ (tid, tmid, ref, t)
| (tid, tmid, ref, locked) <- timeoutExpired
, Just t <- [Map.lookup tid threads]
, NotLocked <- [locked]
]
-- we launch a thread responsible for throwing an AsyncCancelled exception
-- to the thread which timeout expired
throwToThread =
[ let nextId = threadNextTId t
tid' = childThreadId tid nextId
in ( Thread { threadId = tid',
threadControl =
ThreadControl
(ThrowTo (toException (TimeoutException tmid))
tid
(Return ()))
ForkFrame,
threadBlocked = False,
threadMasking = Unmasked,
threadThrowTo = [],
threadClockId = threadClockId t,
threadLabel = Just "timeout-forked-thread",
threadNextTId = 1
}
, ref )
| (tid, tmid, ref, t) <- toThrow
]
-- | Iterate through the control stack to find an enclosing exception handler
-- of the right type, or unwind all the way to the top level for the thread.
--
-- Also return if it's the main thread or a forked thread since we handle the
-- cases differently.
--
unwindControlStack :: forall s a.
SomeException
-> Thread s a
-> Either Bool (Thread s a)
unwindControlStack e thread =
case threadControl thread of
ThreadControl _ ctl -> unwind (threadMasking thread) ctl
where
unwind :: forall s' c. MaskingState
-> ControlStack s' c a
-> Either Bool (Thread s' a)
unwind _ MainFrame = Left True
unwind _ ForkFrame = Left False
unwind _ (MaskFrame _k maskst' ctl) = unwind maskst' ctl
unwind maskst (CatchFrame handler k ctl) =
case fromException e of