42e198b02f8a3dd2da5213f0f30291b4a78c09f5
[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         or return "Bochs error";
270     
271     return "ok";
272 }
273
274 sub grade_test {
275     my ($test) = @_;
276
277     my (@output) = snarf ("output/$test/run.out");
278
279     my ($grade_func) = "grade_$test";
280     $grade_func =~ s/-/_/g;
281     if (-e "$GRADES_DIR/$test.exp" && !defined (&$grade_func)) {
282         eval {
283             verify_common (@output);
284             compare_output ("$GRADES_DIR/$test.exp", @output);
285         }
286     } else {
287         eval "$grade_func (\@output)";
288     }
289     if ($@) {
290         die $@ if $@ =~ /at \S+ line \d+$/;
291         return $@;
292     }
293     return "ok";
294 }
295 \f
296 sub grade_write_normal {
297     my (@output) = @_;
298     verify_common (@output);
299     compare_output ("$GRADES_DIR/write-normal.exp", @output);
300     my ($test_txt) = "output/$test/test.txt";
301     get_file ("test.txt", $test_txt) if ! -e $test_txt;
302
303     my (@actual) = snarf ($test_txt);
304     my (@expected) = snarf ("$GRADES_DIR/sample.txt");
305
306     my ($eq);
307     if ($#actual == $#expected) {
308         $eq = 1;
309         for my $i (0...$#actual) {
310             $eq = 0 if $actual[$i] ne $expected[$i];
311         }
312     } else {
313         $eq = 0;
314     }
315     if (!$eq) {
316         my ($details);
317         $details = "Expected file content:\n";
318         $details .= join ('', map ("  $_\n", @expected));
319         $details .= "Actual file content:\n";
320         $details .= join ('', map ("  $_\n", @actual));
321         $extra{$test} = $details;
322
323         die "File written didn't have expected content.\n";
324     }
325 }
326
327 sub grade_multi_oom {
328     my (@output) = @_;
329     verify_common (@output);
330
331     @output = fix_exit_codes (get_core_output (@output));
332     my ($n) = 0;
333     while (my ($m) = $output[0] =~ /^\(multi-oom\) begin (\d+)$/) {
334         die "Child process $m started out of order.\n" if $m != $n;
335         $n = $m + 1;
336         shift @output;
337     }
338     die "Only $n child process(es) started.\n" if $n < 15;
339
340     # There could be a death notice for a process that didn't get
341     # fully loaded, and/or notices from the loader.
342     while (@output > 0
343            && ($output[0] =~ /^multi-oom: exit\(-1\)$/
344                || $output[0] =~ /^load: /)) {
345         shift @output;
346     }
347
348     while (--$n >= 0) {
349         die "Output ended unexpectedly before process $n finished.\n"
350             if @output < 2;
351
352         local ($_);
353         chomp ($_ = shift @output);
354         die "Found '$_' expecting 'end' message.\n" if !/^\(multi-oom\) end/;
355         die "Child process $n ended out of order.\n"
356             if !/^\(multi-oom\) end $n$/;
357
358         chomp ($_ = shift @output);
359         die "Kernel didn't print proper exit message for process $n.\n"
360             if !/^multi-oom: exit\($n\)$/;
361     }
362     die "Spurious output at end: '$output[0]'.\n" if @output;
363 }
364
365 sub get_file {
366     my ($guest_fn, $host_fn) = @_;
367     xsystem ("pintos "
368              . "--os-disk=pintos/src/vm/build/os.dsk "
369              . "--fs-disk=output/$test/fs.dsk "
370              . "-v get $guest_fn $host_fn",
371              LOG => "$test/get-$guest_fn",
372              TIMEOUT => 10)
373         or die "get $guest_fn failed\n";
374 }
375
376 \f
377 sub verify_common {
378     my (@output) = @_;
379
380     my (@assertion) = grep (/PANIC/, @output);
381     if (@assertion != 0) {
382         my ($details) = "Kernel panic:\n  $assertion[0]\n";
383
384         my (@stack_line) = grep (/Call stack:/, @output);
385         if (@stack_line != 0) {
386             $details .= "  $stack_line[0]\n\n";
387             $details .= "Translation of backtrace:\n";
388             my (@addrs) = $stack_line[0] =~ /Call stack:((?: 0x[0-9a-f]+)+)/;
389
390             my ($A2L);
391             if (`uname -m`
392                 =~ /i.86|pentium.*|[pk][56]|nexgen|viac3|6x86|athlon.*/) {
393                 $A2L = "addr2line";
394             } else {
395                 $A2L = "i386-elf-addr2line";
396             }
397             open (A2L, "$A2L -fe pintos/src/vm/build/kernel.o @addrs|");
398             for (;;) {
399                 my ($function, $line);
400                 last unless defined ($function = <A2L>);
401                 $line = <A2L>;
402                 chomp $function;
403                 chomp $line;
404                 $details .= "  $function ($line)\n";
405             }
406         }
407
408         if ($assertion[0] =~ /sec_no < d->capacity/) {
409             $details .= <<EOF;
410 \nThis assertion commonly fails when accessing a file via
411 an inode that has been closed and freed.  Freeing an inode
412 clears all its sector indexes to 0xcccccccc, which is not
413 a valid sector number for disks smaller than about 1.6 TB.
414 EOF
415         }
416
417         $extra{$test} = $details;
418         die "Kernel panic.  Details at end of file.\n"
419     }
420
421     if (grep (/Pintos booting/, @output) > 1) {
422         my ($details);
423
424         $details = "Pintos spontaneously rebooted during this test.\n";
425         $details .= "This is most often due to unhandled page faults.\n";
426         $details .= "Here's the output from the initial boot through the\n";
427         $details .= "first reboot:\n\n";
428
429         my ($i) = 0;
430         local ($_);
431         for (@output) {
432             $details .= "  $_\n";
433             last if /Pintos booting/ && ++$i > 1;
434         }
435         $details{$test} = $details;
436         die "Triple-fault caused spontaneous reboot(s).  "
437             . "Details at end of file.\n";
438     }
439
440     die "No output at all\n" if @output == 0;
441     die "Didn't start up properly: no \"Pintos booting\" startup message\n"
442         if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
443     die "Didn't start up properly: no \"Boot complete\" startup message\n"
444         if !grep (/Boot complete/, @output);
445     die "Didn't shut down properly: no \"Timer: # ticks\" shutdown message\n"
446         if !grep (/Timer: \d+ ticks/, @output);
447     die "Didn't shut down properly: no \"Powering off\" shutdown message\n"
448         if !grep (/Powering off/, @output);
449 }
450
451 # Get @output without header or trailer.
452 sub get_core_output {
453     my (@output) = @_;
454
455     our ($test);
456     my ($first);
457     for ($first = 0; $first <= $#output; $first++) {
458         $first++, last if $output[$first] =~ /^Executing '$test.*':$/;
459     }
460
461     my ($last);
462     for ($last = $#output; $last >= 0; $last--) {
463         $last--, last if $output[$last] =~ /^Timer: \d+ ticks$/;
464     }
465
466     if ($last < $first) {
467         my ($no_first) = $first > $#output;
468         my ($no_last) = $last < $#output;
469         die "Couldn't locate output.\n";
470     }
471
472     return @output[$first ... $last];
473 }
474
475 sub fix_exit_codes {
476     my (@output) = @_;
477
478     # Remove lines that look like exit codes.
479     # Exit codes are supposed to be printed in the form "process: exit(code)"
480     # but people get unfortunately creative with it.
481     for (my ($i) = 0; $i <= $#output; $i++) {
482         local ($_) = $output[$i];
483         
484         my ($process, $code);
485         if ((($process, $code) = /^([-a-z0-9 ]+):.*[ \(](-?\d+)\b\)?$/)
486             || (($process, $code) = /^([-a-z0-9 ]+) exit\((-?\d+)\)$/)
487             || (($process, $code)
488                 = /^([-a-z0-9 ]+) \(.*\): exit\((-?\d+)\)$/)
489             || (($process, $code) = /^([-a-z0-9 ]+):\( (-?\d+) \) $/)
490             || (($code, $process) = /^shell: exit\((-?\d+)\) \| ([-a-z0-9]+)/)
491             ) {
492             splice (@output, $i, 1);
493             $i--;
494         }
495     }
496
497     return @output;
498 }
499
500 sub compare_output {
501     my ($exp, @actual) = @_;
502     @actual = fix_exit_codes (get_core_output (map ("$_\n", @actual)));
503     die "Program produced no output.\n" if !@actual;
504
505     my ($details) = "";
506     $details .= "$test actual output:\n";
507     $details .= join ('', map ("  $_", @actual));
508
509     my (@exp) = map ("$_\n", snarf ($exp));
510
511     my ($fuzzy_match) = 0;
512     while (@exp != 0) {
513         my (@expected);
514         while (@exp != 0) {
515             my ($s) = shift (@exp);
516             last if $s eq "--OR--\n";
517             push (@expected, $s);
518         }
519
520         $details .= "\n$test acceptable output:\n";
521         $details .= join ('', map ("  $_", @expected));
522
523         # Check whether they're the same.
524         if ($#actual == $#expected) {
525             my ($eq) = 1;
526             for (my ($i) = 0; $i <= $#expected; $i++) {
527                 $eq = 0 if $actual[$i] ne $expected[$i];
528             }
529             return if $eq;
530         }
531
532         # They differ.  Output a diff.
533         my (@diff) = "";
534         my ($d) = Algorithm::Diff->new (\@expected, \@actual);
535         my ($not_fuzzy_match) = 0;
536         while ($d->Next ()) {
537             my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
538             if ($d->Same ()) {
539                 push (@diff, map ("  $_", $d->Items (1)));
540             } else {
541                 push (@diff, map ("- $_", $d->Items (1))) if $d->Items (1);
542                 push (@diff, map ("+ $_", $d->Items (2))) if $d->Items (2);
543                 if ($d->Items (1)
544                     || grep (/\($test\)|exit\(-?\d+\)|dying due to|Page fault/,
545                              $d->Items (2))) {
546                     $not_fuzzy_match = 1;
547                 }
548             }
549         }
550         $fuzzy_match = 1 if !$not_fuzzy_match;
551
552         $details .= "Differences in `diff -u' format:\n";
553         $details .= join ('', @diff);
554         $details .= "(This is considered a `fuzzy match'.)\n"
555             if !$not_fuzzy_match;
556     }
557
558     if ($fuzzy_match) {
559         $details =
560             "This test passed, but with extra, unexpected output.\n"
561             . "Please inspect your code to make sure that it does not\n"
562             . "produce output other than as specified in the project\n"
563             . "description.\n\n"
564             . "$details";
565     } else {
566         $details =
567             "This test failed because its output did not match any\n"
568             . "of the acceptable form(s).\n\n"
569             . "$details";
570     }
571
572     $details{$test} = $details;
573     die "Output differs from expected.  Details at end of file.\n"
574         unless $fuzzy_match;
575 }
576 \f
577 sub write_grades {
578     my (@summary) = snarf ("$GRADES_DIR/tests.txt");
579
580     my ($ploss) = 0;
581     my ($tloss) = 0;
582     my ($total) = 0;
583     my ($warnings) = 0;
584     for (my ($i) = 0; $i <= $#summary; $i++) {
585         local ($_) = $summary[$i];
586         if (my ($loss, $test) = /^  -(\d+) ([-a-zA-Z0-9]+):/) {
587             my ($result) = $result{$test} || "Not tested.";
588
589             if ($result eq 'ok') {
590                 if (!defined $details{$test}) {
591                     # Test successful and no warnings.
592                     splice (@summary, $i, 1);
593                     $i--;
594                 } else {
595                     # Test successful with warnings.
596                     s/-(\d+) //;
597                     $summary[$i] = $_;
598                     splice (@summary, $i + 1, 0,
599                             "     Test passed with warnings.  "
600                             . "Details at end of file.");
601                     $warnings++;
602                 } 
603             } else {
604                 $ploss += $loss;
605                 $tloss += $loss;
606                 splice (@summary, $i + 1, 0,
607                         map ("     $_", split ("\n", $result)));
608             }
609         } elsif (my ($ptotal) = /^Score: \/(\d+)$/) {
610             $total += $ptotal;
611             $summary[$i] = "Score: " . ($ptotal - $ploss) . "/$ptotal";
612             splice (@summary, $i, 0, "  All tests passed.")
613                 if $ploss == 0 && !$warnings;
614             $ploss = 0;
615             $warnings = 0;
616             $i++;
617         }
618     }
619     my ($ts) = "(" . ($total - $tloss) . "/" . $total . ")";
620     $summary[0] =~ s/\[\[total\]\]/$ts/;
621
622     open (SUMMARY, ">tests.out");
623     print SUMMARY map ("$_\n", @summary);
624     close (SUMMARY);
625 }
626
627 sub write_details {
628     open (DETAILS, ">details.out");
629     my ($n) = 0;
630     for my $test (@TESTS) {
631         next if $result{$test} eq 'ok' && !defined $details{$test};
632         
633         my ($details) = $details{$test};
634         next if !defined ($details) && ! -e "output/$test/run.out";
635
636         my ($banner);
637         if ($result{$test} ne 'ok') {
638             $banner = "$test failure details"; 
639         } else {
640             $banner = "$test warnings";
641         }
642
643         print DETAILS "\n" if $n++;
644         print DETAILS "--- $banner ", '-' x (50 - length ($banner));
645         print DETAILS "\n\n";
646
647         if (!defined $details) {
648             my (@output) = snarf ("output/$test/run.out");
649
650             # Print only the first in a series of recursing panics.
651             my ($panic) = 0;
652             for my $i (0...$#output) {
653                 local ($_) = $output[$i];
654                 if (/PANIC/ && $panic++ > 0) {
655                     @output = @output[0...$i];
656                     push (@output,
657                           "[...details of recursive panic omitted...]");
658                     last;
659                 }
660             }
661             $details = "Output:\n\n" . join ('', map ("$_\n", @output));
662         }
663         print DETAILS $details;
664
665         print DETAILS "\n", "-" x 10, "\n\n$extra{$test}"
666             if defined $extra{$test};
667     }
668     close (DETAILS);
669
670 }
671 \f
672 sub xsystem {
673     my ($command, %options) = @_;
674     print "$command\n" if $VERBOSE || $options{VERBOSE};
675
676     my ($log) = $options{LOG};
677
678     my ($pid, $status);
679     eval {
680         local $SIG{ALRM} = sub { die "alarm\n" };
681         alarm $options{TIMEOUT} if defined $options{TIMEOUT};
682         $pid = fork;
683         die "fork: $!\n" if !defined $pid;
684         if (!$pid) {
685             if (defined $log) {
686                 close STDOUT;
687                 open (STDOUT, ">output/$log.out");
688                 close STDERR;
689                 open (STDERR, ">output/$log.err");
690             }
691             exec ($command);
692             exit (-1);
693         }
694         waitpid ($pid, 0);
695         $status = $?;
696         alarm 0;
697     };
698     if ($@) {
699         die unless $@ eq "alarm\n";   # propagate unexpected errors
700         print "Timed out $pid.\n";
701         print "not killed\n" if !kill ('SIGTERM', $pid);
702         $status = 0;
703     }
704
705     if (WIFSIGNALED ($status)) {
706         my ($signal) = WTERMSIG ($status);
707         die "Interrupted\n" if $signal == SIGINT;
708         print "Child terminated with signal $signal\n";
709     }
710
711     unlink ("output/$log.err") if defined ($log) && $status == 0;
712
713     die $options{DIE} if $status != 0 && defined $options{DIE};
714
715     return $status == 0;
716 }
717
718 sub snarf {
719     my ($file) = @_;
720     open (OUTPUT, $file) or die "$file: open: $!\n";
721     my (@lines) = <OUTPUT>;
722     chomp (@lines);
723     close (OUTPUT);
724     return wantarray ? @lines : join ('', map ("$_\n", @lines));
725 }
726
727 sub files_equal {
728     my ($a, $b) = @_;
729     my ($equal);
730     open (A, "<$a") or die "$a: open: $!\n";
731     open (B, "<$b") or die "$b: open: $!\n";
732     if (-s A != -s B) {
733         $equal = 0;
734     } else {
735         my ($sa, $sb);
736         for (;;) {
737             sysread (A, $sa, 1024);
738             sysread (B, $sb, 1024);
739             $equal = 0, last if $sa ne $sb;
740             $equal = 1, last if $sa eq '';
741         }
742     }
743     close (A);
744     close (B);
745     return $equal;
746 }
747
748 sub file_contains {
749     my ($file, $expected) = @_;
750     open (FILE, "<$file") or die "$file: open: $!\n";
751     my ($actual);
752     sysread (FILE, $actual, -s FILE);
753     my ($equal) = $actual eq $expected;
754     close (FILE);
755     return $equal;
756 }
757
758 sub number_lines {
759     my ($ln, $lines) = @_;
760     my ($out);
761     for my $line (@$lines) {
762         chomp $line;
763         $out .= sprintf "%4d  %s\n", $ln++, $line;
764     }
765     return $out;
766 }