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