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