3 # Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
4 # Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
5 # Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com)
6 # Copyright (C) 2007 Eric Seidel <eric@webkit.org>
7 # Copyright (C) 2009 Google Inc. All rights reserved.
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in the
17 # documentation and/or other materials provided with the distribution.
18 # 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
19 # its contributors may be used to endorse or promote products derived
20 # from this software without specific prior written permission.
22 # THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
23 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 # DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
26 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 # Script to run the WebKit Open Source Project layout tests.
35 # Run all the tests passed in on the command line.
36 # If no tests are passed, find all the .html, .shtml, .xml, .xhtml, .pl, .php (and svg) files in the test directory.
39 # Compare against the existing file xxx-expected.txt.
40 # If there is a mismatch, generate xxx-actual.txt and xxx-diffs.txt.
43 # the number of tests that got the expected results
44 # the number of tests that ran, but did not get the expected results
45 # the number of tests that failed to run
46 # the number of tests that were run but had no expected results to compare against
53 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
59 use File::Spec::Functions;
64 use Time::HiRes qw(time usleep);
66 use List::Util 'shuffle';
68 use lib $FindBin::Bin;
73 sub launchWithCurrentEnv(@);
77 sub dumpToolDidCrash();
79 sub countAndPrintLeaks($$$);
80 sub fileNameWithNumber($$);
82 sub openHTTPDIfNeeded();
84 sub processIgnoreTests($$);
87 sub stripExtension($);
88 sub isTextOnlyTest($);
89 sub expectedDirectoryForTest($;$;$);
90 sub countFinishedTest($$$$);
91 sub testCrashedOrTimedOut($$$$$);
93 sub printFailureMessageForTest($$);
97 sub validateSkippedArg($$;$);
98 sub htmlForResultsSection(\@$&);
99 sub deleteExpectedAndActualResults($);
100 sub recordActualResultsAndDiff($$);
101 sub buildPlatformResultHierarchy();
102 sub buildPlatformTestHierarchy(@);
103 sub epiloguesAndPrologues($$);
104 sub parseLeaksandPrintUniqueLeaks();
105 sub readFromDumpToolWithTimer(*;$);
106 sub setFileHandleNonBlocking(*$);
110 my $addPlatformExceptions = 0;
112 my $guardMalloc = '';
113 my $httpdPort = 8000;
114 my $httpdSSLPort = 8443;
115 my $ignoreTests = '';
116 my $launchSafari = 1;
120 my $report10Slowest = 0;
121 my $resetResults = 0;
122 my $shouldCheckLeaks = 0;
124 my $testsPerDumpTool;
127 my $testResultsDirectory = "/tmp/layout-test-results";
130 my $treatSkipped = "default";
133 my $strictTesting = 0;
134 my $generateNewResults = isAppleMacWebKit() ? 1 : 0;
135 my $stripEditingCallbacks = isCygwin();
138 my $reverseTests = 0;
139 my $randomizeTests = 0;
141 my $timeoutSeconds = 15;
142 my $useRemoteLinksToTests = 0;
145 # Default to --no-http for Qt, and wx for now.
146 $testHTTP = 0 if (isQt() || isWx());
148 my $expectedTag = "expected";
149 my $actualTag = "actual";
150 my $prettyDiffTag = "pretty-diff";
151 my $diffsTag = "diffs";
152 my $errorTag = "stderr";
154 my @macPlatforms = ("mac-tiger", "mac-leopard", "mac-snowleopard", "mac");
157 $platform = "mac-tiger";
159 } elsif (isLeopard()) {
160 $platform = "mac-leopard";
162 } elsif (isSnowLeopard()) {
163 $platform = "mac-snowleopard";
165 } elsif (isAppleMacWebKit()) {
174 } elsif (isCygwin()) {
178 if (!defined($platform)) {
179 print "WARNING: Your platform is not recognized. Any platform-specific results will be generated in platform/undefined.\n";
180 $platform = "undefined";
183 my $programName = basename($0);
184 my $launchSafariDefault = $launchSafari ? "launch" : "do not launch";
185 my $httpDefault = $testHTTP ? "run" : "do not run";
186 my $sampleDefault = $runSample ? "run" : "do not run";
188 # FIXME: "--strict" should be renamed to qt-mac-comparison, or something along those lines.
190 Usage: $programName [options] [testdir|testpath ...]
191 --add-platform-exceptions Put new results for non-platform-specific failing tests into the platform-specific results directory
192 --complex-text Use the complex text code path for all text (Mac OS X and Windows only)
193 -c|--configuration config Set DumpRenderTree build configuration
194 -g|--guard-malloc Enable malloc guard
195 --help Show this help message
196 --[no-]http Run (or do not run) http tests (default: $httpDefault)
197 -i|--ignore-tests Comma-separated list of directories or tests to ignore
198 --[no-]launch-safari Launch (or do not launch) Safari to display test results (default: $launchSafariDefault)
199 -l|--leaks Enable leaks checking
200 --[no-]new-test-results Generate results for new tests
201 -p|--pixel-tests Enable pixel tests
202 --tolerance t Ignore image differences less than this percentage (default: $tolerance)
203 --platform Override the detected platform to use for tests and results (default: $platform)
204 --port Web server port to use with http tests
205 -q|--quiet Less verbose output
206 --reset-results Reset ALL results (including pixel tests if --pixel-tests is set)
207 -o|--results-directory Output results directory (default: $testResultsDirectory)
208 --random Run the tests in a random order
209 --reverse Run the tests in reverse alphabetical order
210 --root Path to root tools build
211 --[no-]sample-on-timeout Run sample on timeout (default: $sampleDefault) (Mac OS X only)
212 -1|--singly Isolate each test case run (implies --verbose)
213 --skipped=[default|ignore|only] Specifies how to treat the Skipped file
214 default: Tests/directories listed in the Skipped file are not tested
215 ignore: The Skipped file is ignored
216 only: Only those tests/directories listed in the Skipped file will be run
217 --slowest Report the 10 slowest tests
218 --strict Do a comparison with the output on Mac (Qt only)
219 --[no-]strip-editing-callbacks Remove editing callbacks from expected results
220 -t|--threaded Run a concurrent JavaScript thead with each test
221 --timeout t Sets the number of seconds before a test times out (default: $timeoutSeconds)
222 --valgrind Run DumpRenderTree inside valgrind (Qt/Linux only)
223 -v|--verbose More verbose output (overrides --quiet)
224 -m|--merge-leak-depth arg Merges leak callStacks and prints the number of unique leaks beneath a callstack depth of arg. Defaults to 5.
225 --use-remote-links-to-tests Link to test files within the SVN repository in the results.
230 my $getOptionsResult = GetOptions(
231 'complex-text' => \$complexText,
232 'guard-malloc|g' => \$guardMalloc,
233 'help' => \$showHelp,
234 'http!' => \$testHTTP,
235 'ignore-tests|i=s' => \$ignoreTests,
236 'launch-safari!' => \$launchSafari,
237 'leaks|l' => \$shouldCheckLeaks,
238 'pixel-tests|p' => \$pixelTests,
239 'platform=s' => \$platform,
240 'port=i' => \$httpdPort,
241 'quiet|q' => \$quiet,
242 'reset-results' => \$resetResults,
243 'new-test-results!' => \$generateNewResults,
244 'results-directory|o=s' => \$testResultsDirectory,
245 'singly|1' => sub { $testsPerDumpTool = 1; },
246 'nthly=i' => \$testsPerDumpTool,
247 'skipped=s' => \&validateSkippedArg,
248 'slowest' => \$report10Slowest,
249 'threaded|t' => \$threaded,
250 'tolerance=f' => \$tolerance,
251 'verbose|v' => \$verbose,
252 'valgrind' => \$useValgrind,
253 'sample-on-timeout!' => \$runSample,
254 'strict' => \$strictTesting,
255 'strip-editing-callbacks!' => \$stripEditingCallbacks,
256 'random' => \$randomizeTests,
257 'reverse' => \$reverseTests,
259 'add-platform-exceptions' => \$addPlatformExceptions,
260 'merge-leak-depth|m:5' => \$mergeDepth,
261 'timeout=i' => \$timeoutSeconds,
262 'use-remote-links-to-tests' => \$useRemoteLinksToTests,
265 if (!$getOptionsResult || $showHelp) {
270 my $ignoreSkipped = $treatSkipped eq "ignore";
271 my $skippedOnly = $treatSkipped eq "only";
273 !$skippedOnly || @ARGV == 0 or die "--skipped=only cannot be used when tests are specified on the command line.";
275 my $configuration = configuration();
277 $testsPerDumpTool = 1000 if !$testsPerDumpTool;
279 $verbose = 1 if $testsPerDumpTool == 1;
281 if ($shouldCheckLeaks && $testsPerDumpTool > 1000) {
282 print STDERR "\nWARNING: Running more than 1000 tests at a time with MallocStackLogging enabled may cause a crash.\n\n";
285 # Stack logging does not play well with QuickTime on Tiger (rdar://problem/5537157)
286 $testMedia = 0 if $shouldCheckLeaks && isTiger();
288 # Generating remote links causes a lot of unnecessary spew on the GTK build bot
289 $useRemoteLinksToTests = 0 if isGtk();
291 setConfigurationProductDir(Cwd::abs_path($root)) if (defined($root));
292 my $productDir = productDir();
293 $productDir .= "/bin" if isQt();
294 $productDir .= "/Programs" if isGtk();
298 if (!defined($root)) {
299 # Push the parameters to build-dumprendertree as an array
300 my @args = argumentsForConfiguration();
302 my $buildResult = system "WebKitTools/Scripts/build-dumprendertree", @args;
304 print STDERR "Compiling DumpRenderTree failed!\n";
305 exit exitStatus($buildResult);
309 my $dumpToolName = "DumpRenderTree";
310 $dumpToolName .= "_debug" if isCygwin() && $configuration ne "Release";
311 my $dumpTool = "$productDir/$dumpToolName";
312 die "can't find executable $dumpToolName (looked in $productDir)\n" unless -x $dumpTool;
314 my $imageDiffTool = "$productDir/ImageDiff";
315 $imageDiffTool .= "_debug" if isCygwin() && $configuration ne "Release";
316 die "can't find executable $imageDiffTool (looked in $productDir)\n" if $pixelTests && !-x $imageDiffTool;
318 checkFrameworks() unless isCygwin();
320 my $layoutTestsName = "LayoutTests";
321 my $testDirectory = File::Spec->rel2abs($layoutTestsName);
322 my $expectedDirectory = $testDirectory;
323 my $platformBaseDirectory = catdir($testDirectory, "platform");
324 my $platformTestDirectory = catdir($platformBaseDirectory, $platform);
325 my @platformResultHierarchy = buildPlatformResultHierarchy();
326 my @platformTestHierarchy = buildPlatformTestHierarchy(@platformResultHierarchy);
328 $expectedDirectory = $ENV{"WebKitExpectedTestResultsDirectory"} if $ENV{"WebKitExpectedTestResultsDirectory"};
330 my $testResults = catfile($testResultsDirectory, "results.html");
332 print "Running tests from $testDirectory\n";
334 print "Enabling pixel tests with a tolerance of $tolerance%\n";
336 print "WARNING: Temporarily changing the main display color profile:\n";
337 print "\tThe colors on your screen will change for the duration of the testing.\n";
338 print "\tThis allows the pixel tests to have consistent color values across all machines.\n";
340 if (isPerianInstalled()) {
341 print "WARNING: Perian's QuickTime component is installed and this may affect pixel test results!\n";
342 print "\tYou should avoid generating new pixel results in this environment.\n";
343 print "\tSee https://bugs.webkit.org/show_bug.cgi?id=22615 for details.\n";
351 system "ln", "-s", $testDirectory, "/tmp/LayoutTests" unless -x "/tmp/LayoutTests";
353 my %ignoredFiles = ();
354 my %ignoredDirectories = map { $_ => 1 } qw(platform);
355 my %ignoredLocalDirectories = map { $_ => 1 } qw(.svn _svn resources);
356 my %supportedFileExtensions = map { $_ => 1 } qw(html shtml xml xhtml pl php);
358 # FIXME: We should fix webkitdirs.pm:hasSVG/WMLSupport() to do the correct feature detection for Cygwin.
359 if (checkWebCoreSVGSupport(0)) {
360 $supportedFileExtensions{'svg'} = 1;
361 } elsif (isCygwin()) {
362 $supportedFileExtensions{'svg'} = 1;
364 $ignoredLocalDirectories{'svg'} = 1;
368 $ignoredDirectories{'http'} = 1;
372 $ignoredDirectories{'media'} = 1;
373 $ignoredDirectories{'http/tests/media'} = 1;
376 if (!checkWebCoreAcceleratedCompositingSupport(0)) {
377 $ignoredDirectories{'compositing'} = 1;
380 if (!checkWebCore3DRenderingSupport(0)) {
381 $ignoredDirectories{'animations/3d'} = 1;
382 $ignoredDirectories{'transforms/3d'} = 1;
385 if (checkWebCoreWMLSupport(0)) {
386 $supportedFileExtensions{'wml'} = 1;
388 $ignoredDirectories{'http/tests/wml'} = 1;
389 $ignoredDirectories{'fast/wml'} = 1;
390 $ignoredDirectories{'wml'} = 1;
393 if (!checkWebCoreXHTMLMPSupport(0)) {
394 $ignoredDirectories{'fast/xhtmlmp'} = 1;
397 if (!checkWebCoreWCSSSupport(0)) {
398 $ignoredDirectories{'fast/wcss'} = 1;
402 processIgnoreTests($ignoreTests, "ignore-tests");
405 if (!$ignoreSkipped) {
406 foreach my $level (@platformTestHierarchy) {
407 if (open SKIPPED, "<", "$level/Skipped") {
408 if ($verbose && !$skippedOnly) {
409 my ($dir, $name) = splitpath($level);
410 print "Skipped tests in $name:\n";
416 $skipped =~ s/^[ \n\r]+//;
417 $skipped =~ s/[ \n\r]+$//;
418 if ($skipped && $skipped !~ /^#/) {
420 push(@ARGV, $skipped);
425 processIgnoreTests($skipped, "Skipped");
435 my $directoryFilter = sub {
436 return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
437 return () if exists $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)};
441 my $fileFilter = sub {
443 if ($filename =~ /\.([^.]+)$/) {
444 if (exists $supportedFileExtensions{$1}) {
445 my $path = File::Spec->abs2rel(catfile($File::Find::dir, $filename), $testDirectory);
446 push @tests, $path if !exists $ignoredFiles{$path};
451 for my $test (@ARGV) {
452 $test =~ s/^($layoutTestsName|$testDirectory)\///;
453 my $fullPath = catfile($testDirectory, $test);
454 if (file_name_is_absolute($test)) {
455 print "can't run test $test outside $testDirectory\n";
456 } elsif (-f $fullPath) {
457 my ($filename, $pathname, $fileExtension) = fileparse($test, qr{\.[^.]+$});
458 if (!exists $supportedFileExtensions{substr($fileExtension, 1)}) {
459 print "test $test does not have a supported extension\n";
460 } elsif ($testHTTP || $pathname !~ /^http\//) {
463 } elsif (-d $fullPath) {
464 find({ preprocess => $directoryFilter, wanted => $fileFilter }, $fullPath);
466 for my $level (@platformTestHierarchy) {
467 my $platformPath = catfile($level, $test);
468 find({ preprocess => $directoryFilter, wanted => $fileFilter }, $platformPath) if (-d $platformPath);
471 print "test $test not found\n";
475 find({ preprocess => $directoryFilter, wanted => $fileFilter }, $testDirectory);
477 for my $level (@platformTestHierarchy) {
478 find({ preprocess => $directoryFilter, wanted => $fileFilter }, $level);
482 die "no tests to run\n" if !@tests;
484 @tests = sort pathcmp @tests;
489 my %imageDifferences;
492 my $leaksOutputFileNumber = 1;
496 push @toolArgs, "--pixel-tests" if $pixelTests;
497 push @toolArgs, "--threaded" if $threaded;
498 push @toolArgs, "--complex-text" if $complexText;
501 my @diffToolArgs = ();
502 push @diffToolArgs, "--tolerance", $tolerance;
507 my $isDumpToolOpen = 0;
508 my $dumpToolCrashed = 0;
509 my $imageDiffToolPID;
510 my $isDiffToolOpen = 0;
513 my $lastDirectory = "";
517 sub catch_pipe { $dumpToolCrashed = 1; }
518 $SIG{"PIPE"} = "catch_pipe";
520 print "Testing ", scalar @tests, " test cases.\n";
521 my $overallStartTime = time;
523 my %expectedResultPaths;
526 @tests = reverse @tests if $reverseTests;
529 @tests = shuffle(@tests) if $randomizeTests;
531 for my $test (@tests) {
532 next if $test eq 'results.html';
534 my $newDumpTool = not $isDumpToolOpen;
537 my $base = stripExtension($test);
538 my $expectedExtension = ".txt";
543 if ($newDumpTool || $dir ne $lastDirectory) {
544 foreach my $logue (epiloguesAndPrologues($newDumpTool ? "" : $lastDirectory, $dir)) {
546 $logue = toWindowsPath($logue);
548 $logue = canonpath($logue);
551 print "running epilogue or prologue $logue\n";
553 print OUT "$logue\n";
554 # Throw away output from DumpRenderTree.
555 # Once for the test output and once for pixel results (empty)
566 print "running $test -> ";
569 if ($dir ne $lastDirectory) {
570 print "\n" unless $atLineStart;
577 $lastDirectory = $dir;
581 my $startTime = time if $report10Slowest;
583 # Try to read expected hash file for pixel tests
584 my $suffixExpectedHash = "";
585 if ($pixelTests && !$resetResults) {
586 my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
587 if (open EXPECTEDHASH, "$expectedPixelDir/$base-$expectedTag.checksum") {
588 my $expectedHash = <EXPECTEDHASH>;
589 chomp($expectedHash);
592 # Format expected hash into a suffix string that is appended to the path / URL passed to DRT
593 $suffixExpectedHash = "'$expectedHash";
597 if ($test !~ /^http\//) {
598 my $testPath = "$testDirectory/$test";
600 $testPath = toWindowsPath($testPath);
602 $testPath = canonpath($testPath);
604 print OUT "$testPath$suffixExpectedHash\n";
607 if ($test !~ /^http\/tests\/local\// && $test !~ /^http\/tests\/ssl\// && $test !~ /^http\/tests\/wml\// && $test !~ /^http\/tests\/media\//) {
608 my $path = canonpath($test);
609 $path =~ s/^http\/tests\///;
610 print OUT "http://127.0.0.1:$httpdPort/$path$suffixExpectedHash\n";
611 } elsif ($test =~ /^http\/tests\/ssl\//) {
612 my $path = canonpath($test);
613 $path =~ s/^http\/tests\///;
614 print OUT "https://127.0.0.1:$httpdSSLPort/$path$suffixExpectedHash\n";
616 my $testPath = "$testDirectory/$test";
618 $testPath = toWindowsPath($testPath);
620 $testPath = canonpath($testPath);
622 print OUT "$testPath$suffixExpectedHash\n";
626 # DumpRenderTree is expected to dump two "blocks" to stdout for each test.
627 # Each block is terminated by a #EOF on a line by itself.
628 # The first block is the output of the test (in text, RenderTree or other formats).
629 # The second block is for optional pixel data in PNG format, and may be empty if
630 # pixel tests are not being run, or the test does not dump pixels (e.g. text tests).
632 my $actualRead = readFromDumpToolWithTimer(IN);
633 my $errorRead = readFromDumpToolWithTimer(ERROR, $actualRead->{status} eq "timedOut");
635 my $actual = $actualRead->{output};
636 my $error = $errorRead->{output};
638 $expectedExtension = $actualRead->{extension};
639 my $expectedFileName = "$base-$expectedTag.$expectedExtension";
641 my $isText = isTextOnlyTest($actual);
643 my $expectedDir = expectedDirectoryForTest($base, $isText, $expectedExtension);
644 $expectedResultPaths{$base} = "$expectedDir/$expectedFileName";
646 unless ($actualRead->{status} eq "success" && $errorRead->{status} eq "success") {
647 my $crashed = $actualRead->{status} eq "crashed" || $errorRead->{status} eq "crashed";
648 testCrashedOrTimedOut($test, $base, $crashed, $actual, $error);
649 countFinishedTest($test, $base, $crashed ? "crash" : "timedout", 0);
653 $durations{$test} = time - $startTime if $report10Slowest;
657 if (!$resetResults && open EXPECTED, "<", "$expectedDir/$expectedFileName") {
660 next if $stripEditingCallbacks && $_ =~ /^EDITING DELEGATE:/;
666 if (!isAppleMacWebKit() && $strictTesting && !$isText) {
667 if (!$resetResults && open EXPECTED, "<", "$testDirectory/platform/mac/$expectedFileName") {
676 if ($shouldCheckLeaks && $testsPerDumpTool == 1) {
682 my $diffPercentage = "";
683 my $diffResult = "passed";
686 my $expectedHash = "";
687 my $actualPNGSize = 0;
691 if (/ActualHash: ([a-f0-9]{32})/) {
693 } elsif (/ExpectedHash: ([a-f0-9]{32})/) {
695 } elsif (/Content-Length: (\d+)\s*/) {
697 read(IN, $actualPNG, $actualPNGSize);
701 if ($verbose && $pixelTests && !$resetResults && $actualPNGSize) {
702 if ($actualHash eq "" && $expectedHash eq "") {
703 printFailureMessageForTest($test, "WARNING: actual & expected pixel hashes are missing!");
704 } elsif ($actualHash eq "") {
705 printFailureMessageForTest($test, "WARNING: actual pixel hash is missing!");
706 } elsif ($expectedHash eq "") {
707 printFailureMessageForTest($test, "WARNING: expected pixel hash is missing!");
711 if ($actualPNGSize > 0) {
712 my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
714 if (!$resetResults && ($expectedHash ne $actualHash || ($actualHash eq "" && $expectedHash eq ""))) {
715 if (-f "$expectedPixelDir/$base-$expectedTag.png") {
716 my $expectedPNGSize = -s "$expectedPixelDir/$base-$expectedTag.png";
717 my $expectedPNG = "";
718 open EXPECTEDPNG, "$expectedPixelDir/$base-$expectedTag.png";
719 read(EXPECTEDPNG, $expectedPNG, $expectedPNGSize);
722 print DIFFOUT "Content-Length: $actualPNGSize\n";
723 print DIFFOUT $actualPNG;
725 print DIFFOUT "Content-Length: $expectedPNGSize\n";
726 print DIFFOUT $expectedPNG;
729 last if /^error/ || /^diff:/;
730 if (/Content-Length: (\d+)\s*/) {
731 read(DIFFIN, $diffPNG, $1);
735 if (/^diff: (.+)% (passed|failed)/) {
736 $diffPercentage = $1;
737 $imageDifferences{$base} = $diffPercentage;
741 if ($diffPercentage == 0) {
742 printFailureMessageForTest($test, "pixel hash failed (but pixel test still passes)");
745 printFailureMessageForTest($test, "WARNING: expected image is missing!");
749 if ($resetResults || !-f "$expectedPixelDir/$base-$expectedTag.png") {
750 mkpath catfile($expectedPixelDir, dirname($base)) if $testDirectory ne $expectedPixelDir;
751 writeToFile("$expectedPixelDir/$base-$expectedTag.png", $actualPNG);
754 if ($actualHash ne "" && ($resetResults || !-f "$expectedPixelDir/$base-$expectedTag.checksum")) {
755 writeToFile("$expectedPixelDir/$base-$expectedTag.checksum", $actualHash);
759 if (!isAppleMacWebKit() && $strictTesting && !$isText) {
760 if (defined $expectedMac) {
761 my $simplified_actual;
762 $simplified_actual = $actual;
763 $simplified_actual =~ s/at \(-?[0-9]+,-?[0-9]+\) *//g;
764 $simplified_actual =~ s/size -?[0-9]+x-?[0-9]+ *//g;
765 $simplified_actual =~ s/text run width -?[0-9]+: //g;
766 $simplified_actual =~ s/text run width -?[0-9]+ [a-zA-Z ]+: //g;
767 $simplified_actual =~ s/RenderButton {BUTTON} .*/RenderButton {BUTTON}/g;
768 $simplified_actual =~ s/RenderImage {INPUT} .*/RenderImage {INPUT}/g;
769 $simplified_actual =~ s/RenderBlock {INPUT} .*/RenderBlock {INPUT}/g;
770 $simplified_actual =~ s/RenderTextControl {INPUT} .*/RenderTextControl {INPUT}/g;
771 $simplified_actual =~ s/\([0-9]+px/px/g;
772 $simplified_actual =~ s/ *" *\n +" */ /g;
773 $simplified_actual =~ s/" +$/"/g;
775 $simplified_actual =~ s/- /-/g;
776 $simplified_actual =~ s/\n( *)"\s+/\n$1"/g;
777 $simplified_actual =~ s/\s+"\n/"\n/g;
779 $expectedMac =~ s/at \(-?[0-9]+,-?[0-9]+\) *//g;
780 $expectedMac =~ s/size -?[0-9]+x-?[0-9]+ *//g;
781 $expectedMac =~ s/text run width -?[0-9]+: //g;
782 $expectedMac =~ s/text run width -?[0-9]+ [a-zA-Z ]+: //g;
783 $expectedMac =~ s/RenderButton {BUTTON} .*/RenderButton {BUTTON}/g;
784 $expectedMac =~ s/RenderImage {INPUT} .*/RenderImage {INPUT}/g;
785 $expectedMac =~ s/RenderBlock {INPUT} .*/RenderBlock {INPUT}/g;
786 $expectedMac =~ s/RenderTextControl {INPUT} .*/RenderTextControl {INPUT}/g;
787 $expectedMac =~ s/\([0-9]+px/px/g;
788 $expectedMac =~ s/ *" *\n +" */ /g;
789 $expectedMac =~ s/" +$/"/g;
791 $expectedMac =~ s/- /-/g;
792 $expectedMac =~ s/\n( *)"\s+/\n$1"/g;
793 $expectedMac =~ s/\s+"\n/"\n/g;
795 if ($simplified_actual ne $expectedMac) {
796 writeToFile("/tmp/actual.txt", $simplified_actual);
797 writeToFile("/tmp/expected.txt", $expectedMac);
798 system "diff -u \"/tmp/expected.txt\" \"/tmp/actual.txt\" > \"/tmp/simplified.diff\"";
800 $diffResult = "failed";
803 system "cat /tmp/simplified.diff";
810 if (dumpToolDidCrash()) {
812 testCrashedOrTimedOut($test, $base, 1, $actual, $error);
813 } elsif (!defined $expected) {
815 print "new " . ($resetResults ? "result" : "test") ."\n";
820 if ($generateNewResults || $resetResults) {
821 mkpath catfile($expectedDir, dirname($base)) if $testDirectory ne $expectedDir;
822 writeToFile("$expectedDir/$expectedFileName", $actual);
824 deleteExpectedAndActualResults($base);
825 if ($generateNewResults && !$resetResults) {
826 # Always print the file name for new tests, as they will probably need some manual inspection.
827 # in verbose mode we already printed the test case, so no need to do it again.
829 print "\n" unless $atLineStart;
832 my $resultsDir = catdir($expectedDir, dirname($base));
833 print "new (results generated in $resultsDir)\n";
836 } elsif ($actual eq $expected && $diffResult eq "passed") {
842 deleteExpectedAndActualResults($base);
844 $result = "mismatch";
846 my $pixelTestFailed = $pixelTests && $diffPNG && $diffPNG ne "";
847 my $testFailed = $actual ne $expected;
849 my $message = !$testFailed ? "pixel test failed" : "failed";
851 if (($testFailed || $pixelTestFailed) && $addPlatformExceptions) {
852 my $testBase = catfile($testDirectory, $base);
853 my $expectedBase = catfile($expectedDir, $base);
854 my $testIsMaximallyPlatformSpecific = $testBase =~ m|^\Q$platformTestDirectory\E/|;
855 my $expectedResultIsMaximallyPlatformSpecific = $expectedBase =~ m|^\Q$platformTestDirectory\E/|;
856 if (!$testIsMaximallyPlatformSpecific && !$expectedResultIsMaximallyPlatformSpecific) {
857 mkpath catfile($platformTestDirectory, dirname($base));
859 my $expectedFile = catfile($platformTestDirectory, "$expectedFileName");
860 writeToFile("$expectedFile", $actual);
862 if ($pixelTestFailed) {
863 my $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.checksum");
864 writeToFile("$expectedFile", $actualHash);
866 $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.png");
867 writeToFile("$expectedFile", $actualPNG);
869 $message .= " (results generated in $platformTestDirectory)";
873 printFailureMessageForTest($test, $message);
875 my $dir = "$testResultsDirectory/$base";
876 $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
880 deleteExpectedAndActualResults($base);
881 recordActualResultsAndDiff($base, $actual);
883 if ($pixelTestFailed) {
884 $imagesPresent{$base} = 1;
886 writeToFile("$testResultsDirectory/$base-$actualTag.png", $actualPNG);
887 writeToFile("$testResultsDirectory/$base-$diffsTag.png", $diffPNG);
889 my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
890 copy("$expectedPixelDir/$base-$expectedTag.png", "$testResultsDirectory/$base-$expectedTag.png");
892 open DIFFHTML, ">$testResultsDirectory/$base-$diffsTag.html" or die;
893 print DIFFHTML "<html>\n";
894 print DIFFHTML "<head>\n";
895 print DIFFHTML "<title>$base Image Compare</title>\n";
896 print DIFFHTML "<script language=\"Javascript\" type=\"text/javascript\">\n";
897 print DIFFHTML "var currentImage = 0;\n";
898 print DIFFHTML "var imageNames = new Array(\"Actual\", \"Expected\");\n";
899 print DIFFHTML "var imagePaths = new Array(\"$testName-$actualTag.png\", \"$testName-$expectedTag.png\");\n";
900 if (-f "$testDirectory/$base-w3c.png") {
901 copy("$testDirectory/$base-w3c.png", "$testResultsDirectory/$base-w3c.png");
902 print DIFFHTML "imageNames.push(\"W3C\");\n";
903 print DIFFHTML "imagePaths.push(\"$testName-w3c.png\");\n";
905 print DIFFHTML "function animateImage() {\n";
906 print DIFFHTML " var image = document.getElementById(\"animatedImage\");\n";
907 print DIFFHTML " var imageText = document.getElementById(\"imageText\");\n";
908 print DIFFHTML " image.src = imagePaths[currentImage];\n";
909 print DIFFHTML " imageText.innerHTML = imageNames[currentImage] + \" Image\";\n";
910 print DIFFHTML " currentImage = (currentImage + 1) % imageNames.length;\n";
911 print DIFFHTML " setTimeout('animateImage()',2000);\n";
912 print DIFFHTML "}\n";
913 print DIFFHTML "</script>\n";
914 print DIFFHTML "</head>\n";
915 print DIFFHTML "<body onLoad=\"animateImage();\">\n";
916 print DIFFHTML "<table>\n";
917 if ($diffPercentage) {
918 print DIFFHTML "<tr>\n";
919 print DIFFHTML "<td>Difference between images: <a href=\"$testName-$diffsTag.png\">$diffPercentage%</a></td>\n";
920 print DIFFHTML "</tr>\n";
922 print DIFFHTML "<tr>\n";
923 print DIFFHTML "<td><a href=\"" . toURL("$testDirectory/$test") . "\">test file</a></td>\n";
924 print DIFFHTML "</tr>\n";
925 print DIFFHTML "<tr>\n";
926 print DIFFHTML "<td id=\"imageText\" style=\"text-weight: bold;\">Actual Image</td>\n";
927 print DIFFHTML "</tr>\n";
928 print DIFFHTML "<tr>\n";
929 print DIFFHTML "<td><img src=\"$testName-$actualTag.png\" id=\"animatedImage\"></td>\n";
930 print DIFFHTML "</tr>\n";
931 print DIFFHTML "</table>\n";
932 print DIFFHTML "</body>\n";
933 print DIFFHTML "</html>\n";
938 my $dir = "$testResultsDirectory/$base";
939 $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
942 writeToFile("$testResultsDirectory/$base-$errorTag.txt", $error);
945 push @{$tests{error}}, $test;
948 countFinishedTest($test, $base, $result, $isText);
950 printf "\n%0.2fs total testing time\n", (time - $overallStartTime) . "";
952 !$isDumpToolOpen || die "Failed to close $dumpToolName.\n";
956 # Because multiple instances of this script are running concurrently we cannot
957 # safely delete this symlink.
958 # system "rm /tmp/LayoutTests";
960 # FIXME: Do we really want to check the image-comparison tool for leaks every time?
961 if ($isDiffToolOpen && $shouldCheckLeaks) {
962 $totalLeaks += countAndPrintLeaks("ImageDiff", $imageDiffToolPID, "$testResultsDirectory/ImageDiff-leaks.txt");
967 parseLeaksandPrintUniqueLeaks();
970 print "\nWARNING: $totalLeaks total leaks found!\n";
971 print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
979 if ($report10Slowest) {
980 print "\n\nThe 10 slowest tests:\n\n";
982 for my $test (sort slowestcmp keys %durations) {
983 printf "%0.2f secs: %s\n", $durations{$test}, $test;
984 last if ++$count == 10;
990 if ($skippedOnly && $counts{"match"}) {
991 print "The following tests are in the Skipped file (" . File::Spec->abs2rel("$platformTestDirectory/Skipped", $testDirectory) . "), but succeeded:\n";
992 foreach my $test (@{$tests{"match"}}) {
997 if ($resetResults || ($counts{match} && $counts{match} == $count)) {
998 print "all $count test cases succeeded\n";
1005 match => "succeeded",
1006 mismatch => "had incorrect layout",
1008 timedout => "timed out",
1010 error => "had stderr output"
1013 for my $type ("match", "mismatch", "new", "timedout", "crash", "error") {
1014 my $c = $counts{$type};
1016 my $t = $text{$type};
1020 $message = sprintf "1 test case (%d%%) %s\n", 1 * 100 / $count, $t;
1022 $message = sprintf "%d test cases (%d%%) %s\n", $c, $c * 100 / $count, $t;
1024 $message =~ s-\(0%\)-(<1%)-;
1029 mkpath $testResultsDirectory;
1031 open HTML, ">", $testResults or die "Failed to open $testResults. $!";
1032 print HTML "<html>\n";
1033 print HTML "<head>\n";
1034 print HTML "<title>Layout Test Results</title>\n";
1035 print HTML "</head>\n";
1036 print HTML "<body>\n";
1038 print HTML htmlForResultsSection(@{$tests{mismatch}}, "Tests where results did not match expected results", \&linksForMismatchTest);
1039 print HTML htmlForResultsSection(@{$tests{timedout}}, "Tests that timed out", \&linksForErrorTest);
1040 print HTML htmlForResultsSection(@{$tests{crash}}, "Tests that caused the DumpRenderTree tool to crash", \&linksForErrorTest);
1041 print HTML htmlForResultsSection(@{$tests{error}}, "Tests that had stderr output", \&linksForErrorTest);
1042 print HTML htmlForResultsSection(@{$tests{new}}, "Tests that had no expected results (probably new)", \&linksForNewTest);
1044 print HTML "</body>\n";
1045 print HTML "</html>\n";
1048 my @configurationArgs = argumentsForConfiguration();
1050 if (isQt() || isGtk()) {
1051 system "WebKitTools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
1052 } elsif (isCygwin()) {
1053 system "cygstart", $testResults if $launchSafari;
1055 system "WebKitTools/Scripts/run-safari", @configurationArgs, "-NSOpen", $testResults if $launchSafari;
1058 closeCygpaths() if isCygwin();
1062 sub countAndPrintLeaks($$$)
1064 my ($dumpToolName, $dumpToolPID, $leaksFilePath) = @_;
1066 print "\n" unless $atLineStart;
1069 # We are excluding the following reported leaks so they don't get in our way when looking for WebKit leaks:
1070 # This allows us ignore known leaks and only be alerted when new leaks occur. Some leaks are in the old
1071 # versions of the system frameworks that are being used by the leaks bots. Even though a leak has been
1072 # fixed, it will be listed here until the bot has been updated with the newer frameworks.
1074 my @typesToExclude = (
1077 my @callStacksToExclude = (
1078 "Flash_EnforceLocalSecurity" # leaks in Flash plug-in code, rdar://problem/4449747
1082 # Leak list for the version of Tiger used on the build bot.
1083 push @callStacksToExclude, (
1084 "CFRunLoopRunSpecific \\| malloc_zone_malloc", "CFRunLoopRunSpecific \\| CFAllocatorAllocate ", # leak in CFRunLoopRunSpecific, rdar://problem/4670839
1085 "CGImageSourceGetPropertiesAtIndex", # leak in ImageIO, rdar://problem/4628809
1086 "FOGetCoveredUnicodeChars", # leak in ATS, rdar://problem/3943604
1087 "GetLineDirectionPreference", "InitUnicodeUtilities", # leaks tool falsely reporting leak in CFNotificationCenterAddObserver, rdar://problem/4964790
1088 "ICCFPrefWrapper::GetPrefDictionary", # leaks in Internet Config. code, rdar://problem/4449794
1089 "NSHTTPURLProtocol setResponseHeader:", # leak in multipart/mixed-replace handling in Foundation, no Radar, but fixed in Leopard
1090 "NSURLCache cachedResponseForRequest", # leak in CFURL cache, rdar://problem/4768430
1091 "PCFragPrepareClosureFromFile", # leak in Code Fragment Manager, rdar://problem/3426998
1092 "WebCore::Selection::toRange", # bug in 'leaks', rdar://problem/4967949
1093 "WebCore::SubresourceLoader::create", # bug in 'leaks', rdar://problem/4985806
1094 "_CFPreferencesDomainDeepCopyDictionary", # leak in CFPreferences, rdar://problem/4220786
1095 "_objc_msgForward", # leak in NSSpellChecker, rdar://problem/4965278
1096 "gldGetString", # leak in OpenGL, rdar://problem/5013699
1097 "_setDefaultUserInfoFromURL", # leak in NSHTTPAuthenticator, rdar://problem/5546453
1098 "SSLHandshake", # leak in SSL, rdar://problem/5546440
1099 "SecCertificateCreateFromData", # leak in SSL code, rdar://problem/4464397
1101 push @typesToExclude, (
1102 "THRD", # bug in 'leaks', rdar://problem/3387783
1103 "DRHT", # ditto (endian little hate i)
1108 # Leak list for the version of Leopard used on the build bot.
1109 push @callStacksToExclude, (
1110 "CFHTTPMessageAppendBytes", # leak in CFNetwork, rdar://problem/5435912
1111 "sendDidReceiveDataCallback", # leak in CFNetwork, rdar://problem/5441619
1112 "_CFHTTPReadStreamReadMark", # leak in CFNetwork, rdar://problem/5441468
1113 "httpProtocolStart", # leak in CFNetwork, rdar://problem/5468837
1114 "_CFURLConnectionSendCallbacks", # leak in CFNetwork, rdar://problem/5441600
1115 "DispatchQTMsg", # leak in QuickTime, PPC only, rdar://problem/5667132
1116 "QTMovieContentView createVisualContext", # leak in QuickTime, PPC only, rdar://problem/5667132
1117 "_CopyArchitecturesForJVMVersion", # leak in Java, rdar://problem/5910823
1121 my $leaksTool = sourceDir() . "/WebKitTools/Scripts/run-leaks";
1122 my $excludeString = "--exclude-callstack '" . (join "' --exclude-callstack '", @callStacksToExclude) . "'";
1123 $excludeString .= " --exclude-type '" . (join "' --exclude-type '", @typesToExclude) . "'" if @typesToExclude;
1125 print " ? checking for leaks in $dumpToolName\n";
1126 my $leaksOutput = `$leaksTool $excludeString $dumpToolPID`;
1127 my ($count, $bytes) = $leaksOutput =~ /Process $dumpToolPID: (\d+) leaks? for (\d+) total/;
1128 my ($excluded) = $leaksOutput =~ /(\d+) leaks? excluded/;
1130 my $adjustedCount = $count;
1131 $adjustedCount -= $excluded if $excluded;
1133 if (!$adjustedCount) {
1134 print " - no leaks found\n";
1135 unlink $leaksFilePath;
1138 my $dir = $leaksFilePath;
1139 $dir =~ s|/[^/]+$|| or die;
1143 print " + $adjustedCount leaks ($bytes bytes including $excluded excluded leaks) were found, details in $leaksFilePath\n";
1145 print " + $count leaks ($bytes bytes) were found, details in $leaksFilePath\n";
1148 writeToFile($leaksFilePath, $leaksOutput);
1150 push( @leaksFilenames, $leaksFilePath );
1153 return $adjustedCount;
1158 my ($filePath, $contents) = @_;
1159 open NEWFILE, ">", "$filePath" or die "could not create $filePath\n";
1160 print NEWFILE $contents;
1164 # Break up a path into the directory (with slash) and base name.
1169 my $pathSeparator = "/";
1170 my $dirname = dirname($path) . $pathSeparator;
1171 $dirname = "" if $dirname eq "." . $pathSeparator;
1173 return ($dirname, basename($path));
1176 # Sort first by directory, then by file, so all paths in one directory are grouped
1177 # rather than being interspersed with items from subdirectories.
1178 # Use numericcmp to sort directory and filenames to make order logical.
1181 my ($patha, $pathb) = @_;
1183 my ($dira, $namea) = splitpath($patha);
1184 my ($dirb, $nameb) = splitpath($pathb);
1186 return numericcmp($dira, $dirb) if $dira ne $dirb;
1187 return numericcmp($namea, $nameb);
1190 # Sort numeric parts of strings as numbers, other parts as strings.
1191 # Makes 1.33 come after 1.3, which is cool.
1196 my @a = split /(\d+)/, $aa;
1197 my @b = split /(\d+)/, $bb;
1199 # Compare one chunk at a time.
1200 # Each chunk is either all numeric digits, or all not numeric digits.
1205 # Use numeric comparison if chunks are non-equal numbers.
1206 return $a <=> $b if $a =~ /^\d/ && $b =~ /^\d/ && $a != $b;
1208 # Use string comparison if chunks are any other kind of non-equal string.
1209 return $a cmp $b if $a ne $b;
1212 # One of the two is now empty; compare lengths for result in this case.
1216 # Sort slowest tests first.
1219 my ($testa, $testb) = @_;
1221 my $dura = $durations{$testa};
1222 my $durb = $durations{$testb};
1223 return $durb <=> $dura if $dura != $durb;
1224 return pathcmp($testa, $testb);
1227 sub launchWithCurrentEnv(@)
1231 # Dump the current environment as perl code and then put it in quotes so it is one parameter.
1232 my $environmentDumper = Data::Dumper->new([\%ENV], [qw(*ENV)]);
1233 $environmentDumper->Indent(0);
1234 $environmentDumper->Purity(1);
1235 my $allEnvVars = $environmentDumper->Dump();
1236 unshift @args, "\"$allEnvVars\"";
1238 my $execScript = File::Spec->catfile(sourceDir(), qw(WebKitTools Scripts execAppWithEnv));
1239 unshift @args, $execScript;
1245 return if $isDiffToolOpen;
1246 return if !$pixelTests;
1249 $ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
1250 $imageDiffToolPID = open2(\*DIFFIN, \*DIFFOUT, $imageDiffTool, launchWithCurrentEnv(@diffToolArgs)) or die "unable to open $imageDiffTool\n";
1251 $ENV{MallocStackLogging} = 0 if $shouldCheckLeaks;
1252 $isDiffToolOpen = 1;
1257 return if $isDumpToolOpen;
1259 # Save environment variables required for the linux environment.
1260 my $homeDir = $ENV{'HOME'};
1261 my $libraryPath = $ENV{'LD_LIBRARY_PATH'};
1262 my $dyldLibraryPath = $ENV{'DYLD_LIBRARY_PATH'};
1263 my $dbusAddress = $ENV{'DBUS_SESSION_BUS_ADDRESS'};
1264 my $display = $ENV{'DISPLAY'};
1265 my $testfonts = $ENV{'WEBKIT_TESTFONTS'};
1267 my $homeDrive = $ENV{'HOMEDRIVE'};
1268 my $homePath = $ENV{'HOMEPATH'};
1271 if (isQt() || isGtk()) {
1272 if (defined $display) {
1273 $ENV{DISPLAY} = $display;
1275 $ENV{DISPLAY} = ":1";
1277 $ENV{'WEBKIT_TESTFONTS'} = $testfonts if defined($testfonts);
1278 $ENV{HOME} = $homeDir;
1279 if (defined $libraryPath) {
1280 $ENV{LD_LIBRARY_PATH} = $libraryPath;
1282 if (defined $dyldLibraryPath) {
1283 $ENV{DYLD_LIBRARY_PATH} = $dyldLibraryPath;
1285 if (defined $dbusAddress) {
1286 $ENV{DBUS_SESSION_BUS_ADDRESS} = $dbusAddress;
1289 $ENV{DYLD_FRAMEWORK_PATH} = $productDir;
1290 $ENV{XML_CATALOG_FILES} = ""; # work around missing /etc/catalog <rdar://problem/4292995>
1291 $ENV{DYLD_INSERT_LIBRARIES} = "/usr/lib/libgmalloc.dylib" if $guardMalloc;
1294 $ENV{HOMEDRIVE} = $homeDrive;
1295 $ENV{HOMEPATH} = $homePath;
1297 $ENV{WEBKIT_TESTFONTS} = $testfonts;
1299 setPathForRunningWebKitApp(\%ENV) if isCygwin();
1302 my @args = ($dumpTool, @toolArgs);
1303 if (isAppleMacWebKit() and !isTiger()) {
1304 unshift @args, "arch", "-" . architecture();
1308 unshift @args, "valgrind";
1311 $ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
1312 $dumpToolPID = open3(\*OUT, \*IN, \*ERROR, launchWithCurrentEnv(@args)) or die "Failed to start tool: $dumpTool\n";
1313 $ENV{MallocStackLogging} = 0 if $shouldCheckLeaks;
1314 $isDumpToolOpen = 1;
1315 $dumpToolCrashed = 0;
1320 return if !$isDumpToolOpen;
1324 waitpid $dumpToolPID, 0;
1326 # check for WebCore counter leaks.
1327 if ($shouldCheckLeaks) {
1333 $isDumpToolOpen = 0;
1336 sub dumpToolDidCrash()
1338 return 1 if $dumpToolCrashed;
1339 return 0 unless $isDumpToolOpen;
1341 my $pid = waitpid(-1, WNOHANG);
1342 return 1 if ($pid == $dumpToolPID);
1344 # On Mac OS X, crashing may be significantly delayed by crash reporter.
1345 return 0 unless isAppleMacWebKit();
1347 my $tryingToExit = 0;
1348 open PS, "ps -o state -p $dumpToolPID |";
1350 $tryingToExit = 1 if <PS> =~ /E/;
1352 return $tryingToExit;
1355 sub openHTTPDIfNeeded()
1357 return if $isHttpdOpen;
1359 mkdir "/tmp/WebKit";
1361 if (-f "/tmp/WebKit/httpd.pid") {
1362 my $oldPid = `cat /tmp/WebKit/httpd.pid`;
1364 if (0 != kill 0, $oldPid) {
1365 print "\nhttpd is already running: pid $oldPid, killing...\n";
1368 my $retryCount = 20;
1369 while ((0 != kill 0, $oldPid) && $retryCount) {
1374 die "Timed out waiting for httpd to quit" unless $retryCount;
1378 my $httpdPath = "/usr/sbin/httpd";
1381 my $windowsConfDirectory = "$testDirectory/http/conf/";
1382 unless (-x "/usr/lib/apache/libphp4.dll") {
1383 copy("$windowsConfDirectory/libphp4.dll", "/usr/lib/apache/libphp4.dll");
1384 chmod(0755, "/usr/lib/apache/libphp4.dll");
1386 $httpdConfig = "$windowsConfDirectory/cygwin-httpd.conf";
1387 } elsif (isDebianBased()) {
1388 $httpdPath = "/usr/sbin/apache2";
1389 $httpdConfig = "$testDirectory/http/conf/apache2-debian-httpd.conf";
1391 $httpdConfig = "$testDirectory/http/conf/httpd.conf";
1392 $httpdConfig = "$testDirectory/http/conf/apache2-httpd.conf" if `$httpdPath -v` =~ m|Apache/2|;
1394 my $documentRoot = "$testDirectory/http/tests";
1395 my $jsTestResourcesDirectory = $testDirectory . "/fast/js/resources";
1396 my $typesConfig = "$testDirectory/http/conf/mime.types";
1397 my $listen = "127.0.0.1:$httpdPort";
1398 my $absTestResultsDirectory = File::Spec->rel2abs(glob $testResultsDirectory);
1399 my $sslCertificate = "$testDirectory/http/conf/webkit-httpd.pem";
1401 mkpath $absTestResultsDirectory;
1404 "-f", "$httpdConfig",
1405 "-C", "DocumentRoot \"$documentRoot\"",
1406 # Setup a link to where the js test templates are stored, use -c so that mod_alias will already be laoded.
1407 "-c", "Alias /js-test-resources \"$jsTestResourcesDirectory\"",
1408 "-C", "Listen $listen",
1409 "-c", "TypesConfig \"$typesConfig\"",
1410 "-c", "CustomLog \"$absTestResultsDirectory/access_log.txt\" common",
1411 "-c", "ErrorLog \"$absTestResultsDirectory/error_log.txt\"",
1412 # Apache wouldn't run CGIs with permissions==700 otherwise
1413 "-c", "User \"#$<\""
1416 # FIXME: Enable this on Windows once <rdar://problem/5345985> is fixed
1417 # The version of Apache we use with Cygwin does not support SSL
1418 push(@args, "-c", "SSLCertificateFile \"$sslCertificate\"") unless isCygwin();
1420 open2(\*HTTPDIN, \*HTTPDOUT, $httpdPath, @args);
1422 my $retryCount = 20;
1423 while (system("/usr/bin/curl -q --silent --stderr - --output /dev/null $listen") && $retryCount) {
1428 die "Timed out waiting for httpd to start" unless $retryCount;
1435 return if !$isHttpdOpen;
1440 kill 15, `cat /tmp/WebKit/httpd.pid` if -f "/tmp/WebKit/httpd.pid";
1445 sub fileNameWithNumber($$)
1447 my ($base, $number) = @_;
1448 return "$base$number" if ($number > 1);
1452 sub processIgnoreTests($$) {
1453 my @ignoreList = split(/\s*,\s*/, shift);
1454 my $listName = shift;
1456 my $disabledSuffix = "-disabled";
1458 my $addIgnoredDirectories = sub {
1459 return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
1460 $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)} = 1;
1463 foreach my $item (@ignoreList) {
1464 my $path = catfile($testDirectory, $item);
1466 $ignoredDirectories{$item} = 1;
1467 find({ preprocess => $addIgnoredDirectories, wanted => sub {} }, $path);
1470 $ignoredFiles{$item} = 1;
1471 } elsif (-f $path . $disabledSuffix) {
1472 # The test is disabled, so do nothing.
1474 print "$listName list contained '$item', but no file of that name could be found\n";
1479 sub stripExtension($)
1483 $test =~ s/\.[a-zA-Z]+$//;
1487 sub isTextOnlyTest($)
1491 if ($actual =~ /^layer at/ms) {
1499 sub expectedDirectoryForTest($;$;$)
1501 my ($base, $isText, $expectedExtension) = @_;
1503 my @directories = @platformResultHierarchy;
1504 push @directories, map { catdir($platformBaseDirectory, $_) } qw(mac-snowleopard mac) if isCygwin();
1505 push @directories, $expectedDirectory;
1507 # If we already have expected results, just return their location.
1508 foreach my $directory (@directories) {
1509 return $directory if (-f "$directory/$base-$expectedTag.$expectedExtension");
1512 # For cross-platform tests, text-only results should go in the cross-platform directory,
1513 # while render tree dumps should go in the least-specific platform directory.
1514 return $isText ? $expectedDirectory : $platformResultHierarchy[$#platformResultHierarchy];
1517 sub countFinishedTest($$$$) {
1518 my ($test, $base, $result, $isText) = @_;
1520 if (($count + 1) % $testsPerDumpTool == 0 || $count == $#tests) {
1521 if ($shouldCheckLeaks) {
1523 if ($testsPerDumpTool == 1) {
1524 $fileName = "$testResultsDirectory/$base-leaks.txt";
1526 $fileName = "$testResultsDirectory/" . fileNameWithNumber($dumpToolName, $leaksOutputFileNumber) . "-leaks.txt";
1528 my $leakCount = countAndPrintLeaks($dumpToolName, $dumpToolPID, $fileName);
1529 $totalLeaks += $leakCount;
1530 $leaksOutputFileNumber++ if ($leakCount);
1538 push @{$tests{$result}}, $test;
1539 $testType{$test} = $isText;
1542 sub testCrashedOrTimedOut($$$$$)
1544 my ($test, $base, $didCrash, $actual, $error) = @_;
1546 printFailureMessageForTest($test, $didCrash ? "crashed" : "timed out");
1548 sampleDumpTool() unless $didCrash;
1550 my $dir = "$testResultsDirectory/$base";
1551 $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
1554 deleteExpectedAndActualResults($base);
1556 if (defined($error) && length($error)) {
1557 writeToFile("$testResultsDirectory/$base-$errorTag.txt", $error);
1560 recordActualResultsAndDiff($base, $actual);
1562 kill 9, $dumpToolPID unless $didCrash;
1567 sub printFailureMessageForTest($$)
1569 my ($test, $description) = @_;
1572 print "\n" unless $atLineStart;
1575 print "$description\n";
1581 sub openCygpathIfNeeded($)
1585 return unless isCygwin();
1586 return $cygpaths{$options} if $cygpaths{$options} && $cygpaths{$options}->{"open"};
1588 local (*CYGPATHIN, *CYGPATHOUT);
1589 my $pid = open2(\*CYGPATHIN, \*CYGPATHOUT, "cygpath -f - $options");
1593 "out" => *CYGPATHOUT,
1597 $cygpaths{$options} = $cygpath;
1604 return unless isCygwin();
1606 foreach my $cygpath (values(%cygpaths)) {
1607 close $cygpath->{"in"};
1608 close $cygpath->{"out"};
1609 waitpid($cygpath->{"pid"}, 0);
1610 $cygpath->{"open"} = 0;
1615 sub convertPathUsingCygpath($$)
1617 my ($path, $options) = @_;
1619 my $cygpath = openCygpathIfNeeded($options);
1620 local *inFH = $cygpath->{"in"};
1621 local *outFH = $cygpath->{"out"};
1622 print outFH $path . "\n";
1623 chomp(my $convertedPath = <inFH>);
1624 return $convertedPath;
1627 sub toWindowsPath($)
1630 return unless isCygwin();
1632 return convertPathUsingCygpath($path, "-w");
1639 if ($useRemoteLinksToTests) {
1640 my $relativePath = File::Spec->abs2rel($path, $testDirectory);
1642 # If the file is below the test directory then convert it into a link to the file in SVN
1643 if ($relativePath !~ /^\.\.\//) {
1644 my $revision = svnRevisionForDirectory($testDirectory);
1645 my $svnPath = pathRelativeToSVNRepositoryRootForPath($path);
1646 return "http://trac.webkit.org/export/$revision/$svnPath";
1650 return $path unless isCygwin();
1652 return "file:///" . convertPathUsingCygpath($path, "-m");
1655 sub validateSkippedArg($$;$)
1657 my ($option, $value, $value2) = @_;
1658 my %validSkippedValues = map { $_ => 1 } qw(default ignore only);
1659 $value = lc($value);
1660 die "Invalid argument '" . $value . "' for option $option" unless $validSkippedValues{$value};
1661 $treatSkipped = $value;
1664 sub htmlForResultsSection(\@$&)
1666 my ($tests, $description, $linkGetter) = @_;
1669 return join("\n", @html) unless @{$tests};
1671 push @html, "<p>$description:</p>";
1672 push @html, "<table>";
1673 foreach my $test (@{$tests}) {
1675 push @html, "<td><a href=\"" . toURL("$testDirectory/$test") . "\">$test</a></td>";
1676 foreach my $link (@{&{$linkGetter}($test)}) {
1677 push @html, "<td><a href=\"$link->{href}\">$link->{text}</a></td>";
1679 push @html, "</tr>";
1681 push @html, "</table>";
1683 return join("\n", @html);
1686 sub linksForExpectedAndActualResults($)
1692 return \@links unless -s "$testResultsDirectory/$base-$diffsTag.txt";
1694 my $expectedResultPath = $expectedResultPaths{$base};
1695 my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
1697 push @links, { href => "$base-$expectedTag$expectedResultExtension", text => "expected" };
1698 push @links, { href => "$base-$actualTag$expectedResultExtension", text => "actual" };
1699 push @links, { href => "$base-$diffsTag.txt", text => "diff" };
1700 push @links, { href => "$base-$prettyDiffTag.html", text => "pretty diff" };
1705 sub linksForMismatchTest
1711 my $base = stripExtension($test);
1713 push @links, @{linksForExpectedAndActualResults($base)};
1714 return \@links unless $pixelTests && $imagesPresent{$base};
1716 push @links, { href => "$base-$expectedTag.png", text => "expected image" };
1717 push @links, { href => "$base-$diffsTag.html", text => "image diffs" };
1718 push @links, { href => "$base-$diffsTag.png", text => "$imageDifferences{$base}%" };
1723 sub linksForErrorTest
1729 my $base = stripExtension($test);
1731 push @links, @{linksForExpectedAndActualResults($base)};
1732 push @links, { href => "$base-$errorTag.txt", text => "stderr" };
1743 my $base = stripExtension($test);
1744 my $expectedResultPath = $expectedResultPaths{$base};
1745 my $expectedResultPathMinusExtension = stripExtension($expectedResultPath);
1747 push @links, { href => toURL($expectedResultPath), text => "results" };
1748 if ($pixelTests && -f "$expectedResultPathMinusExtension.png") {
1749 push @links, { href => toURL("$expectedResultPathMinusExtension.png"), text => "image" };
1755 sub deleteExpectedAndActualResults($)
1759 unlink "$testResultsDirectory/$base-$actualTag.txt";
1760 unlink "$testResultsDirectory/$base-$diffsTag.txt";
1761 unlink "$testResultsDirectory/$base-$errorTag.txt";
1764 sub recordActualResultsAndDiff($$)
1766 my ($base, $actualResults) = @_;
1768 return unless defined($actualResults) && length($actualResults);
1770 my $expectedResultPath = $expectedResultPaths{$base};
1771 my ($expectedResultFileNameMinusExtension, $expectedResultDirectoryPath, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
1772 my $actualResultsPath = "$testResultsDirectory/$base-$actualTag$expectedResultExtension";
1773 my $copiedExpectedResultsPath = "$testResultsDirectory/$base-$expectedTag$expectedResultExtension";
1774 writeToFile("$actualResultsPath", $actualResults);
1775 copy("$expectedResultPath", "$copiedExpectedResultsPath");
1777 my $diffOuputBasePath = "$testResultsDirectory/$base";
1778 my $diffOutputPath = "$diffOuputBasePath-$diffsTag.txt";
1779 system "diff -u \"$copiedExpectedResultsPath\" \"$actualResultsPath\" > \"$diffOutputPath\"";
1781 my $prettyDiffOutputPath = "$diffOuputBasePath-$prettyDiffTag.html";
1782 my $prettyPatchPath = "BugsSite/PrettyPatch/";
1783 my $prettifyPath = "$prettyPatchPath/prettify.rb";
1784 system "ruby -I \"$prettyPatchPath\" \"$prettifyPath\" \"$diffOutputPath\" > \"$prettyDiffOutputPath\"";
1787 sub buildPlatformResultHierarchy()
1789 mkpath($platformTestDirectory) if ($platform eq "undefined" && !-d "$platformTestDirectory");
1792 if ($platform =~ /^mac-/) {
1794 for ($i = 0; $i < @macPlatforms; $i++) {
1795 last if $macPlatforms[$i] eq $platform;
1797 for (; $i < @macPlatforms; $i++) {
1798 push @platforms, $macPlatforms[$i];
1801 @platforms = $platform;
1805 for (my $i = 0; $i < @platforms; $i++) {
1806 my $scoped = catdir($platformBaseDirectory, $platforms[$i]);
1807 push(@hierarchy, $scoped) if (-d $scoped);
1813 sub buildPlatformTestHierarchy(@)
1815 my (@platformHierarchy) = @_;
1816 return @platformHierarchy if (@platformHierarchy < 2);
1818 return ($platformHierarchy[0], $platformHierarchy[$#platformHierarchy]);
1821 sub epiloguesAndPrologues($$) {
1822 my ($lastDirectory, $directory) = @_;
1823 my @lastComponents = split('/', $lastDirectory);
1824 my @components = split('/', $directory);
1826 while (@lastComponents) {
1827 if (!defined($components[0]) || $lastComponents[0] ne $components[0]) {
1831 shift @lastComponents;
1835 my $leaving = $lastDirectory;
1836 foreach (@lastComponents) {
1837 my $epilogue = $leaving . "/resources/run-webkit-tests-epilogue.html";
1838 foreach (@platformResultHierarchy) {
1839 push @result, catdir($_, $epilogue) if (stat(catdir($_, $epilogue)));
1841 push @result, catdir($testDirectory, $epilogue) if (stat(catdir($testDirectory, $epilogue)));
1842 $leaving =~ s|(^\|/)[^/]+$||;
1845 my $entering = $leaving;
1846 foreach (@components) {
1847 $entering .= '/' . $_;
1848 my $prologue = $entering . "/resources/run-webkit-tests-prologue.html";
1849 push @result, catdir($testDirectory, $prologue) if (stat(catdir($testDirectory, $prologue)));
1850 foreach (reverse @platformResultHierarchy) {
1851 push @result, catdir($_, $prologue) if (stat(catdir($_, $prologue)));
1857 sub parseLeaksandPrintUniqueLeaks() {
1858 return unless @leaksFilenames;
1860 my $mergedFilenames = join " ", @leaksFilenames;
1861 my $parseMallocHistoryTool = sourceDir() . "/WebKitTools/Scripts/parse-malloc-history";
1863 open MERGED_LEAKS, "cat $mergedFilenames | $parseMallocHistoryTool --merge-depth $mergeDepth - |" ;
1864 my @leakLines = <MERGED_LEAKS>;
1867 my $uniqueLeakCount = 0;
1869 foreach my $line (@leakLines) {
1870 ++$uniqueLeakCount if ($line =~ /^(\d*)\scalls/);
1871 $totalBytes = $1 if $line =~ /^total\:\s(.*)\s\(/;
1874 print "\nWARNING: $totalLeaks total leaks found for a total of $totalBytes!\n";
1875 print "WARNING: $uniqueLeakCount unique leaks found!\n";
1876 print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
1880 sub extensionForMimeType($)
1882 my ($mimeType) = @_;
1884 if ($mimeType eq "application/x-webarchive") {
1885 return "webarchive";
1886 } elsif ($mimeType eq "application/pdf") {
1892 # Read up to the first #EOF (the content block of the test), or until detecting crashes or timeouts.
1893 sub readFromDumpToolWithTimer(*;$)
1895 my ($fh, $dontWaitForTimeOut) = @_;
1897 setFileHandleNonBlocking($fh, 1);
1899 my $maximumSecondsWithoutOutput = $timeoutSeconds;
1900 $maximumSecondsWithoutOutput *= 10 if $guardMalloc;
1901 my $microsecondsToWaitBeforeReadingAgain = 1000;
1903 my $timeOfLastSuccessfulRead = time;
1906 my $status = "success";
1907 my $mimeType = "text/plain";
1908 # We don't have a very good way to know when the "headers" stop
1909 # and the content starts, so we use this as a hack:
1910 my $haveSeenContentType = 0;
1913 if (time - $timeOfLastSuccessfulRead > $maximumSecondsWithoutOutput) {
1914 $status = dumpToolDidCrash() ? "crashed" : "timedOut";
1918 my $line = readline($fh);
1919 if (!defined($line)) {
1921 $status = "crashed";
1925 if ($dontWaitForTimeOut) {
1930 usleep($microsecondsToWaitBeforeReadingAgain);
1934 $timeOfLastSuccessfulRead = time;
1936 if (!$haveSeenContentType && $line =~ /^Content-Type: (\S+)$/) {
1938 $haveSeenContentType = 1;
1941 last if ($line =~ /#EOF/);
1943 push @output, $line;
1946 setFileHandleNonBlocking($fh, 0);
1948 output => join("", @output),
1950 mimeType => $mimeType,
1951 extension => extensionForMimeType($mimeType)
1955 sub setFileHandleNonBlocking(*$)
1957 my ($fh, $nonBlocking) = @_;
1959 my $flags = fcntl($fh, F_GETFL, 0) or die "Couldn't get filehandle flags";
1962 $flags |= O_NONBLOCK;
1964 $flags &= ~O_NONBLOCK;
1967 fcntl($fh, F_SETFL, $flags) or die "Couldn't set filehandle flags";
1972 sub sampleDumpTool()
1974 return unless isAppleMacWebKit();
1975 return unless $runSample;
1977 my $outputDirectory = "$ENV{HOME}/Library/Logs/DumpRenderTree";
1978 -d $outputDirectory or mkdir $outputDirectory;
1980 my $outputFile = "$outputDirectory/HangReport.txt";
1981 system "/usr/bin/sample", $dumpToolPID, qw(10 10 -file), $outputFile;