This repository was archived by the owner on Aug 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBugFindingRuntime.cs
More file actions
1618 lines (1391 loc) · 64.7 KB
/
Copy pathBugFindingRuntime.cs
File metadata and controls
1618 lines (1391 loc) · 64.7 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 file="BugFindingRuntime.cs">
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.PSharp.TestingServices.Coverage;
using Microsoft.PSharp.TestingServices.Scheduling;
using Microsoft.PSharp.TestingServices.SchedulingStrategies;
using Microsoft.PSharp.TestingServices.StateCaching;
using Microsoft.PSharp.TestingServices.Tracing.Error;
using Microsoft.PSharp.TestingServices.Tracing.Machines;
using Microsoft.PSharp.TestingServices.Tracing.Schedule;
using Microsoft.PSharp.IO;
namespace Microsoft.PSharp.TestingServices
{
/// <summary>
/// Class implementing the P# bug-finding runtime.
/// </summary>
internal sealed class BugFindingRuntime : PSharpRuntime
{
#region fields
/// <summary>
/// The bug-finding scheduler.
/// </summary>
internal BugFindingScheduler Scheduler;
/// <summary>
/// The asynchronous task scheduler.
/// </summary>
internal AsynchronousTaskScheduler TaskScheduler;
/// <summary>
/// The P# program schedule trace.
/// </summary>
internal ScheduleTrace ScheduleTrace;
/// <summary>
/// The bug trace.
/// </summary>
internal BugTrace BugTrace;
/// <summary>
/// Data structure containing information
/// regarding testing coverage.
/// </summary>
internal CoverageInfo CoverageInfo;
/// <summary>
/// The P# program state cache.
/// </summary>
internal StateCache StateCache;
/// <summary>
/// List of monitors in the program.
/// </summary>
private List<Monitor> Monitors;
/// <summary>
/// Map from unique machine ids to machines.
/// </summary>
private ConcurrentDictionary<ulong, Machine> MachineMap;
/// <summary>
/// Map from task ids to machines.
/// </summary>
private ConcurrentDictionary<int, Machine> TaskMap;
/// <summary>
/// A map from unique machine ids to action traces.
/// Only used for dynamic data race detection.
/// </summary>
internal IDictionary<MachineId, MachineActionTrace> MachineActionTraceMap;
/// <summary>
/// The root task id.
/// </summary>
internal int? RootTaskId;
#endregion
#region initialization
/// <summary>
/// Constructor.
/// <param name="configuration">Configuration</param>
/// <param name="strategy">SchedulingStrategy</param>
/// </summary>
internal BugFindingRuntime(Configuration configuration, ISchedulingStrategy strategy)
: base(configuration)
{
this.Initialize();
this.ScheduleTrace = new ScheduleTrace();
this.BugTrace = new BugTrace();
this.StateCache = new StateCache(this);
this.TaskScheduler = new AsynchronousTaskScheduler(this, this.TaskMap);
this.CoverageInfo = new CoverageInfo();
if (!(strategy is DPORStrategy) && !(strategy is ReplayStrategy))
{
var reductionStrategy = BasicReductionStrategy.ReductionStrategy.None;
if (configuration.ReductionStrategy == Utilities.ReductionStrategy.OmitSchedulingPoints)
{
reductionStrategy = BasicReductionStrategy.ReductionStrategy.OmitSchedulingPoints;
}
else if (configuration.ReductionStrategy == Utilities.ReductionStrategy.ForceSchedule)
{
reductionStrategy = BasicReductionStrategy.ReductionStrategy.ForceSchedule;
}
strategy = new BasicReductionStrategy(strategy, reductionStrategy);
}
if (configuration.EnableLivenessChecking && configuration.EnableCycleDetection)
{
this.Scheduler = new BugFindingScheduler(this, new CycleDetectionStrategy(
configuration, this.StateCache, this.ScheduleTrace, this.Monitors, strategy));
}
else if (configuration.EnableLivenessChecking)
{
this.Scheduler = new BugFindingScheduler(this, new TemperatureCheckingStrategy(
configuration, this.Monitors, strategy));
}
else
{
this.Scheduler = new BugFindingScheduler(this, strategy);
}
}
/// <summary>
/// Initializes various components of the runtime.
/// </summary>
private void Initialize()
{
this.Monitors = new List<Monitor>();
this.MachineMap = new ConcurrentDictionary<ulong, Machine>();
this.TaskMap = new ConcurrentDictionary<int, Machine>();
this.MachineActionTraceMap = new ConcurrentDictionary<MachineId, MachineActionTrace>();
this.RootTaskId = Task.CurrentId;
}
#endregion
#region interface
/// <summary>
/// Creates a new machine of the specified type and with
/// the specified optional event. This event can only be
/// used to access its payload, and cannot be handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="operationGroupId">Optional operation group id</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
public override MachineId CreateMachine(Type type, Event e = null, Guid? operationGroupId = null)
{
Machine creator = null;
if (this.TaskMap.ContainsKey((int)Task.CurrentId))
{
creator = this.TaskMap[(int)Task.CurrentId];
}
return this.CreateMachine(type, null, e, creator, operationGroupId);
}
/// <summary>
/// Creates a new machine of the specified type and name, and
/// with the specified optional event. This event can only be
/// used to access its payload, and cannot be handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="operationGroupId">Optional operation group id</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
public override MachineId CreateMachine(Type type, string friendlyName, Event e = null, Guid? operationGroupId = null)
{
Machine creator = null;
if (this.TaskMap.ContainsKey((int)Task.CurrentId))
{
creator = this.TaskMap[(int)Task.CurrentId];
}
return this.CreateMachine(type, friendlyName, e, creator, operationGroupId);
}
/// <summary>
/// Creates a new machine of the specified <see cref="Type"/> and name, and
/// with the specified optional <see cref="Event"/>. This event can only be
/// used to access its payload, and cannot be handled. The method returns only
/// when the machine is initialized and the <see cref="Event"/> (if any) is handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="operationGroupId">Optional operation group id</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
public override Task<MachineId> CreateMachineAndExecute(Type type, Event e = null, Guid? operationGroupId = null)
{
Machine creator = null;
if (this.TaskMap.ContainsKey((int)Task.CurrentId))
{
creator = this.TaskMap[(int)Task.CurrentId];
}
return this.CreateMachineAndExecute(type, null, e, creator, operationGroupId);
}
/// <summary>
/// Creates a new machine of the specified <see cref="Type"/> and name, and
/// with the specified optional <see cref="Event"/>. This event can only be
/// used to access its payload, and cannot be handled. The method returns only
/// when the machine is initialized and the <see cref="Event"/> (if any) is handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="operationGroupId">Optional operation group id</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
public override Task<MachineId> CreateMachineAndExecute(Type type, string friendlyName, Event e = null, Guid? operationGroupId = null)
{
Machine creator = null;
if (this.TaskMap.ContainsKey((int)Task.CurrentId))
{
creator = this.TaskMap[(int)Task.CurrentId];
}
return this.CreateMachineAndExecute(type, friendlyName, e, creator, operationGroupId);
}
/// <summary>
/// Creates a new remote machine of the specified type and with
/// the specified optional event. This event can only be used
/// to access its payload, and cannot be handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="endpoint">Endpoint</param>
/// <param name="operationGroupId">Optional operation group id</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
public override MachineId RemoteCreateMachine(Type type, string endpoint, Event e = null, Guid? operationGroupId = null)
{
Machine creator = null;
if (this.TaskMap.ContainsKey((int)Task.CurrentId))
{
creator = this.TaskMap[(int)Task.CurrentId];
}
return this.CreateRemoteMachine(type, null, endpoint, e, creator, operationGroupId);
}
/// <summary>
/// Creates a new remote machine of the specified type and name, and
/// with the specified optional event. This event can only be used
/// to access its payload, and cannot be handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="endpoint">Endpoint</param>
/// <param name="operationGroupId">Optional operation group id</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
public override MachineId RemoteCreateMachine(Type type, string friendlyName,
string endpoint, Event e = null, Guid? operationGroupId = null)
{
Machine creator = null;
if (this.TaskMap.ContainsKey((int)Task.CurrentId))
{
creator = this.TaskMap[(int)Task.CurrentId];
}
return this.CreateRemoteMachine(type, friendlyName, endpoint, e, creator, operationGroupId);
}
/// <summary>
/// Sends an asynchronous event to a machine.
/// </summary>
/// <param name="target">Target machine id</param>
/// <param name="e">Event</param>
/// <param name="operationGroupId">Optional operation group id</param>
public override void SendEvent(MachineId target, Event e, Guid? operationGroupId = null)
{
// If the target machine is null then report an error and exit.
this.Assert(target != null, "Cannot send to a null machine.");
// If the event is null then report an error and exit.
this.Assert(e != null, "Cannot send a null event.");
this.SendEvent(target, e, this.GetCurrentMachine(), operationGroupId);
}
/// <summary>
/// Synchronously delivers an <see cref="Event"/> to a machine
/// and executes it if the machine is available.
/// </summary>
/// <param name="target">Target machine id</param>
/// <param name="e">Event</param>
/// <param name="operationGroupId">Optional operation group id</param>
public override async Task SendEventAndExecute(MachineId target, Event e, Guid? operationGroupId = null)
{
// If the target machine is null then report an error and exit.
this.Assert(target != null, "Cannot send to a null machine.");
// If the event is null then report an error and exit.
this.Assert(e != null, "Cannot send a null event.");
await this.SendEventAndExecute(target, e, this.GetCurrentMachine(), operationGroupId);
}
/// <summary>
/// Sends an asynchronous event to a remote machine, which
/// is modeled as a local machine during testing.
/// </summary>
/// <param name="target">Target machine id</param>
/// <param name="e">Event</param>
/// <param name="operationGroupId">Optional operation group id</param>
public override void RemoteSendEvent(MachineId target, Event e, Guid? operationGroupId = null)
{
this.SendEvent(target, e, operationGroupId);
}
/// <summary>
/// Registers a new specification monitor of the specified <see cref="Type"/>.
/// </summary>
/// <param name="type">Type of the monitor</param>
public override void RegisterMonitor(Type type)
{
this.TryCreateMonitor(type);
}
/// <summary>
/// Invokes the specified monitor with the specified <see cref="Event"/>.
/// </summary>
/// <typeparam name="T">Type of the monitor</typeparam>
/// <param name="e">Event</param>
public override void InvokeMonitor<T>(Event e)
{
this.InvokeMonitor(typeof(T), e);
}
/// <summary>
/// Invokes the specified monitor with the specified <see cref="Event"/>.
/// </summary>
/// <param name="type">Type of the monitor</param>
/// <param name="e">Event</param>
public override void InvokeMonitor(Type type, Event e)
{
// If the event is null then report an error and exit.
base.Assert(e != null, "Cannot monitor a null event.");
this.Monitor(type, null, e);
}
/// <summary>
/// Returns the operation group id of the specified machine. Returns <see cref="Guid.Empty"/>
/// if the id is not set, or if the <see cref="MachineId"/> is not associated with this runtime.
/// During testing, the runtime asserts that the specified machine is currently executing.
/// </summary>
/// <param name="currentMachine">MachineId of the currently executing machine.</param>
/// <returns>Guid</returns>
public override Guid GetCurrentOperationGroupId(MachineId currentMachine)
{
this.Assert(currentMachine == GetCurrentMachineId(), "Trying to access the operation group id of " +
$"'{currentMachine}', which is not the currently executing machine.");
Machine machine = null;
if (!this.MachineMap.TryGetValue(currentMachine.Value, out machine))
{
return Guid.Empty;
}
return machine.Info.OperationGroupId;
}
/// <summary>
/// Notifies each active machine to halt execution to allow the runtime
/// to reach quiescence. This is an experimental feature, which should
/// be used only for testing purposes.
/// </summary>
public override void Stop()
{
base.IsRunning = false;
}
#endregion
#region internal methods
/// <summary>
/// Runs the specified test method inside a test harness machine.
/// </summary>
/// <param name="testAction">Action</param>
/// <param name="testMethod">MethodInfo</param>
internal void RunTestHarness(MethodInfo testMethod, Action<PSharpRuntime> testAction)
{
this.Assert(Task.CurrentId != null, "The test harness machine must execute inside a task.");
this.Assert(testMethod != null || testAction != null, "The test harness machine " +
"cannot execute a null test method or action.");
MachineId mid = new MachineId(typeof(TestHarnessMachine), null, this);
TestHarnessMachine harness = new TestHarnessMachine(testMethod, testAction);
harness.Initialize(this, mid, new SchedulableInfo(mid));
Task task = new Task(() =>
{
try
{
this.Scheduler.NotifyEventHandlerStarted(harness.Info as SchedulableInfo);
harness.Run();
IO.Debug.WriteLine($"<ScheduleDebug> Completed event handler of the test harness machine.");
(harness.Info as SchedulableInfo).NotifyEventHandlerCompleted();
this.Scheduler.Schedule(OperationType.Stop, OperationTargetType.Schedulable, harness.Info.Id);
IO.Debug.WriteLine($"<ScheduleDebug> Exit event handler of the test harness machine.");
}
catch (ExecutionCanceledException)
{
IO.Debug.WriteLine($"<Exception> ExecutionCanceledException was thrown in the test harness.");
}
catch (Exception ex)
{
harness.ReportUnhandledException(ex);
}
});
(harness.Info as SchedulableInfo).NotifyEventHandlerCreated(task.Id, 0);
this.Scheduler.NotifyEventHandlerCreated(harness.Info as SchedulableInfo);
task.Start();
this.Scheduler.WaitForEventHandlerToStart(harness.Info as SchedulableInfo);
}
/// <summary>
/// Creates a new <see cref="Machine"/> of the specified <see cref="Type"/>.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="operationGroupId">Operation group id</param>
/// <param name="e">Event passed during machine construction</param>
/// <param name="creator">Creator machine</param>
/// <returns>MachineId</returns>
internal override MachineId CreateMachine(Type type, string friendlyName, Event e, Machine creator, Guid? operationGroupId)
{
if (creator != null)
{
this.AssertNoPendingTransitionStatement(creator, "CreateMachine");
}
// Using ulong.MaxValue because a 'Create' operation cannot specify
// the id of its target, because the id does not exist yet.
this.Scheduler.Schedule(OperationType.Create, OperationTargetType.Schedulable, ulong.MaxValue);
Machine machine = this.CreateMachine(type, friendlyName);
this.SetOperationGroupIdForMachine(machine, creator, operationGroupId);
this.BugTrace.AddCreateMachineStep(creator, machine.Id, e == null ? null : new EventInfo(e));
if (base.Configuration.EnableDataRaceDetection)
{
// Traces machine actions, if data-race detection is enabled.
this.MachineActionTraceMap.Add(machine.Id, new MachineActionTrace(machine.Id));
if (creator != null && MachineActionTraceMap.Keys.Contains(creator.Id))
{
this.MachineActionTraceMap[creator.Id].AddCreateMachineInfo(machine.Id);
}
}
this.RunMachineEventHandler(machine, e, true, false, null);
return machine.Id;
}
/// <summary>
/// Creates a new <see cref="Machine"/> of the specified <see cref="Type"/>. The
/// method returns only when the machine is initialized and the <see cref="Event"/>
/// (if any) is handled.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="operationGroupId">Operation group id</param>
/// <param name="e">Event passed during machine construction</param>
/// <param name="creator">Creator machine</param>
/// <returns>MachineId</returns>
internal override async Task<MachineId> CreateMachineAndExecute(Type type, string friendlyName, Event e, Machine creator, Guid? operationGroupId)
{
if (creator != null)
{
this.AssertNoPendingTransitionStatement(creator, "CreateMachine");
}
// Using ulong.MaxValue because a 'Create' operation cannot specify
// the id of its target, because the id does not exist yet.
this.Scheduler.Schedule(OperationType.Create, OperationTargetType.Schedulable, ulong.MaxValue);
Machine machine = this.CreateMachine(type, friendlyName);
this.SetOperationGroupIdForMachine(machine, creator, operationGroupId);
this.BugTrace.AddCreateMachineStep(creator, machine.Id, e == null ? null : new EventInfo(e));
if (base.Configuration.EnableDataRaceDetection)
{
// Traces machine actions, if data-race detection is enabled.
this.MachineActionTraceMap.Add(machine.Id, new MachineActionTrace(machine.Id));
if (creator != null && MachineActionTraceMap.Keys.Contains(creator.Id))
{
this.MachineActionTraceMap[creator.Id].AddCreateMachineInfo(machine.Id);
}
}
this.RunMachineEventHandler(machine, e, true, true, null);
return await Task.FromResult(machine.Id);
}
/// <summary>
/// Creates a new remote <see cref="Machine"/> of the specified
/// <see cref="System.Type"/>, which is modeled as a local
/// machine during testing.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="endpoint">Endpoint</param>
/// <param name="operationGroupId">Operation group id</param>
/// <param name="e">Event passed during machine construction</param>
/// <param name="creator">Creator machine</param>
/// <returns>MachineId</returns>
internal override MachineId CreateRemoteMachine(Type type, string friendlyName, string endpoint,
Event e, Machine creator, Guid? operationGroupId)
{
return this.CreateMachine(type, friendlyName, e, creator, operationGroupId);
}
/// <summary>
/// Creates a new <see cref="Machine"/> of the specified <see cref="Type"/>.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <returns>Machine</returns>
private Machine CreateMachine(Type type, string friendlyName)
{
this.Assert(type.IsSubclassOf(typeof(Machine)), $"Type '{type.Name}' is not a machine.");
MachineId mid = new MachineId(type, friendlyName, this);
var isMachineTypeCached = MachineFactory.IsCached(type);
Machine machine = MachineFactory.Create(type);
machine.Initialize(this, mid, new SchedulableInfo(mid));
machine.InitializeStateInformation();
if (base.Configuration.ReportCodeCoverage && !isMachineTypeCached)
{
this.ReportCodeCoverageOfMachine(machine);
}
bool result = this.MachineMap.TryAdd(mid.Value, machine);
this.Assert(result, $"Machine '{mid}' was already created.");
this.Log($"<CreateLog> Machine '{mid}' is created.");
return machine;
}
/// <summary>
/// Sends an asynchronous <see cref="Event"/> to a machine.
/// </summary>
/// <param name="mid">MachineId</param>
/// <param name="e">Event</param>
/// <param name="sender">Sender machine</param>
/// <param name="operationGroupId">Operation group id</param>
internal override void SendEvent(MachineId mid, Event e, AbstractMachine sender, Guid? operationGroupId)
{
this.Scheduler.Schedule(OperationType.Send, OperationTargetType.Inbox, mid.Value);
Machine machine = null;
if (!this.MachineMap.TryGetValue(mid.Value, out machine))
{
if (sender != null)
{
this.Log($"<SendLog> Machine '{sender.Id}' sent event '{e.GetType().FullName}' to a halted machine '{mid}'.");
}
else
{
this.Log($"<SendLog> The event '{e.GetType().FullName}' was sent to a halted machine '{mid}'.");
}
return;
}
bool runNewHandler = false;
EventInfo eventInfo = this.EnqueueEvent(machine, e, sender, operationGroupId, ref runNewHandler);
if (runNewHandler)
{
this.RunMachineEventHandler(machine, null, false, false, eventInfo);
}
}
/// <summary>
/// Sends an asynchronous <see cref="Event"/> to a machine and
/// executes the event handler if the machine is available.
/// </summary>
/// <param name="mid">MachineId</param>
/// <param name="e">Event</param>
/// <param name="sender">Sender machine</param>
/// <param name="operationGroupId">Operation group id</param>
internal override async Task SendEventAndExecute(MachineId mid, Event e, AbstractMachine sender, Guid? operationGroupId)
{
this.Scheduler.Schedule(OperationType.Send, OperationTargetType.Inbox, mid.Value);
Machine machine = null;
if (!this.MachineMap.TryGetValue(mid.Value, out machine))
{
if (sender != null)
{
this.Log($"<SendLog> Machine '{sender.Id}' sent event '{e.GetType().FullName}' to a halted machine '{mid}'.");
}
else
{
this.Log($"<SendLog> The event '{e.GetType().FullName}' was sent to a halted machine '{mid}'.");
}
return;
}
bool runNewHandler = false;
EventInfo eventInfo = this.EnqueueEvent(machine, e, sender, operationGroupId, ref runNewHandler);
if (runNewHandler)
{
this.RunMachineEventHandler(machine, null, false, true, eventInfo);
}
await Task.CompletedTask;
}
/// <summary>
/// Sends an asynchronous <see cref="Event"/> to a remote machine, which
/// is modeled as a local machine during testing.
/// </summary>
/// <param name="mid">MachineId</param>
/// <param name="e">Event</param>
/// <param name="sender">Sender machine</param>
/// <param name="operationGroupId">Operation group id</param>
internal override void SendEventRemotely(MachineId mid, Event e, AbstractMachine sender, Guid? operationGroupId)
{
this.SendEvent(mid, e, sender, operationGroupId);
}
/// <summary>
/// Enqueues an asynchronous <see cref="Event"/> to a machine.
/// </summary>
/// <param name="machine">Machine</param>
/// <param name="e">Event</param>
/// <param name="sender">Sender machine</param>
/// <param name="operationGroupId">Operation group id</param>
/// <param name="runNewHandler">Run a new handler</param>
/// <returns>EventInfo</returns>
private EventInfo EnqueueEvent(Machine machine, Event e, AbstractMachine sender, Guid? operationGroupId, ref bool runNewHandler)
{
if (sender != null && sender is Machine)
{
this.AssertNoPendingTransitionStatement(sender as Machine, "Send");
}
EventOriginInfo originInfo = null;
if (sender != null && sender is Machine)
{
originInfo = new EventOriginInfo(sender.Id, (sender as Machine).GetType().Name,
StateGroup.GetQualifiedStateName((sender as Machine).CurrentState));
}
else
{
// Message comes from outside P#.
originInfo = new EventOriginInfo(null, "Env", "Env");
}
EventInfo eventInfo = new EventInfo(e, originInfo, Scheduler.ScheduledSteps);
this.SetOperationGroupIdForEvent(eventInfo, sender, operationGroupId);
if (sender != null)
{
this.Log($"<SendLog> Machine '{sender.Id}' sent event " +
$"'{eventInfo.EventName}' to '{machine.Id}'.");
}
else
{
this.Log($"<SendLog> Event '{eventInfo.EventName}' was sent to '{machine.Id}'.");
}
if (sender != null)
{
var stateName = sender is Machine ? (sender as Machine).CurrentStateName : "";
this.BugTrace.AddSendEventStep(sender.Id, stateName, eventInfo, machine.Id);
if (base.Configuration.EnableDataRaceDetection)
{
// Traces machine actions, if data-race detection is enabled.
this.MachineActionTraceMap[sender.Id].AddSendActionInfo(machine.Id, e);
}
}
machine.Enqueue(eventInfo, ref runNewHandler);
return eventInfo;
}
/// <summary>
/// Runs a new asynchronous machine event handler.
/// This is a fire and forget invocation.
/// </summary>
/// <param name="machine">Machine that executes this event handler.</param>
/// <param name="initialEvent">Event for initializing the machine.</param>
/// <param name="isFresh">If true, then this is a new machine.</param>
/// <param name="executeSynchronously">If true, this operation executes synchronously.</param>
/// <param name="enablingEvent">If non-null, the event info of the sent event that caused the event handler to be restarted.</param>
private void RunMachineEventHandler(Machine machine, Event initialEvent, bool isFresh,
bool executeSynchronously, EventInfo enablingEvent)
{
Task task = new Task(async () =>
{
try
{
this.Scheduler.NotifyEventHandlerStarted(machine.Info as SchedulableInfo);
machine.IsInsideSynchronousCall = executeSynchronously;
if (isFresh)
{
await machine.GotoStartState(initialEvent);
}
await machine.RunEventHandler(executeSynchronously);
machine.IsInsideSynchronousCall = false;
if (executeSynchronously)
{
await machine.RunEventHandler();
}
IO.Debug.WriteLine($"<ScheduleDebug> Completed event handler of '{machine.Id}'.");
(machine.Info as SchedulableInfo).NotifyEventHandlerCompleted();
if (machine.Info.IsHalted)
{
this.Scheduler.Schedule(OperationType.Stop, OperationTargetType.Schedulable, machine.Info.Id);
}
else
{
this.Scheduler.Schedule(OperationType.Receive, OperationTargetType.Inbox, machine.Info.Id);
}
IO.Debug.WriteLine($"<ScheduleDebug> Exit event handler of '{machine.Id}'.");
}
catch (ExecutionCanceledException)
{
IO.Debug.WriteLine($"<Exception> ExecutionCanceledException was thrown from machine '{machine.Id}'.");
}
finally
{
this.TaskMap.TryRemove(Task.CurrentId.Value, out machine);
}
});
this.TaskMap.TryAdd(task.Id, machine);
(machine.Info as SchedulableInfo).NotifyEventHandlerCreated(task.Id, enablingEvent?.SendStep ?? 0);
this.Scheduler.NotifyEventHandlerCreated(machine.Info as SchedulableInfo);
task.Start(this.TaskScheduler);
this.Scheduler.WaitForEventHandlerToStart(machine.Info as SchedulableInfo);
}
/// <summary>
/// Checks that a machine can start its event handler. Returns false if the event
/// handler should not be started. The bug finding runtime may return false because
/// it knows that there are currently no events in the inbox that can be handled.
/// </summary>
/// <param name="machine">Machine</param>
/// <returns>Boolean</returns>
internal override bool CheckStartEventHandler(Machine machine)
{
return machine.TryDequeueEvent(true) != null;
}
/// <summary>
/// Waits until all P# machines have finished execution.
/// </summary>
internal void Wait()
{
this.Scheduler.Wait();
base.IsRunning = false;
}
#endregion
#region specifications and error checking
/// <summary>
/// Tries to create a new monitor of the given type.
/// </summary>
/// <param name="type">Type of the monitor</param>
internal override void TryCreateMonitor(Type type)
{
this.Assert(type.IsSubclassOf(typeof(Monitor)), $"Type '{type.Name}' " +
"is not a subclass of Monitor.\n");
MachineId mid = new MachineId(type, null, this);
SchedulableInfo info = new SchedulableInfo(mid);
Scheduler.NotifyMonitorRegistered(info);
Monitor monitor = Activator.CreateInstance(type) as Monitor;
monitor.Initialize(mid);
monitor.InitializeStateInformation();
this.Log($"<CreateLog> Monitor '{type.Name}' is created.");
this.ReportCodeCoverageOfMonitor(monitor);
this.BugTrace.AddCreateMonitorStep(mid);
this.Monitors.Add(monitor);
monitor.GotoStartState();
}
/// <summary>
/// Invokes the specified monitor with the given event.
/// </summary>
/// <param name="sender">Sender machine</param>
/// <param name="type">Type of the monitor</param>
/// <param name="e">Event</param>
internal override void Monitor(Type type, AbstractMachine sender, Event e)
{
if (sender != null && sender is Machine)
{
this.AssertNoPendingTransitionStatement(sender as Machine, "Monitor");
}
foreach (var m in this.Monitors)
{
if (m.GetType() == type)
{
if (base.Configuration.ReportCodeCoverage)
{
this.ReportCodeCoverageOfMonitorEvent(sender, m, e);
this.ReportCodeCoverageOfMonitorTransition(m, e);
}
m.MonitorEvent(e);
}
}
}
/// <summary>
/// Checks if the assertion holds, and if not it throws an
/// <see cref="AssertionFailureException"/> exception.
/// </summary>
/// <param name="predicate">Predicate</param>
public override void Assert(bool predicate)
{
if (!predicate)
{
string message = "Detected an assertion failure.";
this.Scheduler.NotifyAssertionFailure(message);
}
}
/// <summary>
/// Checks if the assertion holds, and if not it throws an
/// <see cref="AssertionFailureException"/> exception.
/// </summary>
/// <param name="predicate">Predicate</param>
/// <param name="s">Message</param>
/// <param name="args">Message arguments</param>
public override void Assert(bool predicate, string s, params object[] args)
{
if (!predicate)
{
string message = IO.Utilities.Format(s, args);
this.Scheduler.NotifyAssertionFailure(message);
}
}
/// <summary>
/// Asserts that a transition statement (Raise/Goto/Pop) has not already
/// been called. Records that RGP has been called.
/// </summary>
/// <param name="machine">Machine</param>
internal void AssertTransitionStatement(Machine machine)
{
this.Assert(!machine.Info.IsInsideOnExit, "Machine '{0}' has called raise/goto/pop " +
"inside an OnExit method.", machine.Id.Name);
this.Assert(!machine.Info.CurrentActionCalledTransitionStatement, "Machine '{0}' has called multiple " +
"raise/goto/pop in the same action.", machine.Id.Name);
machine.Info.CurrentActionCalledTransitionStatement = true;
}
/// <summary>
/// Asserts that a transition statement (Raise/Goto/Pop) has not
/// already been called.
/// </summary>
/// <param name="machine">Machine</param>
/// <param name="calledAPI">Called API</param>
internal void AssertNoPendingTransitionStatement(Machine machine, string calledAPI)
{
this.Assert(!machine.Info.CurrentActionCalledTransitionStatement, "Machine '{0}' cannot call API '{1}' " +
"after calling raise/goto/pop in the same action.", machine.Id.Name, calledAPI);
}
/// <summary>
/// Checks that no monitor is in a hot state upon program termination.
/// If the program is still running, then this method returns without
/// performing a check.
/// </summary>
internal void AssertNoMonitorInHotStateAtTermination()
{
if (!this.Scheduler.HasFullyExploredSchedule)
{
return;
}
foreach (var monitor in this.Monitors)
{
string stateName = "";
if (monitor.IsInHotState(out stateName))
{
string message = IO.Utilities.Format("Monitor '{0}' detected liveness bug " +
"in hot state '{1}' at the end of program execution.",
monitor.GetType().Name, stateName);
this.Scheduler.NotifyAssertionFailure(message, false);
}
}
}
#endregion
#region nondeterministic choices
/// <summary>
/// Returns a nondeterministic boolean choice, that can be
/// controlled during analysis or testing.
/// </summary>
/// <param name="caller">Machine</param>
/// <param name="maxValue">Max value</param>
/// <returns>Boolean</returns>
internal override bool GetNondeterministicBooleanChoice(AbstractMachine caller, int maxValue)
{
if (caller != null && caller is Machine)
{
this.AssertNoPendingTransitionStatement(caller as Machine, "Random");
(caller as Machine).Info.ProgramCounter++;
}
var choice = this.Scheduler.GetNextNondeterministicBooleanChoice(maxValue);
if (caller != null)
{
this.Log($"<RandomLog> Machine '{caller.Id}' nondeterministically chose '{choice}'.");
}
else
{
this.Log($"<RandomLog> Runtime nondeterministically chose '{choice}'.");
}
var stateName = caller is Machine ? (caller as Machine).CurrentStateName : "";
this.BugTrace.AddRandomChoiceStep(caller == null ? null : caller.Id, stateName, choice);
return choice;
}
/// <summary>
/// Returns a fair nondeterministic boolean choice, that can be
/// controlled during analysis or testing.
/// </summary>
/// <param name="caller">Machine</param>
/// <param name="uniqueId">Unique id</param>
/// <returns>Boolean</returns>
internal override bool GetFairNondeterministicBooleanChoice(AbstractMachine caller, string uniqueId)
{
if (caller != null && caller is Machine)
{
this.AssertNoPendingTransitionStatement(caller as Machine, "FairRandom");
(caller as Machine).Info.ProgramCounter++;
}
var choice = this.Scheduler.GetNextNondeterministicBooleanChoice(2, uniqueId);
if (caller != null)
{
this.Log($"<RandomLog> Machine '{caller.Id}' " +