Add more tests.
[pintos-anon] / grading / userprog / run-tests
1 #! /usr/bin/perl
2
3 use warnings;
4 use strict;
5 use POSIX;
6 use Algorithm::Diff;
7 use Getopt::Long;
8
9 our ($VERBOSE) = 0;     # Verbosity of output
10 our (@TESTS);           # Tests to run.
11 my ($clean) = 0;
12 my ($grade) = 0;
13
14 GetOptions ("v|verbose+" => \$VERBOSE,
15             "h|help" => sub { usage (0) },
16             "t|test=s" => \@TESTS,
17             "c|clean" => \$clean,
18             "g|grade" => \$grade)
19     or die "Malformed command line; use --help for help.\n";
20 die "Non-option argument not supported; use --help for help.\n"
21     if @ARGV > 0;
22
23 sub usage {
24     my ($exitcode) = @_;
25     print "run-tests, for grading Pintos multiprogramming projects.\n\n";
26     print "Invoke from a directory containing a student tarball named by\n";
27     print "the submit script, e.g. username.Oct.12.04.20.04.09.tar.gz.\n";
28     print "In normal usage, no options are needed.\n\n";
29     print "Output is produced in tests.out and details.out.\n\n";
30     print "Options:\n";
31     print "  -c, --clean     Remove old output files before starting\n";
32     print "  -t, --test=TEST Execute TEST only (allowed multiple times)\n";
33     print "  -g, --grade     Instead of running tests, compose grade.out\n";
34     print "  -v, --verbose   Print commands before executing them\n";
35     print "  -h, --help      Print this help message\n";
36     exit $exitcode;
37 }
38
39 # Default set of tests.
40 @TESTS = qw (args-argc args-argv0 args-argvn args-single args-multiple
41              args-dbl-space
42              sc-bad-sp sc-bad-arg sc-boundary
43              halt exit
44              create-normal create-empty create-null create-bad-ptr 
45              create-long create-exists create-bound
46              open-normal open-missing open-boundary open-empty open-null
47              open-bad-ptr open-twice
48              close-normal close-twice close-stdin close-stdout close-bad-fd
49              read-normal read-bad-ptr read-boundary read-zero read-stdout
50              read-bad-fd
51              write-normal write-bad-ptr write-boundary write-zero write-stdin
52              write-bad-fd
53              exec-once exec-arg exec-multiple exec-missing exec-bad-ptr
54              multi-recurse multi-oom
55              ) unless @TESTS > 0;
56
57 our (%args);
58 for my $key ('args-argc', 'args-argv0', 'args-argvn', 'args-multiple') {
59     $args{$key} = "some arguments for you!";
60 }
61 $args{'args-single'} = "onearg";
62 $args{'args-dbl-space'} = "two  args";
63 $args{'multi-recurse'} = "15";
64 $args{'multi-oom'} = "0";
65
66 # Handle final grade mode.
67 if ($grade) {
68     open (OUT, ">grade.out") or die "grade.out: create: $!\n";
69
70     open (GRADE, "<grade.txt") or die "grade.txt: open: $!\n";
71     while (<GRADE>) {
72         last if /^\s*$/;
73         print OUT;
74     }
75     close (GRADE);
76     
77     my (@tests) = snarf ("tests.out");
78     my ($p_got, $p_pos) = $tests[0] =~ m%\((\d+)/(\d+)\)% or die;
79
80     my (@review) = snarf ("review.txt");
81     my ($part_lost) = (0, 0);
82     for (my ($i) = $#review; $i >= 0; $i--) {
83         local ($_) = $review[$i];
84         if (my ($loss) = /^\s*([-+]\d+)/) {
85             $part_lost += $loss;
86         } elsif (my ($out_of) = m%\[\[/(\d+)\]\]%) {
87             my ($got) = $out_of + $part_lost;
88             $got = 0 if $got < 0;
89             $review[$i] =~ s%\[\[/\d+\]\]%($got/$out_of)% or die;
90             $part_lost = 0;
91
92             $p_got += $got;
93             $p_pos += $out_of;
94         }
95     }
96     die "Lost points outside a section\n" if $part_lost;
97
98     for (my ($i) = 1; $i <= $#review; $i++) {
99         if ($review[$i] =~ /^-{3,}\s*$/ && $review[$i - 1] !~ /^\s*$/) {
100             $review[$i] = '-' x (length ($review[$i - 1]));
101         }
102     }
103
104     print OUT "\nOVERALL SCORE\n";
105     print OUT "-------------\n";
106     print OUT "$p_got points out of $p_pos total\n\n";
107
108     print OUT map ("$_\n", @tests), "\n";
109     print OUT map ("$_\n", @review), "\n";
110
111     print OUT "DETAILS\n";
112     print OUT "-------\n\n";
113     print OUT map ("$_\n", snarf ("details.out"));
114
115     exit 0;
116 }
117
118 # Find the directory that contains the grading files.
119 our ($GRADES_DIR);
120 ($GRADES_DIR = $0) =~ s#/[^/]+$##;
121 -d $GRADES_DIR or die "$GRADES_DIR: stat: $!\n";
122
123 if ($clean) {
124     # Verify that we're roughly in the correct directory
125     # before we go blasting away files.
126     choose_tarball ();
127
128     xsystem ("rm -rf output pintos", VERBOSE => 1);
129     xsystem ("rm -f details.out tests.out", VERBOSE => 1);
130 }
131
132 # Create output directory, if it doesn't already exist.
133 -d ("output") || mkdir ("output") or die "output: mkdir: $!\n";
134
135 # Extract submission.
136 extract_tarball () if ! -d "pintos";
137
138 # Compile submission.
139 compile ();
140
141 # Verify that the proper directory was submitted.
142 -d "pintos/src/threads" or die "pintos/src/threads: stat: $!\n";
143
144 # Run and grade the tests.
145 our $test;
146 our %result;
147 our %details;
148 our %extra;
149 for $test (@TESTS) {
150     print "$test: ";
151     my ($result) = run_test ($test);
152     if ($result eq 'ok') {
153         $result = grade_test ($test);
154         $result =~ s/\n$//;
155     }
156     print "$result";
157     print " - with warnings" if $result eq 'ok' && defined $details{$test};
158     print "\n";
159     
160     $result{$test} = $result;
161 }
162
163 # Write output.
164 write_grades ();
165 write_details ();
166 \f
167 sub choose_tarball {
168     my (@tarballs)
169         = grep (/^[a-z0-9]+\.[A-Za-z]+\.\d+\.\d+\.\d+\.\d+.\d+\.tar\.gz$/,
170                 glob ("*.tar.gz"));
171     die "no pintos dir and no source tarball\n" if scalar (@tarballs) == 0;
172
173     # Sort tarballs in reverse order by time.
174     @tarballs = sort { ext_mdyHMS ($b) cmp ext_mdyHMS ($a) } @tarballs;
175
176     print "Multiple tarballs: choosing $tarballs[0]\n"
177         if scalar (@tarballs) > 1;
178     return $tarballs[0];
179 }
180
181 sub extract_tarball {
182     my ($tarball) = choose_tarball ();
183
184     mkdir "pintos" or die "pintos: mkdir: $!\n";
185     mkdir "pintos/src" or die "pintos: mkdir: $!\n";
186
187     print "Extracting $tarball...\n";
188     xsystem ("cd pintos/src && tar xzf ../../$tarball",
189              DIE => "extraction failed\n");
190
191     print "Patching...\n";
192     xsystem ("patch -fs pintos/src/lib/debug.c < $GRADES_DIR/panic.diff",
193              LOG => "patch",
194              DIE => "patch failed\n");
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/userprog && 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
261     # Run.
262     my ($timeout) = 10;
263     $timeout = 60 if $test eq 'multi-oom';
264     my ($testargs) = defined ($args{$test}) ? " $args{$test}" : "";
265     xsystem ("pintos "
266              . "--os-disk=pintos/src/userprog/build/os.dsk "
267              . "--fs-disk=output/$test/fs.dsk "
268              . "-v run -q -ex \"$test$testargs\"",
269              LOG => "$test/run",
270              TIMEOUT => $timeout)
271         or return "Bochs error";
272     
273     return "ok";
274 }
275
276 sub grade_test {
277     my ($test) = @_;
278
279     my (@output) = snarf ("output/$test/run.out");
280
281     my ($grade_func) = "grade_$test";
282     $grade_func =~ s/-/_/g;
283     if (-e "$GRADES_DIR/$test.exp" && !defined (&$grade_func)) {
284         eval {
285             verify_common (@output);
286             compare_output ("$GRADES_DIR/$test.exp", @output);
287         }
288     } else {
289         eval "$grade_func (\@output)";
290     }
291     if ($@) {
292         die $@ if $@ =~ /at \S+ line \d+$/;
293         return $@;
294     }
295     return "ok";
296 }
297 \f
298 sub grade_write_normal {
299     my (@output) = @_;
300     verify_common (@output);
301     compare_output ("$GRADES_DIR/write-normal.exp", @output);
302     my ($test_txt) = "output/$test/test.txt";
303     get_file ("test.txt", $test_txt) if ! -e $test_txt;
304
305     my (@actual) = snarf ($test_txt);
306     my (@expected) = snarf ("$GRADES_DIR/sample.txt");
307
308     my ($eq);
309     if ($#actual == $#expected) {
310         $eq = 1;
311         for my $i (0...$#actual) {
312             $eq = 0 if $actual[$i] ne $expected[$i];
313         }
314     } else {
315         $eq = 0;
316     }
317     if (!$eq) {
318         my ($details);
319         $details = "Expected file content:\n";
320         $details .= join ('', map ("  $_\n", @expected));
321         $details .= "Actual file content:\n";
322         $details .= join ('', map ("  $_\n", @actual));
323         $extra{$test} = $details;
324
325         die "File written didn't have expected content.\n";
326     }
327 }
328
329 sub grade_multi_oom {
330     my (@output) = @_;
331     verify_common (@output);
332
333     @output = fix_exit_codes (get_core_output (@output));
334     my ($n) = 0;
335     while (my ($m) = $output[0] =~ /^\(multi-oom\) begin (\d+)$/) {
336         die "Child process $m started out of order.\n" if $m != $n;
337         $n = $m + 1;
338         shift @output;
339     }
340     die "Only $n child processes started.\n" if $n < 15;
341     while (--$n >= 0) {
342         die "Output ended unexpectedly before process $n finished.\n"
343             if @output < 2;
344         die "Child process $n ended out of order.\n"
345             if $output[0] !~ /^\(multi-oom\) end $n$/;
346         shift @output;
347
348         die "Child process $n didn't print proper exit message.\n"
349             if $output[0] !~ /^multi-oom: exit\($n\)$/;
350         shift @output;
351     }
352     die "Spurious output at end: '$output[0]'.\n" if @output;
353 }
354
355 sub get_file {
356     my ($guest_fn, $host_fn) = @_;
357     xsystem ("pintos "
358              . "--os-disk=pintos/src/userprog/build/os.dsk "
359              . "--fs-disk=output/$test/fs.dsk "
360              . "-v get $guest_fn $host_fn",
361              LOG => "$test/get-$guest_fn",
362              TIMEOUT => 10)
363         or die "get $guest_fn failed\n";
364 }
365
366 \f
367 sub verify_common {
368     my (@output) = @_;
369
370     my (@assertion) = grep (/PANIC/, @output);
371     if (@assertion != 0) {
372         my ($details) = "Kernel panic:\n  $assertion[0]\n";
373
374         my (@stack_line) = grep (/Call stack:/, @output);
375         if (@stack_line != 0) {
376             $details .= "  $stack_line[0]\n\n";
377             $details .= "Translation of backtrace:\n";
378             my (@addrs) = $stack_line[0] =~ /Call stack:((?: 0x[0-9a-f]+)+)/;
379
380             my ($A2L);
381             if (`uname -m`
382                 =~ /i.86|pentium.*|[pk][56]|nexgen|viac3|6x86|athlon.*/) {
383                 $A2L = "addr2line";
384             } else {
385                 $A2L = "i386-elf-addr2line";
386             }
387             open (A2L, "$A2L -fe output/$test/kernel.o @addrs|");
388             for (;;) {
389                 my ($function, $line);
390                 last unless defined ($function = <A2L>);
391                 $line = <A2L>;
392                 chomp $function;
393                 chomp $line;
394                 $details .= "  $function ($line)\n";
395             }
396         }
397         $extra{$test} = $details;
398         die "Kernel panic.  Details at end of file.\n"
399     }
400
401     die "No output at all\n" if @output == 0;
402     die "Didn't start up properly: no \"Pintos booting\" startup message\n"
403         if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
404     die "Didn't start up properly: no \"Boot complete\" startup message\n"
405         if !grep (/Boot complete/, @output);
406     die "Didn't shut down properly: no \"Timer: # ticks\" shutdown message\n"
407         if !grep (/Timer: \d+ ticks/, @output);
408     die "Didn't shut down properly: no \"Powering off\" shutdown message\n"
409         if !grep (/Powering off/, @output);
410 }
411
412 # Get @output without header or trailer.
413 sub get_core_output {
414     my (@output) = @_;
415
416     our ($test);
417     my ($first);
418     for ($first = 0; $first <= $#output; $first++) {
419         $first++, last if $output[$first] =~ /^Executing '$test.*':$/;
420     }
421
422     my ($last);
423     for ($last = $#output; $last >= 0; $last--) {
424         $last--, last if $output[$last] =~ /^Timer: \d+ ticks$/;
425     }
426
427     if ($last < $first) {
428         my ($no_first) = $first > $#output;
429         my ($no_last) = $last < $#output;
430         die "Couldn't locate output.\n";
431     }
432
433     return @output[$first ... $last];
434 }
435
436 sub fix_exit_codes {
437     my (@output) = @_;
438
439     # Fix up lines that look like exit codes.
440     for my $i (0...$#output) {
441         if (my ($process, $code)
442             = $output[$i] =~ /^([-a-zA-Z0-9 ]+):.*[ \(](-?\d+)\b\)?$/) {
443             $process = substr ($process, 0, 15);
444             $process =~ s/\s.*//;
445             $output[$i] = "$process: exit($code)\n";
446         }
447     }
448
449     return @output;
450 }
451
452 sub compare_output {
453     my ($exp, @actual) = @_;
454     @actual = fix_exit_codes (get_core_output (map ("$_\n", @actual)));
455
456     my ($details) = "";
457     $details .= "$test actual output:\n";
458     $details .= join ('', map ("  $_", @actual));
459
460     my (@exp) = map ("$_\n", snarf ($exp));
461
462     my ($fuzzy_match) = 0;
463     while (@exp != 0) {
464         my (@expected);
465         while (@exp != 0) {
466             my ($s) = shift (@exp);
467             last if $s eq "--OR--\n";
468             push (@expected, $s);
469         }
470
471         $details .= "\n$test acceptable output:\n";
472         $details .= join ('', map ("  $_", @expected));
473
474         # Check whether they're the same.
475         if ($#actual == $#expected) {
476             my ($eq) = 1;
477             for (my ($i) = 0; $i <= $#expected; $i++) {
478                 $eq = 0 if $actual[$i] ne $expected[$i];
479             }
480             return if $eq;
481         }
482
483         # They differ.  Output a diff.
484         my (@diff) = "";
485         my ($d) = Algorithm::Diff->new (\@expected, \@actual);
486         my ($not_fuzzy_match) = 0;
487         while ($d->Next ()) {
488             my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
489             if ($d->Same ()) {
490                 push (@diff, map ("  $_", $d->Items (1)));
491             } else {
492                 push (@diff, map ("- $_", $d->Items (1))) if $d->Items (1);
493                 push (@diff, map ("+ $_", $d->Items (2))) if $d->Items (2);
494                 if ($d->Items (1)
495                     || grep (/\($test\)|exit\(-?\d+\)/, $d->Items (2))) {
496                     $not_fuzzy_match = 1;
497                 }
498             }
499         }
500         $fuzzy_match = 1 if !$not_fuzzy_match;
501
502         $details .= "Differences in `diff -u' format:\n";
503         $details .= join ('', @diff);
504         $details .= "(This is considered a `fuzzy match'.)\n" if $fuzzy_match;
505     }
506
507     $details{$test} = $details;
508     die "Output differs from expected.  Details at end of file.\n"
509         unless $fuzzy_match;
510 }
511 \f
512 sub write_grades {
513     my (@summary) = snarf ("$GRADES_DIR/tests.txt");
514
515     my ($ploss) = 0;
516     my ($tloss) = 0;
517     my ($total) = 0;
518     for (my ($i) = 0; $i <= $#summary; $i++) {
519         local ($_) = $summary[$i];
520         if (my ($loss, $test) = /^  -(\d+) ([-a-zA-Z0-9]+):/) {
521             my ($result) = $result{$test} || "Not tested.";
522
523             if ($result eq 'ok') {
524                 splice (@summary, $i, 1);
525                 $i--;
526             } else {
527                 $ploss += $loss;
528                 $tloss += $loss;
529                 splice (@summary, $i + 1, 0,
530                         map ("     $_", split ("\n", $result)));
531             }
532         } elsif (my ($ptotal) = /^Score: \/(\d+)$/) {
533             $total += $ptotal;
534             $summary[$i] = "Score: " . ($ptotal - $ploss) . "/$ptotal";
535             splice (@summary, $i, 0, "  All tests passed.") if $ploss == 0;
536             $ploss = 0;
537             $i++;
538         }
539     }
540     my ($ts) = "(" . ($total - $tloss) . "/" . $total . ")";
541     $summary[0] =~ s/\[\[total\]\]/$ts/;
542
543     open (SUMMARY, ">tests.out");
544     print SUMMARY map ("$_\n", @summary);
545     close (SUMMARY);
546 }
547
548 sub write_details {
549     open (DETAILS, ">details.out");
550     my ($n) = 0;
551     for my $test (@TESTS) {
552         next if $result{$test} eq 'ok' && !defined $details{$test};
553         
554         my ($details) = $details{$test};
555         next if !defined ($details) && ! -e "output/$test/run.out";
556
557         print DETAILS "\n" if $n++;
558         print DETAILS "--- $test details ", '-' x (50 - length ($test));
559         print DETAILS "\n\n";
560
561         if (!defined $details) {
562             $details = "Output:\n\n" . snarf ("output/$test/run.out");
563         }
564         print DETAILS $details;
565
566         print DETAILS "\n", "-" x 10, "\n\n$extra{$test}"
567             if defined $extra{$test};
568     }
569     close (DETAILS);
570
571 }
572 \f
573 sub xsystem {
574     my ($command, %options) = @_;
575     print "$command\n" if $VERBOSE || $options{VERBOSE};
576
577     my ($log) = $options{LOG};
578     if (defined ($log)) {
579         $command = "($command) >output/$log.out 2>output/$log.err";
580     }
581
582     my ($pid, $status);
583     eval {
584         local $SIG{ALRM} = sub { die "alarm\n" };
585         alarm $options{TIMEOUT} if defined $options{TIMEOUT};
586         $pid = fork;
587         die "fork: $!\n" if !defined $pid;
588         exec ($command), die "$command: exec: $!\n" if !$pid;
589         waitpid ($pid, 0);
590         $status = $?;
591         alarm 0;
592     };
593     if ($@) {
594         die unless $@ eq "alarm\n";   # propagate unexpected errors
595         print "Timed out.\n";
596         kill SIGTERM, $pid;
597         $status = 0;
598     }
599
600     if (WIFSIGNALED ($status)) {
601         my ($signal) = WTERMSIG ($status);
602         die "Interrupted\n" if $signal == SIGINT;
603         print "Child terminated with signal $signal\n";
604     }
605
606     unlink ("output/$log.err") if defined ($log) && $status == 0;
607
608     die $options{DIE} if $status != 0 && defined $options{DIE};
609
610     return $status == 0;
611 }
612
613 sub snarf {
614     my ($file) = @_;
615     open (OUTPUT, $file) or die "$file: open: $!\n";
616     my (@lines) = <OUTPUT>;
617     chomp (@lines);
618     close (OUTPUT);
619     return wantarray ? @lines : join ('', map ("$_\n", @lines));
620 }
621
622 sub files_equal {
623     my ($a, $b) = @_;
624     my ($equal);
625     open (A, "<$a") or die "$a: open: $!\n";
626     open (B, "<$b") or die "$b: open: $!\n";
627     if (-s A != -s B) {
628         $equal = 0;
629     } else {
630         my ($sa, $sb);
631         for (;;) {
632             sysread (A, $sa, 1024);
633             sysread (B, $sb, 1024);
634             $equal = 0, last if $sa ne $sb;
635             $equal = 1, last if $sa eq '';
636         }
637     }
638     close (A);
639     close (B);
640     return $equal;
641 }
642
643 sub file_contains {
644     my ($file, $expected) = @_;
645     open (FILE, "<$file") or die "$file: open: $!\n";
646     my ($actual);
647     sysread (FILE, $actual, -s FILE);
648     my ($equal) = $actual eq $expected;
649     close (FILE);
650     return $equal;
651 }
652
653 sub number_lines {
654     my ($ln, $lines) = @_;
655     my ($out);
656     for my $line (@$lines) {
657         chomp $line;
658         $out .= sprintf "%4d  %s\n", $ln++, $line;
659     }
660     return $out;
661 }