-
Notifications
You must be signed in to change notification settings - Fork 15
/
Internal.hs
1705 lines (1510 loc) · 71.4 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 DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTSyntax #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- incomplete uni patterns in 'schedule' (when interpreting 'StmTxCommitted')
-- and 'reschedule'.
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns -Wno-unused-matches #-}
module Control.Monad.IOSimPOR.Internal
( IOSim (..)
, SimM
, runIOSim
, runSimTraceST
, traceM
, traceSTM
, STM
, STMSim
, SimSTM
, setCurrentTime
, unshareClock
, TimeoutException (..)
, EventlogEvent (..)
, EventlogMarker (..)
, ThreadId
, ThreadLabel
, Labelled (..)
, SimTrace
, Trace.Trace (SimPORTrace, Trace, TraceMainReturn, TraceMainException, TraceDeadlock)
, SimEvent (..)
, SimResult (..)
, SimEventType (..)
, TraceEvent
, liftST
, execReadTVar
, controlSimTraceST
, ScheduleControl (..)
, ScheduleMod (..)
) where
import Prelude hiding (read)
import Data.Dynamic
import Data.Foldable (traverse_)
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.Ord
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 Control.Exception (NonTermination (..), assert, throw)
import Control.Monad (join)
import Control.Monad (when)
import Control.Monad.ST.Lazy
import Control.Monad.ST.Lazy.Unsafe (unsafeIOToST, unsafeInterleaveST)
import Data.STRef.Lazy
import Control.Monad.Class.MonadSTM hiding (STM, TVar)
import Control.Monad.Class.MonadThrow as MonadThrow
import Control.Monad.Class.MonadTime
import Control.Monad.Class.MonadTimer
import Control.Monad.IOSim.InternalTypes
import Control.Monad.IOSim.Types hiding (SimEvent (SimEvent),
Trace (SimTrace))
import Control.Monad.IOSim.Types (SimEvent)
import Control.Monad.IOSimPOR.Timeout (unsafeTimeout)
import Control.Monad.IOSimPOR.Types
--
-- Simulation interpreter
--
data Thread s a = Thread {
threadId :: !ThreadId,
threadControl :: !(ThreadControl s a),
threadBlocked :: !Bool,
threadDone :: !Bool,
threadMasking :: !MaskingState,
-- other threads blocked in a ThrowTo to us because we are or were masked
threadThrowTo :: ![(SomeException, Labelled ThreadId, VectorClock)],
threadClockId :: !ClockId,
threadLabel :: Maybe ThreadLabel,
threadNextTId :: !Int,
threadStep :: !Int,
threadVClock :: VectorClock,
threadEffect :: Effect, -- in the current step
threadRacy :: !Bool
}
deriving Show
threadStepId :: Thread s a -> (ThreadId, Int)
threadStepId Thread{ threadId, threadStep } = (threadId, threadStep)
isRacyThreadId :: ThreadId -> Bool
isRacyThreadId (RacyThreadId _) = True
isRacyThreadId _ = True
isNotRacyThreadId :: ThreadId -> Bool
isNotRacyThreadId (ThreadId _) = True
isNotRacyThreadId _ = False
bottomVClock :: VectorClock
bottomVClock = VectorClock Map.empty
insertVClock :: ThreadId -> Int -> VectorClock -> VectorClock
insertVClock tid !step (VectorClock m) = VectorClock (Map.insert tid step m)
leastUpperBoundVClock :: VectorClock -> VectorClock -> VectorClock
leastUpperBoundVClock (VectorClock m) (VectorClock m') =
VectorClock (Map.unionWith max m m')
-- hbfVClock :: VectorClock -> VectorClock -> Bool
-- hbfVClock (VectorClock m) (VectorClock m') = Map.isSubmapOfBy (<=) m m'
happensBeforeStep :: Step -- ^ an earlier step
-> Step -- ^ a later step
-> Bool
happensBeforeStep step step' =
Just (stepStep step)
<= Map.lookup (stepThreadId step)
(getVectorClock $ stepVClock step')
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 retain 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. First one supports 'newTimeout' api, the second
-- one 'registerDelay'.
--
data TimerVars s = TimerVars !(TVar s TimeoutState) !(TVar s Bool)
type RunQueue = OrdPSQ (Down ThreadId) (Down ThreadId) ()
-- | Internal state.
--
data SimState s a = SimState {
runqueue :: !RunQueue,
-- | All threads other than the currently running thread: both running
-- and blocked threads.
threads :: !(Map ThreadId (Thread s a)),
-- | current time
curTime :: !Time,
-- | ordered list of timers
timers :: !(OrdPSQ TimeoutId Time (TimerVars s)),
-- | list of clocks
clocks :: !(Map ClockId UTCTime),
nextVid :: !TVarId, -- ^ next unused 'TVarId'
nextTmid :: !TimeoutId, -- ^ next unused 'TimeoutId'
-- | previous steps (which we may race with).
-- Note this is *lazy*, so that we don't compute races we will not reverse.
races :: Races,
-- | control the schedule followed, and initial value
control :: !ScheduleControl,
control0 :: !ScheduleControl,
-- | limit on the computation time allowed per scheduling step, for
-- catching infinite loops etc
perStepTimeLimit :: Maybe Int
}
initialState :: SimState s a
initialState =
SimState {
runqueue = PSQ.empty,
threads = Map.empty,
curTime = Time 0,
timers = PSQ.empty,
clocks = Map.singleton (ClockId []) epoch1970,
nextVid = TVarId 0,
nextTmid = TimeoutId 0,
races = noRaces,
control = ControlDefault,
control0 = ControlDefault,
perStepTimeLimit = Nothing
}
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 (not (Down (threadId running) `PSQ.member` runqueue))
. assert (threadClockId running `Map.member` clocks)
. invariant Nothing simstate
invariant Nothing SimState{runqueue,threads,clocks} =
assert (PSQ.fold' (\(Down tid) _ _ a -> tid `Map.member` threads && a) True runqueue)
. assert (and [ (threadBlocked t || threadDone t) == not (Down (threadId t) `PSQ.member` runqueue)
| t <- Map.elems threads ])
. assert (and (zipWith (\(Down tid, _, _) (Down tid', _, _) -> tid > tid')
(PSQ.toList runqueue)
(drop 1 (PSQ.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)
-- | Insert thread into `runqueue`.
--
insertThread :: Thread s a -> RunQueue -> RunQueue
insertThread Thread { threadId } = PSQ.insert (Down threadId) (Down threadId) ()
-- | 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,
threadStep = tstep,
threadVClock = vClock,
threadEffect = effect
}
simstate@SimState {
runqueue,
threads,
timers,
clocks,
nextVid, nextTmid,
curTime = time,
control,
perStepTimeLimit
}
| controlTargets (tid,tstep) control =
-- The next step is to be delayed according to the
-- specified schedule. Switch to following the schedule.
SimPORTrace time tid tstep tlbl (EventFollowControl control) <$>
schedule thread simstate{ control = followControl control }
| not $ controlFollows (tid,tstep) control =
-- the control says this is not the next step to
-- follow. We should be at the beginning of a step;
-- we put the present thread to sleep and reschedule
-- the correct thread.
assert (effect == mempty) $
( SimPORTrace time tid tstep tlbl (EventAwaitControl (tid,tstep) control)
. SimPORTrace time tid tstep tlbl (EventDeschedule Sleep)
) <$> deschedule Sleep thread simstate
| otherwise =
invariant (Just thread) simstate $
case control of
ControlFollow (s:_) _
-> fmap (SimPORTrace time tid tstep tlbl (EventPerformAction (tid,tstep)))
_ -> id
$
-- The next line forces the evaluation of action, which should be unevaluated up to
-- this point. This is where we actually *run* user code.
case maybe Just unsafeTimeout perStepTimeLimit action of
Nothing -> return TraceLoop
Just _ -> case action of
Return x -> case ctl of
MainFrame ->
-- the main thread is done, so we're done
-- even if other threads are still running
return $ SimPORTrace time tid tstep tlbl EventThreadFinished
$ traceFinalRacesFound simstate
$ TraceMainReturn time x ( labelledThreads
. Map.filter (not . threadDone)
$ threads
)
ForkFrame -> do
-- this thread is done
!trace <- deschedule Terminated thread simstate
return $ SimPORTrace time tid tstep tlbl EventThreadFinished
$ SimPORTrace time tid tstep tlbl (EventDeschedule Terminated)
$ 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 $ SimPORTrace time tid tstep tlbl (EventMask maskst')
$ SimPORTrace time tid tstep 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
Throw e -> case unwindControlStack e thread of
Right thread0@Thread { threadMasking = maskst' } -> do
-- We found a suitable exception handler, continue with that
-- We record a step, in case there is no exception handler on replay.
let thread' = stepThread thread0
control' = advanceControl (threadStepId thread0) control
races' = updateRacesInSimState thread0 simstate
trace <- schedule thread' simstate{ races = races', control = control' }
return (SimPORTrace time tid tstep tlbl (EventThrow e) $
SimPORTrace time tid tstep 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 (SimPORTrace time tid tstep tlbl (EventThrow e) $
SimPORTrace time tid tstep tlbl (EventThreadUnhandled e) $
traceFinalRacesFound simstate $
TraceMainException time e (labelledThreads threads))
| otherwise -> do
-- An unhandled exception in any other thread terminates the thread
!trace <- deschedule Terminated thread simstate
return $ SimPORTrace time tid tstep tlbl (EventThrow e)
$ SimPORTrace time tid tstep tlbl (EventThreadUnhandled e)
$ SimPORTrace time tid tstep tlbl (EventDeschedule Terminated)
$ trace
Catch action' handler k -> 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 -> 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 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 -> do
let thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate
return (SimPORTrace time tid tstep tlbl (EventSay msg) trace)
Output x k -> do
let thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate
return (SimPORTrace time tid tstep tlbl (EventLog x) trace)
LiftST st k -> do
x <- strictToLazyST st
let thread' = thread { threadControl = ThreadControl (k x) ctl }
schedule thread' simstate
GetMonoTime k -> do
let thread' = thread { threadControl = ThreadControl (k time) ctl }
schedule thread' simstate
GetWallTime k -> 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 -> 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 -> 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 -> do
let t = NegativeTimeout nextTmid
expiry = d `addTime` time
thread' = thread { threadControl = ThreadControl (k t) ctl }
trace <- schedule thread' simstate { nextTmid = succ nextTmid }
return (SimPORTrace time tid tstep tlbl (EventTimerCreated nextTmid nextVid expiry) $
SimPORTrace time tid tstep tlbl (EventTimerCancelled nextTmid) $
trace)
NewTimeout d k -> do
tvar <- execNewTVar nextVid
(Just $ "<<timeout-state " ++ show (unTimeoutId nextTmid) ++ ">>")
TimeoutPending
modifySTRef (tvarVClock tvar) (leastUpperBoundVClock vClock)
tvar' <- execNewTVar (succ nextVid)
(Just $ "<<timeout " ++ show (unTimeoutId nextTmid) ++ ">>")
False
modifySTRef (tvarVClock tvar') (leastUpperBoundVClock vClock)
let expiry = d `addTime` time
t = Timeout tvar tvar' nextTmid
timers' = PSQ.insert nextTmid expiry (TimerVars tvar tvar') timers
thread' = thread { threadControl = ThreadControl (k t) ctl }
!trace <- schedule thread' simstate { timers = timers'
, nextVid = succ (succ nextVid)
, nextTmid = succ nextTmid }
return (SimPORTrace time tid tstep tlbl (EventTimerCreated nextTmid nextVid expiry) trace)
-- we do not follow `GHC.Event` behaviour here; updating a timer to the past
-- effectively cancels it.
UpdateTimeout (Timeout _tvar _tvar' tmid) d k | d < 0 -> do
let timers' = PSQ.delete tmid timers
thread' = thread { threadControl = ThreadControl k ctl }
trace <- schedule thread' simstate { timers = timers' }
return (SimPORTrace time tid tstep tlbl (EventTimerCancelled tmid) trace)
UpdateTimeout (Timeout _tvar _tvar' tmid) d k -> 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 (SimPORTrace time tid tstep tlbl (EventTimerUpdated tmid expiry) trace)
-- updating a negative timer is a no-op, unlike in `GHC.Event`.
UpdateTimeout (NegativeTimeout _tmid) _d k -> do
let thread' = thread { threadControl = ThreadControl k ctl }
schedule thread' simstate
CancelTimeout (Timeout tvar tvar' tmid) k -> do
let timers' = PSQ.delete tmid timers
written <- execAtomically' (runSTM $ writeTVar tvar TimeoutCancelled)
(wakeup, wokeby) <- threadsUnblockedByWrites written
mapM_ (\(SomeTVar var) -> unblockAllThreadsFromTVar var) written
let effect' = effect
<> writeEffects written
<> wakeupEffects wakeup
thread' = thread { threadControl = ThreadControl k ctl
, threadEffect = effect'
}
(unblocked,
simstate') = unblockThreads vClock wakeup simstate
modifySTRef (tvarVClock tvar) (leastUpperBoundVClock vClock)
modifySTRef (tvarVClock tvar') (leastUpperBoundVClock vClock)
!trace <- deschedule Yield thread' simstate' { timers = timers' }
return $ SimPORTrace time tid tstep tlbl (EventTimerCancelled tmid)
$ traceMany
-- TODO: step
[ (time, tid', (-1), tlbl', EventTxWakeup vids)
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads
, let Just vids = Set.toList <$> Map.lookup tid' wokeby ]
$ SimPORTrace time tid tstep tlbl (EventDeschedule Yield)
$ trace
-- cancelling a negative timer is a no-op
CancelTimeout (NegativeTimeout _tmid) k -> do
-- negative timers are promptly removed from the state
let thread' = thread { threadControl = ThreadControl k ctl }
schedule thread' simstate
Fork a k -> do
let nextTId = threadNextTId thread
tid' | threadRacy thread = setRacyThread $ childThreadId tid nextTId
| otherwise = childThreadId tid nextTId
thread' = thread { threadControl = ThreadControl (k tid') ctl,
threadNextTId = nextTId + 1,
threadEffect = effect <> forkEffect tid' }
thread'' = Thread { threadId = tid'
, threadControl = ThreadControl (runIOSim a)
ForkFrame
, threadBlocked = False
, threadDone = False
, threadMasking = threadMasking thread
, threadThrowTo = []
, threadClockId = threadClockId thread
, threadLabel = Nothing
, threadNextTId = 1
, threadStep = 0
, threadVClock = insertVClock tid' 0
$ vClock
, threadEffect = mempty
, threadRacy = threadRacy thread
}
threads' = Map.insert tid' thread'' threads
-- A newly forked thread may have a higher priority, so we deschedule this one.
!trace <- deschedule Yield thread'
simstate { runqueue = insertThread thread'' runqueue
, threads = threads' }
return $ SimPORTrace time tid tstep tlbl (EventThreadForked tid')
$ SimPORTrace time tid tstep tlbl (EventDeschedule Yield)
$ trace
Atomically a k -> 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
vClockRead <- leastUpperBoundTVarVClocks read
let vClock' = vClock `leastUpperBoundVClock` vClockRead
effect' = effect
<> readEffects read
<> writeEffects written
<> wakeupEffects unblocked
thread' = thread { threadControl = ThreadControl (k x) ctl,
threadVClock = vClock',
threadEffect = effect' }
(unblocked,
simstate') = unblockThreads vClock' wakeup simstate
sequence_ [ modifySTRef (tvarVClock r) (leastUpperBoundVClock vClock')
| SomeTVar r <- created ++ written ]
written' <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) written
created' <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) created
-- We deschedule a thread after a transaction... another may have woken up.
!trace <- deschedule Yield thread' simstate' { nextVid = nextVid' }
return $
SimPORTrace time tid tstep tlbl (EventTxCommitted written' created' (Just effect')) $
traceMany
[ (time, tid', tstep, tlbl', EventTxWakeup vids')
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads
, let Just vids' = Set.toList <$> Map.lookup tid' wokeby ] $
traceMany
[ (time, tid, tstep, tlbl, EventLog tr)
| tr <- tvarDynamicTraces
] $
traceMany
[ (time, tid, tstep, tlbl, EventSay str)
| str <- tvarStringTraces
] $
SimPORTrace time tid tstep tlbl (EventUnblocked unblocked) $
SimPORTrace time tid tstep tlbl (EventDeschedule Yield) $
trace
StmTxAborted read e -> do
-- schedule this thread to immediately raise the exception
vClockRead <- leastUpperBoundTVarVClocks read
let effect' = effect <> readEffects read
thread' = thread { threadControl = ThreadControl (Throw e) ctl,
threadVClock = vClock `leastUpperBoundVClock` vClockRead,
threadEffect = effect' }
trace <- schedule thread' simstate
return $ SimPORTrace time tid tstep tlbl (EventTxAborted (Just effect'))
$ trace
StmTxBlocked read -> do
mapM_ (\(SomeTVar tvar) -> blockThreadOnTVar tid tvar) read
vids <- traverse (\(SomeTVar tvar) -> labelledTVarId tvar) read
vClockRead <- leastUpperBoundTVarVClocks read
let effect' = effect <> readEffects read
thread' = thread { threadVClock = vClock `leastUpperBoundVClock` vClockRead,
threadEffect = effect' }
!trace <- deschedule Blocked thread' simstate
return $ SimPORTrace time tid tstep tlbl (EventTxBlocked vids (Just effect'))
$ SimPORTrace time tid tstep tlbl (EventDeschedule Blocked)
$ trace
GetThreadId k -> do
let thread' = thread { threadControl = ThreadControl (k tid) ctl }
schedule thread' simstate
LabelThread tid' l k | tid' == tid -> do
let thread' = thread { threadControl = ThreadControl k ctl
, threadLabel = Just l }
schedule thread' simstate
LabelThread tid' l k -> do
let thread' = thread { threadControl = ThreadControl k ctl }
threads' = Map.adjust (\t -> t { threadLabel = Just l }) tid' threads
schedule thread' simstate { threads = threads' }
ExploreRaces k -> do
let thread' = thread { threadControl = ThreadControl k ctl
, threadRacy = True }
schedule thread' simstate
Fix f k -> 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
GetMaskState k -> do
let thread' = thread { threadControl = ThreadControl (k maskst) ctl }
schedule thread' simstate
SetMaskState maskst' action' k -> 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 -> SimPORTrace time tid tstep tlbl (EventDeschedule Interruptable)
<$> deschedule Interruptable thread' simstate
_ -> schedule thread' simstate
return $ SimPORTrace time tid tstep tlbl (EventMask maskst')
$ trace
ThrowTo e tid' _ | tid' == tid -> 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 e) ctl }
trace <- schedule thread' simstate
return (SimPORTrace time tid tstep tlbl (EventThrowTo e tid) trace)
ThrowTo e tid' k -> do
let thread' = thread { threadControl = ThreadControl k ctl,
threadEffect = effect <> throwToEffect tid' <> wakeUpEffect,
threadVClock = vClock `leastUpperBoundVClock` vClockTgt }
(vClockTgt,
wakeUpEffect,
willBlock) = (threadVClock t,
if threadBlocked t then wakeupEffects [tid'] else mempty,
not (threadInterruptible t || threadDone t))
where Just t = Map.lookup tid' threads
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, vClock) : threadThrowTo t }
threads' = Map.adjust adjustTarget tid' threads
trace <- deschedule Blocked thread' simstate { threads = threads' }
return $ SimPORTrace time tid tstep tlbl (EventThrowTo e tid')
$ SimPORTrace time tid tstep tlbl EventThrowToBlocked
$ SimPORTrace time tid tstep 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 adjustTarget t@Thread{ threadControl = ThreadControl _ ctl',
threadVClock = vClock' } =
t { threadControl = ThreadControl (Throw e) ctl'
, threadBlocked = False
, threadVClock = vClock' `leastUpperBoundVClock` vClock }
simstate'@SimState { threads = threads' }
= snd (unblockThreads vClock [tid'] simstate)
threads'' = Map.adjust adjustTarget tid' threads'
simstate'' = simstate' { threads = threads'' }
-- We yield at this point because the target thread may be higher
-- priority, so this should be a step for race detection.
trace <- deschedule Yield thread' simstate''
return $ SimPORTrace time tid tstep tlbl (EventThrowTo e tid')
$ trace
-- intentionally a no-op (at least for now)
YieldSim k -> do
let 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@Thread { threadId = tid }
simstate@SimState{runqueue, threads, control} =
-- We don't interrupt runnable threads anywhere else.
-- We do it here by inserting the current thread into the runqueue in priority order.
let thread' = stepThread thread
runqueue' = insertThread thread' runqueue
threads' = Map.insert tid thread' threads
control' = advanceControl (threadStepId thread) control in
reschedule simstate { runqueue = runqueue', threads = threads',
races = updateRacesInSimState thread simstate,
control = control' }
deschedule Interruptable thread@Thread {
threadId = tid,
threadStep = tstep,
threadControl = ThreadControl _ ctl,
threadMasking = Unmasked,
threadThrowTo = (e, tid', vClock') : etids,
threadLabel = tlbl,
threadVClock = vClock
}
simstate@SimState{ curTime = time, threads } = do
-- We're unmasking, but there are pending blocked async exceptions.
-- So immediately raise the exception and unblock the blocked thread
-- if possible.
let thread' = thread { threadControl = ThreadControl (Throw e) ctl
, threadMasking = MaskedInterruptible
, threadThrowTo = etids
, threadVClock = vClock `leastUpperBoundVClock` vClock' }
(unblocked,
simstate') = unblockThreads vClock [l_labelled tid'] simstate
-- the thread is stepped when we Yield
!trace <- deschedule Yield thread' simstate'
return $ SimPORTrace time tid tstep tlbl (EventDeschedule Yield)
$ SimPORTrace time tid tstep tlbl (EventThrowToUnmasked tid')
-- TODO: step
$ traceMany [ (time, tid'', (-1), tlbl'', EventThrowToWakeup)
| tid'' <- unblocked
, let tlbl'' = lookupThreadLabel tid'' threads ]
trace
deschedule Interruptable thread simstate@SimState{ control } =
-- Either masked or unmasked but no pending async exceptions.
-- Either way, just carry on.
-- Record a step, though, in case on replay there is an async exception.
let thread' = stepThread thread in
schedule thread'
simstate{ races = updateRacesInSimState thread simstate,
control = advanceControl (threadStepId thread) control }
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.
deschedule Interruptable thread { threadMasking = Unmasked } simstate
deschedule Blocked thread simstate@SimState{threads, control} =
let thread1 = thread { threadBlocked = True }
thread' = stepThread $ thread1
threads' = Map.insert (threadId thread') thread' threads in
reschedule simstate { threads = threads',
races = updateRacesInSimState thread1 simstate,
control = advanceControl (threadStepId thread1) control }
deschedule Terminated thread@Thread { threadId = tid, threadVClock = vClock }
simstate@SimState{ curTime = time, control } = do
-- This thread is done. If there are other threads blocked in a
-- ThrowTo targeted at this thread then we can wake them up now.
let thread' = stepThread $ thread{ threadDone = True }
wakeup = map (\(_,tid',_) -> l_labelled tid') (reverse (threadThrowTo thread))
(unblocked,
simstate'@SimState{threads}) =
unblockThreads vClock wakeup simstate
threads' = Map.insert tid thread' threads
-- We must keep terminated threads in the state to preserve their vector clocks,
-- which matters when other threads throwTo them.
!trace <- reschedule simstate' { races = threadTerminatesRaces tid $
updateRacesInSimState thread simstate,
control = advanceControl (threadStepId thread) control,
threads = threads' }
return $ traceMany
-- TODO: step
[ (time, tid', (-1), tlbl', EventThrowToWakeup)
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads ]
trace
deschedule Sleep thread@Thread { threadId = tid }
simstate@SimState{runqueue, threads} =
-- Schedule control says we should run a different thread. Put
-- this one to sleep without recording a step.
let runqueue' = insertThread thread runqueue
threads' = Map.insert tid thread threads in
reschedule simstate { runqueue = runqueue', threads = threads' }
-- Choose the next thread to run.
reschedule :: SimState s a -> ST s (SimTrace a)
-- If we are following a controlled schedule, just do that.
reschedule simstate@SimState{ runqueue, threads,
control=control@(ControlFollow ((tid,tstep):_) _),
curTime=time
} =
fmap (SimPORTrace time tid tstep Nothing (EventReschedule control)) $
assert (Down tid `PSQ.member` runqueue) $
assert (tid `Map.member` threads) $
invariant Nothing simstate $
let thread = threads Map.! tid in
assert (threadId thread == tid) $
--assert (threadStep thread == tstep) $
if threadStep thread /= tstep then
error $ "Thread step out of sync\n"
++ " runqueue: "++show runqueue++"\n"
++ " follows: "++show tid++", step "++show tstep++"\n"
++ " actual step: "++show (threadStep thread)++"\n"
++ "Thread:\n" ++ show thread ++ "\n"
else
schedule thread simstate { runqueue = PSQ.delete (Down tid) runqueue
, threads = Map.delete tid threads }
-- When there is no current running thread but the runqueue is non-empty then
-- schedule the next one to run.
reschedule simstate@SimState{ runqueue, threads }
| Just (Down !tid, _, _, runqueue') <- PSQ.minView runqueue =
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, races } =
invariant Nothing simstate $
-- time is moving on
--Debug.trace ("Rescheduling at "++show time++", "++
--show (length (concatMap stepInfoRaces (activeRaces races++completeRaces races)))++" races") $
-- important to get all events that expire at this time
case removeMinimums timers of
Nothing -> return (traceFinalRacesFound simstate $
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_ timeoutAction fired)
(wakeup, wokeby) <- threadsUnblockedByWrites written
mapM_ (\(SomeTVar tvar) -> unblockAllThreadsFromTVar tvar) written
-- TODO: the vector clock below cannot be right, can it?
let (unblocked,
simstate') = unblockThreads bottomVClock wakeup simstate
-- all open races will be completed and reported at this time
simstate'' = simstate'{ races = noRaces }
!trace <- reschedule simstate'' { curTime = time'
, timers = timers' }
let traceEntries =
[ (time', ThreadId [-1], (-1), Just "timer", EventTimerExpired tmid)
| tmid <- tmids ]
++ [ (time', tid', (-1), tlbl', EventTxWakeup vids)
| tid' <- unblocked
, let tlbl' = lookupThreadLabel tid' threads
, let Just vids = Set.toList <$> Map.lookup tid' wokeby ]
return $
traceFinalRacesFound simstate $
traceMany traceEntries trace
where
timeoutAction (TimerVars var bvar) = do
x <- readTVar var
case x of
TimeoutPending -> writeTVar var TimeoutFired
>> writeTVar bvar True
TimeoutFired -> error "MonadTimer(Sim): invariant violation"
TimeoutCancelled -> return ()
unblockThreads :: forall s a.
VectorClock
-> [ThreadId]
-> SimState s a
-> ([ThreadId], SimState s a)
unblockThreads vClock wakeup simstate@SimState {runqueue, threads} =
-- To preserve our invariants (that threadBlocked is correct)
-- we update the runqueue and threads together here
( unblockedIds
, simstate { runqueue = foldr insertThread runqueue unblocked,
threads = threads'
})
where
-- can only unblock if the thread exists and is blocked (not running)
unblocked :: [Thread s a]
!unblocked = [ thread
| tid <- wakeup
, thread <-
case Map.lookup tid threads of
Just Thread { threadDone = True } -> [ ]
Just t@Thread { threadBlocked = True } -> [t]
_ -> [ ]
]
unblockedIds :: [ThreadId]
!unblockedIds = map threadId unblocked
-- and in which case we mark them as now running
!threads' = List.foldl'
(flip (Map.adjust
(\t -> t { threadBlocked = False,
threadVClock = vClock `leastUpperBoundVClock` threadVClock t })))
threads unblockedIds
-- | 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
-- not the right type, unwind to the next containing handler
Nothing -> unwind maskst ctl
-- Ok! We will be able to continue the thread with the handler
-- followed by the continuation after the catch
Just e' -> Right thread {
-- As per async exception rules, the handler is run masked
threadControl = ThreadControl (handler e')
(MaskFrame k maskst ctl),
threadMasking = atLeastInterruptibleMask maskst
}
atLeastInterruptibleMask :: MaskingState -> MaskingState
atLeastInterruptibleMask Unmasked = MaskedInterruptible
atLeastInterruptibleMask ms = ms
removeMinimums :: (Ord k, Ord p)
=> OrdPSQ k p a
-> Maybe ([k], p, [a], OrdPSQ k p a)
removeMinimums = \psq ->
case PSQ.minView psq of
Nothing -> Nothing
Just (k, p, x, psq') -> Just (collectAll [k] p [x] psq')
where
collectAll ks p xs psq =
case PSQ.minView psq of
Just (k, p', x, psq')
| p == p' -> collectAll (k:ks) p (x:xs) psq'
_ -> (reverse ks, p, reverse xs, psq)
traceMany :: [(Time, ThreadId, Int, Maybe ThreadLabel, SimEventType)]
-> SimTrace a -> SimTrace a
traceMany [] trace = trace
traceMany ((time, tid, tstep, tlbl, event):ts) trace =
SimPORTrace time tid tstep tlbl event (traceMany ts trace)
lookupThreadLabel :: ThreadId -> Map ThreadId (Thread s a) -> Maybe ThreadLabel