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