Grade MLFQS.
[pintos-anon] / grading / threads / run-tests
1 #! /usr/bin/perl
2
3 use warnings;
4 use strict;
5 use POSIX;
6 use Algorithm::Diff;
7 use Getopt::Long;
8
9 our ($VERBOSE) = 0;     # Verbosity of output
10 our (@TESTS);           # Tests to run.
11 my ($clean) = 0;
12 my ($grade) = 0;
13
14 GetOptions ("v|verbose+" => \$VERBOSE,
15             "h|help" => sub { usage (0) },
16             "t|test=s" => \@TESTS,
17             "c|clean" => \$clean,
18             "g|grade" => \$grade)
19     or die "Malformed command line; use --help for help.\n";
20 die "Non-option argument not supported; use --help for help.\n"
21     if @ARGV > 0;
22
23 sub usage {
24     my ($exitcode) = @_;
25     print "run-tests, for grading Pintos thread projects.\n\n";
26     print "Invoke from a directory containing a student tarball named by\n";
27     print "the submit script, e.g. username.Oct.12.04.20.04.09.tar.gz.\n";
28     print "In normal usage, no options are needed.\n\n";
29     print "Output is produced in tests.out and details.out.\n\n";
30     print "Options:\n";
31     print "  -c, --clean     Remove old output files before starting\n";
32     print "  -t, --test=TEST Execute TEST only (allowed multiple times)\n";
33     print "  -g, --grade     Instead of running tests, compose grade.out\n";
34     print "  -v, --verbose   Print commands before executing them\n";
35     print "  -h, --help      Print this help message\n";
36     exit $exitcode;
37 }
38
39 # Default set of tests.
40 @TESTS = ("alarm-single", "alarm-multiple", "alarm-zero", "alarm-negative",
41           "join-simple",
42           "join-quick", "join-multiple", "join-nested",
43           "join-dummy", "join-invalid", "join-no",
44           "priority-preempt", "priority-fifo", "priority-donate-one",
45           "priority-donate-multiple", "priority-donate-nest",
46           "mlfqs-on", "mlfqs-off")
47     unless @TESTS > 0;
48
49 # Handle final grade mode.
50 if ($grade) {
51     open (OUT, ">grade.out") or die "grade.out: create: $!\n";
52
53     open (GRADE, "<grade.txt") or die "grade.txt: open: $!\n";
54     while (<GRADE>) {
55         last if /^\s*$/;
56         print OUT;
57     }
58     close (GRADE);
59     
60     my (@tests) = snarf ("tests.out");
61     my ($p_got, $p_pos) = $tests[0] =~ m%\((\d+)/(\d+)\)% or die;
62
63     my (@review) = snarf ("review.txt");
64     my ($part_lost) = (0, 0);
65     for (my ($i) = $#review; $i >= 0; $i--) {
66         local ($_) = $review[$i];
67         if (my ($loss) = /^\s*([-+]\d+)/) {
68             $part_lost += $loss;
69         } elsif (my ($out_of) = m%\[\[/(\d+)\]\]%) {
70             my ($got) = $out_of + $part_lost;
71             $got = 0 if $got < 0;
72             $review[$i] =~ s%\[\[/\d+\]\]%($got/$out_of)% or die;
73             $part_lost = 0;
74
75             $p_got += $got;
76             $p_pos += $out_of;
77         }
78     }
79     die "Lost points outside a section\n" if $part_lost;
80
81     for (my ($i) = 1; $i <= $#review; $i++) {
82         if ($review[$i] =~ /^-{3,}\s*$/ && $review[$i - 1] !~ /^\s*$/) {
83             $review[$i] = '-' x (length ($review[$i - 1]));
84         }
85     }
86
87     print OUT "\nOVERALL SCORE\n";
88     print OUT "-------------\n";
89     print OUT "$p_got points out of $p_pos total\n\n";
90
91     print OUT map ("$_\n", @tests), "\n";
92     print OUT map ("$_\n", @review);
93
94     exit 0;
95 }
96
97 # Find the directory that contains the grading files.
98 our ($GRADES_DIR);
99 ($GRADES_DIR = $0) =~ s#/[^/]+$##;
100 -d $GRADES_DIR or die "$GRADES_DIR: stat: $!\n";
101
102 if ($clean) {
103     # Verify that we're roughly in the correct directory
104     # before we go blasting away files.
105     choose_tarball ();
106
107     xsystem ("rm -rf output pintos", VERBOSE => 1);
108     xsystem ("rm -f details.out tests.out", VERBOSE => 1);
109 }
110
111 # Create output directory, if it doesn't already exist.
112 -d ("output") || mkdir ("output") or die "output: mkdir: $!\n";
113
114 # Extract submission.
115 extract_tarball () if ! -d "pintos";
116
117 # Verify that the proper directory was submitted.
118 -d "pintos/src/threads" or die "pintos/src/threads: stat: $!\n";
119
120 # Run and grade the tests.
121 our $test;
122 our %result;
123 our %details;
124 our %extra;
125 for $test (@TESTS) {
126     print "$test: ";
127     my ($result) = run_test ($test);
128     if ($result eq 'ok') {
129         $result = grade_test ($test);
130         $result =~ s/\n$//;
131     }
132     print "$result\n";
133     
134     $result{$test} = $result;
135 }
136
137 # MLFQS takes results from mlfqs-on and mlfqs-off.
138 grade_mlfqs_speedup ();
139 grade_mlfqs_priority ();
140
141 # Write output.
142 write_grades ();
143 write_details ();
144 \f
145 sub choose_tarball {
146     my (@tarballs)
147         = grep (/^[a-z0-9]+\.[A-Za-z]+\.\d+\.\d+\.\d+\.\d+.\d+\.tar\.gz$/,
148                 glob ("*.tar.gz"));
149     die "no pintos dir and no source tarball\n" if scalar (@tarballs) == 0;
150
151     # Sort tarballs in reverse order by time.
152     @tarballs = sort { ext_mdyHMS ($b) cmp ext_mdyHMS ($a) } @tarballs;
153
154     print "Multiple tarballs: choosing $tarballs[0]\n"
155         if scalar (@tarballs) > 1;
156     return $tarballs[0];
157 }
158
159 sub extract_tarball {
160     my ($tarball) = choose_tarball ();
161
162     mkdir "pintos" or die "pintos: mkdir: $!\n";
163     mkdir "pintos/src" or die "pintos: mkdir: $!\n";
164
165     print "Extracting $tarball...\n";
166     xsystem ("cd pintos/src && tar xzf ../../$tarball",
167              DIE => "extraction failed\n");
168
169     print "Patching...\n";
170     xsystem ("patch -fs pintos/src/lib/debug.c < $GRADES_DIR/panic.diff",
171              LOG => "patch",
172              DIE => "patch failed\n");
173 }
174
175 sub ext_mdyHMS {
176     my ($s) = @_;
177     my ($ms, $d, $y, $H, $M, $S) =
178         $s =~ /.([A-Za-z]+)\.(\d+)\.(\d+)\.(\d+)\.(\d+).(\d+)\.tar\.gz$/
179         or die;
180     my ($m) = index ("janfebmaraprmayjunjulaugsepoctnovdec", lc $ms) / 3
181         or die;
182     return sprintf "%02d-%02d-%02d %02d:%02d:%02d", $y, $m, $d, $H, $M, $S;
183 }
184 \f
185 sub test_source {
186     my ($test) = @_;
187     my ($src) = "$GRADES_DIR/$test.c";
188     $src = "$GRADES_DIR/mlfqs.c" if $test =~ /^mlfqs/;
189     -e $src or die "$src: stat: $!\n";
190     return $src;
191 }
192
193 sub test_constants {
194    my ($defines) = "";
195    $defines .= "#define MLFQS 1\n" if $test eq 'mlfqs-on';
196    return $defines;
197  }
198
199 sub run_test {
200     my ($test) = @_;
201
202     # Reuse older results if any.
203     if (open (DONE, "<output/$test/done")) {
204         my ($status);
205         $status = <DONE>;
206         chomp $status;
207         close (DONE);
208         return $status;
209     }
210
211     # Really run the test.
212     my ($status) = really_run_test ($test);
213
214     # Save the results for later.
215     open (DONE, ">output/$test/done") or die "output/$test/done: create: $!\n";
216     print DONE "$status\n";
217     close (DONE);
218
219     return $status;
220 }
221
222 sub really_run_test {
223     # Need to run it.
224     # If there's residue from an earlier test, move it to .old.
225     # If there's already a .old, delete it.
226     xsystem ("rm -rf output/$test.old", VERBOSE => 1) if -d "output/$test.old";
227     rename "output/$test", "output/$test.old" or die "rename: $!\n"
228         if -d "output/$test";
229
230     # Make output directory.
231     mkdir "output/$test";
232
233     # Change constants.h if necessary.
234     my ($defines) = test_constants ($test);
235     if ($defines ne snarf ("pintos/src/constants.h")) {
236         open (CONSTANTS, ">pintos/src/constants.h");
237         print CONSTANTS $defines;
238         close (CONSTANTS);
239     }
240
241     # Copy in the new test.c and delete enough files to ensure a full rebuild.
242     my ($src) = test_source ($test);
243     xsystem ("cp $src pintos/src/threads/test.c", DIE => "cp failed\n");
244     unlink ("pintos/src/threads/build/threads/test.o");
245     unlink ("pintos/src/threads/build/kernel.o");
246     unlink ("pintos/src/threads/build/kernel.bin");
247     unlink ("pintos/src/threads/build/os.dsk");
248
249     # Build.
250     xsystem ("cd pintos/src/threads && make", LOG => "$test/make")
251         or return "compile error";
252
253     # Copy out files for backtraces later.
254     xsystem ("cp pintos/src/threads/build/kernel.o output/$test");
255     xsystem ("cp pintos/src/threads/build/os.dsk output/$test");
256
257     # Run.
258     my ($timeout) = 10;
259     $timeout = 600 if $test =~ /^mlfqs/;
260     xsystem ("cd pintos/src/threads/build && pintos -v run -q",
261              LOG => "$test/run",
262              TIMEOUT => $timeout)
263         or return "Bochs error";
264     
265     return "ok";
266 }
267
268 sub grade_test {
269     my ($test) = @_;
270
271     my (@output) = snarf ("output/$test/run.out");
272
273     if (-e "$GRADES_DIR/$test.exp") {
274         eval {
275             verify_common (@output);
276             compare_output ("$GRADES_DIR/$test.exp", @output);
277         }
278     } else {
279         my ($grade_func);
280         ($grade_func = $test) =~ s/-/_/g;
281         eval "grade_$grade_func (\@output)";
282     }
283     if ($@) {
284         die $@ if $@ =~ /at \S+ line \d+$/;
285         return $@;
286     }
287     return "ok";
288 }
289 \f
290 sub grade_alarm_single {
291     verify_alarm (1, @_);
292 }
293
294 sub grade_alarm_multiple {
295     verify_alarm (7, @_);
296 }
297
298 sub verify_alarm {
299     my ($iterations, @output) = @_;
300
301     verify_common (@output);
302
303     my (@products);
304     for (my ($i) = 0; $i < $iterations; $i++) {
305         for (my ($t) = 0; $t < 5; $t++) {
306             push (@products, ($i + 1) * ($t + 1) * 10);
307         }
308     }
309     @products = sort {$a <=> $b} @products;
310
311     local ($_);
312     foreach (@output) {
313         die $_ if /Out of order/;
314
315         my ($p) = /product=(\d+)$/;
316         next if !defined $p;
317
318         my ($q) = shift (@products);
319         die "Too many wakeups.\n" if !defined $q;
320         die "Out of order wakeups ($p vs. $q).\n" if $p != $q; # FIXME
321     }
322     die scalar (@products) . " fewer wakeups than expected.\n"
323         if @products != 0;
324 }
325
326 sub grade_alarm_zero {
327     my (@output) = @_;
328     verify_common (@output);
329     die "Crashed in timer_sleep()\n" if !grep (/^Success\.$/, @output);
330 }
331
332 sub grade_alarm_negative {
333     my (@output) = @_;
334     verify_common (@output);
335     die "Crashed in timer_sleep()\n" if !grep (/^Success\.$/, @output);
336 }
337
338 sub grade_join_invalid {
339     my (@output) = @_;
340     verify_common (@output);
341     grep (/Testing invalid join/, @output) or die "Test didn't start\n";
342     grep (/Invalid join test done/, @output) or die "Test didn't complete\n";
343 }
344
345 sub grade_join_no {
346     my (@output) = @_;
347     verify_common (@output);
348     grep (/Testing no join/, @output) or die "Test didn't start\n";
349     grep (/No join test done/, @output) or die "Test didn't complete\n";
350 }
351
352 sub grade_join_multiple {
353     my (@output) = @_;
354
355     verify_common (@output);
356     my (@t);
357     $t[4] = $t[5] = $t[6] = -1;
358     local ($_);
359     foreach (@output) {
360         my ($idx) = /^Thread (\d+)/ or next;
361         my ($iter) = /iteration (\d+)$/;
362         $iter = 5 if /done!$/;
363         die "Malformed output\n" if !defined $iter;
364         if ($idx == 6) {
365             die "Thread 6 started before either other thread finished\n"
366                 if $t[4] < 5 && $t[5] < 5;
367             die "Thread 6 started before thread 4 finished\n"
368                 if $t[4] < 5;
369             die "Thread 6 started before thread 5 finished\n"
370                 if $t[5] < 5;
371         }
372         die "Thread $idx out of order output\n" if $t[$idx] != $iter - 1;
373         $t[$idx] = $iter;
374     }
375
376     my ($err) = "";
377     for my $idx (4, 5, 6) {
378         if ($t[$idx] == -1) {
379             $err .= "Thread $idx did not run at all\n";
380         } elsif ($t[$idx] != 5) {
381             $err .= "Thread $idx only completed $t[$idx] iterations\n";
382         }
383     }
384     die $err if $err ne '';
385 }
386
387 sub grade_priority_fifo {
388     my (@output) = @_;
389
390     verify_common (@output);
391     my ($thread_cnt) = 10;
392     my ($iter_cnt) = 5;
393     my (@order);
394     my (@t) = (-1) x $thread_cnt;
395     local ($_);
396     foreach (@output) {
397         my ($idx) = /^Thread (\d+)/ or next;
398         my ($iter) = /iteration (\d+)$/;
399         $iter = $iter_cnt if /done!$/;
400         die "Malformed output\n" if !defined $iter;
401         if (@order < $thread_cnt) {
402             push (@order, $idx);
403             die "Thread $idx repeated within first $thread_cnt iterations: "
404                 . join (' ', @order) . ".\n"
405                 if grep ($_ == $idx, @order) != 1;
406         } else {
407             die "Thread $idx ran when $order[0] should have.\n"
408                 if $idx != $order[0];
409             push (@order, shift @order);
410         }
411         die "Thread $idx out of order output.\n" if $t[$idx] != $iter - 1;
412         $t[$idx] = $iter;
413     }
414
415     my ($err) = "";
416     for my $idx (0..$#t) {
417         if ($t[$idx] == -1) {
418             $err .= "Thread $idx did not run at all.\n";
419         } elsif ($t[$idx] != $iter_cnt) {
420             $err .= "Thread $idx only completed $t[$idx] iterations.\n";
421         }
422     }
423     die $err if $err ne '';
424 }
425
426 sub grade_mlfqs_on {
427     my (@output) = @_;
428     verify_common (@output);
429     our (@mlfqs_on_stats) = mlfqs_stats (@output);
430 }
431
432 sub grade_mlfqs_off {
433     my (@output) = @_;
434     verify_common (@output);
435     our (@mlfqs_off_stats) = mlfqs_stats (@output);
436 }
437
438 sub grade_mlfqs_speedup {
439     our (@mlfqs_off_stats);
440     our (@mlfqs_on_stats);
441     eval {
442         check_mlfqs ();
443         my ($off_ticks) = $mlfqs_off_stats[1];
444         my ($on_ticks) = $mlfqs_on_stats[1];
445         die "$off_ticks ticks without MLFQS, $on_ticks with MLFQS\n"
446             if $on_ticks >= $off_ticks;
447         die "ok\n";
448     };
449     chomp $@;
450     $result{'mlfqs-speedup'} = $@;
451 }
452
453 sub grade_mlfqs_priority {
454     our (@mlfqs_off_stats);
455     our (@mlfqs_on_stats);
456     eval {
457         check_mlfqs () if !defined (@mlfqs_on_stats);
458         for my $cat qw (CPU IO MIX) {
459             die "Priority changed away from PRI_DEFAULT (29) without MLFQS\n"
460                 if $mlfqs_off_stats[0]{$cat}{MIN} != 29
461                 || $mlfqs_off_stats[0]{$cat}{MAX} != 29;
462             die "Minimum priority never changed from PRI_DEFAULT (29) "
463                 . "with MLFQS\n"
464                 if $mlfqs_on_stats[0]{$cat}{MIN} == 29;
465             die "Maximum priority never changed from PRI_DEFAULT (29) "
466                 . "with MLFQS\n"
467                 if $mlfqs_on_stats[0]{$cat}{MAX} == 29;
468         }
469         die "ok\n";
470     };
471     chomp $@;
472     $result{'mlfqs-priority'} = $@;
473 }
474
475 sub check_mlfqs {
476     our (@mlfqs_off_stats);
477     our (@mlfqs_on_stats);
478     die "p1-4 didn't finish with MLFQS on or off\n"
479         if !defined (@mlfqs_off_stats) && !defined (@mlfqs_on_stats);
480     die "p1-4 didn't finish with MLFQS on\n"
481         if !defined (@mlfqs_on_stats);
482     die "p1-4 didn't finish with MLFQS off\n"
483         if !defined (@mlfqs_off_stats);
484 }
485
486 sub mlfqs_stats {
487     my (@output) = @_;
488     my (%stats) = (CPU => {}, IO => {}, MIX => {});
489     my (%map) = ("CPU intensive" => 'CPU',
490                  "IO intensive" => 'IO',
491                  "Alternating IO/CPU" => 'MIX');
492     my (%rmap) = reverse %map;
493     my ($ticks);
494     local ($_);
495     foreach (@output) {
496         $ticks = $1 if /Timer: (\d+) ticks/;
497         my ($thread, $pri) = /^([A-Za-z\/ ]+): (\d+)$/ or next;
498         my ($t) = $map{$thread} or next;
499         
500         my ($s) = $stats{$t};
501         $$s{N}++;
502         $$s{SUM} += $pri;
503         $$s{SUM2} += $pri * $pri;
504         $$s{MIN} = $pri if !defined ($$s{MIN}) || $pri < $$s{MIN};
505         $$s{MAX} = $pri if !defined ($$s{MAX}) || $pri > $$s{MAX};
506     }
507
508     my (%expect_n) = (CPU => 5000, IO => 1000, MIX => 12000);
509     for my $cat (values (%map)) {
510         my ($s) = $stats{$cat};
511         die "$rmap{$cat} printed $$s{N} times, not $expect_n{$cat}\n"
512             if $$s{N} != $expect_n{$cat};
513         die "$rmap{$cat} priority dropped to $$s{MIN}, below PRI_MIN (0)\n"
514             if $$s{MIN} < 0;
515         die "$rmap{$cat} priority rose to $$s{MAX}, above PRI_MAX (59)\n"
516             if $$s{MAX} > 59;
517         $$s{MEAN} = $$s{SUM} / $$s{N};
518     }
519
520     return (\%stats, $ticks);
521 }
522 \f
523 sub verify_common {
524     my (@output) = @_;
525
526     my (@assertion) = grep (/PANIC/, @output);
527     if (@assertion != 0) {
528         my ($details) = "Kernel panic:\n  $assertion[0]\n";
529
530         my (@stack_line) = grep (/Call stack:/, @output);
531         if (@stack_line != 0) {
532             $details .= "  $stack_line[0]\n\n";
533             $details .= "Translation of backtrace:\n";
534             my (@addrs) = $stack_line[0] =~ /Call stack:((?: 0x[0-9a-f]+)+)/;
535
536             my ($A2L);
537             if (`uname -m`
538                 =~ /i.86|pentium.*|[pk][56]|nexgen|viac3|6x86|athlon.*/) {
539                 $A2L = "addr2line";
540             } else {
541                 $A2L = "i386-elf-addr2line";
542             }
543             open (A2L, "$A2L -fe output/$test/kernel.o @addrs|");
544             for (;;) {
545                 my ($function, $line);
546                 last unless defined ($function = <A2L>);
547                 $line = <A2L>;
548                 chomp $function;
549                 chomp $line;
550                 $details .= "  $function ($line)\n";
551             }
552         }
553         $extra{$test} = $details;
554         die "Kernel panic.  Details at end of file.\n"
555     }
556
557     die "No output at all\n" if @output == 0;
558     die "Didn't start up properly: no \"Pintos booting\" startup message\n"
559         if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
560     die "Didn't start up properly: no \"Boot complete\" startup message\n"
561         if !grep (/Boot complete/, @output);
562     die "Didn't shut down properly: no \"Timer: # ticks\" shutdown message\n"
563         if !grep (/Timer: \d+ ticks/, @output);
564     die "Didn't shut down properly: no \"Powering off\" shutdown message\n"
565         if !grep (/Powering off/, @output);
566 }
567
568 sub compare_output {
569     my ($exp_file, @actual) = @_;
570     my (@expected) = snarf ($exp_file);
571
572     @actual = map ("$_\n", @actual);
573     @expected = map ("$_\n", @expected);
574
575     # Trim header and trailer from @actual.
576     while (scalar (@actual) && $actual[0] ne $expected[0]) {
577         shift (@actual);
578     }
579     die "First line of expected output was not present.\n" if !@actual;
580     while (scalar (@actual) && $actual[$#actual] ne $expected[$#expected]) {
581         pop (@actual);
582     }
583     die "Final line of expected output was not present.\n" if !@actual;
584     
585     # Check whether they're the same.
586     if ($#actual == $#expected) {
587         my ($eq) = 1;
588         for (my ($i) = 0; $i <= $#expected; $i++) {
589             $eq = 0 if $actual[$i] ne $expected[$i];
590         }
591         return if $eq;
592     }
593
594     # They differ.  Output a diff.
595     my ($diff) = "";
596     my ($d) = Algorithm::Diff->new (\@expected, \@actual);
597     $d->Base (1);
598     while ($d->Next ()) {
599         my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
600         if ($d->Same ()) {
601             if ($af != $al) {
602                 $diff .= "Actual lines $af...$al match expected lines "
603                     . "$ef...$el.\n";
604             } else {
605                 $diff .= "Actual line $af matches expected line $ef.\n";
606             }
607         } else {
608             my (@i1) = $d->Items (1);
609             my (@i2) = $d->Items (2);
610             if (!@i1) {
611                 $diff .= "Extra or misplaced line(s) $af...$al "
612                     . "in actual output:\n";
613                 $diff .= number_lines ($af, \@i2);
614             } elsif (!$d->Items (2)) {
615                 $diff .= "Expected line(s) $ef...$el missing or misplaced:\n";
616                 $diff .= number_lines ($ef, \@i1);
617             } else {
618                 $diff .= "The following expected line(s) $ef...$el:\n";
619                 $diff .= number_lines ($ef, \@i1);
620                 $diff .= "became actual line(s) $af...$al:\n";
621                 $diff .= number_lines ($af, \@i2);
622             }
623         }
624     }
625
626     my ($details) = "";
627     $details .= "$test actual output (line numbers added):\n";
628     $details .= number_lines (1, \@actual);
629     $details .= "\n$test expected output (line numbers added):\n";
630     $details .= number_lines (1, \@expected);
631     $details .= "\n$diff\n";
632     $details{$test} = $details;
633     die "Output differs from expected.  Details at end of file.\n";
634 }
635 \f
636 sub write_grades {
637     my (@summary) = snarf ("$GRADES_DIR/tests.txt");
638
639     my ($ploss) = 0;
640     my ($tloss) = 0;
641     my ($total) = 0;
642     for (my ($i) = 0; $i <= $#summary; $i++) {
643         local ($_) = $summary[$i];
644         if (my ($loss, $test) = /^  -(\d+) ([-a-zA-Z0-9]+):/) {
645             my ($result) = $result{$test} || "Not tested.";
646
647             if ($result eq 'ok') {
648                 splice (@summary, $i, 1);
649                 $i--;
650             } else {
651                 $ploss += $loss;
652                 $tloss += $loss;
653                 splice (@summary, $i + 1, 0,
654                         map ("     $_", split ("\n", $result)));
655             }
656         } elsif (my ($ptotal) = /^Score: \/(\d+)$/) {
657             $total += $ptotal;
658             $summary[$i] = "Score: " . ($ptotal - $ploss) . "/$ptotal";
659             splice (@summary, $i, 0, "  All tests passed.") if $ploss == 0;
660             $ploss = 0;
661             $i++;
662         }
663     }
664     my ($ts) = "(" . ($total - $tloss) . "/" . $total . ")";
665     $summary[0] =~ s/\[\[total\]\]/$ts/;
666
667     open (SUMMARY, ">tests.out");
668     print SUMMARY map ("$_\n", @summary);
669     close (SUMMARY);
670 }
671
672 sub write_details {
673     open (DETAILS, ">details.out");
674     my ($n) = 0;
675     for my $test (@TESTS) {
676         next if $result{$test} eq 'ok';
677         
678         my ($details) = $details{$test};
679         next if !defined ($details) && ! -e "output/$test/run.out";
680
681         print DETAILS "\n" if $n++;
682         print DETAILS "--- $test details ", '-' x (50 - length ($test));
683         print DETAILS "\n\n";
684
685         if (!defined $details) {
686             $details = "Output:\n\n" . snarf ("output/$test/run.out");
687         }
688         print DETAILS $details;
689
690         print DETAILS "\n", "-" x 10, "\n\n$extra{$test}"
691             if defined $extra{$test};
692     }
693     close (DETAILS);
694
695 }
696 \f
697 sub xsystem {
698     my ($command, %options) = @_;
699     print "$command\n" if $VERBOSE || $options{VERBOSE};
700
701     my ($log) = $options{LOG};
702     if (defined ($log)) {
703         $command = "($command) >output/$log.out 2>output/$log.err";
704     }
705
706     my ($pid, $status);
707     eval {
708         local $SIG{ALRM} = sub { die "alarm\n" };
709         alarm $options{TIMEOUT} if defined $options{TIMEOUT};
710         $pid = fork;
711         die "fork: $!\n" if !defined $pid;
712         exec ($command), die "$command: exec: $!\n" if !$pid;
713         waitpid ($pid, 0);
714         $status = $?;
715         alarm 0;
716     };
717     if ($@) {
718         die unless $@ eq "alarm\n";   # propagate unexpected errors
719         print "Timed out.\n";
720         kill SIGTERM, $pid;
721         $status = 0;
722     }
723
724     if (WIFSIGNALED ($status)) {
725         my ($signal) = WTERMSIG ($status);
726         die "Interrupted\n" if $signal == SIGINT;
727         print "Child terminated with signal $signal\n";
728     }
729
730     unlink ("output/$log.err") if defined ($log) && $status == 0;
731
732     return $status == 0;
733 }
734
735 sub snarf {
736     my ($file) = @_;
737     open (OUTPUT, $file) or die "$file: open: $!\n";
738     my (@lines) = <OUTPUT>;
739     chomp (@lines);
740     close (OUTPUT);
741     return wantarray ? @lines : join ('', map ("$_\n", @lines));
742 }
743
744 sub files_equal {
745     my ($a, $b) = @_;
746     my ($equal);
747     open (A, "<$a") or die "$a: open: $!\n";
748     open (B, "<$b") or die "$b: open: $!\n";
749     if (-s A != -s B) {
750         $equal = 0;
751     } else {
752         my ($sa, $sb);
753         for (;;) {
754             sysread (A, $sa, 1024);
755             sysread (B, $sb, 1024);
756             $equal = 0, last if $sa ne $sb;
757             $equal = 1, last if $sa eq '';
758         }
759     }
760     close (A);
761     close (B);
762     return $equal;
763 }
764
765 sub file_contains {
766     my ($file, $expected) = @_;
767     open (FILE, "<$file") or die "$file: open: $!\n";
768     my ($actual);
769     sysread (FILE, $actual, -s FILE);
770     my ($equal) = $actual eq $expected;
771     close (FILE);
772     return $equal;
773 }
774
775 sub number_lines {
776     my ($ln, $lines) = @_;
777     my ($out);
778     for my $line (@$lines) {
779         chomp $line;
780         $out .= sprintf "%4d  %s\n", $ln++, $line;
781     }
782     return $out;
783 }