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 pathBugFindingScheduler.cs
More file actions
591 lines (499 loc) · 20.2 KB
/
BugFindingScheduler.cs
File metadata and controls
591 lines (499 loc) · 20.2 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
//-----------------------------------------------------------------------
// <copyright file="BugFindingScheduler.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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.PSharp.IO;
using Microsoft.PSharp.TestingServices.SchedulingStrategies;
namespace Microsoft.PSharp.TestingServices.Scheduling
{
/// <summary>
/// Class implementing the basic P# bug-finding scheduler.
/// </summary>
internal sealed class BugFindingScheduler
{
#region fields
/// <summary>
/// The P# bug-finding runtime.
/// </summary>
private BugFindingRuntime Runtime;
/// <summary>
/// The scheduling strategy to be used for bug-finding.
/// </summary>
private ISchedulingStrategy Strategy;
/// <summary>
/// Map from unique ids to schedulable infos.
/// </summary>
private Dictionary<ulong, SchedulableInfo> SchedulableInfoMap;
/// <summary>
/// The scheduler completion source.
/// </summary>
private readonly TaskCompletionSource<bool> CompletionSource;
/// <summary>
/// Checks if the scheduler is running.
/// </summary>
private bool IsSchedulerRunning;
#endregion
#region properties
/// <summary>
/// The currently schedulable info.
/// </summary>
internal SchedulableInfo ScheduledMachine { get; private set; }
/// <summary>
/// Number of scheduled steps.
/// </summary>
internal int ScheduledSteps => this.Strategy.GetScheduledSteps();
/// <summary>
/// Checks if the schedule has been fully explored.
/// </summary>
internal bool HasFullyExploredSchedule { get; private set; }
/// <summary>
/// True if a bug was found.
/// </summary>
internal bool BugFound { get; private set; }
/// <summary>
/// Bug report.
/// </summary>
internal string BugReport { get; private set; }
#endregion
#region constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="runtime">BugFindingRuntime</param>
/// <param name="strategy">SchedulingStrategy</param>
internal BugFindingScheduler(BugFindingRuntime runtime, ISchedulingStrategy strategy)
{
this.Runtime = runtime;
this.Strategy = strategy;
this.SchedulableInfoMap = new Dictionary<ulong, SchedulableInfo>();
this.CompletionSource = new TaskCompletionSource<bool>();
this.IsSchedulerRunning = true;
this.BugFound = false;
this.HasFullyExploredSchedule = false;
}
#endregion
#region scheduling methods
/// <summary>
/// Schedules the next <see cref="ISchedulable"/> operation to execute.
/// </summary>
/// <param name="operationType">Type of the operation.</param>
/// <param name="targetType">Type of the target of the operation.</param>
/// <param name="targetId">Id of the target.</param>
internal void Schedule(OperationType operationType, OperationTargetType targetType, ulong targetId)
{
int? taskId = Task.CurrentId;
// If the caller is the root task, then return.
if (taskId != null && taskId == this.Runtime.RootTaskId)
{
return;
}
if (!this.IsSchedulerRunning)
{
this.Stop();
}
// Checks if synchronisation not controlled by P# was used.
this.CheckIfExternalSynchronizationIsUsed();
// Checks if the scheduling steps bound has been reached.
this.CheckIfSchedulingStepsBoundIsReached();
SchedulableInfo current = this.ScheduledMachine;
current.SetNextOperation(operationType, targetType, targetId);
// Get and order the schedulable choices by their id.
var choices = this.SchedulableInfoMap.Values.OrderBy(choice => choice.Id).Select(choice => choice as ISchedulable).ToList();
ISchedulable next = null;
bool CheckCycle = false;
if (operationType.Equals(OperationType.Send)/* && !operationType.Equals(OperationType.Create)*/
/*&& !operationType.Equals(OperationType.Receive)*/)
CheckCycle = true;
if (!this.Strategy.GetNext(out next, choices, current, CheckCycle))
{
// Checks if the program has livelocked.
this.CheckIfProgramHasLivelocked(choices.Select(choice => choice as SchedulableInfo));
Debug.WriteLine("<ScheduleDebug> Schedule explored.");
this.HasFullyExploredSchedule = true;
this.Stop();
}
this.ScheduledMachine = next as SchedulableInfo;
this.Runtime.ScheduleTrace.AddSchedulingChoice(next.Id);
(next as MachineInfo).ProgramCounter = 0;
Debug.WriteLine($"<ScheduleDebug> Schedule '{next.Name}' with task id '{this.ScheduledMachine.TaskId}'.");
if (current != next)
{
current.IsActive = false;
lock (next)
{
this.ScheduledMachine.IsActive = true;
System.Threading.Monitor.PulseAll(next);
}
lock (current)
{
if (!current.IsEventHandlerRunning)
{
return;
}
while (!current.IsActive)
{
Debug.WriteLine($"<ScheduleDebug> Sleep '{current.Name}' with task id '{current.TaskId}'.");
System.Threading.Monitor.Wait(current);
Debug.WriteLine($"<ScheduleDebug> Wake up '{current.Name}' with task id '{current.TaskId}'.");
}
if (!current.IsEnabled)
{
throw new ExecutionCanceledException();
}
}
}
}
/// <summary>
/// Returns the next nondeterministic boolean choice.
/// </summary>
/// <param name="maxValue">Max value</param>
/// <param name="uniqueId">Unique id</param>
/// <returns>Boolean</returns>
internal bool GetNextNondeterministicBooleanChoice(int maxValue, string uniqueId = null)
{
// Checks if synchronisation not controlled by P# was used.
this.CheckIfExternalSynchronizationIsUsed();
// Checks if the scheduling steps bound has been reached.
this.CheckIfSchedulingStepsBoundIsReached();
var choice = false;
if (!this.Strategy.GetNextBooleanChoice(maxValue, out choice))
{
Debug.WriteLine("<ScheduleDebug> Schedule explored.");
this.Stop();
}
if (uniqueId == null)
{
this.Runtime.ScheduleTrace.AddNondeterministicBooleanChoice(choice);
}
else
{
this.Runtime.ScheduleTrace.AddFairNondeterministicBooleanChoice(uniqueId, choice);
}
return choice;
}
/// <summary>
/// Returns the next nondeterministic integer choice.
/// </summary>
/// <param name="maxValue">Max value</param>
/// <returns>Integer</returns>
internal int GetNextNondeterministicIntegerChoice(int maxValue)
{
// Checks if synchronisation not controlled by P# was used.
this.CheckIfExternalSynchronizationIsUsed();
// Checks if the scheduling steps bound has been reached.
this.CheckIfSchedulingStepsBoundIsReached();
var choice = 0;
if (!this.Strategy.GetNextIntegerChoice(maxValue, out choice))
{
Debug.WriteLine("<ScheduleDebug> Schedule explored.");
this.Stop();
}
this.Runtime.ScheduleTrace.AddNondeterministicIntegerChoice(choice);
return choice;
}
/// <summary>
/// Waits for the event handler to start.
/// </summary>
/// <param name="info">SchedulableInfo</param>
internal void WaitForEventHandlerToStart(SchedulableInfo info)
{
lock (info)
{
if (this.SchedulableInfoMap.Count == 1)
{
info.IsActive = true;
System.Threading.Monitor.PulseAll(info);
}
else
{
while (!info.IsEventHandlerRunning)
{
System.Threading.Monitor.Wait(info);
}
}
}
}
/// <summary>
/// Stops the scheduler.
/// </summary>
internal void Stop()
{
this.IsSchedulerRunning = false;
this.KillRemainingMachines();
// Check if the completion source is completed. If not synchronize on
// it (as it can only be set once) and set its result.
if (!this.CompletionSource.Task.IsCompleted)
{
lock (this.CompletionSource)
{
if (!this.CompletionSource.Task.IsCompleted)
{
this.CompletionSource.SetResult(true);
}
}
}
throw new ExecutionCanceledException();
}
/// <summary>
/// Blocks until the scheduler terminates.
/// </summary>
internal void Wait() => this.CompletionSource.Task.Wait();
#endregion
#region notifications
/// <summary>
/// Notify that an event handler has been created.
/// </summary>
/// <param name="info">SchedulableInfo</param>
internal void NotifyEventHandlerCreated(SchedulableInfo info)
{
if (!this.SchedulableInfoMap.ContainsKey(info.Id))
{
if (this.SchedulableInfoMap.Count == 0)
{
this.ScheduledMachine = info;
}
this.SchedulableInfoMap.Add(info.Id, info);
}
Debug.WriteLine($"<ScheduleDebug> Created event handler of '{info.Name}' with task id '{info.TaskId}'.");
}
/// <summary>
/// Notify that a monitor was registered.
/// </summary>
/// <param name="info">SchedulableInfo</param>
internal void NotifyMonitorRegistered(SchedulableInfo info)
{
SchedulableInfoMap.Add(info.Id, info);
Debug.WriteLine($"<ScheduleDebug> Created monitor of '{info.Name}'.");
}
/// <summary>
/// Notify that the event handler has started.
/// </summary>
/// <param name="info">SchedulableInfo</param>
internal void NotifyEventHandlerStarted(SchedulableInfo info)
{
Debug.WriteLine($"<ScheduleDebug> Started event handler of '{info.Name}' with task id '{info.TaskId}'.");
lock (info)
{
info.IsEventHandlerRunning = true;
System.Threading.Monitor.PulseAll(info);
while (!info.IsActive)
{
Debug.WriteLine($"<ScheduleDebug> Sleep '{info.Name}' with task id '{info.TaskId}'.");
System.Threading.Monitor.Wait(info);
Debug.WriteLine($"<ScheduleDebug> Wake up '{info.Name}' with task id '{info.TaskId}'.");
}
if (!info.IsEnabled)
{
throw new ExecutionCanceledException();
}
}
}
/// <summary>
/// Notify that an assertion has failed.
/// </summary>
/// <param name="text">Bug report</param>
/// <param name="killTasks">Kill tasks</param>
internal void NotifyAssertionFailure(string text, bool killTasks = true)
{
if (!this.BugFound)
{
this.BugReport = text;
this.Runtime.Log($"<ErrorLog> {text}");
this.Runtime.Log("<StrategyLog> Found bug using " +
$"'{this.Runtime.Configuration.SchedulingStrategy}' strategy.");
if (this.Strategy.GetDescription().Length > 0)
{
this.Runtime.Log($"<StrategyLog> {this.Strategy.GetDescription()}");
}
this.BugFound = true;
if (this.Runtime.Configuration.AttachDebugger)
{
System.Diagnostics.Debugger.Break();
}
}
if (killTasks)
{
this.Stop();
}
}
#endregion
#region utilities
/// <summary>
/// Returns the enabled schedulable ids.
/// </summary>
/// <returns>Enabled machine ids</returns>
internal HashSet<ulong> GetEnabledSchedulableIds()
{
var enabledSchedulableIds = new HashSet<ulong>();
foreach (var machineInfo in this.SchedulableInfoMap.Values)
{
if (machineInfo.IsEnabled)
{
enabledSchedulableIds.Add(machineInfo.Id);
}
}
return enabledSchedulableIds;
}
/// <summary>
/// Returns a test report with the scheduling statistics.
/// </summary>
/// <returns>TestReport</returns>
internal TestReport GetReport()
{
TestReport report = new TestReport(this.Runtime.Configuration);
if (this.BugFound)
{
report.NumOfFoundBugs++;
report.BugReports.Add(this.BugReport);
}
if (this.Strategy.IsFair())
{
report.NumOfExploredFairSchedules++;
if (this.Strategy.HasReachedMaxSchedulingSteps())
{
report.MaxFairStepsHitInFairTests++;
}
if (this.ScheduledSteps >= report.Configuration.MaxUnfairSchedulingSteps)
{
report.MaxUnfairStepsHitInFairTests++;
}
if (!this.Strategy.HasReachedMaxSchedulingSteps())
{
report.TotalExploredFairSteps += this.ScheduledSteps;
if (report.MinExploredFairSteps < 0 ||
report.MinExploredFairSteps > this.ScheduledSteps)
{
report.MinExploredFairSteps = this.ScheduledSteps;
}
if (report.MaxExploredFairSteps < this.ScheduledSteps)
{
report.MaxExploredFairSteps = this.ScheduledSteps;
}
}
}
else
{
report.NumOfExploredUnfairSchedules++;
if (this.Strategy.HasReachedMaxSchedulingSteps())
{
report.MaxUnfairStepsHitInUnfairTests++;
}
}
return report;
}
#endregion
#region private methods
/// <summary>
/// Returns the number of available machines to schedule.
/// </summary>
/// <returns>Int</returns>
private int NumberOfAvailableMachinesToSchedule()
{
var availableMachines = this.SchedulableInfoMap.Values.Where(choice => choice.IsEnabled).ToList();
return availableMachines.Count;
}
/// <summary>
/// Checks for a livelock. This happens when there are no more enabled
/// machines, but there is one or more non-enabled machines that are
/// waiting to receive an event.
/// </summary>
/// <param name="choices">SchedulableInfos</param>
private void CheckIfProgramHasLivelocked(IEnumerable<SchedulableInfo> choices)
{
var blockedChoices = choices.Where(choice => choice.IsWaitingToReceive).ToList();
if (blockedChoices.Count > 0)
{
string message = "Livelock detected.";
for (int i = 0; i < blockedChoices.Count; i++)
{
message += IO.Utilities.Format($" '{blockedChoices[i].Name}'");
if (i == blockedChoices.Count - 2)
{
message += " and";
}
else if (i < blockedChoices.Count - 1)
{
message += ",";
}
}
message += blockedChoices.Count == 1 ? " is " : " are ";
message += "waiting for an event, but no other schedulable choices are enabled.";
this.Runtime.Scheduler.NotifyAssertionFailure(message, true);
}
}
/// <summary>
/// Checks if external (non-P#) synchronisation was used to invoke
/// the scheduler. If yes, it stops the scheduler, reports an error
/// and kills all enabled machines.
/// </summary>
private void CheckIfExternalSynchronizationIsUsed()
{
int? taskId = Task.CurrentId;
if (taskId == null)
{
string message = IO.Utilities.Format("Detected synchronization context " +
"that is not controlled by the P# runtime.");
this.NotifyAssertionFailure(message, true);
}
if (this.ScheduledMachine.TaskId != taskId.Value)
{
string message = IO.Utilities.Format($"Detected task with id '{taskId}' " +
"that is not controlled by the P# runtime.");
this.NotifyAssertionFailure(message, true);
}
}
/// <summary>
/// Checks if the scheduling steps bound has been reached. If yes,
/// it stops the scheduler and kills all enabled machines.
/// </summary>
private void CheckIfSchedulingStepsBoundIsReached()
{
if (this.Strategy.HasReachedMaxSchedulingSteps())
{
var msg = IO.Utilities.Format("Scheduling steps bound of {0} reached.",
this.Strategy.IsFair() ? this.Runtime.Configuration.MaxFairSchedulingSteps :
this.Runtime.Configuration.MaxUnfairSchedulingSteps);
if (this.Runtime.Configuration.ConsiderDepthBoundHitAsBug)
{
this.Runtime.Scheduler.NotifyAssertionFailure(msg, true);
}
else
{
Debug.WriteLine($"<ScheduleDebug> {msg}");
this.Stop();
}
}
}
/// <summary>
/// Kills any remaining machines at the end of the schedule.
/// </summary>
private void KillRemainingMachines()
{
foreach (var machineInfo in this.SchedulableInfoMap.Values)
{
machineInfo.IsActive = true;
machineInfo.IsEnabled = false;
if (machineInfo.IsEventHandlerRunning)
{
lock (machineInfo)
{
System.Threading.Monitor.PulseAll(machineInfo);
}
}
}
}
#endregion
}
}