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