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