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