WebKitTools/Scripts/old-run-webkit-tests
changeset 0 4f2f89ce4247
equal deleted inserted replaced
-1:000000000000 0:4f2f89ce4247
       
     1 #!/usr/bin/perl
       
     2 
       
     3 # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 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.
       
     8 # Copyright (C) 2009 Andras Becsi (becsi.andras@stud.u-szeged.hu), University of Szeged
       
     9 #
       
    10 # Redistribution and use in source and binary forms, with or without
       
    11 # modification, are permitted provided that the following conditions
       
    12 # are met:
       
    13 #
       
    14 # 1.  Redistributions of source code must retain the above copyright
       
    15 #     notice, this list of conditions and the following disclaimer. 
       
    16 # 2.  Redistributions in binary form must reproduce the above copyright
       
    17 #     notice, this list of conditions and the following disclaimer in the
       
    18 #     documentation and/or other materials provided with the distribution. 
       
    19 # 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
       
    20 #     its contributors may be used to endorse or promote products derived
       
    21 #     from this software without specific prior written permission. 
       
    22 #
       
    23 # THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
       
    24 # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
       
    25 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
       
    26 # DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
       
    27 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
       
    28 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
       
    29 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
       
    30 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       
    31 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
       
    32 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    33 
       
    34 # Script to run the WebKit Open Source Project layout tests.
       
    35 
       
    36 # Run all the tests passed in on the command line.
       
    37 # If no tests are passed, find all the .html, .shtml, .xml, .xhtml, .xhtmlmp, .pl, .php (and svg) files in the test directory.
       
    38 
       
    39 # Run each text.
       
    40 # Compare against the existing file xxx-expected.txt.
       
    41 # If there is a mismatch, generate xxx-actual.txt and xxx-diffs.txt.
       
    42 
       
    43 # At the end, report:
       
    44 #   the number of tests that got the expected results
       
    45 #   the number of tests that ran, but did not get the expected results
       
    46 #   the number of tests that failed to run
       
    47 #   the number of tests that were run but had no expected results to compare against
       
    48 
       
    49 use strict;
       
    50 use warnings;
       
    51 
       
    52 use Cwd;
       
    53 use Data::Dumper;
       
    54 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
       
    55 use File::Basename;
       
    56 use File::Copy;
       
    57 use File::Find;
       
    58 use File::Path;
       
    59 use File::Spec;
       
    60 use File::Spec::Functions;
       
    61 use File::Temp;
       
    62 use FindBin;
       
    63 use Getopt::Long;
       
    64 use IPC::Open2;
       
    65 use IPC::Open3;
       
    66 use Time::HiRes qw(time usleep);
       
    67 
       
    68 use List::Util 'shuffle';
       
    69 
       
    70 use lib $FindBin::Bin;
       
    71 use webkitperl::features;
       
    72 use webkitperl::httpd;
       
    73 use webkitdirs;
       
    74 use VCSUtils;
       
    75 use POSIX;
       
    76 
       
    77 sub buildPlatformResultHierarchy();
       
    78 sub buildPlatformTestHierarchy(@);
       
    79 sub checkPythonVersion();
       
    80 sub closeCygpaths();
       
    81 sub closeDumpTool();
       
    82 sub closeWebSocketServer();
       
    83 sub configureAndOpenHTTPDIfNeeded();
       
    84 sub countAndPrintLeaks($$$);
       
    85 sub countFinishedTest($$$$);
       
    86 sub deleteExpectedAndActualResults($);
       
    87 sub dumpToolDidCrash();
       
    88 sub epiloguesAndPrologues($$);
       
    89 sub expectedDirectoryForTest($;$;$);
       
    90 sub fileNameWithNumber($$);
       
    91 sub htmlForResultsSection(\@$&);
       
    92 sub isTextOnlyTest($);
       
    93 sub launchWithEnv(\@\%);
       
    94 sub resolveAndMakeTestResultsDirectory();
       
    95 sub numericcmp($$);
       
    96 sub openDiffTool();
       
    97 sub openDumpTool();
       
    98 sub parseLeaksandPrintUniqueLeaks();
       
    99 sub openWebSocketServerIfNeeded();
       
   100 sub pathcmp($$);
       
   101 sub printFailureMessageForTest($$);
       
   102 sub processIgnoreTests($$);
       
   103 sub readFromDumpToolWithTimer(**);
       
   104 sub readSkippedFiles($);
       
   105 sub recordActualResultsAndDiff($$);
       
   106 sub sampleDumpTool();
       
   107 sub setFileHandleNonBlocking(*$);
       
   108 sub slowestcmp($$);
       
   109 sub splitpath($);
       
   110 sub stopRunningTestsEarlyIfNeeded();
       
   111 sub stripExtension($);
       
   112 sub stripMetrics($$);
       
   113 sub testCrashedOrTimedOut($$$$$);
       
   114 sub toURL($);
       
   115 sub toWindowsPath($);
       
   116 sub validateSkippedArg($$;$);
       
   117 sub writeToFile($$);
       
   118 
       
   119 # Argument handling
       
   120 my $addPlatformExceptions = 0;
       
   121 my $complexText = 0;
       
   122 my $exitAfterNFailures = 0;
       
   123 my $exitAfterNCrashesOrTimeouts = 0;
       
   124 my $generateNewResults = isAppleMacWebKit() ? 1 : 0;
       
   125 my $guardMalloc = '';
       
   126 # FIXME: Dynamic HTTP-port configuration in this file is wrong.  The various
       
   127 # apache config files in LayoutTests/http/config govern the port numbers.
       
   128 # Dynamic configuration as-written will also cause random failures in
       
   129 # an IPv6 environment.  See https://bugs.webkit.org/show_bug.cgi?id=37104.
       
   130 my $httpdPort = 8000;
       
   131 my $httpdSSLPort = 8443;
       
   132 my $ignoreMetrics = 0;
       
   133 my $webSocketPort = 8880;
       
   134 # wss is disabled until all platforms support pyOpenSSL.
       
   135 # my $webSocketSecurePort = 9323;
       
   136 my $ignoreTests = '';
       
   137 my $iterations = 1;
       
   138 my $launchSafari = 1;
       
   139 my $mergeDepth;
       
   140 my $pixelTests = '';
       
   141 my $platform;
       
   142 my $quiet = '';
       
   143 my $randomizeTests = 0;
       
   144 my $repeatEach = 1;
       
   145 my $report10Slowest = 0;
       
   146 my $resetResults = 0;
       
   147 my $reverseTests = 0;
       
   148 my $root;
       
   149 my $runSample = 1;
       
   150 my $shouldCheckLeaks = 0;
       
   151 my $showHelp = 0;
       
   152 my $stripEditingCallbacks = isCygwin();
       
   153 my $testHTTP = 1;
       
   154 my $testWebSocket = 1;
       
   155 my $testMedia = 1;
       
   156 my $tmpDir = "/tmp";
       
   157 my $testResultsDirectory = File::Spec->catfile($tmpDir, "layout-test-results");
       
   158 my $testsPerDumpTool = 1000;
       
   159 my $threaded = 0;
       
   160 my $html5treebuilder = 0;
       
   161 # DumpRenderTree has an internal timeout of 30 seconds, so this must be > 30.
       
   162 my $timeoutSeconds = 35;
       
   163 my $tolerance = 0;
       
   164 my $treatSkipped = "default";
       
   165 my $useRemoteLinksToTests = 0;
       
   166 my $useValgrind = 0;
       
   167 my $verbose = 0;
       
   168 my $shouldWaitForHTTPD = 0;
       
   169 my $useWebKitTestRunner = 0;
       
   170 
       
   171 my @leaksFilenames;
       
   172 
       
   173 if (isWindows() || isMsys()) {
       
   174     print "This script has to be run under Cygwin to function correctly.\n";
       
   175     exit 1;
       
   176 }
       
   177 
       
   178 # Default to --no-http for wx for now.
       
   179 $testHTTP = 0 if (isWx());
       
   180 
       
   181 my $expectedTag = "expected";
       
   182 my $actualTag = "actual";
       
   183 my $prettyDiffTag = "pretty-diff";
       
   184 my $diffsTag = "diffs";
       
   185 my $errorTag = "stderr";
       
   186 
       
   187 my $realPlatform;
       
   188 
       
   189 my @macPlatforms = ("mac-tiger", "mac-leopard", "mac-snowleopard", "mac");
       
   190 my @winPlatforms = ("win-xp", "win-vista", "win-7", "win");
       
   191 
       
   192 if (isAppleMacWebKit()) {
       
   193     if (isTiger()) {
       
   194         $platform = "mac-tiger";
       
   195         $tolerance = 1.0;
       
   196     } elsif (isLeopard()) {
       
   197         $platform = "mac-leopard";
       
   198         $tolerance = 0.1;
       
   199     } elsif (isSnowLeopard()) {
       
   200         $platform = "mac-snowleopard";
       
   201         $tolerance = 0.1;
       
   202     } else {
       
   203         $platform = "mac";
       
   204     }
       
   205 } elsif (isQt()) {
       
   206     if (isDarwin()) {
       
   207         $platform = "qt-mac";
       
   208     } elsif (isLinux()) {
       
   209         $platform = "qt-linux";
       
   210     } elsif (isWindows() || isCygwin()) {
       
   211         $platform = "qt-win";
       
   212     } else {
       
   213         $platform = "qt";
       
   214     }
       
   215 } elsif (isGtk()) {
       
   216     $platform = "gtk";
       
   217     if (!$ENV{"WEBKIT_TESTFONTS"}) {
       
   218         print "The WEBKIT_TESTFONTS environment variable is not defined.\n";
       
   219         print "You must set it before running the tests.\n";
       
   220         print "Use git to grab the actual fonts from http://gitorious.org/qtwebkit/testfonts\n";
       
   221         exit 1;
       
   222     }
       
   223 } elsif (isWx()) {
       
   224     $platform = "wx";
       
   225 } elsif (isCygwin()) {
       
   226     if (isWindowsXP()) {
       
   227         $platform = "win-xp";
       
   228     } elsif (isWindowsVista()) {
       
   229         $platform = "win-vista";
       
   230     } elsif (isWindows7()) {
       
   231         $platform = "win-7";
       
   232     } else {
       
   233         $platform = "win";
       
   234     }
       
   235 }
       
   236 
       
   237 if (!defined($platform)) {
       
   238     print "WARNING: Your platform is not recognized. Any platform-specific results will be generated in platform/undefined.\n";
       
   239     $platform = "undefined";
       
   240 }
       
   241 
       
   242 if (!checkPythonVersion()) {
       
   243     print "WARNING: Your platform does not have Python 2.5+, which is required to run websocket server, so disabling websocket/tests.\n";
       
   244     $testWebSocket = 0;
       
   245 }
       
   246 
       
   247 my $programName = basename($0);
       
   248 my $launchSafariDefault = $launchSafari ? "launch" : "do not launch";
       
   249 my $httpDefault = $testHTTP ? "run" : "do not run";
       
   250 my $sampleDefault = $runSample ? "run" : "do not run";
       
   251 
       
   252 my $usage = <<EOF;
       
   253 Usage: $programName [options] [testdir|testpath ...]
       
   254   --add-platform-exceptions       Put new results for non-platform-specific failing tests into the platform-specific results directory
       
   255   --complex-text                  Use the complex text code path for all text (Mac OS X and Windows only)
       
   256   -c|--configuration config       Set DumpRenderTree build configuration
       
   257   -g|--guard-malloc               Enable malloc guard
       
   258   --exit-after-n-failures N       Exit after the first N failures (includes crashes) instead of running all tests
       
   259   --exit-after-n-crashes-or-timeouts N
       
   260                                   Exit after the first N crashes instead of running all tests
       
   261   -h|--help                       Show this help message
       
   262   --[no-]http                     Run (or do not run) http tests (default: $httpDefault)
       
   263   --[no-]wait-for-httpd           Wait for httpd if some other test session is using it already (same as WEBKIT_WAIT_FOR_HTTPD=1). (default: $shouldWaitForHTTPD) 
       
   264   -i|--ignore-tests               Comma-separated list of directories or tests to ignore
       
   265   --iterations n                  Number of times to run the set of tests (e.g. ABCABCABC)
       
   266   --[no-]launch-safari            Launch (or do not launch) Safari to display test results (default: $launchSafariDefault)
       
   267   -l|--leaks                      Enable leaks checking
       
   268   --[no-]new-test-results         Generate results for new tests
       
   269   --nthly n                       Restart DumpRenderTree every n tests (default: $testsPerDumpTool)
       
   270   -p|--pixel-tests                Enable pixel tests
       
   271   --tolerance t                   Ignore image differences less than this percentage (default: $tolerance)
       
   272   --platform                      Override the detected platform to use for tests and results (default: $platform)
       
   273   --port                          Web server port to use with http tests
       
   274   -q|--quiet                      Less verbose output
       
   275   --reset-results                 Reset ALL results (including pixel tests if --pixel-tests is set)
       
   276   -o|--results-directory          Output results directory (default: $testResultsDirectory)
       
   277   --random                        Run the tests in a random order
       
   278   --repeat-each n                 Number of times to run each test (e.g. AAABBBCCC)
       
   279   --reverse                       Run the tests in reverse alphabetical order
       
   280   --root                          Path to root tools build
       
   281   --[no-]sample-on-timeout        Run sample on timeout (default: $sampleDefault) (Mac OS X only)
       
   282   -1|--singly                     Isolate each test case run (implies --nthly 1 --verbose)
       
   283   --skipped=[default|ignore|only] Specifies how to treat the Skipped file
       
   284                                      default: Tests/directories listed in the Skipped file are not tested
       
   285                                      ignore:  The Skipped file is ignored
       
   286                                      only:    Only those tests/directories listed in the Skipped file will be run
       
   287   --slowest                       Report the 10 slowest tests
       
   288   --ignore-metrics                Ignore metrics in tests
       
   289   --[no-]strip-editing-callbacks  Remove editing callbacks from expected results
       
   290   -t|--threaded                   Run a concurrent JavaScript thead with each test
       
   291   --html5-treebuilder             Run the tests using the HTML5 tree builder
       
   292   --timeout t                     Sets the number of seconds before a test times out (default: $timeoutSeconds)
       
   293   --valgrind                      Run DumpRenderTree inside valgrind (Qt/Linux only)
       
   294   -v|--verbose                    More verbose output (overrides --quiet)
       
   295   -m|--merge-leak-depth arg       Merges leak callStacks and prints the number of unique leaks beneath a callstack depth of arg.  Defaults to 5.
       
   296   --use-remote-links-to-tests     Link to test files within the SVN repository in the results.
       
   297   --webkit-test-runner            Use WebKitTestRunner rather than DumpRenderTree.
       
   298 EOF
       
   299 
       
   300 setConfiguration();
       
   301 
       
   302 my $getOptionsResult = GetOptions(
       
   303     'add-platform-exceptions' => \$addPlatformExceptions,
       
   304     'complex-text' => \$complexText,
       
   305     'exit-after-n-failures=i' => \$exitAfterNFailures,
       
   306     'exit-after-n-crashes-or-timeouts=i' => \$exitAfterNCrashesOrTimeouts,
       
   307     'guard-malloc|g' => \$guardMalloc,
       
   308     'help|h' => \$showHelp,
       
   309     'http!' => \$testHTTP,
       
   310     'wait-for-httpd!' => \$shouldWaitForHTTPD,
       
   311     'ignore-metrics!' => \$ignoreMetrics,
       
   312     'ignore-tests|i=s' => \$ignoreTests,
       
   313     'iterations=i' => \$iterations,
       
   314     'launch-safari!' => \$launchSafari,
       
   315     'leaks|l' => \$shouldCheckLeaks,
       
   316     'merge-leak-depth|m:5' => \$mergeDepth,
       
   317     'new-test-results!' => \$generateNewResults,
       
   318     'nthly=i' => \$testsPerDumpTool,
       
   319     'pixel-tests|p' => \$pixelTests,
       
   320     'platform=s' => \$platform,
       
   321     'port=i' => \$httpdPort,
       
   322     'quiet|q' => \$quiet,
       
   323     'random' => \$randomizeTests,
       
   324     'repeat-each=i' => \$repeatEach,
       
   325     'reset-results' => \$resetResults,
       
   326     'results-directory|o=s' => \$testResultsDirectory,
       
   327     'reverse' => \$reverseTests,
       
   328     'root=s' => \$root,
       
   329     'sample-on-timeout!' => \$runSample,
       
   330     'singly|1' => sub { $testsPerDumpTool = 1; },
       
   331     'skipped=s' => \&validateSkippedArg,
       
   332     'slowest' => \$report10Slowest,
       
   333     'strip-editing-callbacks!' => \$stripEditingCallbacks,
       
   334     'threaded|t' => \$threaded,
       
   335     'html5-treebuilder' => \$html5treebuilder,
       
   336     'timeout=i' => \$timeoutSeconds,
       
   337     'tolerance=f' => \$tolerance,
       
   338     'use-remote-links-to-tests' => \$useRemoteLinksToTests,
       
   339     'valgrind' => \$useValgrind,
       
   340     'verbose|v' => \$verbose,
       
   341     'webkit-test-runner' => \$useWebKitTestRunner,
       
   342 );
       
   343 
       
   344 if (!$getOptionsResult || $showHelp) {
       
   345     print STDERR $usage;
       
   346     exit 1;
       
   347 }
       
   348 
       
   349 if ($useWebKitTestRunner) {
       
   350     if (isAppleMacWebKit()) {
       
   351         $realPlatform = $platform;
       
   352         $platform = "mac-wk2";
       
   353     }
       
   354 }
       
   355 
       
   356 
       
   357 my $ignoreSkipped = $treatSkipped eq "ignore";
       
   358 my $skippedOnly = $treatSkipped eq "only";
       
   359 
       
   360 my $configuration = configuration();
       
   361 
       
   362 # We need an environment variable to be able to enable the feature per-slave
       
   363 $shouldWaitForHTTPD = $ENV{"WEBKIT_WAIT_FOR_HTTPD"} unless ($shouldWaitForHTTPD);
       
   364 $verbose = 1 if $testsPerDumpTool == 1;
       
   365 
       
   366 if ($shouldCheckLeaks && $testsPerDumpTool > 1000) {
       
   367     print STDERR "\nWARNING: Running more than 1000 tests at a time with MallocStackLogging enabled may cause a crash.\n\n";
       
   368 }
       
   369 
       
   370 # Stack logging does not play well with QuickTime on Tiger (rdar://problem/5537157)
       
   371 $testMedia = 0 if $shouldCheckLeaks && isTiger();
       
   372 
       
   373 # Generating remote links causes a lot of unnecessary spew on GTK build bot
       
   374 $useRemoteLinksToTests = 0 if isGtk();
       
   375 
       
   376 setConfigurationProductDir(Cwd::abs_path($root)) if (defined($root));
       
   377 my $productDir = productDir();
       
   378 $productDir .= "/bin" if isQt();
       
   379 $productDir .= "/Programs" if isGtk();
       
   380 
       
   381 chdirWebKit();
       
   382 
       
   383 my $dumpToolName = $useWebKitTestRunner ? "WebKitTestRunner" : "DumpRenderTree";
       
   384 
       
   385 if (!defined($root)) {
       
   386     my $dumpToolBuildScript =  "build-" . lc($dumpToolName);
       
   387     print STDERR "Running $dumpToolBuildScript\n";
       
   388 
       
   389     local *DEVNULL;
       
   390     my ($childIn, $childOut, $childErr);
       
   391     if ($quiet) {
       
   392         open(DEVNULL, ">", File::Spec->devnull()) or die "Failed to open /dev/null";
       
   393         $childOut = ">&DEVNULL";
       
   394         $childErr = ">&DEVNULL";
       
   395     } else {
       
   396         # When not quiet, let the child use our stdout/stderr.
       
   397         $childOut = ">&STDOUT";
       
   398         $childErr = ">&STDERR";
       
   399     }
       
   400 
       
   401     my @args = argumentsForConfiguration();
       
   402     my $buildProcess = open3($childIn, $childOut, $childErr, "WebKitTools/Scripts/$dumpToolBuildScript", @args) or die "Failed to run build-dumprendertree";
       
   403     close($childIn);
       
   404     waitpid $buildProcess, 0;
       
   405     my $buildResult = $?;
       
   406     close($childOut);
       
   407     close($childErr);
       
   408 
       
   409     close DEVNULL if ($quiet);
       
   410 
       
   411     if ($buildResult) {
       
   412         print STDERR "Compiling $dumpToolName failed!\n";
       
   413         exit exitStatus($buildResult);
       
   414     }
       
   415 }
       
   416 
       
   417 $dumpToolName .= "_debug" if isCygwin() && configurationForVisualStudio() !~ /^Release|Debug_Internal$/;
       
   418 my $dumpTool = "$productDir/$dumpToolName";
       
   419 die "can't find executable $dumpToolName (looked in $productDir)\n" unless -x $dumpTool;
       
   420 
       
   421 my $imageDiffTool = "$productDir/ImageDiff";
       
   422 $imageDiffTool .= "_debug" if isCygwin() && configurationForVisualStudio() !~ /^Release|Debug_Internal$/;
       
   423 die "can't find executable $imageDiffTool (looked in $productDir)\n" if $pixelTests && !-x $imageDiffTool;
       
   424 
       
   425 checkFrameworks() unless isCygwin();
       
   426 
       
   427 if (isAppleMacWebKit()) {
       
   428     push @INC, $productDir;
       
   429     require DumpRenderTreeSupport;
       
   430 }
       
   431 
       
   432 my $layoutTestsName = "LayoutTests";
       
   433 my $testDirectory = File::Spec->rel2abs($layoutTestsName);
       
   434 my $expectedDirectory = $testDirectory;
       
   435 my $platformBaseDirectory = catdir($testDirectory, "platform");
       
   436 my $platformTestDirectory = catdir($platformBaseDirectory, $platform);
       
   437 my @platformResultHierarchy = buildPlatformResultHierarchy();
       
   438 my @platformTestHierarchy = buildPlatformTestHierarchy(@platformResultHierarchy);
       
   439 
       
   440 $expectedDirectory = $ENV{"WebKitExpectedTestResultsDirectory"} if $ENV{"WebKitExpectedTestResultsDirectory"};
       
   441 
       
   442 $testResultsDirectory = File::Spec->rel2abs($testResultsDirectory);
       
   443 my $testResults = File::Spec->catfile($testResultsDirectory, "results.html");
       
   444 
       
   445 if (isAppleMacWebKit()) {
       
   446     print STDERR "Compiling Java tests\n";
       
   447     my $javaTestsDirectory = catdir($testDirectory, "java");
       
   448 
       
   449     if (system("/usr/bin/make", "-C", "$javaTestsDirectory")) {
       
   450         exit 1;
       
   451     }
       
   452 }
       
   453 
       
   454 
       
   455 print "Running tests from $testDirectory\n";
       
   456 if ($pixelTests) {
       
   457     print "Enabling pixel tests with a tolerance of $tolerance%\n";
       
   458     if (isDarwin()) {
       
   459         print "WARNING: Temporarily changing the main display color profile:\n";
       
   460         print "\tThe colors on your screen will change for the duration of the testing.\n";
       
   461         print "\tThis allows the pixel tests to have consistent color values across all machines.\n";
       
   462         
       
   463         if (isPerianInstalled()) {
       
   464             print "WARNING: Perian's QuickTime component is installed and this may affect pixel test results!\n";
       
   465             print "\tYou should avoid generating new pixel results in this environment.\n";
       
   466             print "\tSee https://bugs.webkit.org/show_bug.cgi?id=22615 for details.\n";
       
   467         }
       
   468     }
       
   469 }
       
   470 
       
   471 system "ln", "-s", $testDirectory, "/tmp/LayoutTests" unless -x "/tmp/LayoutTests";
       
   472 
       
   473 my %ignoredFiles = ( "results.html" => 1 );
       
   474 my %ignoredDirectories = map { $_ => 1 } qw(platform);
       
   475 my %ignoredLocalDirectories = map { $_ => 1 } qw(.svn _svn resources script-tests);
       
   476 my %supportedFileExtensions = map { $_ => 1 } qw(html shtml xml xhtml xhtmlmp pl php);
       
   477 
       
   478 if (!checkWebCoreFeatureSupport("MathML", 0)) {
       
   479     $ignoredDirectories{'mathml'} = 1;
       
   480 }
       
   481 
       
   482 # FIXME: We should fix webkitperl/features.pm:hasFeature() to do the correct feature detection for Cygwin.
       
   483 if (checkWebCoreFeatureSupport("SVG", 0)) {
       
   484     $supportedFileExtensions{'svg'} = 1;
       
   485 } elsif (isCygwin()) {
       
   486     $supportedFileExtensions{'svg'} = 1;
       
   487 } else {
       
   488     $ignoredLocalDirectories{'svg'} = 1;
       
   489 }
       
   490 
       
   491 if (!$testHTTP) {
       
   492     $ignoredDirectories{'http'} = 1;
       
   493     $ignoredDirectories{'websocket'} = 1;
       
   494 }
       
   495 if (!$testWebSocket) {
       
   496     $ignoredDirectories{'websocket'} = 1;
       
   497 }
       
   498 
       
   499 if (!$testMedia) {
       
   500     $ignoredDirectories{'media'} = 1;
       
   501     $ignoredDirectories{'http/tests/media'} = 1;
       
   502 }
       
   503 
       
   504 my $supportedFeaturesResult = "";
       
   505 
       
   506 if (isCygwin()) {
       
   507     # Collect supported features list
       
   508     setPathForRunningWebKitApp(\%ENV);
       
   509     my $supportedFeaturesCommand = $dumpTool . " --print-supported-features 2>&1";
       
   510     $supportedFeaturesResult = `$supportedFeaturesCommand 2>&1`;
       
   511 }
       
   512 
       
   513 my $hasAcceleratedCompositing = 0;
       
   514 my $has3DRendering = 0;
       
   515 
       
   516 if (isCygwin()) {
       
   517     $hasAcceleratedCompositing = $supportedFeaturesResult =~ /AcceleratedCompositing/;
       
   518     $has3DRendering = $supportedFeaturesResult =~ /3DRendering/;
       
   519 } else {
       
   520     $hasAcceleratedCompositing = checkWebCoreFeatureSupport("Accelerated Compositing", 0);
       
   521     $has3DRendering = checkWebCoreFeatureSupport("3D Rendering", 0);
       
   522 }
       
   523 
       
   524 if (!$hasAcceleratedCompositing) {
       
   525     $ignoredDirectories{'compositing'} = 1;
       
   526 }
       
   527 
       
   528 if (!$has3DRendering) {
       
   529     $ignoredDirectories{'animations/3d'} = 1;
       
   530     $ignoredDirectories{'transforms/3d'} = 1;
       
   531 }
       
   532 
       
   533 if (!checkWebCoreFeatureSupport("3D Canvas", 0)) {
       
   534     $ignoredDirectories{'fast/canvas/webgl'} = 1;
       
   535     $ignoredDirectories{'compositing/webgl'} = 1;
       
   536 }
       
   537 
       
   538 if (checkWebCoreFeatureSupport("WML", 0)) {
       
   539     $supportedFileExtensions{'wml'} = 1;
       
   540 } else {
       
   541     $ignoredDirectories{'http/tests/wml'} = 1;
       
   542     $ignoredDirectories{'fast/wml'} = 1;
       
   543     $ignoredDirectories{'wml'} = 1;
       
   544 }
       
   545 
       
   546 if (!checkWebCoreFeatureSupport("WCSS", 0)) {
       
   547     $ignoredDirectories{'fast/wcss'} = 1;
       
   548 }
       
   549 
       
   550 if (!checkWebCoreFeatureSupport("XHTMLMP", 0)) {
       
   551     $ignoredDirectories{'fast/xhtmlmp'} = 1;
       
   552 }
       
   553 
       
   554 processIgnoreTests($ignoreTests, "ignore-tests") if $ignoreTests;
       
   555 if (!$ignoreSkipped) {
       
   556     if (!$skippedOnly || @ARGV == 0) {
       
   557         readSkippedFiles("");
       
   558     } else {
       
   559         # Since readSkippedFiles() appends to @ARGV, we must use a foreach
       
   560         # loop so that we only iterate over the original argument list.
       
   561         foreach my $argnum (0 .. $#ARGV) {
       
   562             readSkippedFiles(shift @ARGV);
       
   563         }
       
   564     }
       
   565 }
       
   566 
       
   567 my @tests = findTestsToRun();
       
   568 
       
   569 die "no tests to run\n" if !@tests;
       
   570 
       
   571 my %counts;
       
   572 my %tests;
       
   573 my %imagesPresent;
       
   574 my %imageDifferences;
       
   575 my %durations;
       
   576 my $count = 0;
       
   577 my $leaksOutputFileNumber = 1;
       
   578 my $totalLeaks = 0;
       
   579 
       
   580 my @toolArgs = ();
       
   581 push @toolArgs, "--pixel-tests" if $pixelTests;
       
   582 push @toolArgs, "--threaded" if $threaded;
       
   583 push @toolArgs, "--html5-treebuilder" if $html5treebuilder;
       
   584 push @toolArgs, "--complex-text" if $complexText;
       
   585 push @toolArgs, "-";
       
   586 
       
   587 my @diffToolArgs = ();
       
   588 push @diffToolArgs, "--tolerance", $tolerance;
       
   589 
       
   590 $| = 1;
       
   591 
       
   592 my $dumpToolPID;
       
   593 my $isDumpToolOpen = 0;
       
   594 my $dumpToolCrashed = 0;
       
   595 my $imageDiffToolPID;
       
   596 my $isDiffToolOpen = 0;
       
   597 
       
   598 my $atLineStart = 1;
       
   599 my $lastDirectory = "";
       
   600 
       
   601 my $isHttpdOpen = 0;
       
   602 my $isWebSocketServerOpen = 0;
       
   603 my $webSocketServerPidFile = 0;
       
   604 my $failedToStartWebSocketServer = 0;
       
   605 # wss is disabled until all platforms support pyOpenSSL.
       
   606 # my $webSocketSecureServerPID = 0;
       
   607 
       
   608 sub catch_pipe { $dumpToolCrashed = 1; }
       
   609 $SIG{"PIPE"} = "catch_pipe";
       
   610 
       
   611 print "Testing ", scalar @tests, " test cases";
       
   612 print " $iterations times" if ($iterations > 1);
       
   613 print ", repeating each test $repeatEach times" if ($repeatEach > 1);
       
   614 print ".\n";
       
   615 
       
   616 my $overallStartTime = time;
       
   617 
       
   618 my %expectedResultPaths;
       
   619 
       
   620 my @originalTests = @tests;
       
   621 # Add individual test repetitions
       
   622 if ($repeatEach > 1) {
       
   623     @tests = ();
       
   624     foreach my $test (@originalTests) {
       
   625         for (my $i = 0; $i < $repeatEach; $i++) {
       
   626             push(@tests, $test);
       
   627         }
       
   628     }
       
   629 }
       
   630 # Add test set repetitions
       
   631 for (my $i = 1; $i < $iterations; $i++) {
       
   632     push(@tests, @originalTests);
       
   633 }
       
   634 
       
   635 for my $test (@tests) {
       
   636     my $newDumpTool = not $isDumpToolOpen;
       
   637     openDumpTool();
       
   638 
       
   639     my $base = stripExtension($test);
       
   640     my $expectedExtension = ".txt";
       
   641     
       
   642     my $dir = $base;
       
   643     $dir =~ s|/[^/]+$||;
       
   644 
       
   645     if ($newDumpTool || $dir ne $lastDirectory) {
       
   646         foreach my $logue (epiloguesAndPrologues($newDumpTool ? "" : $lastDirectory, $dir)) {
       
   647             if (isCygwin()) {
       
   648                 $logue = toWindowsPath($logue);
       
   649             } else {
       
   650                 $logue = canonpath($logue);
       
   651             }
       
   652             if ($verbose) {
       
   653                 print "running epilogue or prologue $logue\n";
       
   654             }
       
   655             print OUT "$logue\n";
       
   656             # Throw away output from DumpRenderTree.
       
   657             # Once for the test output and once for pixel results (empty)
       
   658             while (<IN>) {
       
   659                 last if /#EOF/;
       
   660             }
       
   661             while (<IN>) {
       
   662                 last if /#EOF/;
       
   663             }
       
   664         }
       
   665     }
       
   666 
       
   667     if ($verbose) {
       
   668         print "running $test -> ";
       
   669         $atLineStart = 0;
       
   670     } elsif (!$quiet) {
       
   671         if ($dir ne $lastDirectory) {
       
   672             print "\n" unless $atLineStart;
       
   673             print "$dir ";
       
   674         }
       
   675         print ".";
       
   676         $atLineStart = 0;
       
   677     }
       
   678 
       
   679     $lastDirectory = $dir;
       
   680 
       
   681     my $result;
       
   682 
       
   683     my $startTime = time if $report10Slowest;
       
   684 
       
   685     # Try to read expected hash file for pixel tests
       
   686     my $suffixExpectedHash = "";
       
   687     if ($pixelTests && !$resetResults) {
       
   688         my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
       
   689         if (open EXPECTEDHASH, "$expectedPixelDir/$base-$expectedTag.checksum") {
       
   690             my $expectedHash = <EXPECTEDHASH>;
       
   691             chomp($expectedHash);
       
   692             close EXPECTEDHASH;
       
   693             
       
   694             # Format expected hash into a suffix string that is appended to the path / URL passed to DRT
       
   695             $suffixExpectedHash = "'$expectedHash";
       
   696         }
       
   697     }
       
   698 
       
   699     if ($test =~ /^http\//) {
       
   700         configureAndOpenHTTPDIfNeeded();
       
   701         if ($test !~ /^http\/tests\/local\// && $test !~ /^http\/tests\/ssl\// && $test !~ /^http\/tests\/wml\// && $test !~ /^http\/tests\/media\//) {
       
   702             my $path = canonpath($test);
       
   703             $path =~ s/^http\/tests\///;
       
   704             print OUT "http://127.0.0.1:$httpdPort/$path$suffixExpectedHash\n";
       
   705         } elsif ($test =~ /^http\/tests\/ssl\//) {
       
   706             my $path = canonpath($test);
       
   707             $path =~ s/^http\/tests\///;
       
   708             print OUT "https://127.0.0.1:$httpdSSLPort/$path$suffixExpectedHash\n";
       
   709         } else {
       
   710             my $testPath = "$testDirectory/$test";
       
   711             if (isCygwin()) {
       
   712                 $testPath = toWindowsPath($testPath);
       
   713             } else {
       
   714                 $testPath = canonpath($testPath);
       
   715             }
       
   716             print OUT "$testPath$suffixExpectedHash\n";
       
   717         }
       
   718     } elsif ($test =~ /^websocket\//) {
       
   719         if ($test =~ /^websocket\/tests\/local\//) {
       
   720             my $testPath = "$testDirectory/$test";
       
   721             if (isCygwin()) {
       
   722                 $testPath = toWindowsPath($testPath);
       
   723             } else {
       
   724                 $testPath = canonpath($testPath);
       
   725             }
       
   726             print OUT "$testPath\n";
       
   727         } else {
       
   728             if (openWebSocketServerIfNeeded()) {
       
   729                 my $path = canonpath($test);
       
   730                 if ($test =~ /^websocket\/tests\/ssl\//) {
       
   731                     # wss is disabled until all platforms support pyOpenSSL.
       
   732                     print STDERR "Error: wss is disabled until all platforms support pyOpenSSL.";
       
   733                     # print OUT "https://127.0.0.1:$webSocketSecurePort/$path\n";
       
   734                 } else {
       
   735                     print OUT "http://127.0.0.1:$webSocketPort/$path\n";
       
   736                 }
       
   737             } else {
       
   738                 # We failed to launch the WebSocket server.  Display a useful error message rather than attempting
       
   739                 # to run tests that expect the server to be available.
       
   740                 my $errorMessagePath = "$testDirectory/websocket/resources/server-failed-to-start.html";
       
   741                 $errorMessagePath = isCygwin() ? toWindowsPath($errorMessagePath) : canonpath($errorMessagePath);
       
   742                 print OUT "$errorMessagePath\n";
       
   743             }
       
   744         }
       
   745     } else {
       
   746         my $testPath = "$testDirectory/$test";
       
   747         if (isCygwin()) {
       
   748             $testPath = toWindowsPath($testPath);
       
   749         } else {
       
   750             $testPath = canonpath($testPath);
       
   751         }
       
   752         print OUT "$testPath$suffixExpectedHash\n" if defined $testPath;
       
   753     }
       
   754 
       
   755     # DumpRenderTree is expected to dump two "blocks" to stdout for each test.
       
   756     # Each block is terminated by a #EOF on a line by itself.
       
   757     # The first block is the output of the test (in text, RenderTree or other formats).
       
   758     # The second block is for optional pixel data in PNG format, and may be empty if
       
   759     # pixel tests are not being run, or the test does not dump pixels (e.g. text tests).
       
   760     my $readResults = readFromDumpToolWithTimer(IN, ERROR);
       
   761 
       
   762     my $actual = $readResults->{output};
       
   763     my $error = $readResults->{error};
       
   764 
       
   765     $expectedExtension = $readResults->{extension};
       
   766     my $expectedFileName = "$base-$expectedTag.$expectedExtension";
       
   767 
       
   768     my $isText = isTextOnlyTest($actual);
       
   769 
       
   770     my $expectedDir = expectedDirectoryForTest($base, $isText, $expectedExtension);
       
   771     $expectedResultPaths{$base} = "$expectedDir/$expectedFileName";
       
   772 
       
   773     unless ($readResults->{status} eq "success") {
       
   774         my $crashed = $readResults->{status} eq "crashed";
       
   775         testCrashedOrTimedOut($test, $base, $crashed, $actual, $error);
       
   776         countFinishedTest($test, $base, $crashed ? "crash" : "timedout", 0);
       
   777         last if stopRunningTestsEarlyIfNeeded();
       
   778         next;
       
   779     }
       
   780 
       
   781     $durations{$test} = time - $startTime if $report10Slowest;
       
   782 
       
   783     my $expected;
       
   784 
       
   785     if (!$resetResults && open EXPECTED, "<", "$expectedDir/$expectedFileName") {
       
   786         $expected = "";
       
   787         while (<EXPECTED>) {
       
   788             next if $stripEditingCallbacks && $_ =~ /^EDITING DELEGATE:/;
       
   789             $expected .= $_;
       
   790         }
       
   791         close EXPECTED;
       
   792     }
       
   793 
       
   794     if ($ignoreMetrics && !$isText && defined $expected) {
       
   795         ($actual, $expected) = stripMetrics($actual, $expected);
       
   796     }
       
   797 
       
   798     if ($shouldCheckLeaks && $testsPerDumpTool == 1) {
       
   799         print "        $test -> ";
       
   800     }
       
   801 
       
   802     my $actualPNG = "";
       
   803     my $diffPNG = "";
       
   804     my $diffPercentage = 0;
       
   805     my $diffResult = "passed";
       
   806 
       
   807     my $actualHash = "";
       
   808     my $expectedHash = "";
       
   809     my $actualPNGSize = 0;
       
   810 
       
   811     while (<IN>) {
       
   812         last if /#EOF/;
       
   813         if (/ActualHash: ([a-f0-9]{32})/) {
       
   814             $actualHash = $1;
       
   815         } elsif (/ExpectedHash: ([a-f0-9]{32})/) {
       
   816             $expectedHash = $1;
       
   817         } elsif (/Content-Length: (\d+)\s*/) {
       
   818             $actualPNGSize = $1;
       
   819             read(IN, $actualPNG, $actualPNGSize);
       
   820         }
       
   821     }
       
   822 
       
   823     if ($verbose && $pixelTests && !$resetResults && $actualPNGSize) {
       
   824         if ($actualHash eq "" && $expectedHash eq "") {
       
   825             printFailureMessageForTest($test, "WARNING: actual & expected pixel hashes are missing!");
       
   826         } elsif ($actualHash eq "") {
       
   827             printFailureMessageForTest($test, "WARNING: actual pixel hash is missing!");
       
   828         } elsif ($expectedHash eq "") {
       
   829             printFailureMessageForTest($test, "WARNING: expected pixel hash is missing!");
       
   830         }
       
   831     }
       
   832 
       
   833     if ($actualPNGSize > 0) {
       
   834         my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
       
   835 
       
   836         if (!$resetResults && ($expectedHash ne $actualHash || ($actualHash eq "" && $expectedHash eq ""))) {
       
   837             if (-f "$expectedPixelDir/$base-$expectedTag.png") {
       
   838                 my $expectedPNGSize = -s "$expectedPixelDir/$base-$expectedTag.png";
       
   839                 my $expectedPNG = "";
       
   840                 open EXPECTEDPNG, "$expectedPixelDir/$base-$expectedTag.png";
       
   841                 read(EXPECTEDPNG, $expectedPNG, $expectedPNGSize);
       
   842 
       
   843                 openDiffTool();
       
   844                 print DIFFOUT "Content-Length: $actualPNGSize\n";
       
   845                 print DIFFOUT $actualPNG;
       
   846 
       
   847                 print DIFFOUT "Content-Length: $expectedPNGSize\n";
       
   848                 print DIFFOUT $expectedPNG;
       
   849 
       
   850                 while (<DIFFIN>) {
       
   851                     last if /^error/ || /^diff:/;
       
   852                     if (/Content-Length: (\d+)\s*/) {
       
   853                         read(DIFFIN, $diffPNG, $1);
       
   854                     }
       
   855                 }
       
   856 
       
   857                 if (/^diff: (.+)% (passed|failed)/) {
       
   858                     $diffPercentage = $1 + 0;
       
   859                     $imageDifferences{$base} = $diffPercentage;
       
   860                     $diffResult = $2;
       
   861                 }
       
   862                 
       
   863                 if (!$diffPercentage) {
       
   864                     printFailureMessageForTest($test, "pixel hash failed (but pixel test still passes)");
       
   865                 }
       
   866             } elsif ($verbose) {
       
   867                 printFailureMessageForTest($test, "WARNING: expected image is missing!");
       
   868             }
       
   869         }
       
   870 
       
   871         if ($resetResults || !-f "$expectedPixelDir/$base-$expectedTag.png") {
       
   872             mkpath catfile($expectedPixelDir, dirname($base)) if $testDirectory ne $expectedPixelDir;
       
   873             writeToFile("$expectedPixelDir/$base-$expectedTag.png", $actualPNG);
       
   874         }
       
   875 
       
   876         if ($actualHash ne "" && ($resetResults || !-f "$expectedPixelDir/$base-$expectedTag.checksum")) {
       
   877             writeToFile("$expectedPixelDir/$base-$expectedTag.checksum", $actualHash);
       
   878         }
       
   879     }
       
   880 
       
   881     if (dumpToolDidCrash()) {
       
   882         $result = "crash";
       
   883         testCrashedOrTimedOut($test, $base, 1, $actual, $error);
       
   884     } elsif (!defined $expected) {
       
   885         if ($verbose) {
       
   886             print "new " . ($resetResults ? "result" : "test") ."\n";
       
   887             $atLineStart = 1;
       
   888         }
       
   889         $result = "new";
       
   890 
       
   891         if ($generateNewResults || $resetResults) {
       
   892             mkpath catfile($expectedDir, dirname($base)) if $testDirectory ne $expectedDir;
       
   893             writeToFile("$expectedDir/$expectedFileName", $actual);
       
   894         }
       
   895         deleteExpectedAndActualResults($base);
       
   896         recordActualResultsAndDiff($base, $actual);
       
   897         if (!$resetResults) {
       
   898             # Always print the file name for new tests, as they will probably need some manual inspection.
       
   899             # in verbose mode we already printed the test case, so no need to do it again.
       
   900             unless ($verbose) {
       
   901                 print "\n" unless $atLineStart;
       
   902                 print "$test -> ";
       
   903             }
       
   904             my $resultsDir = catdir($expectedDir, dirname($base));
       
   905             if ($generateNewResults) {
       
   906                 print "new (results generated in $resultsDir)\n";
       
   907             } else {
       
   908                 print "new\n";
       
   909             }
       
   910             $atLineStart = 1;
       
   911         }
       
   912     } elsif ($actual eq $expected && $diffResult eq "passed") {
       
   913         if ($verbose) {
       
   914             print "succeeded\n";
       
   915             $atLineStart = 1;
       
   916         }
       
   917         $result = "match";
       
   918         deleteExpectedAndActualResults($base);
       
   919     } else {
       
   920         $result = "mismatch";
       
   921 
       
   922         my $pixelTestFailed = $pixelTests && $diffPNG && $diffPNG ne "";
       
   923         my $testFailed = $actual ne $expected;
       
   924 
       
   925         my $message = !$testFailed ? "pixel test failed" : "failed";
       
   926 
       
   927         if (($testFailed || $pixelTestFailed) && $addPlatformExceptions) {
       
   928             my $testBase = catfile($testDirectory, $base);
       
   929             my $expectedBase = catfile($expectedDir, $base);
       
   930             my $testIsMaximallyPlatformSpecific = $testBase =~ m|^\Q$platformTestDirectory\E/|;
       
   931             my $expectedResultIsMaximallyPlatformSpecific = $expectedBase =~ m|^\Q$platformTestDirectory\E/|;
       
   932             if (!$testIsMaximallyPlatformSpecific && !$expectedResultIsMaximallyPlatformSpecific) {
       
   933                 mkpath catfile($platformTestDirectory, dirname($base));
       
   934                 if ($testFailed) {
       
   935                     my $expectedFile = catfile($platformTestDirectory, "$expectedFileName");
       
   936                     writeToFile("$expectedFile", $actual);
       
   937                 }
       
   938                 if ($pixelTestFailed) {
       
   939                     my $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.checksum");
       
   940                     writeToFile("$expectedFile", $actualHash);
       
   941 
       
   942                     $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.png");
       
   943                     writeToFile("$expectedFile", $actualPNG);
       
   944                 }
       
   945                 $message .= " (results generated in $platformTestDirectory)";
       
   946             }
       
   947         }
       
   948 
       
   949         printFailureMessageForTest($test, $message);
       
   950 
       
   951         my $dir = "$testResultsDirectory/$base";
       
   952         $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
       
   953         my $testName = $1;
       
   954         mkpath $dir;
       
   955 
       
   956         deleteExpectedAndActualResults($base);
       
   957         recordActualResultsAndDiff($base, $actual);
       
   958 
       
   959         if ($pixelTestFailed) {
       
   960             $imagesPresent{$base} = 1;
       
   961 
       
   962             writeToFile("$testResultsDirectory/$base-$actualTag.png", $actualPNG);
       
   963             writeToFile("$testResultsDirectory/$base-$diffsTag.png", $diffPNG);
       
   964 
       
   965             my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
       
   966             copy("$expectedPixelDir/$base-$expectedTag.png", "$testResultsDirectory/$base-$expectedTag.png");
       
   967 
       
   968             open DIFFHTML, ">$testResultsDirectory/$base-$diffsTag.html" or die;
       
   969             print DIFFHTML "<html>\n";
       
   970             print DIFFHTML "<head>\n";
       
   971             print DIFFHTML "<title>$base Image Compare</title>\n";
       
   972             print DIFFHTML "<script language=\"Javascript\" type=\"text/javascript\">\n";
       
   973             print DIFFHTML "var currentImage = 0;\n";
       
   974             print DIFFHTML "var imageNames = new Array(\"Actual\", \"Expected\");\n";
       
   975             print DIFFHTML "var imagePaths = new Array(\"$testName-$actualTag.png\", \"$testName-$expectedTag.png\");\n";
       
   976             if (-f "$testDirectory/$base-w3c.png") {
       
   977                 copy("$testDirectory/$base-w3c.png", "$testResultsDirectory/$base-w3c.png");
       
   978                 print DIFFHTML "imageNames.push(\"W3C\");\n";
       
   979                 print DIFFHTML "imagePaths.push(\"$testName-w3c.png\");\n";
       
   980             }
       
   981             print DIFFHTML "function animateImage() {\n";
       
   982             print DIFFHTML "    var image = document.getElementById(\"animatedImage\");\n";
       
   983             print DIFFHTML "    var imageText = document.getElementById(\"imageText\");\n";
       
   984             print DIFFHTML "    image.src = imagePaths[currentImage];\n";
       
   985             print DIFFHTML "    imageText.innerHTML = imageNames[currentImage] + \" Image\";\n";
       
   986             print DIFFHTML "    currentImage = (currentImage + 1) % imageNames.length;\n";
       
   987             print DIFFHTML "    setTimeout('animateImage()',2000);\n";
       
   988             print DIFFHTML "}\n";
       
   989             print DIFFHTML "</script>\n";
       
   990             print DIFFHTML "</head>\n";
       
   991             print DIFFHTML "<body onLoad=\"animateImage();\">\n";
       
   992             print DIFFHTML "<table>\n";
       
   993             if ($diffPercentage) {
       
   994                 print DIFFHTML "<tr>\n";
       
   995                 print DIFFHTML "<td>Difference between images: <a href=\"$testName-$diffsTag.png\">$diffPercentage%</a></td>\n";
       
   996                 print DIFFHTML "</tr>\n";
       
   997             }
       
   998             print DIFFHTML "<tr>\n";
       
   999             print DIFFHTML "<td><a href=\"" . toURL("$testDirectory/$test") . "\">test file</a></td>\n";
       
  1000             print DIFFHTML "</tr>\n";
       
  1001             print DIFFHTML "<tr>\n";
       
  1002             print DIFFHTML "<td id=\"imageText\" style=\"text-weight: bold;\">Actual Image</td>\n";
       
  1003             print DIFFHTML "</tr>\n";
       
  1004             print DIFFHTML "<tr>\n";
       
  1005             print DIFFHTML "<td><img src=\"$testName-$actualTag.png\" id=\"animatedImage\"></td>\n";
       
  1006             print DIFFHTML "</tr>\n";
       
  1007             print DIFFHTML "</table>\n";
       
  1008             print DIFFHTML "</body>\n";
       
  1009             print DIFFHTML "</html>\n";
       
  1010         }
       
  1011     }
       
  1012 
       
  1013     if ($error) {
       
  1014         my $dir = "$testResultsDirectory/$base";
       
  1015         $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
       
  1016         mkpath $dir;
       
  1017         
       
  1018         writeToFile("$testResultsDirectory/$base-$errorTag.txt", $error);
       
  1019         
       
  1020         $counts{error}++;
       
  1021         push @{$tests{error}}, $test;
       
  1022     }
       
  1023 
       
  1024     countFinishedTest($test, $base, $result, $isText);
       
  1025     last if stopRunningTestsEarlyIfNeeded();
       
  1026 }
       
  1027 
       
  1028 my $totalTestingTime = time - $overallStartTime;
       
  1029 my $waitTime = getWaitTime();
       
  1030 if ($waitTime > 0.1) {
       
  1031     my $normalizedTestingTime = $totalTestingTime - $waitTime;
       
  1032     printf "\n%0.2fs HTTPD waiting time\n", $waitTime . "";
       
  1033     printf "%0.2fs normalized testing time", $normalizedTestingTime . "";
       
  1034 }
       
  1035 printf "\n%0.2fs total testing time\n", $totalTestingTime . "";
       
  1036 
       
  1037 !$isDumpToolOpen || die "Failed to close $dumpToolName.\n";
       
  1038 
       
  1039 $isHttpdOpen = !closeHTTPD();
       
  1040 closeWebSocketServer();
       
  1041 
       
  1042 # Because multiple instances of this script are running concurrently we cannot 
       
  1043 # safely delete this symlink.
       
  1044 # system "rm /tmp/LayoutTests";
       
  1045 
       
  1046 # FIXME: Do we really want to check the image-comparison tool for leaks every time?
       
  1047 if ($isDiffToolOpen && $shouldCheckLeaks) {
       
  1048     $totalLeaks += countAndPrintLeaks("ImageDiff", $imageDiffToolPID, "$testResultsDirectory/ImageDiff-leaks.txt");
       
  1049 }
       
  1050 
       
  1051 if ($totalLeaks) {
       
  1052     if ($mergeDepth) {
       
  1053         parseLeaksandPrintUniqueLeaks();
       
  1054     } else { 
       
  1055         print "\nWARNING: $totalLeaks total leaks found!\n";
       
  1056         print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
       
  1057     }
       
  1058 }
       
  1059 
       
  1060 close IN;
       
  1061 close OUT;
       
  1062 close ERROR;
       
  1063 
       
  1064 if ($report10Slowest) {
       
  1065     print "\n\nThe 10 slowest tests:\n\n";
       
  1066     my $count = 0;
       
  1067     for my $test (sort slowestcmp keys %durations) {
       
  1068         printf "%0.2f secs: %s\n", $durations{$test}, $test;
       
  1069         last if ++$count == 10;
       
  1070     }
       
  1071 }
       
  1072 
       
  1073 print "\n";
       
  1074 
       
  1075 if ($skippedOnly && $counts{"match"}) {
       
  1076     print "The following tests are in the Skipped file (" . File::Spec->abs2rel("$platformTestDirectory/Skipped", $testDirectory) . "), but succeeded:\n";
       
  1077     foreach my $test (@{$tests{"match"}}) {
       
  1078         print "  $test\n";
       
  1079     }
       
  1080 }
       
  1081 
       
  1082 if ($resetResults || ($counts{match} && $counts{match} == $count)) {
       
  1083     print "all $count test cases succeeded\n";
       
  1084     unlink $testResults;
       
  1085     exit;
       
  1086 }
       
  1087 
       
  1088 printResults();
       
  1089 
       
  1090 mkpath $testResultsDirectory;
       
  1091 
       
  1092 open HTML, ">", $testResults or die "Failed to open $testResults. $!";
       
  1093 print HTML "<html>\n";
       
  1094 print HTML "<head>\n";
       
  1095 print HTML "<title>Layout Test Results</title>\n";
       
  1096 print HTML "</head>\n";
       
  1097 print HTML "<body>\n";
       
  1098 
       
  1099 if ($ignoreMetrics) {
       
  1100     print HTML "<h4>Tested with metrics ignored.</h4>";
       
  1101 }
       
  1102 
       
  1103 print HTML htmlForResultsSection(@{$tests{mismatch}}, "Tests where results did not match expected results", \&linksForMismatchTest);
       
  1104 print HTML htmlForResultsSection(@{$tests{timedout}}, "Tests that timed out", \&linksForErrorTest);
       
  1105 print HTML htmlForResultsSection(@{$tests{crash}}, "Tests that caused the DumpRenderTree tool to crash", \&linksForErrorTest);
       
  1106 print HTML htmlForResultsSection(@{$tests{error}}, "Tests that had stderr output", \&linksForErrorTest);
       
  1107 print HTML htmlForResultsSection(@{$tests{new}}, "Tests that had no expected results (probably new)", \&linksForNewTest);
       
  1108 
       
  1109 print HTML "</body>\n";
       
  1110 print HTML "</html>\n";
       
  1111 close HTML;
       
  1112 
       
  1113 my @configurationArgs = argumentsForConfiguration();
       
  1114 
       
  1115 if (isGtk()) {
       
  1116   system "WebKitTools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
       
  1117 } elsif (isQt()) {
       
  1118   unshift @configurationArgs, qw(-graphicssystem raster -style windows);
       
  1119   if (isCygwin()) {
       
  1120     $testResults = "/" . toWindowsPath($testResults);
       
  1121     $testResults =~ s/\\/\//g;
       
  1122   }
       
  1123   system "WebKitTools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
       
  1124 } elsif (isCygwin()) {
       
  1125   system "cygstart", $testResults if $launchSafari;
       
  1126 } else {
       
  1127   system "WebKitTools/Scripts/run-safari", @configurationArgs, "-NSOpen", $testResults if $launchSafari;
       
  1128 }
       
  1129 
       
  1130 closeCygpaths() if isCygwin();
       
  1131 
       
  1132 exit 1;
       
  1133 
       
  1134 sub countAndPrintLeaks($$$)
       
  1135 {
       
  1136     my ($dumpToolName, $dumpToolPID, $leaksFilePath) = @_;
       
  1137 
       
  1138     print "\n" unless $atLineStart;
       
  1139     $atLineStart = 1;
       
  1140 
       
  1141     # We are excluding the following reported leaks so they don't get in our way when looking for WebKit leaks:
       
  1142     # This allows us ignore known leaks and only be alerted when new leaks occur. Some leaks are in the old
       
  1143     # versions of the system frameworks that are being used by the leaks bots. Even though a leak has been
       
  1144     # fixed, it will be listed here until the bot has been updated with the newer frameworks.
       
  1145 
       
  1146     my @typesToExclude = (
       
  1147     );
       
  1148 
       
  1149     my @callStacksToExclude = (
       
  1150         "Flash_EnforceLocalSecurity" # leaks in Flash plug-in code, rdar://problem/4449747
       
  1151     );
       
  1152 
       
  1153     if (isTiger()) {
       
  1154         # Leak list for the version of Tiger used on the build bot.
       
  1155         push @callStacksToExclude, (
       
  1156             "CFRunLoopRunSpecific \\| malloc_zone_malloc", "CFRunLoopRunSpecific \\| CFAllocatorAllocate ", # leak in CFRunLoopRunSpecific, rdar://problem/4670839
       
  1157             "CGImageSourceGetPropertiesAtIndex", # leak in ImageIO, rdar://problem/4628809
       
  1158             "FOGetCoveredUnicodeChars", # leak in ATS, rdar://problem/3943604
       
  1159             "GetLineDirectionPreference", "InitUnicodeUtilities", # leaks tool falsely reporting leak in CFNotificationCenterAddObserver, rdar://problem/4964790
       
  1160             "ICCFPrefWrapper::GetPrefDictionary", # leaks in Internet Config. code, rdar://problem/4449794
       
  1161             "NSHTTPURLProtocol setResponseHeader:", # leak in multipart/mixed-replace handling in Foundation, no Radar, but fixed in Leopard
       
  1162             "NSURLCache cachedResponseForRequest", # leak in CFURL cache, rdar://problem/4768430
       
  1163             "PCFragPrepareClosureFromFile", # leak in Code Fragment Manager, rdar://problem/3426998
       
  1164             "WebCore::Selection::toRange", # bug in 'leaks', rdar://problem/4967949
       
  1165             "WebCore::SubresourceLoader::create", # bug in 'leaks', rdar://problem/4985806
       
  1166             "_CFPreferencesDomainDeepCopyDictionary", # leak in CFPreferences, rdar://problem/4220786
       
  1167             "_objc_msgForward", # leak in NSSpellChecker, rdar://problem/4965278
       
  1168             "gldGetString", # leak in OpenGL, rdar://problem/5013699
       
  1169             "_setDefaultUserInfoFromURL", # leak in NSHTTPAuthenticator, rdar://problem/5546453 
       
  1170             "SSLHandshake", # leak in SSL, rdar://problem/5546440 
       
  1171             "SecCertificateCreateFromData", # leak in SSL code, rdar://problem/4464397
       
  1172         );
       
  1173         push @typesToExclude, (
       
  1174             "THRD", # bug in 'leaks', rdar://problem/3387783
       
  1175             "DRHT", # ditto (endian little hate i)
       
  1176         );
       
  1177     }
       
  1178 
       
  1179     if (isLeopard()) {
       
  1180         # Leak list for the version of Leopard used on the build bot.
       
  1181         push @callStacksToExclude, (
       
  1182             "CFHTTPMessageAppendBytes", # leak in CFNetwork, rdar://problem/5435912
       
  1183             "sendDidReceiveDataCallback", # leak in CFNetwork, rdar://problem/5441619
       
  1184             "_CFHTTPReadStreamReadMark", # leak in CFNetwork, rdar://problem/5441468
       
  1185             "httpProtocolStart", # leak in CFNetwork, rdar://problem/5468837
       
  1186             "_CFURLConnectionSendCallbacks", # leak in CFNetwork, rdar://problem/5441600
       
  1187             "DispatchQTMsg", # leak in QuickTime, PPC only, rdar://problem/5667132
       
  1188             "QTMovieContentView createVisualContext", # leak in QuickTime, PPC only, rdar://problem/5667132
       
  1189             "_CopyArchitecturesForJVMVersion", # leak in Java, rdar://problem/5910823
       
  1190         );
       
  1191     }
       
  1192 
       
  1193     if (isSnowLeopard()) {
       
  1194         push @callStacksToExclude, (
       
  1195             "readMakerNoteProps", # <rdar://problem/7156432> leak in ImageIO
       
  1196             "QTKitMovieControllerView completeUISetup", # <rdar://problem/7155156> leak in QTKit
       
  1197             "getVMInitArgs", # <rdar://problem/7714444> leak in Java
       
  1198             "Java_java_lang_System_initProperties", # <rdar://problem/7714465> leak in Java
       
  1199             "glrCompExecuteKernel", # <rdar://problem/7815391> leak in graphics driver while using OpenGL
       
  1200         );
       
  1201     }
       
  1202 
       
  1203     if (isDarwin() && !isTiger() && !isLeopard() && !isSnowLeopard()) {
       
  1204         push @callStacksToExclude, (
       
  1205             "CGGradientCreateWithColorComponents", # leak in CoreGraphics, <rdar://problem/7888492>
       
  1206         );
       
  1207     }
       
  1208 
       
  1209     my $leaksTool = sourceDir() . "/WebKitTools/Scripts/run-leaks";
       
  1210     my $excludeString = "--exclude-callstack '" . (join "' --exclude-callstack '", @callStacksToExclude) . "'";
       
  1211     $excludeString .= " --exclude-type '" . (join "' --exclude-type '", @typesToExclude) . "'" if @typesToExclude;
       
  1212 
       
  1213     print " ? checking for leaks in $dumpToolName\n";
       
  1214     my $leaksOutput = `$leaksTool $excludeString $dumpToolPID`;
       
  1215     my ($count, $bytes) = $leaksOutput =~ /Process $dumpToolPID: (\d+) leaks? for (\d+) total/;
       
  1216     my ($excluded) = $leaksOutput =~ /(\d+) leaks? excluded/;
       
  1217 
       
  1218     my $adjustedCount = $count;
       
  1219     $adjustedCount -= $excluded if $excluded;
       
  1220 
       
  1221     if (!$adjustedCount) {
       
  1222         print " - no leaks found\n";
       
  1223         unlink $leaksFilePath;
       
  1224         return 0;
       
  1225     } else {
       
  1226         my $dir = $leaksFilePath;
       
  1227         $dir =~ s|/[^/]+$|| or die;
       
  1228         mkpath $dir;
       
  1229 
       
  1230         if ($excluded) {
       
  1231             print " + $adjustedCount leaks ($bytes bytes including $excluded excluded leaks) were found, details in $leaksFilePath\n";
       
  1232         } else {
       
  1233             print " + $count leaks ($bytes bytes) were found, details in $leaksFilePath\n";
       
  1234         }
       
  1235 
       
  1236         writeToFile($leaksFilePath, $leaksOutput);
       
  1237         
       
  1238         push @leaksFilenames, $leaksFilePath;
       
  1239     }
       
  1240 
       
  1241     return $adjustedCount;
       
  1242 }
       
  1243 
       
  1244 sub writeToFile($$)
       
  1245 {
       
  1246     my ($filePath, $contents) = @_;
       
  1247     open NEWFILE, ">", "$filePath" or die "Could not create $filePath. $!\n";
       
  1248     print NEWFILE $contents;
       
  1249     close NEWFILE;
       
  1250 }
       
  1251 
       
  1252 # Break up a path into the directory (with slash) and base name.
       
  1253 sub splitpath($)
       
  1254 {
       
  1255     my ($path) = @_;
       
  1256 
       
  1257     my $pathSeparator = "/";
       
  1258     my $dirname = dirname($path) . $pathSeparator;
       
  1259     $dirname = "" if $dirname eq "." . $pathSeparator;
       
  1260 
       
  1261     return ($dirname, basename($path));
       
  1262 }
       
  1263 
       
  1264 # Sort first by directory, then by file, so all paths in one directory are grouped
       
  1265 # rather than being interspersed with items from subdirectories.
       
  1266 # Use numericcmp to sort directory and filenames to make order logical.
       
  1267 sub pathcmp($$)
       
  1268 {
       
  1269     my ($patha, $pathb) = @_;
       
  1270 
       
  1271     my ($dira, $namea) = splitpath($patha);
       
  1272     my ($dirb, $nameb) = splitpath($pathb);
       
  1273 
       
  1274     return numericcmp($dira, $dirb) if $dira ne $dirb;
       
  1275     return numericcmp($namea, $nameb);
       
  1276 }
       
  1277 
       
  1278 # Sort numeric parts of strings as numbers, other parts as strings.
       
  1279 # Makes 1.33 come after 1.3, which is cool.
       
  1280 sub numericcmp($$)
       
  1281 {
       
  1282     my ($aa, $bb) = @_;
       
  1283 
       
  1284     my @a = split /(\d+)/, $aa;
       
  1285     my @b = split /(\d+)/, $bb;
       
  1286 
       
  1287     # Compare one chunk at a time.
       
  1288     # Each chunk is either all numeric digits, or all not numeric digits.
       
  1289     while (@a && @b) {
       
  1290         my $a = shift @a;
       
  1291         my $b = shift @b;
       
  1292         
       
  1293         # Use numeric comparison if chunks are non-equal numbers.
       
  1294         return $a <=> $b if $a =~ /^\d/ && $b =~ /^\d/ && $a != $b;
       
  1295 
       
  1296         # Use string comparison if chunks are any other kind of non-equal string.
       
  1297         return $a cmp $b if $a ne $b;
       
  1298     }
       
  1299     
       
  1300     # One of the two is now empty; compare lengths for result in this case.
       
  1301     return @a <=> @b;
       
  1302 }
       
  1303 
       
  1304 # Sort slowest tests first.
       
  1305 sub slowestcmp($$)
       
  1306 {
       
  1307     my ($testa, $testb) = @_;
       
  1308 
       
  1309     my $dura = $durations{$testa};
       
  1310     my $durb = $durations{$testb};
       
  1311     return $durb <=> $dura if $dura != $durb;
       
  1312     return pathcmp($testa, $testb);
       
  1313 }
       
  1314 
       
  1315 sub launchWithEnv(\@\%)
       
  1316 {
       
  1317     my ($args, $env) = @_;
       
  1318 
       
  1319     # Dump the current environment as perl code and then put it in quotes so it is one parameter.
       
  1320     my $environmentDumper = Data::Dumper->new([\%{$env}], [qw(*ENV)]);
       
  1321     $environmentDumper->Indent(0);
       
  1322     $environmentDumper->Purity(1);
       
  1323     my $allEnvVars = $environmentDumper->Dump();
       
  1324     unshift @{$args}, "\"$allEnvVars\"";
       
  1325 
       
  1326     my $execScript = File::Spec->catfile(sourceDir(), qw(WebKitTools Scripts execAppWithEnv));
       
  1327     unshift @{$args}, $execScript;
       
  1328     return @{$args};
       
  1329 }
       
  1330 
       
  1331 sub resolveAndMakeTestResultsDirectory()
       
  1332 {
       
  1333     my $absTestResultsDirectory = File::Spec->rel2abs(glob $testResultsDirectory);
       
  1334     mkpath $absTestResultsDirectory;
       
  1335     return $absTestResultsDirectory;
       
  1336 }
       
  1337 
       
  1338 sub openDiffTool()
       
  1339 {
       
  1340     return if $isDiffToolOpen;
       
  1341     return if !$pixelTests;
       
  1342 
       
  1343     my %CLEAN_ENV;
       
  1344     $CLEAN_ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
       
  1345     $imageDiffToolPID = open2(\*DIFFIN, \*DIFFOUT, $imageDiffTool, launchWithEnv(@diffToolArgs, %CLEAN_ENV)) or die "unable to open $imageDiffTool\n";
       
  1346     $isDiffToolOpen = 1;
       
  1347 }
       
  1348 
       
  1349 sub openDumpTool()
       
  1350 {
       
  1351     return if $isDumpToolOpen;
       
  1352 
       
  1353     my %CLEAN_ENV;
       
  1354 
       
  1355     # Generic environment variables
       
  1356     if (defined $ENV{'WEBKIT_TESTFONTS'}) {
       
  1357         $CLEAN_ENV{WEBKIT_TESTFONTS} = $ENV{'WEBKIT_TESTFONTS'};
       
  1358     }
       
  1359 
       
  1360     # unique temporary directory for each DumpRendertree - needed for running more DumpRenderTree in parallel
       
  1361     $CLEAN_ENV{DUMPRENDERTREE_TEMP} = File::Temp::tempdir('DumpRenderTree-XXXXXX', TMPDIR => 1, CLEANUP => 1);
       
  1362     $CLEAN_ENV{XML_CATALOG_FILES} = ""; # work around missing /etc/catalog <rdar://problem/4292995>
       
  1363 
       
  1364     # Platform spesifics
       
  1365     if (isLinux()) {
       
  1366         if (defined $ENV{'DISPLAY'}) {
       
  1367             $CLEAN_ENV{DISPLAY} = $ENV{'DISPLAY'};
       
  1368         } else {
       
  1369             $CLEAN_ENV{DISPLAY} = ":1";
       
  1370         }
       
  1371         if (defined $ENV{'XAUTHORITY'}) {
       
  1372             $CLEAN_ENV{XAUTHORITY} = $ENV{'XAUTHORITY'};
       
  1373         }
       
  1374 
       
  1375         $CLEAN_ENV{HOME} = $ENV{'HOME'};
       
  1376 
       
  1377         if (defined $ENV{'LD_LIBRARY_PATH'}) {
       
  1378             $CLEAN_ENV{LD_LIBRARY_PATH} = $ENV{'LD_LIBRARY_PATH'};
       
  1379         }
       
  1380         if (defined $ENV{'DBUS_SESSION_BUS_ADDRESS'}) {
       
  1381             $CLEAN_ENV{DBUS_SESSION_BUS_ADDRESS} = $ENV{'DBUS_SESSION_BUS_ADDRESS'};
       
  1382         }
       
  1383     } elsif (isDarwin()) {
       
  1384         if (defined $ENV{'DYLD_LIBRARY_PATH'}) {
       
  1385             $CLEAN_ENV{DYLD_LIBRARY_PATH} = $ENV{'DYLD_LIBRARY_PATH'};
       
  1386         }
       
  1387 
       
  1388         $CLEAN_ENV{DYLD_FRAMEWORK_PATH} = $productDir;
       
  1389         $CLEAN_ENV{DYLD_INSERT_LIBRARIES} = "/usr/lib/libgmalloc.dylib" if $guardMalloc;
       
  1390     } elsif (isCygwin()) {
       
  1391         $CLEAN_ENV{HOMEDRIVE} = $ENV{'HOMEDRIVE'};
       
  1392         $CLEAN_ENV{HOMEPATH} = $ENV{'HOMEPATH'};
       
  1393 
       
  1394         setPathForRunningWebKitApp(\%CLEAN_ENV);
       
  1395     }
       
  1396 
       
  1397     # Port specifics
       
  1398     if (isGtk()) {
       
  1399         $CLEAN_ENV{GTK_MODULES} = "gail";
       
  1400     }
       
  1401 
       
  1402     if (isQt()) {
       
  1403         $CLEAN_ENV{QTWEBKIT_PLUGIN_PATH} = productDir() . "/lib/plugins";
       
  1404         $CLEAN_ENV{QT_DRT_WEBVIEW_MODE} = $ENV{"QT_DRT_WEBVIEW_MODE"};
       
  1405     }
       
  1406     
       
  1407     my @args = ($dumpTool, @toolArgs);
       
  1408     if (isAppleMacWebKit() and !isTiger()) { 
       
  1409         unshift @args, "arch", "-" . architecture();             
       
  1410     }
       
  1411 
       
  1412     if ($useValgrind) {
       
  1413         unshift @args, "valgrind", "--suppressions=$platformBaseDirectory/qt/SuppressedValgrindErrors";
       
  1414     } 
       
  1415 
       
  1416     $CLEAN_ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
       
  1417 
       
  1418     $dumpToolPID = open3(\*OUT, \*IN, \*ERROR, launchWithEnv(@args, %CLEAN_ENV)) or die "Failed to start tool: $dumpTool\n";
       
  1419     $isDumpToolOpen = 1;
       
  1420     $dumpToolCrashed = 0;
       
  1421 }
       
  1422 
       
  1423 sub closeDumpTool()
       
  1424 {
       
  1425     return if !$isDumpToolOpen;
       
  1426 
       
  1427     close IN;
       
  1428     close OUT;
       
  1429     waitpid $dumpToolPID, 0;
       
  1430     
       
  1431     # check for WebCore counter leaks.
       
  1432     if ($shouldCheckLeaks) {
       
  1433         while (<ERROR>) {
       
  1434             print;
       
  1435         }
       
  1436     }
       
  1437     close ERROR;
       
  1438     $isDumpToolOpen = 0;
       
  1439 }
       
  1440 
       
  1441 sub dumpToolDidCrash()
       
  1442 {
       
  1443     return 1 if $dumpToolCrashed;
       
  1444     return 0 unless $isDumpToolOpen;
       
  1445     my $pid = waitpid(-1, WNOHANG);
       
  1446     return 1 if ($pid == $dumpToolPID);
       
  1447 
       
  1448     # On Mac OS X, crashing may be significantly delayed by crash reporter.
       
  1449     return 0 unless isAppleMacWebKit();
       
  1450 
       
  1451     return DumpRenderTreeSupport::processIsCrashing($dumpToolPID);
       
  1452 }
       
  1453 
       
  1454 sub configureAndOpenHTTPDIfNeeded()
       
  1455 {
       
  1456     return if $isHttpdOpen;
       
  1457     my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
       
  1458     my $listen = "127.0.0.1:$httpdPort";
       
  1459     my @args = (
       
  1460         "-c", "CustomLog \"$absTestResultsDirectory/access_log.txt\" common",
       
  1461         "-c", "ErrorLog \"$absTestResultsDirectory/error_log.txt\"",
       
  1462         "-C", "Listen $listen"
       
  1463     );
       
  1464 
       
  1465     my @defaultArgs = getDefaultConfigForTestDirectory($testDirectory);
       
  1466     @args = (@defaultArgs, @args);
       
  1467 
       
  1468     waitForHTTPDLock() if $shouldWaitForHTTPD;
       
  1469     $isHttpdOpen = openHTTPD(@args);
       
  1470 }
       
  1471 
       
  1472 sub checkPythonVersion()
       
  1473 {
       
  1474     # we have not chdir to sourceDir yet.
       
  1475     system sourceDir() . "/WebKitTools/Scripts/ensure-valid-python", "--check-only";
       
  1476     return exitStatus($?) == 0;
       
  1477 }
       
  1478 
       
  1479 sub openWebSocketServerIfNeeded()
       
  1480 {
       
  1481     return 1 if $isWebSocketServerOpen;
       
  1482     return 0 if $failedToStartWebSocketServer;
       
  1483 
       
  1484     my $webSocketHandlerDir = "$testDirectory";
       
  1485     my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
       
  1486     $webSocketServerPidFile = "$absTestResultsDirectory/websocket.pid";
       
  1487 
       
  1488     my @args = (
       
  1489         "WebKitTools/Scripts/new-run-webkit-websocketserver",
       
  1490         "--server", "start",
       
  1491         "--port", "$webSocketPort",
       
  1492         "--root", "$webSocketHandlerDir",
       
  1493         "--output-dir", "$absTestResultsDirectory",
       
  1494         "--pidfile", "$webSocketServerPidFile"
       
  1495     );
       
  1496     system "/usr/bin/python", @args;
       
  1497 
       
  1498     $isWebSocketServerOpen = 1;
       
  1499     return 1;
       
  1500 }
       
  1501 
       
  1502 sub closeWebSocketServer()
       
  1503 {
       
  1504     return if !$isWebSocketServerOpen;
       
  1505 
       
  1506     my @args = (
       
  1507         "WebKitTools/Scripts/new-run-webkit-websocketserver",
       
  1508         "--server", "stop",
       
  1509         "--pidfile", "$webSocketServerPidFile"
       
  1510     );
       
  1511     system "/usr/bin/python", @args;
       
  1512     unlink "$webSocketServerPidFile";
       
  1513 
       
  1514     # wss is disabled until all platforms support pyOpenSSL.
       
  1515     $isWebSocketServerOpen = 0;
       
  1516 }
       
  1517 
       
  1518 sub fileNameWithNumber($$)
       
  1519 {
       
  1520     my ($base, $number) = @_;
       
  1521     return "$base$number" if ($number > 1);
       
  1522     return $base;
       
  1523 }
       
  1524 
       
  1525 sub processIgnoreTests($$)
       
  1526 {
       
  1527     my @ignoreList = split(/\s*,\s*/, shift);
       
  1528     my $listName = shift;
       
  1529 
       
  1530     my $disabledSuffix = "-disabled";
       
  1531 
       
  1532     my $addIgnoredDirectories = sub {
       
  1533         return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
       
  1534         $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)} = 1;
       
  1535         return @_;
       
  1536     };
       
  1537     foreach my $item (@ignoreList) {
       
  1538         my $path = catfile($testDirectory, $item); 
       
  1539         if (-d $path) {
       
  1540             $ignoredDirectories{$item} = 1;
       
  1541             find({ preprocess => $addIgnoredDirectories, wanted => sub {} }, $path);
       
  1542         }
       
  1543         elsif (-f $path) {
       
  1544             $ignoredFiles{$item} = 1;
       
  1545         } elsif (-f $path . $disabledSuffix) {
       
  1546             # The test is disabled, so do nothing.
       
  1547         } else {
       
  1548             print "$listName list contained '$item', but no file of that name could be found\n";
       
  1549         }
       
  1550     }
       
  1551 }
       
  1552 
       
  1553 sub stripExtension($)
       
  1554 {
       
  1555     my ($test) = @_;
       
  1556 
       
  1557     $test =~ s/\.[a-zA-Z]+$//;
       
  1558     return $test;
       
  1559 }
       
  1560 
       
  1561 sub isTextOnlyTest($)
       
  1562 {
       
  1563     my ($actual) = @_;
       
  1564     my $isText;
       
  1565     if ($actual =~ /^layer at/ms) {
       
  1566         $isText = 0;
       
  1567     } else {
       
  1568         $isText = 1;
       
  1569     }
       
  1570     return $isText;
       
  1571 }
       
  1572 
       
  1573 sub expectedDirectoryForTest($;$;$)
       
  1574 {
       
  1575     my ($base, $isText, $expectedExtension) = @_;
       
  1576 
       
  1577     my @directories = @platformResultHierarchy;
       
  1578     push @directories, map { catdir($platformBaseDirectory, $_) } qw(mac-snowleopard mac) if isCygwin();
       
  1579     push @directories, $expectedDirectory;
       
  1580 
       
  1581     # If we already have expected results, just return their location.
       
  1582     foreach my $directory (@directories) {
       
  1583         return $directory if (-f "$directory/$base-$expectedTag.$expectedExtension");
       
  1584     }
       
  1585 
       
  1586     # For cross-platform tests, text-only results should go in the cross-platform directory,
       
  1587     # while render tree dumps should go in the least-specific platform directory.
       
  1588     return $isText ? $expectedDirectory : $platformResultHierarchy[$#platformResultHierarchy];
       
  1589 }
       
  1590 
       
  1591 sub countFinishedTest($$$$)
       
  1592 {
       
  1593     my ($test, $base, $result, $isText) = @_;
       
  1594 
       
  1595     if (($count + 1) % $testsPerDumpTool == 0 || $count == $#tests) {
       
  1596         if ($shouldCheckLeaks) {
       
  1597             my $fileName;
       
  1598             if ($testsPerDumpTool == 1) {
       
  1599                 $fileName = "$testResultsDirectory/$base-leaks.txt";
       
  1600             } else {
       
  1601                 $fileName = "$testResultsDirectory/" . fileNameWithNumber($dumpToolName, $leaksOutputFileNumber) . "-leaks.txt";
       
  1602             }
       
  1603             my $leakCount = countAndPrintLeaks($dumpToolName, $dumpToolPID, $fileName);
       
  1604             $totalLeaks += $leakCount;
       
  1605             $leaksOutputFileNumber++ if ($leakCount);
       
  1606         }
       
  1607 
       
  1608         closeDumpTool();
       
  1609     }
       
  1610     
       
  1611     $count++;
       
  1612     $counts{$result}++;
       
  1613     push @{$tests{$result}}, $test;
       
  1614 }
       
  1615 
       
  1616 sub testCrashedOrTimedOut($$$$$)
       
  1617 {
       
  1618     my ($test, $base, $didCrash, $actual, $error) = @_;
       
  1619 
       
  1620     printFailureMessageForTest($test, $didCrash ? "crashed" : "timed out");
       
  1621 
       
  1622     sampleDumpTool() unless $didCrash;
       
  1623 
       
  1624     my $dir = "$testResultsDirectory/$base";
       
  1625     $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
       
  1626     mkpath $dir;
       
  1627 
       
  1628     deleteExpectedAndActualResults($base);
       
  1629 
       
  1630     if (defined($error) && length($error)) {
       
  1631         writeToFile("$testResultsDirectory/$base-$errorTag.txt", $error);
       
  1632     }
       
  1633 
       
  1634     recordActualResultsAndDiff($base, $actual);
       
  1635 
       
  1636     kill 9, $dumpToolPID unless $didCrash;
       
  1637 
       
  1638     closeDumpTool();
       
  1639     
       
  1640     return unless isCygwin() && !$didCrash && $base =~ /^http/;
       
  1641     # On Cygwin, http tests timing out can be a symptom of a non-responsive httpd.
       
  1642     # If we timed out running an http test, try restarting httpd.
       
  1643     $isHttpdOpen = !closeHTTPD();
       
  1644     configureAndOpenHTTPDIfNeeded();
       
  1645 }
       
  1646 
       
  1647 sub printFailureMessageForTest($$)
       
  1648 {
       
  1649     my ($test, $description) = @_;
       
  1650 
       
  1651     unless ($verbose) {
       
  1652         print "\n" unless $atLineStart;
       
  1653         print "$test -> ";
       
  1654     }
       
  1655     print "$description\n";
       
  1656     $atLineStart = 1;
       
  1657 }
       
  1658 
       
  1659 my %cygpaths = ();
       
  1660 
       
  1661 sub openCygpathIfNeeded($)
       
  1662 {
       
  1663     my ($options) = @_;
       
  1664 
       
  1665     return unless isCygwin();
       
  1666     return $cygpaths{$options} if $cygpaths{$options} && $cygpaths{$options}->{"open"};
       
  1667 
       
  1668     local (*CYGPATHIN, *CYGPATHOUT);
       
  1669     my $pid = open2(\*CYGPATHIN, \*CYGPATHOUT, "cygpath -f - $options");
       
  1670     my $cygpath =  {
       
  1671         "pid" => $pid,
       
  1672         "in" => *CYGPATHIN,
       
  1673         "out" => *CYGPATHOUT,
       
  1674         "open" => 1
       
  1675     };
       
  1676 
       
  1677     $cygpaths{$options} = $cygpath;
       
  1678 
       
  1679     return $cygpath;
       
  1680 }
       
  1681 
       
  1682 sub closeCygpaths()
       
  1683 {
       
  1684     return unless isCygwin();
       
  1685 
       
  1686     foreach my $cygpath (values(%cygpaths)) {
       
  1687         close $cygpath->{"in"};
       
  1688         close $cygpath->{"out"};
       
  1689         waitpid($cygpath->{"pid"}, 0);
       
  1690         $cygpath->{"open"} = 0;
       
  1691 
       
  1692     }
       
  1693 }
       
  1694 
       
  1695 sub convertPathUsingCygpath($$)
       
  1696 {
       
  1697     my ($path, $options) = @_;
       
  1698 
       
  1699     # cygpath -f (at least in Cygwin 1.7) converts spaces into newlines. We remove spaces here and
       
  1700     # add them back in after conversion to work around this.
       
  1701     my $spaceSubstitute = "__NOTASPACE__";
       
  1702     $path =~ s/ /\Q$spaceSubstitute\E/g;
       
  1703 
       
  1704     my $cygpath = openCygpathIfNeeded($options);
       
  1705     local *inFH = $cygpath->{"in"};
       
  1706     local *outFH = $cygpath->{"out"};
       
  1707     print outFH $path . "\n";
       
  1708     my $convertedPath = <inFH>;
       
  1709     chomp($convertedPath) if defined $convertedPath;
       
  1710 
       
  1711     $convertedPath =~ s/\Q$spaceSubstitute\E/ /g;
       
  1712     return $convertedPath;
       
  1713 }
       
  1714 
       
  1715 sub toWindowsPath($)
       
  1716 {
       
  1717     my ($path) = @_;
       
  1718     return unless isCygwin();
       
  1719 
       
  1720     return convertPathUsingCygpath($path, "-w");
       
  1721 }
       
  1722 
       
  1723 sub toURL($)
       
  1724 {
       
  1725     my ($path) = @_;
       
  1726 
       
  1727     if ($useRemoteLinksToTests) {
       
  1728         my $relativePath = File::Spec->abs2rel($path, $testDirectory);
       
  1729 
       
  1730         # If the file is below the test directory then convert it into a link to the file in SVN
       
  1731         if ($relativePath !~ /^\.\.\//) {
       
  1732             my $revision = svnRevisionForDirectory($testDirectory);
       
  1733             my $svnPath = pathRelativeToSVNRepositoryRootForPath($path);
       
  1734             return "http://trac.webkit.org/export/$revision/$svnPath";
       
  1735         }
       
  1736     }
       
  1737 
       
  1738     return $path unless isCygwin();
       
  1739 
       
  1740     return "file:///" . convertPathUsingCygpath($path, "-m");
       
  1741 }
       
  1742 
       
  1743 sub validateSkippedArg($$;$)
       
  1744 {
       
  1745     my ($option, $value, $value2) = @_;
       
  1746     my %validSkippedValues = map { $_ => 1 } qw(default ignore only);
       
  1747     $value = lc($value);
       
  1748     die "Invalid argument '" . $value . "' for option $option" unless $validSkippedValues{$value};
       
  1749     $treatSkipped = $value;
       
  1750 }
       
  1751 
       
  1752 sub htmlForResultsSection(\@$&)
       
  1753 {
       
  1754     my ($tests, $description, $linkGetter) = @_;
       
  1755 
       
  1756     my @html = ();
       
  1757     return join("\n", @html) unless @{$tests};
       
  1758 
       
  1759     push @html, "<p>$description:</p>";
       
  1760     push @html, "<table>";
       
  1761     foreach my $test (@{$tests}) {
       
  1762         push @html, "<tr>";
       
  1763         push @html, "<td><a href=\"" . toURL("$testDirectory/$test") . "\">$test</a></td>";
       
  1764         foreach my $link (@{&{$linkGetter}($test)}) {
       
  1765             push @html, "<td><a href=\"$link->{href}\">$link->{text}</a></td>";
       
  1766         }
       
  1767         push @html, "</tr>";
       
  1768     }
       
  1769     push @html, "</table>";
       
  1770 
       
  1771     return join("\n", @html);
       
  1772 }
       
  1773 
       
  1774 sub linksForExpectedAndActualResults($)
       
  1775 {
       
  1776     my ($base) = @_;
       
  1777 
       
  1778     my @links = ();
       
  1779 
       
  1780     return \@links unless -s "$testResultsDirectory/$base-$diffsTag.txt";
       
  1781     
       
  1782     my $expectedResultPath = $expectedResultPaths{$base};
       
  1783     my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
       
  1784 
       
  1785     push @links, { href => "$base-$expectedTag$expectedResultExtension", text => "expected" };
       
  1786     push @links, { href => "$base-$actualTag$expectedResultExtension", text => "actual" };
       
  1787     push @links, { href => "$base-$diffsTag.txt", text => "diff" };
       
  1788     push @links, { href => "$base-$prettyDiffTag.html", text => "pretty diff" };
       
  1789 
       
  1790     return \@links;
       
  1791 }
       
  1792 
       
  1793 sub linksForMismatchTest
       
  1794 {
       
  1795     my ($test) = @_;
       
  1796 
       
  1797     my @links = ();
       
  1798 
       
  1799     my $base = stripExtension($test);
       
  1800 
       
  1801     push @links, @{linksForExpectedAndActualResults($base)};
       
  1802     return \@links unless $pixelTests && $imagesPresent{$base};
       
  1803 
       
  1804     push @links, { href => "$base-$expectedTag.png", text => "expected image" };
       
  1805     push @links, { href => "$base-$diffsTag.html", text => "image diffs" };
       
  1806     push @links, { href => "$base-$diffsTag.png", text => "$imageDifferences{$base}%" };
       
  1807 
       
  1808     return \@links;
       
  1809 }
       
  1810 
       
  1811 sub linksForErrorTest
       
  1812 {
       
  1813     my ($test) = @_;
       
  1814 
       
  1815     my @links = ();
       
  1816 
       
  1817     my $base = stripExtension($test);
       
  1818 
       
  1819     push @links, @{linksForExpectedAndActualResults($base)};
       
  1820     push @links, { href => "$base-$errorTag.txt", text => "stderr" };
       
  1821 
       
  1822     return \@links;
       
  1823 }
       
  1824 
       
  1825 sub linksForNewTest
       
  1826 {
       
  1827     my ($test) = @_;
       
  1828 
       
  1829     my @links = ();
       
  1830 
       
  1831     my $base = stripExtension($test);
       
  1832 
       
  1833     my $expectedResultPath = $expectedResultPaths{$base};
       
  1834     my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
       
  1835 
       
  1836     push @links, { href => "$base-$actualTag$expectedResultExtension", text => "result" };
       
  1837     if ($pixelTests && $imagesPresent{$base}) {
       
  1838         push @links, { href => "$base-$expectedTag.png", text => "image" };
       
  1839     }
       
  1840 
       
  1841     return \@links;
       
  1842 }
       
  1843 
       
  1844 sub deleteExpectedAndActualResults($)
       
  1845 {
       
  1846     my ($base) = @_;
       
  1847 
       
  1848     unlink "$testResultsDirectory/$base-$actualTag.txt";
       
  1849     unlink "$testResultsDirectory/$base-$diffsTag.txt";
       
  1850     unlink "$testResultsDirectory/$base-$errorTag.txt";
       
  1851 }
       
  1852 
       
  1853 sub recordActualResultsAndDiff($$)
       
  1854 {
       
  1855     my ($base, $actualResults) = @_;
       
  1856 
       
  1857     return unless defined($actualResults) && length($actualResults);
       
  1858 
       
  1859     my $expectedResultPath = $expectedResultPaths{$base};
       
  1860     my ($expectedResultFileNameMinusExtension, $expectedResultDirectoryPath, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
       
  1861     my $actualResultsPath = "$testResultsDirectory/$base-$actualTag$expectedResultExtension";
       
  1862     my $copiedExpectedResultsPath = "$testResultsDirectory/$base-$expectedTag$expectedResultExtension";
       
  1863 
       
  1864     mkpath(dirname($actualResultsPath));
       
  1865     writeToFile("$actualResultsPath", $actualResults);
       
  1866 
       
  1867     if (-f $expectedResultPath) {
       
  1868         copy("$expectedResultPath", "$copiedExpectedResultsPath");
       
  1869     } else {
       
  1870         open EMPTY, ">$copiedExpectedResultsPath";
       
  1871         close EMPTY;
       
  1872     }
       
  1873 
       
  1874     my $diffOuputBasePath = "$testResultsDirectory/$base";
       
  1875     my $diffOutputPath = "$diffOuputBasePath-$diffsTag.txt";
       
  1876     system "diff -u \"$copiedExpectedResultsPath\" \"$actualResultsPath\" > \"$diffOutputPath\"";
       
  1877 
       
  1878     my $prettyDiffOutputPath = "$diffOuputBasePath-$prettyDiffTag.html";
       
  1879     my $prettyPatchPath = "BugsSite/PrettyPatch/";
       
  1880     my $prettifyPath = "$prettyPatchPath/prettify.rb";
       
  1881     system "ruby -I \"$prettyPatchPath\" \"$prettifyPath\" \"$diffOutputPath\" > \"$prettyDiffOutputPath\"";
       
  1882 }
       
  1883 
       
  1884 sub buildPlatformResultHierarchy()
       
  1885 {
       
  1886     mkpath($platformTestDirectory) if ($platform eq "undefined" && !-d "$platformTestDirectory");
       
  1887 
       
  1888     my @platforms;
       
  1889     
       
  1890     my $isMac = $platform =~ /^mac/;
       
  1891     my $isWin = $platform =~ /^win/;
       
  1892     if ($isMac || $isWin) {
       
  1893         my $effectivePlatform = $platform;
       
  1894         if ($platform eq "mac-wk2") {
       
  1895             push @platforms, "mac-wk2";
       
  1896             $effectivePlatform = $realPlatform;
       
  1897         }
       
  1898 
       
  1899         my @platformList = $isMac ? @macPlatforms : @winPlatforms;
       
  1900         my $i;
       
  1901         for ($i = 0; $i < @platformList; $i++) {
       
  1902             last if $platformList[$i] eq $effectivePlatform;
       
  1903         }
       
  1904         for (; $i < @platformList; $i++) {
       
  1905             push @platforms, $platformList[$i];
       
  1906         }
       
  1907     } elsif ($platform =~ /^qt-/) {
       
  1908         push @platforms, $platform;
       
  1909         push @platforms, "qt";
       
  1910     } else {
       
  1911         @platforms = $platform;
       
  1912     }
       
  1913 
       
  1914     my @hierarchy;
       
  1915     for (my $i = 0; $i < @platforms; $i++) {
       
  1916         my $scoped = catdir($platformBaseDirectory, $platforms[$i]);
       
  1917         push(@hierarchy, $scoped) if (-d $scoped);
       
  1918     }
       
  1919     
       
  1920     return @hierarchy;
       
  1921 }
       
  1922 
       
  1923 sub buildPlatformTestHierarchy(@)
       
  1924 {
       
  1925     my (@platformHierarchy) = @_;
       
  1926     return @platformHierarchy if (@platformHierarchy < 2);
       
  1927     if ($platformHierarchy[0] =~ /mac-wk2/) {
       
  1928         return ($platformHierarchy[0], $platformHierarchy[1], $platformHierarchy[$#platformHierarchy]);
       
  1929     }
       
  1930     return ($platformHierarchy[0], $platformHierarchy[$#platformHierarchy]);
       
  1931 }
       
  1932 
       
  1933 sub epiloguesAndPrologues($$)
       
  1934 {
       
  1935     my ($lastDirectory, $directory) = @_;
       
  1936     my @lastComponents = split('/', $lastDirectory);
       
  1937     my @components = split('/', $directory);
       
  1938 
       
  1939     while (@lastComponents) {
       
  1940         if (!defined($components[0]) || $lastComponents[0] ne $components[0]) {
       
  1941             last;
       
  1942         }
       
  1943         shift @components;
       
  1944         shift @lastComponents;
       
  1945     }
       
  1946 
       
  1947     my @result;
       
  1948     my $leaving = $lastDirectory;
       
  1949     foreach (@lastComponents) {
       
  1950         my $epilogue = $leaving . "/resources/run-webkit-tests-epilogue.html";
       
  1951         foreach (@platformResultHierarchy) {
       
  1952             push @result, catdir($_, $epilogue) if (stat(catdir($_, $epilogue)));
       
  1953         }
       
  1954         push @result, catdir($testDirectory, $epilogue) if (stat(catdir($testDirectory, $epilogue)));
       
  1955         $leaving =~ s|(^\|/)[^/]+$||;
       
  1956     }
       
  1957 
       
  1958     my $entering = $leaving;
       
  1959     foreach (@components) {
       
  1960         $entering .= '/' . $_;
       
  1961         my $prologue = $entering . "/resources/run-webkit-tests-prologue.html";
       
  1962         push @result, catdir($testDirectory, $prologue) if (stat(catdir($testDirectory, $prologue)));
       
  1963         foreach (reverse @platformResultHierarchy) {
       
  1964             push @result, catdir($_, $prologue) if (stat(catdir($_, $prologue)));
       
  1965         }
       
  1966     }
       
  1967     return @result;
       
  1968 }
       
  1969     
       
  1970 sub parseLeaksandPrintUniqueLeaks()
       
  1971 {
       
  1972     return unless @leaksFilenames;
       
  1973      
       
  1974     my $mergedFilenames = join " ", @leaksFilenames;
       
  1975     my $parseMallocHistoryTool = sourceDir() . "/WebKitTools/Scripts/parse-malloc-history";
       
  1976     
       
  1977     open MERGED_LEAKS, "cat $mergedFilenames | $parseMallocHistoryTool --merge-depth $mergeDepth  - |" ;
       
  1978     my @leakLines = <MERGED_LEAKS>;
       
  1979     close MERGED_LEAKS;
       
  1980     
       
  1981     my $uniqueLeakCount = 0;
       
  1982     my $totalBytes;
       
  1983     foreach my $line (@leakLines) {
       
  1984         ++$uniqueLeakCount if ($line =~ /^(\d*)\scalls/);
       
  1985         $totalBytes = $1 if $line =~ /^total\:\s(.*)\s\(/;
       
  1986     }
       
  1987     
       
  1988     print "\nWARNING: $totalLeaks total leaks found for a total of $totalBytes!\n";
       
  1989     print "WARNING: $uniqueLeakCount unique leaks found!\n";
       
  1990     print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
       
  1991     
       
  1992 }
       
  1993 
       
  1994 sub extensionForMimeType($)
       
  1995 {
       
  1996     my ($mimeType) = @_;
       
  1997 
       
  1998     if ($mimeType eq "application/x-webarchive") {
       
  1999         return "webarchive";
       
  2000     } elsif ($mimeType eq "application/pdf") {
       
  2001         return "pdf";
       
  2002     }
       
  2003     return "txt";
       
  2004 }
       
  2005 
       
  2006 # Read up to the first #EOF (the content block of the test), or until detecting crashes or timeouts.
       
  2007 sub readFromDumpToolWithTimer(**)
       
  2008 {
       
  2009     my ($fhIn, $fhError) = @_;
       
  2010 
       
  2011     setFileHandleNonBlocking($fhIn, 1);
       
  2012     setFileHandleNonBlocking($fhError, 1);
       
  2013 
       
  2014     my $maximumSecondsWithoutOutput = $timeoutSeconds;
       
  2015     $maximumSecondsWithoutOutput *= 10 if $guardMalloc;
       
  2016     my $microsecondsToWaitBeforeReadingAgain = 1000;
       
  2017 
       
  2018     my $timeOfLastSuccessfulRead = time;
       
  2019 
       
  2020     my @output = ();
       
  2021     my @error = ();
       
  2022     my $status = "success";
       
  2023     my $mimeType = "text/plain";
       
  2024     # We don't have a very good way to know when the "headers" stop
       
  2025     # and the content starts, so we use this as a hack:
       
  2026     my $haveSeenContentType = 0;
       
  2027     my $haveSeenEofIn = 0;
       
  2028     my $haveSeenEofError = 0;
       
  2029 
       
  2030     while (1) {
       
  2031         if (time - $timeOfLastSuccessfulRead > $maximumSecondsWithoutOutput) {
       
  2032             $status = dumpToolDidCrash() ? "crashed" : "timedOut";
       
  2033             last;
       
  2034         }
       
  2035 
       
  2036         # Once we've seen the EOF, we must not read anymore.
       
  2037         my $lineIn = readline($fhIn) unless $haveSeenEofIn;
       
  2038         my $lineError = readline($fhError) unless $haveSeenEofError;
       
  2039         if (!defined($lineIn) && !defined($lineError)) {
       
  2040             last if ($haveSeenEofIn && $haveSeenEofError);
       
  2041 
       
  2042             if ($! != EAGAIN) {
       
  2043                 $status = "crashed";
       
  2044                 last;
       
  2045             }
       
  2046 
       
  2047             # No data ready
       
  2048             usleep($microsecondsToWaitBeforeReadingAgain);
       
  2049             next;
       
  2050         }
       
  2051 
       
  2052         $timeOfLastSuccessfulRead = time;
       
  2053 
       
  2054         if (defined($lineIn)) {
       
  2055             if (!$haveSeenContentType && $lineIn =~ /^Content-Type: (\S+)$/) {
       
  2056                 $mimeType = $1;
       
  2057                 $haveSeenContentType = 1;
       
  2058             } elsif ($lineIn =~ /#EOF/) {
       
  2059                 $haveSeenEofIn = 1;
       
  2060             } else {
       
  2061                 push @output, $lineIn;
       
  2062             }
       
  2063         }
       
  2064         if (defined($lineError)) {
       
  2065             if ($lineError =~ /#EOF/) {
       
  2066                 $haveSeenEofError = 1;
       
  2067             } else {
       
  2068                 push @error, $lineError;
       
  2069             }
       
  2070         }
       
  2071     }
       
  2072 
       
  2073     setFileHandleNonBlocking($fhIn, 0);
       
  2074     setFileHandleNonBlocking($fhError, 0);
       
  2075     return {
       
  2076         output => join("", @output),
       
  2077         error => join("", @error),
       
  2078         status => $status,
       
  2079         mimeType => $mimeType,
       
  2080         extension => extensionForMimeType($mimeType)
       
  2081     };
       
  2082 }
       
  2083 
       
  2084 sub setFileHandleNonBlocking(*$)
       
  2085 {
       
  2086     my ($fh, $nonBlocking) = @_;
       
  2087 
       
  2088     my $flags = fcntl($fh, F_GETFL, 0) or die "Couldn't get filehandle flags";
       
  2089 
       
  2090     if ($nonBlocking) {
       
  2091         $flags |= O_NONBLOCK;
       
  2092     } else {
       
  2093         $flags &= ~O_NONBLOCK;
       
  2094     }
       
  2095 
       
  2096     fcntl($fh, F_SETFL, $flags) or die "Couldn't set filehandle flags";
       
  2097 
       
  2098     return 1;
       
  2099 }
       
  2100 
       
  2101 sub sampleDumpTool()
       
  2102 {
       
  2103     return unless isAppleMacWebKit();
       
  2104     return unless $runSample;
       
  2105 
       
  2106     my $outputDirectory = "$ENV{HOME}/Library/Logs/DumpRenderTree";
       
  2107     -d $outputDirectory or mkdir $outputDirectory;
       
  2108 
       
  2109     my $outputFile = "$outputDirectory/HangReport.txt";
       
  2110     system "/usr/bin/sample", $dumpToolPID, qw(10 10 -file), $outputFile;
       
  2111 }
       
  2112 
       
  2113 sub stripMetrics($$)
       
  2114 {
       
  2115     my ($actual, $expected) = @_;
       
  2116 
       
  2117     foreach my $result ($actual, $expected) {
       
  2118         $result =~ s/at \(-?[0-9]+,-?[0-9]+\) *//g;
       
  2119         $result =~ s/size -?[0-9]+x-?[0-9]+ *//g;
       
  2120         $result =~ s/text run width -?[0-9]+: //g;
       
  2121         $result =~ s/text run width -?[0-9]+ [a-zA-Z ]+: //g;
       
  2122         $result =~ s/RenderButton {BUTTON} .*/RenderButton {BUTTON}/g;
       
  2123         $result =~ s/RenderImage {INPUT} .*/RenderImage {INPUT}/g;
       
  2124         $result =~ s/RenderBlock {INPUT} .*/RenderBlock {INPUT}/g;
       
  2125         $result =~ s/RenderTextControl {INPUT} .*/RenderTextControl {INPUT}/g;
       
  2126         $result =~ s/\([0-9]+px/px/g;
       
  2127         $result =~ s/ *" *\n +" */ /g;
       
  2128         $result =~ s/" +$/"/g;
       
  2129 
       
  2130         $result =~ s/- /-/g;
       
  2131         $result =~ s/\n( *)"\s+/\n$1"/g;
       
  2132         $result =~ s/\s+"\n/"\n/g;
       
  2133         $result =~ s/scrollWidth [0-9]+/scrollWidth/g;
       
  2134         $result =~ s/scrollHeight [0-9]+/scrollHeight/g;
       
  2135     }
       
  2136 
       
  2137     return ($actual, $expected);
       
  2138 }
       
  2139 
       
  2140 sub fileShouldBeIgnored
       
  2141 {
       
  2142     my ($filePath) = @_;
       
  2143     foreach my $ignoredDir (keys %ignoredDirectories) {
       
  2144         if ($filePath =~ m/^$ignoredDir/) {
       
  2145             return 1;
       
  2146         }
       
  2147     }
       
  2148     return 0;
       
  2149 }
       
  2150 
       
  2151 sub readSkippedFiles($)
       
  2152 {
       
  2153     my ($constraintPath) = @_;
       
  2154 
       
  2155     foreach my $level (@platformTestHierarchy) {
       
  2156         if (open SKIPPED, "<", "$level/Skipped") {
       
  2157             if ($verbose) {
       
  2158                 my ($dir, $name) = splitpath($level);
       
  2159                 print "Skipped tests in $name:\n";
       
  2160             }
       
  2161 
       
  2162             while (<SKIPPED>) {
       
  2163                 my $skipped = $_;
       
  2164                 chomp $skipped;
       
  2165                 $skipped =~ s/^[ \n\r]+//;
       
  2166                 $skipped =~ s/[ \n\r]+$//;
       
  2167                 if ($skipped && $skipped !~ /^#/) {
       
  2168                     if ($skippedOnly) {
       
  2169                         if (!fileShouldBeIgnored($skipped)) {
       
  2170                             if (!$constraintPath) {
       
  2171                                 # Always add $skipped since no constraint path was specified on the command line.
       
  2172                                 push(@ARGV, $skipped);
       
  2173                             } elsif ($skipped =~ /^($constraintPath)/) {
       
  2174                                 # Add $skipped only if it matches the current path constraint, e.g.,
       
  2175                                 # "--skipped=only dir1" with "dir1/file1.html" on the skipped list.
       
  2176                                 push(@ARGV, $skipped);
       
  2177                             } elsif ($constraintPath =~ /^($skipped)/) {
       
  2178                                 # Add current path constraint if it is more specific than the skip list entry,
       
  2179                                 # e.g., "--skipped=only dir1/dir2/dir3" with "dir1" on the skipped list.
       
  2180                                 push(@ARGV, $constraintPath);
       
  2181                             }
       
  2182                         } elsif ($verbose) {
       
  2183                             print "    $skipped\n";
       
  2184                         }
       
  2185                     } else {
       
  2186                         if ($verbose) {
       
  2187                             print "    $skipped\n";
       
  2188                         }
       
  2189                         processIgnoreTests($skipped, "Skipped");
       
  2190                     }
       
  2191                 }
       
  2192             }
       
  2193             close SKIPPED;
       
  2194         }
       
  2195     }
       
  2196 }
       
  2197 
       
  2198 my @testsFound;
       
  2199 
       
  2200 sub directoryFilter
       
  2201 {
       
  2202     return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
       
  2203     return () if exists $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)};
       
  2204     return @_;
       
  2205 }
       
  2206 
       
  2207 sub fileFilter
       
  2208 {
       
  2209     my $filename = $_;
       
  2210     if ($filename =~ /\.([^.]+)$/) {
       
  2211         if (exists $supportedFileExtensions{$1}) {
       
  2212             my $path = File::Spec->abs2rel(catfile($File::Find::dir, $filename), $testDirectory);
       
  2213             push @testsFound, $path if !exists $ignoredFiles{$path};
       
  2214         }
       
  2215     }
       
  2216 }
       
  2217 
       
  2218 sub findTestsToRun
       
  2219 {
       
  2220     my @testsToRun = ();
       
  2221 
       
  2222     for my $test (@ARGV) {
       
  2223         $test =~ s/^($layoutTestsName|$testDirectory)\///;
       
  2224         my $fullPath = catfile($testDirectory, $test);
       
  2225         if (file_name_is_absolute($test)) {
       
  2226             print "can't run test $test outside $testDirectory\n";
       
  2227         } elsif (-f $fullPath) {
       
  2228             my ($filename, $pathname, $fileExtension) = fileparse($test, qr{\.[^.]+$});
       
  2229             if (!exists $supportedFileExtensions{substr($fileExtension, 1)}) {
       
  2230                 print "test $test does not have a supported extension\n";
       
  2231             } elsif ($testHTTP || $pathname !~ /^http\//) {
       
  2232                 push @testsToRun, $test;
       
  2233             }
       
  2234         } elsif (-d $fullPath) {
       
  2235             @testsFound = ();
       
  2236             find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $fullPath);
       
  2237             for my $level (@platformTestHierarchy) {
       
  2238                 my $platformPath = catfile($level, $test);
       
  2239                 find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $platformPath) if (-d $platformPath);
       
  2240             }
       
  2241             push @testsToRun, sort pathcmp @testsFound;
       
  2242             @testsFound = ();
       
  2243         } else {
       
  2244             print "test $test not found\n";
       
  2245         }
       
  2246     }
       
  2247 
       
  2248     if (!scalar @ARGV) {
       
  2249         @testsFound = ();
       
  2250         find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $testDirectory);
       
  2251         for my $level (@platformTestHierarchy) {
       
  2252             find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $level);
       
  2253         }
       
  2254         push @testsToRun, sort pathcmp @testsFound;
       
  2255         @testsFound = ();
       
  2256 
       
  2257         # We need to minimize the time when Apache and WebSocketServer is locked by tests
       
  2258         # so run them last if no explicit order was specified in the argument list.
       
  2259         my @httpTests;
       
  2260         my @websocketTests;
       
  2261         my @otherTests;
       
  2262         foreach my $test (@testsToRun) {
       
  2263             if ($test =~ /^http\//) {
       
  2264                 push(@httpTests, $test);
       
  2265             } elsif ($test =~ /^websocket\//) {
       
  2266                 push(@websocketTests, $test);
       
  2267             } else {
       
  2268                 push(@otherTests, $test);
       
  2269             }
       
  2270         }
       
  2271         @testsToRun = (@otherTests, @httpTests, @websocketTests);
       
  2272     }
       
  2273 
       
  2274     # Reverse the tests
       
  2275     @testsToRun = reverse @testsToRun if $reverseTests;
       
  2276 
       
  2277     # Shuffle the array
       
  2278     @testsToRun = shuffle(@testsToRun) if $randomizeTests;
       
  2279 
       
  2280     return @testsToRun;
       
  2281 }
       
  2282 
       
  2283 sub printResults
       
  2284 {
       
  2285     my %text = (
       
  2286         match => "succeeded",
       
  2287         mismatch => "had incorrect layout",
       
  2288         new => "were new",
       
  2289         timedout => "timed out",
       
  2290         crash => "crashed",
       
  2291         error => "had stderr output"
       
  2292     );
       
  2293 
       
  2294     for my $type ("match", "mismatch", "new", "timedout", "crash", "error") {
       
  2295         my $typeCount = $counts{$type};
       
  2296         next unless $typeCount;
       
  2297         my $typeText = $text{$type};
       
  2298         my $message;
       
  2299         if ($typeCount == 1) {
       
  2300             $typeText =~ s/were/was/;
       
  2301             $message = sprintf "1 test case (%d%%) %s\n", 1 * 100 / $count, $typeText;
       
  2302         } else {
       
  2303             $message = sprintf "%d test cases (%d%%) %s\n", $typeCount, $typeCount * 100 / $count, $typeText;
       
  2304         }
       
  2305         $message =~ s-\(0%\)-(<1%)-;
       
  2306         print $message;
       
  2307     }
       
  2308 }
       
  2309 
       
  2310 sub stopRunningTestsEarlyIfNeeded()
       
  2311 {
       
  2312     # --reset-results does not check pass vs. fail, so exitAfterNFailures makes no sense with --reset-results.
       
  2313     return 0 if $resetResults;
       
  2314 
       
  2315     my $passCount = $counts{match} || 0; # $counts{match} will be undefined if we've not yet passed a test (e.g. the first test fails).
       
  2316     my $newCount = $counts{new} || 0;
       
  2317     my $failureCount = $count - $passCount - $newCount; # "Failure" here includes timeouts, crashes, etc.
       
  2318     if ($exitAfterNFailures && $failureCount >= $exitAfterNFailures) {
       
  2319         print "\nExiting early after $failureCount failures. $count tests run.";
       
  2320         closeDumpTool();
       
  2321         return 1;
       
  2322     }
       
  2323 
       
  2324     my $crashCount = $counts{crash} || 0;
       
  2325     my $timeoutCount = $counts{timedout} || 0;
       
  2326     if ($exitAfterNCrashesOrTimeouts && $crashCount + $timeoutCount >= $exitAfterNCrashesOrTimeouts) {
       
  2327         print "\nExiting early after $crashCount crashes and $timeoutCount timeouts. $count tests run.";
       
  2328         closeDumpTool();
       
  2329         return 1;
       
  2330     }
       
  2331 
       
  2332     return 0;
       
  2333 }