Improve.
[pintos-anon] / grading / threads / 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
13 GetOptions ("v|verbose+" => \$VERBOSE,
14             "h|help" => sub { usage (0) },
15             "t|test=s" => \@TESTS,
16             "c|clean" => \$clean)
17     or die "Malformed command line; use --help for help.\n";
18 die "Non-option argument not supported; use --help for help.\n"
19     if @ARGV > 0;
20
21 sub usage {
22     my ($exitcode) = @_;
23     print "run-tests, for grading Pintos thread projects.\n\n";
24     print "Invoke from a directory containing a student tarball named by\n";
25     print "the submit script, e.g. username.Oct.12.04.20.04.09.tar.gz.\n";
26     print "In normal usage, no options are needed.\n\n";
27     print "Output is produced in tests.out and details.out.\n\n";
28     print "Options:\n";
29     print "  -c, --clean     Remove old output files before starting\n";
30     print "  -t, --test=TEST Execute TEST only (allowed multiple times)\n";
31     print "  -v, --verbose   Print commands before executing them\n";
32     print "  -h, --help      Print this help message\n";
33     exit $exitcode;
34 }
35
36 # Default set of tests.
37 @TESTS = ("alarm-single", "alarm-multiple", "alarm-zero", "alarm-negative",
38           "join-simple",
39           "join-quick", "join-multiple", "join-nested",
40           "join-dummy", "join-invalid", "join-no",
41           "priority-preempt", "priority-fifo", "priority-donate-one",
42           "priority-donate-multiple", "priority-donate-nest",
43           "mlfqs-on", "mlfqs-off")
44     unless @TESTS > 0;
45
46 # Find the directory that contains the grading files.
47 our ($GRADES_DIR);
48 ($GRADES_DIR = $0) =~ s#/[^/]+$##;
49 -d $GRADES_DIR or die "$GRADES_DIR: stat: $!\n";
50
51 if ($clean) {
52     # Verify that we're roughly in the correct directory
53     # before we go blasting away files.
54     choose_tarball ();
55
56     xsystem ("rm -rf output pintos", VERBOSE => 1);
57     xsystem ("rm -f details.out tests.out", VERBOSE => 1);
58 }
59
60 # Create output directory, if it doesn't already exist.
61 -d ("output") || mkdir ("output") or die "output: mkdir: $!\n";
62
63 # Extract submission.
64 extract_tarball () if ! -d "pintos";
65
66 # Verify that the proper directory was submitted.
67 -d "pintos/src/threads" or die "pintos/src/threads: stat: $!\n";
68
69 # Run and grade the tests.
70 our $test;
71 our %result;
72 our %details;
73 our %extra;
74 for $test (@TESTS) {
75     print "$test: ";
76     my ($result) = run_test ($test);
77     if ($result eq 'ok') {
78         $result = grade_test ($test);
79         $result =~ s/\n$//;
80     }
81     print "$result\n";
82     
83     $result{$test} = $result;
84 }
85
86 # Write output.
87 write_grades ();
88 write_details ();
89 \f
90 sub choose_tarball {
91     my (@tarballs)
92         = grep (/^[a-z0-9]+\.[A-Za-z]+\.\d+\.\d+\.\d+\.\d+.\d+\.tar\.gz$/,
93                 glob ("*.tar.gz"));
94     die "no pintos dir and no source tarball\n" if scalar (@tarballs) == 0;
95
96     # Sort tarballs in reverse order by time.
97     @tarballs = sort { ext_mdyHMS ($b) cmp ext_mdyHMS ($a) } @tarballs;
98
99     print "Multiple tarballs: choosing $tarballs[0]\n"
100         if scalar (@tarballs) > 1;
101     return $tarballs[0];
102 }
103
104 sub extract_tarball {
105     my ($tarball) = choose_tarball ();
106
107     mkdir "pintos" or die "pintos: mkdir: $!\n";
108     mkdir "pintos/src" or die "pintos: mkdir: $!\n";
109
110     print "Extracting $tarball...\n";
111     xsystem ("cd pintos/src && tar xzf ../../$tarball",
112              DIE => "extraction failed\n");
113
114     print "Patching...\n";
115     xsystem ("patch -fs pintos/src/lib/debug.c < $GRADES_DIR/panic.diff",
116              LOG => "patch",
117              DIE => "patch failed\n");
118 }
119
120 sub ext_mdyHMS {
121     my ($s) = @_;
122     my ($ms, $d, $y, $H, $M, $S) =
123         $s =~ /.([A-Za-z]+)\.(\d+)\.(\d+)\.(\d+)\.(\d+).(\d+)\.tar\.gz$/
124         or die;
125     my ($m) = index ("janfebmaraprmayjunjulaugsepoctnovdec", lc $ms) / 3
126         or die;
127     return sprintf "%02d-%02d-%02d %02d:%02d:%02d", $y, $m, $d, $H, $M, $S;
128 }
129 \f
130 sub test_source {
131     my ($test) = @_;
132     my ($src) = "$GRADES_DIR/$test.c";
133     $src = "$GRADES_DIR/mlfqs.c" if $test =~ /^mlfqs/;
134     -e $src or die "$src: stat: $!\n";
135     return $src;
136 }
137
138 sub test_constants {
139    my ($defines) = "";
140    $defines .= "#define MLFQS 1\n" if $test eq 'mlfqs-on';
141    return $defines;
142  }
143
144 sub run_test {
145     my ($test) = @_;
146     return "ok" if -f "output/$test/done";
147
148     # Reuse older results if any.
149     if (open (DONE, "<output/$test/done")) {
150         my ($status);
151         $status = <DONE>;
152         chomp $status;
153         close (DONE);
154         return $status;
155     }
156
157     # Really run the test.
158     my ($status) = really_run_test ($test);
159
160     # Save the results for later.
161     open (DONE, ">output/$test/done") or die "output/$test/done: create: $!\n";
162     print DONE "$status\n";
163     close (DONE);
164
165     return $status;
166 }
167
168 sub really_run_test {
169     # Need to run it.
170     # If there's residue from an earlier test, move it to .old.
171     # If there's already a .old, delete it.
172     xsystem ("rm -rf output/$test.old", VERBOSE => 1) if -d "output/$test.old";
173     rename "output/$test", "output/$test.old" or die "rename: $!\n"
174         if -d "output/$test";
175
176     # Make output directory.
177     mkdir "output/$test";
178
179     # Change constants.h if necessary.
180     my ($defines) = test_constants ($test);
181     if ($defines ne snarf ("pintos/src/constants.h")) {
182         open (CONSTANTS, ">pintos/src/constants.h");
183         print CONSTANTS $defines;
184         close (CONSTANTS);
185     }
186
187     # Copy in the new test.c and delete enough files to ensure a full rebuild.
188     my ($src) = test_source ($test);
189     xsystem ("cp $src pintos/src/threads/test.c", DIE => "cp failed\n");
190     unlink ("pintos/src/threads/build/threads/test.o");
191     unlink ("pintos/src/threads/build/kernel.o");
192     unlink ("pintos/src/threads/build/kernel.bin");
193     unlink ("pintos/src/threads/build/os.dsk");
194
195     # Build.
196     xsystem ("cd pintos/src/threads && make", LOG => "$test/make")
197         or return "compile error";
198
199     # Copy out files for backtraces later.
200     xsystem ("cp pintos/src/threads/build/kernel.o output/$test");
201     xsystem ("cp pintos/src/threads/build/os.dsk output/$test");
202
203     # Run.
204     my ($timeout) = 10;
205     $timeout = 600 if $test =~ /^mlfqs/;
206     xsystem ("cd pintos/src/threads/build && pintos -v run -q",
207              LOG => "$test/run",
208              TIMEOUT => $timeout)
209         or return "Bochs error";
210     
211     return "ok";
212 }
213
214 sub grade_test {
215     my ($test) = @_;
216
217     my (@output) = snarf ("output/$test/run.out");
218
219     if (-e "$GRADES_DIR/$test.exp") {
220         eval {
221             verify_common (@output);
222             compare_output ("$GRADES_DIR/$test.exp", @output);
223         }
224     } else {
225         my ($grade_func);
226         ($grade_func = $test) =~ s/-/_/g;
227         eval "grade_$grade_func (\@output)";
228     }
229     if ($@) {
230         die $@ if $@ =~ /at \S+ line \d+$/;
231         return $@;
232     }
233     return "ok";
234 }
235 \f
236 sub grade_alarm_single {
237     verify_alarm (1, @_);
238 }
239
240 sub grade_alarm_multiple {
241     verify_alarm (7, @_);
242 }
243
244 sub verify_alarm {
245     my ($iterations, @output) = @_;
246
247     verify_common (@output);
248
249     my (@products);
250     for (my ($i) = 0; $i < $iterations; $i++) {
251         for (my ($t) = 0; $t < 5; $t++) {
252             push (@products, ($i + 1) * ($t + 1) * 10);
253         }
254     }
255     @products = sort {$a <=> $b} @products;
256
257     local ($_);
258     foreach (@output) {
259         die $_ if /Out of order/;
260
261         my ($p) = /product=(\d+)$/;
262         next if !defined $p;
263
264         my ($q) = shift (@products);
265         die "Too many wakeups.\n" if !defined $q;
266         die "Out of order wakeups ($p vs. $q).\n" if $p != $q; # FIXME
267     }
268     die scalar (@products) . " fewer wakeups than expected.\n"
269         if @products != 0;
270 }
271
272 sub grade_alarm_zero {
273     my (@output) = @_;
274     verify_common (@output);
275     die "Crashed in timer_sleep()\n" if !grep (/^Success\.$/, @output);
276 }
277
278 sub grade_alarm_negative {
279     my (@output) = @_;
280     verify_common (@output);
281     die "Crashed in timer_sleep()\n" if !grep (/^Success\.$/, @output);
282 }
283
284 sub grade_join_invalid {
285     my (@output) = @_;
286     verify_common (@output);
287     grep (/Testing invalid join/, @output) or die "Test didn't start\n";
288     grep (/Invalid join test done/, @output) or die "Test didn't complete\n";
289 }
290
291 sub grade_join_no {
292     my (@output) = @_;
293     verify_common (@output);
294     grep (/Testing no join/, @output) or die "Test didn't start\n";
295     grep (/No join test done/, @output) or die "Test didn't complete\n";
296 }
297
298 sub grade_join_multiple {
299     my (@output) = @_;
300
301     verify_common (@output);
302     my (@t);
303     $t[4] = $t[5] = $t[6] = -1;
304     local ($_);
305     foreach (@output) {
306         my ($idx) = /^Thread (\d+)/ or next;
307         my ($iter) = /iteration (\d+)$/;
308         $iter = 5 if /done!$/;
309         die "Malformed output\n" if !defined $iter;
310         if ($idx == 6) {
311             die "Thread 6 started before either other thread finished\n"
312                 if $t[4] < 5 && $t[5] < 5;
313             die "Thread 6 started before thread 4 finished\n"
314                 if $t[4] < 5;
315             die "Thread 6 started before thread 5 finished\n"
316                 if $t[5] < 5;
317         }
318         die "Thread $idx out of order output\n" if $t[$idx] != $iter - 1;
319         $t[$idx] = $iter;
320     }
321
322     my ($err) = "";
323     for my $idx (4, 5, 6) {
324         if ($t[$idx] == -1) {
325             $err .= "Thread $idx did not run at all\n";
326         } elsif ($t[$idx] != 5) {
327             $err .= "Thread $idx only completed $t[$idx] iterations\n";
328         }
329     }
330     die $err if $err ne '';
331 }
332
333 sub grade_priority_fifo {
334     my (@output) = @_;
335
336     verify_common (@output);
337     my ($thread_cnt) = 10;
338     my ($iter_cnt) = 5;
339     my (@order);
340     my (@t) = (-1) x $thread_cnt;
341     local ($_);
342     foreach (@output) {
343         my ($idx) = /^Thread (\d+)/ or next;
344         my ($iter) = /iteration (\d+)$/;
345         $iter = $iter_cnt if /done!$/;
346         die "Malformed output\n" if !defined $iter;
347         if (@order < $thread_cnt) {
348             push (@order, $idx);
349             die "Thread $idx repeated within first $thread_cnt iterations: "
350                 . join (' ', @order) . ".\n"
351                 if grep ($_ == $idx, @order) != 1;
352         } else {
353             die "Thread $idx ran when $order[0] should have.\n"
354                 if $idx != $order[0];
355             push (@order, shift @order);
356         }
357         die "Thread $idx out of order output.\n" if $t[$idx] != $iter - 1;
358         $t[$idx] = $iter;
359     }
360
361     my ($err) = "";
362     for my $idx (0..$#t) {
363         if ($t[$idx] == -1) {
364             $err .= "Thread $idx did not run at all.\n";
365         } elsif ($t[$idx] != $iter_cnt) {
366             $err .= "Thread $idx only completed $t[$idx] iterations.\n";
367         }
368     }
369     die $err if $err ne '';
370 }
371
372 sub grade_mlfqs_on {
373     my (@output) = @_;
374     verify_common (@output);
375     mlfqs_stats (@output);
376 }
377
378 sub grade_mlfqs_off {
379     my (@output) = @_;
380     verify_common (@output);
381     mlfqs_stats (@output);
382 }
383
384 sub mlfqs_stats {
385     my (@output) = @_;
386     my (%stats) = ("io" => {}, "cpu" => {}, "mix" => {});
387     my (%map) = ("CPU intensive" => "cpu",
388                  "IO intensive" => "io",
389                  "Alternating IO/CPU" => "mix");
390     local ($_);
391     foreach (@output) {
392         my ($thread, $pri) = /^([A-Za-z\/ ]+): (\d+)$/ or next;
393         my ($t) = $map{$thread} or next;
394         
395         my ($s) = $stats{$t};
396         $$s{"n"}++;
397         $$s{"sum"} += $pri;
398         $$s{"sum2"} += $pri * $pri;
399         $$s{"min"} = $pri if !defined ($$s{"min"}) || $pri < $$s{"min"};
400         $$s{"max"} = $pri if !defined ($$s{"max"}) || $pri > $$s{"max"};
401     }
402
403     my ($details) = "";
404     for my $t (keys %stats) {
405         my ($s) = $stats{$t};
406         $details .= "$t: n=$$s{'n'}, min=$$s{'min'}, max=$$s{'max'}, avg=" . int ($$s{'sum'} / $$s{'n'}) . "\n";
407     }
408     $details{$test} = $details;
409     die "MLFQS\n";
410 }
411 \f
412 sub verify_common {
413     my (@output) = @_;
414
415     my (@assertion) = grep (/PANIC/, @output);
416     if (@assertion != 0) {
417         my ($details) = "Kernel panic:\n  $assertion[0]\n";
418
419         my (@stack_line) = grep (/Call stack:/, @output);
420         if (@stack_line != 0) {
421             $details .= "  $stack_line[0]\n\n";
422             $details .= "Translation of backtrace:\n";
423             my (@addrs) = $stack_line[0] =~ /Call stack:((?: 0x[0-9a-f]+)+)/;
424
425             my ($A2L);
426             if (`uname -m`
427                 =~ /i.86|pentium.*|[pk][56]|nexgen|viac3|6x86|athlon.*/) {
428                 $A2L = "addr2line";
429             } else {
430                 $A2L = "i386-elf-addr2line";
431             }
432             open (A2L, "$A2L -fe output/$test/kernel.o @addrs|");
433             for (;;) {
434                 my ($function, $line);
435                 last unless $function = <A2L>;
436                 $line = <A2L>;
437                 chomp $function;
438                 chomp $line;
439                 $details .= "  $function ($line)\n";
440             }
441         }
442         $extra{$test} = $details;
443         die "Kernel panic.  Details at end of file.\n"
444     }
445
446     die "No output at all\n" if @output == 0;
447     die "Didn't start up properly: no \"Pintos booting\" startup message\n"
448         if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
449     die "Didn't start up properly: no \"Boot complete\" startup message\n"
450         if !grep (/Boot complete/, @output);
451     die "Didn't shut down properly: no \"Timer: # ticks\" shutdown message\n"
452         if !grep (/Timer: \d+ ticks/, @output);
453     die "Didn't shut down properly: no \"Powering off\" shutdown message\n"
454         if !grep (/Powering off/, @output);
455 }
456
457 sub compare_output {
458     my ($exp_file, @actual) = @_;
459     my (@expected) = snarf ($exp_file);
460
461     @actual = map ("$_\n", @actual);
462     @expected = map ("$_\n", @expected);
463
464     # Trim header and trailer from @actual.
465     while (scalar (@actual) && $actual[0] ne $expected[0]) {
466         shift (@actual);
467     }
468     die "First line of expected output was not present.\n" if !@actual;
469     while (scalar (@actual) && $actual[$#actual] ne $expected[$#expected]) {
470         pop (@actual);
471     }
472     die "Final line of expected output was not present.\n" if !@actual;
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     $d->Base (1);
487     while ($d->Next ()) {
488         my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
489         if ($d->Same ()) {
490             if ($af != $al) {
491                 $diff .= "Actual lines $af...$al match expected lines "
492                     . "$ef...$el.\n";
493             } else {
494                 $diff .= "Actual line $af matches expected line $ef.\n";
495             }
496         } else {
497             my (@i1) = $d->Items (1);
498             my (@i2) = $d->Items (2);
499             if (!@i1) {
500                 $diff .= "Extra or misplaced line(s) $af...$al "
501                     . "in actual output:\n";
502                 $diff .= number_lines ($af, \@i2);
503             } elsif (!$d->Items (2)) {
504                 $diff .= "Expected line(s) $ef...$el missing or misplaced:\n";
505                 $diff .= number_lines ($ef, \@i1);
506             } else {
507                 $diff .= "The following expected line(s) $ef...$el:\n";
508                 $diff .= number_lines ($ef, \@i1);
509                 $diff .= "became actual line(s) $af...$al:\n";
510                 $diff .= number_lines ($af, \@i2);
511             }
512         }
513     }
514
515     my ($details) = "";
516     $details .= "$test actual output (line numbers added):\n";
517     $details .= number_lines (1, \@actual);
518     $details .= "\n$test expected output (line numbers added):\n";
519     $details .= number_lines (1, \@expected);
520     $details .= "\n$diff\n";
521     $details{$test} = $details;
522     die "Output differs from expected.  Details at end of file.\n";
523 }
524 \f
525 sub write_grades {
526     my (@summary) = snarf ("$GRADES_DIR/tests.txt");
527
528     my ($ploss) = 0;
529     my ($tloss) = 0;
530     my ($total) = 0;
531     for (my ($i) = 0; $i <= $#summary; $i++) {
532         local ($_) = $summary[$i];
533         if (my ($loss, $test) = /^  -(\d+) ([-a-zA-Z0-9]+):/) {
534             my ($result) = $result{$test} || "Not tested.";
535
536             if ($result eq 'ok') {
537                 splice (@summary, $i, 1);
538                 $i--;
539             } else {
540                 $ploss += $loss;
541                 $tloss += $loss;
542                 splice (@summary, $i + 1, 0,
543                         map ("     $_", split ("\n", $result)));
544             }
545         } elsif (my ($ptotal) = /^Score: \/(\d+)$/) {
546             $total += $ptotal;
547             $summary[$i] = "Score: " . ($ptotal - $ploss) . "/$ptotal";
548             splice (@summary, $i, 0, "  All tests passed.") if $ploss == 0;
549             $ploss = 0;
550             $i++;
551         }
552     }
553     my ($ts) = "(" . ($total - $tloss) . "/" . $total . ")";
554     $summary[0] =~ s/\[\[total\]\]/$ts/;
555
556     open (SUMMARY, ">tests.out");
557     print SUMMARY map ("$_\n", @summary);
558     close (SUMMARY);
559 }
560
561 sub write_details {
562     open (DETAILS, ">details.out");
563     my ($n) = 0;
564     for my $test (@TESTS) {
565         next if $result{$test} eq 'ok';
566         
567         my ($details) = $details{$test};
568         next if !defined ($details) && ! -e "output/$test/run.out";
569
570         print DETAILS "\n" if $n++;
571         print DETAILS "--- $test details ", '-' x (50 - length ($test));
572         print DETAILS "\n\n";
573
574         if (!defined $details) {
575             $details = "Output:\n\n" . snarf ("output/$test/run.out");
576         }
577         print DETAILS $details;
578
579         print DETAILS "\n", "-" x 10, "\n\n$extra{$test}"
580             if defined $extra{$test};
581     }
582     close (DETAILS);
583
584 }
585 \f
586 sub xsystem {
587     my ($command, %options) = @_;
588     print "$command\n" if $VERBOSE || $options{VERBOSE};
589
590     my ($log) = $options{LOG};
591     if (defined ($log)) {
592         $command = "($command) >output/$log.out 2>output/$log.err";
593     }
594
595     my ($pid, $status);
596     eval {
597         local $SIG{ALRM} = sub { die "alarm\n" };
598         alarm $options{TIMEOUT} if defined $options{TIMEOUT};
599         $pid = fork;
600         die "fork: $!\n" if !defined $pid;
601         exec ($command), die "$command: exec: $!\n" if !$pid;
602         waitpid ($pid, 0);
603         $status = $?;
604         alarm 0;
605     };
606     if ($@) {
607         die unless $@ eq "alarm\n";   # propagate unexpected errors
608         print "Timed out.\n";
609         kill SIGTERM, $pid;
610         $status = 0;
611     }
612
613     if (WIFSIGNALED ($status)) {
614         my ($signal) = WTERMSIG ($status);
615         die "Interrupted\n" if $signal == SIGINT;
616         print "Child terminated with signal $signal\n";
617     }
618
619     unlink ("output/$log.err") if defined ($log) && $status == 0;
620
621     return $status == 0;
622 }
623
624 sub snarf {
625     my ($file) = @_;
626     open (OUTPUT, $file) or die "$file: open: $!\n";
627     my (@lines) = <OUTPUT>;
628     chomp (@lines);
629     close (OUTPUT);
630     return wantarray ? @lines : join ('', map ("$_\n", @lines));
631 }
632
633 sub files_equal {
634     my ($a, $b) = @_;
635     my ($equal);
636     open (A, "<$a") or die "$a: open: $!\n";
637     open (B, "<$b") or die "$b: open: $!\n";
638     if (-s A != -s B) {
639         $equal = 0;
640     } else {
641         my ($sa, $sb);
642         for (;;) {
643             sysread (A, $sa, 1024);
644             sysread (B, $sb, 1024);
645             $equal = 0, last if $sa ne $sb;
646             $equal = 1, last if $sa eq '';
647         }
648     }
649     close (A);
650     close (B);
651     return $equal;
652 }
653
654 sub file_contains {
655     my ($file, $expected) = @_;
656     open (FILE, "<$file") or die "$file: open: $!\n";
657     my ($actual);
658     sysread (FILE, $actual, -s FILE);
659     my ($equal) = $actual eq $expected;
660     close (FILE);
661     return $equal;
662 }
663
664 sub number_lines {
665     my ($ln, $lines) = @_;
666     my ($out);
667     for my $line (@$lines) {
668         chomp $line;
669         $out .= sprintf "%4d  %s\n", $ln++, $line;
670     }
671     return $out;
672 }