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           )
45     unless @TESTS > 0;
46
47 # Find the directory that contains the grading files.
48 our ($GRADES_DIR);
49 ($GRADES_DIR = $0) =~ s#/[^/]+$##;
50 -d $GRADES_DIR or die "$GRADES_DIR: stat: $!\n";
51
52 if ($clean) {
53     # Verify that we're roughly in the correct directory
54     # before we go blasting away files.
55     choose_tarball ();
56
57     xsystem ("rm -rf output pintos", VERBOSE => 1);
58     xsystem ("rm -f details.out tests.out", VERBOSE => 1);
59 }
60
61 # Create output directory, if it doesn't already exist.
62 -d ("output") || mkdir ("output") or die "output: mkdir: $!\n";
63
64 # Extract submission.
65 extract_tarball () if ! -d "pintos";
66
67 # Verify that the proper directory was submitted.
68 -d "pintos/src/threads" or die "pintos/src/threads: stat: $!\n";
69
70 # Run and grade the tests.
71 our $test;
72 our %result;
73 our %details;
74 our %extra;
75 for $test (@TESTS) {
76     print "$test: ";
77     my ($result) = run_test ($test);
78     if ($result eq 'ok') {
79         $result = grade_test ($test);
80         $result =~ s/\n$//;
81     }
82     print "$result\n";
83     
84     $result{$test} = $result;
85 }
86
87 # Write output.
88 write_grades ();
89 write_details ();
90 \f
91 sub choose_tarball {
92     my (@tarballs)
93         = grep (/^[a-z0-9]+\.[A-Za-z]+\.\d+\.\d+\.\d+\.\d+.\d+\.tar\.gz$/,
94                 glob ("*.tar.gz"));
95     die "no pintos dir and no source tarball\n" if scalar (@tarballs) == 0;
96
97     # Sort tarballs in reverse order by time.
98     @tarballs = sort { ext_mdyHMS ($b) cmp ext_mdyHMS ($a) } @tarballs;
99
100     print "Multiple tarballs: choosing $tarballs[0]\n"
101         if scalar (@tarballs) > 1;
102     return $tarballs[0];
103 }
104
105 sub extract_tarball {
106     my ($tarball) = choose_tarball ();
107
108     mkdir "pintos" or die "pintos: mkdir: $!\n";
109     mkdir "pintos/src" or die "pintos: mkdir: $!\n";
110
111     print "Extracting $tarball...\n";
112     xsystem ("cd pintos/src && tar xzf ../../$tarball",
113              DIE => "extraction failed\n");
114
115     print "Patching...\n";
116     xsystem ("patch -fs pintos/src/lib/debug.c < $GRADES_DIR/panic.diff",
117              LOG => "patch",
118              DIE => "patch failed\n");
119 }
120
121 sub ext_mdyHMS {
122     my ($s) = @_;
123     my ($ms, $d, $y, $H, $M, $S) =
124         $s =~ /.([A-Za-z]+)\.(\d+)\.(\d+)\.(\d+)\.(\d+).(\d+)\.tar\.gz$/
125         or die;
126     my ($m) = index ("janfebmaraprmayjunjulaugsepoctnovdec", lc $ms) / 3
127         or die;
128     return sprintf "%02d-%02d-%02d %02d:%02d:%02d", $y, $m, $d, $H, $M, $S;
129 }
130 \f
131 sub test_source {
132     my ($test) = @_;
133     my ($src) = "$GRADES_DIR/$test.c";
134     $src = "$GRADES_DIR/mlfqs.c" if $test =~ /^mlfqs/;
135     -e $src or die "$src: stat: $!\n";
136     return $src;
137 }
138
139 sub test_constants {
140    my ($defines) = "";
141    $defines .= "#define MLFQS 1\n" if $test eq 'mlfqs-on';
142    return $defines;
143  }
144
145 sub run_test {
146     my ($test) = @_;
147     return "ok" if -f "output/$test/done";
148
149     # Reuse older results if any.
150     if (open (DONE, "<output/$test/done")) {
151         my ($status);
152         $status = <DONE>;
153         chomp $status;
154         close (DONE);
155         return $status;
156     }
157
158     # Really run the test.
159     $status = really_run_test ($test);
160
161     # Save the results for later.
162     open (DONE, ">output/$test/done") or die "output/$test/done: create: $!\n";
163     print DONE "$status\n";
164     close (DONE);
165
166     return $status;
167 }
168
169 sub really_run_test {
170     # Need to run it.
171     # If there's residue from an earlier test, move it to .old.
172     # If there's already a .old, delete it.
173     xsystem ("rm -rf output/$test.old", VERBOSE => 1) if -d "output/$test.old";
174     rename "output/$test", "output/$test.old" or die "rename: $!\n";
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             while (my $function = <A2L>) {
434                 my ($line) = <A2L>;
435                 chomp $function;
436                 chomp $line;
437                 $details .= "  $function ($line)\n";
438             }
439         }
440         $extra{$test} = $details;
441         die "Kernel panic.  Details at end of file.\n"
442     }
443
444     die "No output at all\n" if @output == 0;
445     die "Didn't start up properly: no \"Pintos booting\" startup message\n"
446         if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
447     die "Didn't start up properly: no \"Boot complete\" startup message\n"
448         if !grep (/Boot complete/, @output);
449     die "Didn't shut down properly: no \"Timer: # ticks\" shutdown message\n"
450         if !grep (/Timer: \d+ ticks/, @output);
451     die "Didn't shut down properly: no \"Powering off\" shutdown message\n"
452         if !grep (/Powering off/, @output);
453 }
454
455 sub compare_output {
456     my ($exp_file, @actual) = @_;
457     my (@expected) = snarf ($exp_file);
458
459     @actual = map ("$_\n", @actual);
460     @expected = map ("$_\n", @expected);
461
462     # Trim header and trailer from @actual.
463     while (scalar (@actual) && $actual[0] ne $expected[0]) {
464         shift (@actual);
465     }
466     die "First line of expected output was not present.\n" if !@actual;
467     while (scalar (@actual) && $actual[$#actual] ne $expected[$#expected]) {
468         pop (@actual);
469     }
470     die "Final line of expected output was not present.\n" if !@actual;
471     
472     # Check whether they're the same.
473     if ($#actual == $#expected) {
474         my ($eq) = 1;
475         for (my ($i) = 0; $i <= $#expected; $i++) {
476             $eq = 0 if $actual[$i] ne $expected[$i];
477         }
478         return if $eq;
479     }
480
481     # They differ.  Output a diff.
482     my ($diff) = "";
483     my ($d) = Algorithm::Diff->new (\@expected, \@actual);
484     $d->Base (1);
485     while ($d->Next ()) {
486         my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
487         if ($d->Same ()) {
488             if ($af != $al) {
489                 $diff .= "Actual lines $af...$al match expected lines "
490                     . "$ef...$el.\n";
491             } else {
492                 $diff .= "Actual line $af matches expected line $ef.\n";
493             }
494         } else {
495             my (@i1) = $d->Items (1);
496             my (@i2) = $d->Items (2);
497             if (!@i1) {
498                 $diff .= "Extra or misplaced line(s) $af...$al "
499                     . "in actual output:\n";
500                 $diff .= number_lines ($af, \@i2);
501             } elsif (!$d->Items (2)) {
502                 $diff .= "Expected line(s) $ef...$el missing or misplaced:\n";
503                 $diff .= number_lines ($ef, \@i1);
504             } else {
505                 $diff .= "The following expected line(s) $ef...$el:\n";
506                 $diff .= number_lines ($ef, \@i1);
507                 $diff .= "became actual line(s) $af...$al:\n";
508                 $diff .= number_lines ($af, \@i2);
509             }
510         }
511     }
512
513     my ($details) = "";
514     $details .= "$test actual output (line numbers added):\n";
515     $details .= number_lines (1, \@actual);
516     $details .= "\n$test expected output (line numbers added):\n";
517     $details .= number_lines (1, \@expected);
518     $details .= "\n$diff\n";
519     $details{$test} = $details;
520     die "Output differs from expected.  Details at end of file.\n";
521 }
522 \f
523 sub write_grades {
524     my (@summary) = snarf ("$GRADES_DIR/tests.txt");
525
526     my ($ploss) = 0;
527     my ($tloss) = 0;
528     my ($total) = 0;
529     for (my ($i) = 0; $i <= $#summary; $i++) {
530         local ($_) = $summary[$i];
531         if (my ($loss, $test) = /^  -(\d+) ([-a-zA-Z0-9]+):/) {
532             my ($result) = $result{$test} || "Not tested.";
533
534             if ($result eq 'ok') {
535                 splice (@summary, $i, 1);
536                 $i--;
537             } else {
538                 $ploss += $loss;
539                 $tloss += $loss;
540                 splice (@summary, $i + 1, 0,
541                         map ("     $_", split ("\n", $result)));
542             }
543         } elsif (my ($ptotal) = /^Score: \/(\d+)$/) {
544             $total += $ptotal;
545             $summary[$i] = "Score: " . ($ptotal - $ploss) . "/$ptotal";
546             splice (@summary, $i, 0, "  All tests passed.") if $ploss == 0;
547             $ploss = 0;
548             $i++;
549         }
550     }
551     my ($ts) = "(" . ($total - $tloss) . "/" . $total . ")";
552     $summary[0] =~ s/\[\[total\]\]/$ts/;
553
554     open (SUMMARY, ">tests.out");
555     print SUMMARY map ("$_\n", @summary);
556     close (SUMMARY);
557 }
558
559 sub write_details {
560     open (DETAILS, ">details.out");
561     my ($n) = 0;
562     for my $test (@TESTS) {
563         next if $result{$test} eq 'ok';
564         
565         my ($details) = $details{$test};
566         next if !defined ($details) && ! -e "output/$test/run.out";
567
568         print DETAILS "\n" if $n++;
569         print DETAILS "--- $test details ", '-' x (50 - length ($test));
570         print DETAILS "\n\n";
571
572         if (!defined $details) {
573             $details = "Output:\n\n" . snarf ("output/$test/run.out");
574         }
575         print DETAILS $details;
576
577         print DETAILS "\n", "-" x 10, "\n\n$extra{$test}"
578             if defined $extra{$test};
579     }
580     close (DETAILS);
581
582 }
583 \f
584 sub xsystem {
585     my ($command, %options) = @_;
586     print "$command\n" if $VERBOSE || $options{VERBOSE};
587
588     my ($log) = $options{LOG};
589     if (defined ($log)) {
590         $command = "($command) >output/$log.out 2>output/$log.err";
591     }
592
593     my ($pid, $status);
594     eval {
595         local $SIG{ALRM} = sub { die "alarm\n" };
596         alarm $options{TIMEOUT} if defined $options{TIMEOUT};
597         $pid = fork;
598         die "fork: $!\n" if !defined $pid;
599         exec ($command), die "$command: exec: $!\n" if !$pid;
600         waitpid ($pid, 0);
601         $status = $?;
602         alarm 0;
603     };
604     if ($@) {
605         die unless $@ eq "alarm\n";   # propagate unexpected errors
606         print "Timed out.\n";
607         kill SIGTERM, $pid;
608         $status = 0;
609     }
610
611     if (WIFSIGNALED ($status)) {
612         my ($signal) = WTERMSIG ($status);
613         die "Interrupted\n" if $signal == SIGINT;
614         print "Child terminated with signal $signal\n";
615     }
616
617     unlink ("output/$log.err") if defined ($log) && $status == 0;
618
619     return $status == 0;
620 }
621
622 sub snarf {
623     my ($file) = @_;
624     open (OUTPUT, $file) or die "$file: open: $!\n";
625     my (@lines) = <OUTPUT>;
626     chomp (@lines);
627     close (OUTPUT);
628     return wantarray ? @lines : join ('', map ("$_\n", @lines));
629 }
630
631 sub files_equal {
632     my ($a, $b) = @_;
633     my ($equal);
634     open (A, "<$a") or die "$a: open: $!\n";
635     open (B, "<$b") or die "$b: open: $!\n";
636     if (-s A != -s B) {
637         $equal = 0;
638     } else {
639         my ($sa, $sb);
640         for (;;) {
641             sysread (A, $sa, 1024);
642             sysread (B, $sb, 1024);
643             $equal = 0, last if $sa ne $sb;
644             $equal = 1, last if $sa eq '';
645         }
646     }
647     close (A);
648     close (B);
649     return $equal;
650 }
651
652 sub file_contains {
653     my ($file, $expected) = @_;
654     open (FILE, "<$file") or die "$file: open: $!\n";
655     my ($actual);
656     sysread (FILE, $actual, -s FILE);
657     my ($equal) = $actual eq $expected;
658     close (FILE);
659     return $equal;
660 }
661
662 sub number_lines {
663     my ($ln, $lines) = @_;
664     my ($out);
665     for my $line (@$lines) {
666         chomp $line;
667         $out .= sprintf "%4d  %s\n", $ln++, $line;
668     }
669     return $out;
670 }