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     my ($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         if -d "output/$test";
176
177     # Make output directory.
178     mkdir "output/$test";
179
180     # Change constants.h if necessary.
181     my ($defines) = test_constants ($test);
182     if ($defines ne snarf ("pintos/src/constants.h")) {
183         open (CONSTANTS, ">pintos/src/constants.h");
184         print CONSTANTS $defines;
185         close (CONSTANTS);
186     }
187
188     # Copy in the new test.c and delete enough files to ensure a full rebuild.
189     my ($src) = test_source ($test);
190     xsystem ("cp $src pintos/src/threads/test.c", DIE => "cp failed\n");
191     unlink ("pintos/src/threads/build/threads/test.o");
192     unlink ("pintos/src/threads/build/kernel.o");
193     unlink ("pintos/src/threads/build/kernel.bin");
194     unlink ("pintos/src/threads/build/os.dsk");
195
196     # Build.
197     xsystem ("cd pintos/src/threads && make", LOG => "$test/make")
198         or return "compile error";
199
200     # Copy out files for backtraces later.
201     xsystem ("cp pintos/src/threads/build/kernel.o output/$test");
202     xsystem ("cp pintos/src/threads/build/os.dsk output/$test");
203
204     # Run.
205     my ($timeout) = 10;
206     $timeout = 600 if $test =~ /^mlfqs/;
207     xsystem ("cd pintos/src/threads/build && pintos -v run -q",
208              LOG => "$test/run",
209              TIMEOUT => $timeout)
210         or return "Bochs error";
211     
212     return "ok";
213 }
214
215 sub grade_test {
216     my ($test) = @_;
217
218     my (@output) = snarf ("output/$test/run.out");
219
220     if (-e "$GRADES_DIR/$test.exp") {
221         eval {
222             verify_common (@output);
223             compare_output ("$GRADES_DIR/$test.exp", @output);
224         }
225     } else {
226         my ($grade_func);
227         ($grade_func = $test) =~ s/-/_/g;
228         eval "grade_$grade_func (\@output)";
229     }
230     if ($@) {
231         die $@ if $@ =~ /at \S+ line \d+$/;
232         return $@;
233     }
234     return "ok";
235 }
236 \f
237 sub grade_alarm_single {
238     verify_alarm (1, @_);
239 }
240
241 sub grade_alarm_multiple {
242     verify_alarm (7, @_);
243 }
244
245 sub verify_alarm {
246     my ($iterations, @output) = @_;
247
248     verify_common (@output);
249
250     my (@products);
251     for (my ($i) = 0; $i < $iterations; $i++) {
252         for (my ($t) = 0; $t < 5; $t++) {
253             push (@products, ($i + 1) * ($t + 1) * 10);
254         }
255     }
256     @products = sort {$a <=> $b} @products;
257
258     local ($_);
259     foreach (@output) {
260         die $_ if /Out of order/;
261
262         my ($p) = /product=(\d+)$/;
263         next if !defined $p;
264
265         my ($q) = shift (@products);
266         die "Too many wakeups.\n" if !defined $q;
267         die "Out of order wakeups ($p vs. $q).\n" if $p != $q; # FIXME
268     }
269     die scalar (@products) . " fewer wakeups than expected.\n"
270         if @products != 0;
271 }
272
273 sub grade_alarm_zero {
274     my (@output) = @_;
275     verify_common (@output);
276     die "Crashed in timer_sleep()\n" if !grep (/^Success\.$/, @output);
277 }
278
279 sub grade_alarm_negative {
280     my (@output) = @_;
281     verify_common (@output);
282     die "Crashed in timer_sleep()\n" if !grep (/^Success\.$/, @output);
283 }
284
285 sub grade_join_invalid {
286     my (@output) = @_;
287     verify_common (@output);
288     grep (/Testing invalid join/, @output) or die "Test didn't start\n";
289     grep (/Invalid join test done/, @output) or die "Test didn't complete\n";
290 }
291
292 sub grade_join_no {
293     my (@output) = @_;
294     verify_common (@output);
295     grep (/Testing no join/, @output) or die "Test didn't start\n";
296     grep (/No join test done/, @output) or die "Test didn't complete\n";
297 }
298
299 sub grade_join_multiple {
300     my (@output) = @_;
301
302     verify_common (@output);
303     my (@t);
304     $t[4] = $t[5] = $t[6] = -1;
305     local ($_);
306     foreach (@output) {
307         my ($idx) = /^Thread (\d+)/ or next;
308         my ($iter) = /iteration (\d+)$/;
309         $iter = 5 if /done!$/;
310         die "Malformed output\n" if !defined $iter;
311         if ($idx == 6) {
312             die "Thread 6 started before either other thread finished\n"
313                 if $t[4] < 5 && $t[5] < 5;
314             die "Thread 6 started before thread 4 finished\n"
315                 if $t[4] < 5;
316             die "Thread 6 started before thread 5 finished\n"
317                 if $t[5] < 5;
318         }
319         die "Thread $idx out of order output\n" if $t[$idx] != $iter - 1;
320         $t[$idx] = $iter;
321     }
322
323     my ($err) = "";
324     for my $idx (4, 5, 6) {
325         if ($t[$idx] == -1) {
326             $err .= "Thread $idx did not run at all\n";
327         } elsif ($t[$idx] != 5) {
328             $err .= "Thread $idx only completed $t[$idx] iterations\n";
329         }
330     }
331     die $err if $err ne '';
332 }
333
334 sub grade_priority_fifo {
335     my (@output) = @_;
336
337     verify_common (@output);
338     my ($thread_cnt) = 10;
339     my ($iter_cnt) = 5;
340     my (@order);
341     my (@t) = (-1) x $thread_cnt;
342     local ($_);
343     foreach (@output) {
344         my ($idx) = /^Thread (\d+)/ or next;
345         my ($iter) = /iteration (\d+)$/;
346         $iter = $iter_cnt if /done!$/;
347         die "Malformed output\n" if !defined $iter;
348         if (@order < $thread_cnt) {
349             push (@order, $idx);
350             die "Thread $idx repeated within first $thread_cnt iterations: "
351                 . join (' ', @order) . ".\n"
352                 if grep ($_ == $idx, @order) != 1;
353         } else {
354             die "Thread $idx ran when $order[0] should have.\n"
355                 if $idx != $order[0];
356             push (@order, shift @order);
357         }
358         die "Thread $idx out of order output.\n" if $t[$idx] != $iter - 1;
359         $t[$idx] = $iter;
360     }
361
362     my ($err) = "";
363     for my $idx (0..$#t) {
364         if ($t[$idx] == -1) {
365             $err .= "Thread $idx did not run at all.\n";
366         } elsif ($t[$idx] != $iter_cnt) {
367             $err .= "Thread $idx only completed $t[$idx] iterations.\n";
368         }
369     }
370     die $err if $err ne '';
371 }
372
373 sub grade_mlfqs_on {
374     my (@output) = @_;
375     verify_common (@output);
376     mlfqs_stats (@output);
377 }
378
379 sub grade_mlfqs_off {
380     my (@output) = @_;
381     verify_common (@output);
382     mlfqs_stats (@output);
383 }
384
385 sub mlfqs_stats {
386     my (@output) = @_;
387     my (%stats) = ("io" => {}, "cpu" => {}, "mix" => {});
388     my (%map) = ("CPU intensive" => "cpu",
389                  "IO intensive" => "io",
390                  "Alternating IO/CPU" => "mix");
391     local ($_);
392     foreach (@output) {
393         my ($thread, $pri) = /^([A-Za-z\/ ]+): (\d+)$/ or next;
394         my ($t) = $map{$thread} or next;
395         
396         my ($s) = $stats{$t};
397         $$s{"n"}++;
398         $$s{"sum"} += $pri;
399         $$s{"sum2"} += $pri * $pri;
400         $$s{"min"} = $pri if !defined ($$s{"min"}) || $pri < $$s{"min"};
401         $$s{"max"} = $pri if !defined ($$s{"max"}) || $pri > $$s{"max"};
402     }
403
404     my ($details) = "";
405     for my $t (keys %stats) {
406         my ($s) = $stats{$t};
407         $details .= "$t: n=$$s{'n'}, min=$$s{'min'}, max=$$s{'max'}, avg=" . int ($$s{'sum'} / $$s{'n'}) . "\n";
408     }
409     $details{$test} = $details;
410     die "MLFQS\n";
411 }
412 \f
413 sub verify_common {
414     my (@output) = @_;
415
416     my (@assertion) = grep (/PANIC/, @output);
417     if (@assertion != 0) {
418         my ($details) = "Kernel panic:\n  $assertion[0]\n";
419
420         my (@stack_line) = grep (/Call stack:/, @output);
421         if (@stack_line != 0) {
422             $details .= "  $stack_line[0]\n\n";
423             $details .= "Translation of backtrace:\n";
424             my (@addrs) = $stack_line[0] =~ /Call stack:((?: 0x[0-9a-f]+)+)/;
425
426             my ($A2L);
427             if (`uname -m`
428                 =~ /i.86|pentium.*|[pk][56]|nexgen|viac3|6x86|athlon.*/) {
429                 $A2L = "addr2line";
430             } else {
431                 $A2L = "i386-elf-addr2line";
432             }
433             open (A2L, "$A2L -fe output/$test/kernel.o @addrs|");
434             for (;;) {
435                 my ($function, $line);
436                 last unless $function = <A2L>;
437                 $line = <A2L>;
438                 chomp $function;
439                 chomp $line;
440                 $details .= "  $function ($line)\n";
441             }
442         }
443         $extra{$test} = $details;
444         die "Kernel panic.  Details at end of file.\n"
445     }
446
447     die "No output at all\n" if @output == 0;
448     die "Didn't start up properly: no \"Pintos booting\" startup message\n"
449         if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
450     die "Didn't start up properly: no \"Boot complete\" startup message\n"
451         if !grep (/Boot complete/, @output);
452     die "Didn't shut down properly: no \"Timer: # ticks\" shutdown message\n"
453         if !grep (/Timer: \d+ ticks/, @output);
454     die "Didn't shut down properly: no \"Powering off\" shutdown message\n"
455         if !grep (/Powering off/, @output);
456 }
457
458 sub compare_output {
459     my ($exp_file, @actual) = @_;
460     my (@expected) = snarf ($exp_file);
461
462     @actual = map ("$_\n", @actual);
463     @expected = map ("$_\n", @expected);
464
465     # Trim header and trailer from @actual.
466     while (scalar (@actual) && $actual[0] ne $expected[0]) {
467         shift (@actual);
468     }
469     die "First line of expected output was not present.\n" if !@actual;
470     while (scalar (@actual) && $actual[$#actual] ne $expected[$#expected]) {
471         pop (@actual);
472     }
473     die "Final line of expected output was not present.\n" if !@actual;
474     
475     # Check whether they're the same.
476     if ($#actual == $#expected) {
477         my ($eq) = 1;
478         for (my ($i) = 0; $i <= $#expected; $i++) {
479             $eq = 0 if $actual[$i] ne $expected[$i];
480         }
481         return if $eq;
482     }
483
484     # They differ.  Output a diff.
485     my ($diff) = "";
486     my ($d) = Algorithm::Diff->new (\@expected, \@actual);
487     $d->Base (1);
488     while ($d->Next ()) {
489         my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
490         if ($d->Same ()) {
491             if ($af != $al) {
492                 $diff .= "Actual lines $af...$al match expected lines "
493                     . "$ef...$el.\n";
494             } else {
495                 $diff .= "Actual line $af matches expected line $ef.\n";
496             }
497         } else {
498             my (@i1) = $d->Items (1);
499             my (@i2) = $d->Items (2);
500             if (!@i1) {
501                 $diff .= "Extra or misplaced line(s) $af...$al "
502                     . "in actual output:\n";
503                 $diff .= number_lines ($af, \@i2);
504             } elsif (!$d->Items (2)) {
505                 $diff .= "Expected line(s) $ef...$el missing or misplaced:\n";
506                 $diff .= number_lines ($ef, \@i1);
507             } else {
508                 $diff .= "The following expected line(s) $ef...$el:\n";
509                 $diff .= number_lines ($ef, \@i1);
510                 $diff .= "became actual line(s) $af...$al:\n";
511                 $diff .= number_lines ($af, \@i2);
512             }
513         }
514     }
515
516     my ($details) = "";
517     $details .= "$test actual output (line numbers added):\n";
518     $details .= number_lines (1, \@actual);
519     $details .= "\n$test expected output (line numbers added):\n";
520     $details .= number_lines (1, \@expected);
521     $details .= "\n$diff\n";
522     $details{$test} = $details;
523     die "Output differs from expected.  Details at end of file.\n";
524 }
525 \f
526 sub write_grades {
527     my (@summary) = snarf ("$GRADES_DIR/tests.txt");
528
529     my ($ploss) = 0;
530     my ($tloss) = 0;
531     my ($total) = 0;
532     for (my ($i) = 0; $i <= $#summary; $i++) {
533         local ($_) = $summary[$i];
534         if (my ($loss, $test) = /^  -(\d+) ([-a-zA-Z0-9]+):/) {
535             my ($result) = $result{$test} || "Not tested.";
536
537             if ($result eq 'ok') {
538                 splice (@summary, $i, 1);
539                 $i--;
540             } else {
541                 $ploss += $loss;
542                 $tloss += $loss;
543                 splice (@summary, $i + 1, 0,
544                         map ("     $_", split ("\n", $result)));
545             }
546         } elsif (my ($ptotal) = /^Score: \/(\d+)$/) {
547             $total += $ptotal;
548             $summary[$i] = "Score: " . ($ptotal - $ploss) . "/$ptotal";
549             splice (@summary, $i, 0, "  All tests passed.") if $ploss == 0;
550             $ploss = 0;
551             $i++;
552         }
553     }
554     my ($ts) = "(" . ($total - $tloss) . "/" . $total . ")";
555     $summary[0] =~ s/\[\[total\]\]/$ts/;
556
557     open (SUMMARY, ">tests.out");
558     print SUMMARY map ("$_\n", @summary);
559     close (SUMMARY);
560 }
561
562 sub write_details {
563     open (DETAILS, ">details.out");
564     my ($n) = 0;
565     for my $test (@TESTS) {
566         next if $result{$test} eq 'ok';
567         
568         my ($details) = $details{$test};
569         next if !defined ($details) && ! -e "output/$test/run.out";
570
571         print DETAILS "\n" if $n++;
572         print DETAILS "--- $test details ", '-' x (50 - length ($test));
573         print DETAILS "\n\n";
574
575         if (!defined $details) {
576             $details = "Output:\n\n" . snarf ("output/$test/run.out");
577         }
578         print DETAILS $details;
579
580         print DETAILS "\n", "-" x 10, "\n\n$extra{$test}"
581             if defined $extra{$test};
582     }
583     close (DETAILS);
584
585 }
586 \f
587 sub xsystem {
588     my ($command, %options) = @_;
589     print "$command\n" if $VERBOSE || $options{VERBOSE};
590
591     my ($log) = $options{LOG};
592     if (defined ($log)) {
593         $command = "($command) >output/$log.out 2>output/$log.err";
594     }
595
596     my ($pid, $status);
597     eval {
598         local $SIG{ALRM} = sub { die "alarm\n" };
599         alarm $options{TIMEOUT} if defined $options{TIMEOUT};
600         $pid = fork;
601         die "fork: $!\n" if !defined $pid;
602         exec ($command), die "$command: exec: $!\n" if !$pid;
603         waitpid ($pid, 0);
604         $status = $?;
605         alarm 0;
606     };
607     if ($@) {
608         die unless $@ eq "alarm\n";   # propagate unexpected errors
609         print "Timed out.\n";
610         kill SIGTERM, $pid;
611         $status = 0;
612     }
613
614     if (WIFSIGNALED ($status)) {
615         my ($signal) = WTERMSIG ($status);
616         die "Interrupted\n" if $signal == SIGINT;
617         print "Child terminated with signal $signal\n";
618     }
619
620     unlink ("output/$log.err") if defined ($log) && $status == 0;
621
622     return $status == 0;
623 }
624
625 sub snarf {
626     my ($file) = @_;
627     open (OUTPUT, $file) or die "$file: open: $!\n";
628     my (@lines) = <OUTPUT>;
629     chomp (@lines);
630     close (OUTPUT);
631     return wantarray ? @lines : join ('', map ("$_\n", @lines));
632 }
633
634 sub files_equal {
635     my ($a, $b) = @_;
636     my ($equal);
637     open (A, "<$a") or die "$a: open: $!\n";
638     open (B, "<$b") or die "$b: open: $!\n";
639     if (-s A != -s B) {
640         $equal = 0;
641     } else {
642         my ($sa, $sb);
643         for (;;) {
644             sysread (A, $sa, 1024);
645             sysread (B, $sb, 1024);
646             $equal = 0, last if $sa ne $sb;
647             $equal = 1, last if $sa eq '';
648         }
649     }
650     close (A);
651     close (B);
652     return $equal;
653 }
654
655 sub file_contains {
656     my ($file, $expected) = @_;
657     open (FILE, "<$file") or die "$file: open: $!\n";
658     my ($actual);
659     sysread (FILE, $actual, -s FILE);
660     my ($equal) = $actual eq $expected;
661     close (FILE);
662     return $equal;
663 }
664
665 sub number_lines {
666     my ($ln, $lines) = @_;
667     my ($out);
668     for my $line (@$lines) {
669         chomp $line;
670         $out .= sprintf "%4d  %s\n", $ln++, $line;
671     }
672     return $out;
673 }