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