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