initial import
[vuplus_webkit] / Tools / Scripts / old-run-webkit-tests
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 CGI;
53 use Config;
54 use Cwd;
55 use Data::Dumper;
56 use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
57 use File::Basename;
58 use File::Copy;
59 use File::Find;
60 use File::Path;
61 use File::Spec;
62 use File::Spec::Functions;
63 use File::Temp;
64 use FindBin;
65 use Getopt::Long;
66 use IPC::Open2;
67 use IPC::Open3;
68 use MIME::Base64;
69 use Time::HiRes qw(time usleep);
70
71 use List::Util 'shuffle';
72
73 use lib $FindBin::Bin;
74 use webkitperl::features;
75 use webkitperl::httpd;
76 use webkitdirs;
77 use VCSUtils;
78 use POSIX;
79
80 sub buildPlatformResultHierarchy();
81 sub buildPlatformTestHierarchy(@);
82 sub captureSavedCrashLog($$);
83 sub checkPythonVersion();
84 sub closeCygpaths();
85 sub closeDumpTool();
86 sub closeWebSocketServer();
87 sub configureAndOpenHTTPDIfNeeded();
88 sub countAndPrintLeaks($$$);
89 sub countFinishedTest($$$$);
90 sub deleteExpectedAndActualResults($);
91 sub dumpToolDidCrash();
92 sub epiloguesAndPrologues($$);
93 sub expectedDirectoryForTest($;$;$);
94 sub fileNameWithNumber($$);
95 sub findNewestFileMatchingGlob($);
96 sub htmlForResultsSection(\@$&);
97 sub isTextOnlyTest($);
98 sub launchWithEnv(\@\%);
99 sub resolveAndMakeTestResultsDirectory();
100 sub numericcmp($$);
101 sub openDiffTool();
102 sub buildDumpTool($);
103 sub openDumpTool();
104 sub parseLeaksandPrintUniqueLeaks();
105 sub openWebSocketServerIfNeeded();
106 sub pathcmp($$);
107 sub printFailureMessageForTest($$);
108 sub processIgnoreTests($$);
109 sub readChecksumFromPng($);
110 sub readFromDumpToolWithTimer(**);
111 sub readSkippedFiles($);
112 sub recordActualResultsAndDiff($$);
113 sub sampleDumpTool();
114 sub setFileHandleNonBlocking(*$);
115 sub setUpWindowsCrashLogSaving();
116 sub slowestcmp($$);
117 sub splitpath($);
118 sub stopRunningTestsEarlyIfNeeded();
119 sub stripExtension($);
120 sub stripMetrics($$);
121 sub testCrashedOrTimedOut($$$$$$);
122 sub toCygwinPath($);
123 sub toURL($);
124 sub toWindowsPath($);
125 sub validateSkippedArg($$;$);
126 sub writeToFile($$);
127
128 # Argument handling
129 my $addPlatformExceptions = 0;
130 my @additionalPlatformDirectories = ();
131 my $complexText = 0;
132 my $exitAfterNFailures = 0;
133 my $exitAfterNCrashesOrTimeouts = 0;
134 my $generateNewResults = isAppleMacWebKit() ? 1 : 0;
135 my $guardMalloc = '';
136 # FIXME: Dynamic HTTP-port configuration in this file is wrong.  The various
137 # apache config files in LayoutTests/http/config govern the port numbers.
138 # Dynamic configuration as-written will also cause random failures in
139 # an IPv6 environment.  See https://bugs.webkit.org/show_bug.cgi?id=37104.
140 my $httpdPort = 8000;
141 my $httpdSSLPort = 8443;
142 my $ignoreMetrics = 0;
143 my $webSocketPort = 8880;
144 # wss is disabled until all platforms support pyOpenSSL.
145 # my $webSocketSecurePort = 9323;
146 my @ignoreTests;
147 my $iterations = 1;
148 my $launchSafari = 1;
149 my $mergeDepth;
150 my $pixelTests = '';
151 my $platform;
152 my $quiet = '';
153 my $randomizeTests = 0;
154 my $repeatEach = 1;
155 my $report10Slowest = 0;
156 my $resetResults = 0;
157 my $reverseTests = 0;
158 my $root;
159 my $runSample = 1;
160 my $shouldCheckLeaks = 0;
161 my $showHelp = 0;
162 my $stripEditingCallbacks;
163 my $testHTTP = 1;
164 my $testWebSocket = 1;
165 my $testMedia = 1;
166 my $tmpDir = "/tmp";
167 my $testResultsDirectory = File::Spec->catdir($tmpDir, "layout-test-results");
168 my $testsPerDumpTool = 1000;
169 my $threaded = 0;
170 my $gcBetweenTests = 0;
171 # DumpRenderTree has an internal timeout of 30 seconds, so this must be > 30.
172 my $timeoutSeconds = 35;
173 my $tolerance = 0;
174 my $treatSkipped = "default";
175 my $useRemoteLinksToTests = 0;
176 my $useValgrind = 0;
177 my $verbose = 0;
178 my $shouldWaitForHTTPD = 0;
179 my $useWebKitTestRunner = 0;
180 my $noBuildDumpTool = 0;
181
182 # These arguments are ignored, but exist for compatibility with new-run-webkit-tests.
183 my $builderName = '';
184 my $buildNumber = '';
185 my $masterName = '';
186 my $testResultsServer = '';
187
188 my @leaksFilenames;
189
190 if (isWindows() || isMsys()) {
191     print "This script has to be run under Cygwin to function correctly.\n";
192     exit 1;
193 }
194
195 # Default to --no-http for wx for now.
196 $testHTTP = 0 if (isWx());
197
198 my $perlInterpreter = "perl";
199
200 my $expectedTag = "expected";
201 my $mismatchTag = "mismatch";
202 my $actualTag = "actual";
203 my $prettyDiffTag = "pretty-diff";
204 my $diffsTag = "diffs";
205 my $errorTag = "stderr";
206 my $crashLogTag = "crash-log";
207
208 my $windowsCrashLogFilePrefix = "CrashLog";
209
210 # These are defined here instead of closer to where they are used so that they
211 # will always be accessible from the END block that uses them, even if the user
212 # presses Ctrl-C before Perl has finished evaluating this whole file.
213 my $windowsPostMortemDebuggerKey = "/HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/AeDebug";
214 my %previousWindowsPostMortemDebuggerValues;
215
216 my $realPlatform;
217
218 my @macPlatforms = ("mac-leopard", "mac-snowleopard", "mac-lion", "mac");
219 my @winPlatforms = ("win-xp", "win-vista", "win-7sp0", "win");
220
221 if (isAppleMacWebKit()) {
222     if (isLeopard()) {
223         $platform = "mac-leopard";
224         $tolerance = 0.1;
225     } elsif (isSnowLeopard()) {
226         $platform = "mac-snowleopard";
227         $tolerance = 0.1;
228     } elsif (isLion()) {
229         $platform = "mac-lion";
230         $tolerance = 0.1;
231     } else {
232         $platform = "mac";
233     }
234 } elsif (isQt()) {
235     if (isDarwin()) {
236         $platform = "qt-mac";
237     } elsif (isARM()) {
238         $platform = "qt-arm";
239     } elsif (getQtVersion() eq "4.8") {
240         $platform = "qt-4.8";
241     } elsif (isLinux()) {
242         $platform = "qt-linux";
243     } elsif (isWindows() || isCygwin()) {
244         $platform = "qt-win";
245     } else {
246         $platform = "qt";
247     }
248 } elsif (isGtk()) {
249     $platform = "gtk";
250 } elsif (isWx()) {
251     $platform = "wx";
252 } elsif (isCygwin() || isWindows()) {
253     if (isWindowsXP()) {
254         $platform = "win-xp";
255     } elsif (isWindowsVista()) {
256         $platform = "win-vista";
257     } elsif (isWindows7SP0()) {
258         $platform = "win-7sp0";
259     } else {
260         $platform = "win";
261     }
262 }
263
264 if (isQt() || isAppleWinWebKit()) {
265     my $testfontPath = $ENV{"WEBKIT_TESTFONTS"};
266     if (!$testfontPath || !-d "$testfontPath") {
267         print "The WEBKIT_TESTFONTS environment variable is not defined or not set properly\n";
268         print "You must set it before running the tests.\n";
269         print "Use git to grab the actual fonts from http://gitorious.org/qtwebkit/testfonts\n";
270         exit 1;
271     }
272 }
273
274 if (!defined($platform)) {
275     print "WARNING: Your platform is not recognized. Any platform-specific results will be generated in platform/undefined.\n";
276     $platform = "undefined";
277 }
278
279 if (!checkPythonVersion()) {
280     print "WARNING: Your platform does not have Python 2.5+, which is required to run websocket server, so disabling websocket/tests.\n";
281     $testWebSocket = 0;
282 }
283
284 my $programName = basename($0);
285 my $launchSafariDefault = $launchSafari ? "launch" : "do not launch";
286 my $httpDefault = $testHTTP ? "run" : "do not run";
287 my $sampleDefault = $runSample ? "run" : "do not run";
288
289 my $usage = <<EOF;
290 Usage: $programName [options] [testdir|testpath ...]
291   --add-platform-exceptions       Put new results for non-platform-specific failing tests into the platform-specific results directory
292   --additional-platform-directory path/to/directory
293                                   Look in the specified directory before looking in any of the default platform-specific directories
294   --complex-text                  Use the complex text code path for all text (Mac OS X and Windows only)
295   -c|--configuration config       Set DumpRenderTree build configuration
296   --gc-between-tests              Force garbage collection between each test
297   -g|--guard-malloc               Enable malloc guard
298   --exit-after-n-failures N       Exit after the first N failures (includes crashes) instead of running all tests
299   --exit-after-n-crashes-or-timeouts N
300                                   Exit after the first N crashes instead of running all tests
301   -h|--help                       Show this help message
302   --[no-]http                     Run (or do not run) http tests (default: $httpDefault)
303   --[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) 
304   -i|--ignore-tests               Comma-separated list of directories or tests to ignore
305   --iterations n                  Number of times to run the set of tests (e.g. ABCABCABC)
306   --[no-]launch-safari            Launch (or do not launch) Safari to display test results (default: $launchSafariDefault)
307   -l|--leaks                      Enable leaks checking
308   --[no-]new-test-results         Generate results for new tests
309   --nthly n                       Restart DumpRenderTree every n tests (default: $testsPerDumpTool)
310   -p|--pixel-tests                Enable pixel tests
311   --tolerance t                   Ignore image differences less than this percentage (default: $tolerance)
312   --platform                      Override the detected platform to use for tests and results (default: $platform)
313   --port                          Web server port to use with http tests
314   -q|--quiet                      Less verbose output
315   --reset-results                 Reset ALL results (including pixel tests if --pixel-tests is set)
316   -o|--results-directory          Output results directory (default: $testResultsDirectory)
317   --random                        Run the tests in a random order
318   --repeat-each n                 Number of times to run each test (e.g. AAABBBCCC)
319   --reverse                       Run the tests in reverse alphabetical order
320   --root                          Path to root tools build
321   --[no-]sample-on-timeout        Run sample on timeout (default: $sampleDefault) (Mac OS X only)
322   -1|--singly                     Isolate each test case run (implies --nthly 1 --verbose)
323   --skipped=[default|ignore|only] Specifies how to treat the Skipped file
324                                      default: Tests/directories listed in the Skipped file are not tested
325                                      ignore:  The Skipped file is ignored
326                                      only:    Only those tests/directories listed in the Skipped file will be run
327   --slowest                       Report the 10 slowest tests
328   --ignore-metrics                Ignore metrics in tests
329   --[no-]strip-editing-callbacks  Remove editing callbacks from expected results
330   -t|--threaded                   Run a concurrent JavaScript thead with each test
331   --timeout t                     Sets the number of seconds before a test times out (default: $timeoutSeconds)
332   --valgrind                      Run DumpRenderTree inside valgrind (Qt/Linux only)
333   -v|--verbose                    More verbose output (overrides --quiet)
334   -m|--merge-leak-depth arg       Merges leak callStacks and prints the number of unique leaks beneath a callstack depth of arg.  Defaults to 5.
335   --use-remote-links-to-tests     Link to test files within the SVN repository in the results.
336   -2|--webkit-test-runner         Use WebKitTestRunner rather than DumpRenderTree.
337 EOF
338
339 setConfiguration();
340
341 my $getOptionsResult = GetOptions(
342     'add-platform-exceptions' => \$addPlatformExceptions,
343     'additional-platform-directory=s' => \@additionalPlatformDirectories,
344     'complex-text' => \$complexText,
345     'exit-after-n-failures=i' => \$exitAfterNFailures,
346     'exit-after-n-crashes-or-timeouts=i' => \$exitAfterNCrashesOrTimeouts,
347     'gc-between-tests' => \$gcBetweenTests,
348     'guard-malloc|g' => \$guardMalloc,
349     'help|h' => \$showHelp,
350     'http!' => \$testHTTP,
351     'wait-for-httpd!' => \$shouldWaitForHTTPD,
352     'ignore-metrics!' => \$ignoreMetrics,
353     'ignore-tests|i=s' => \@ignoreTests,
354     'iterations=i' => \$iterations,
355     'launch-safari!' => \$launchSafari,
356     'leaks|l' => \$shouldCheckLeaks,
357     'merge-leak-depth|m:5' => \$mergeDepth,
358     'new-test-results!' => \$generateNewResults,
359     'no-build' => \$noBuildDumpTool,
360     'nthly=i' => \$testsPerDumpTool,
361     'pixel-tests|p' => \$pixelTests,
362     'platform=s' => \$platform,
363     'port=i' => \$httpdPort,
364     'quiet|q' => \$quiet,
365     'random' => \$randomizeTests,
366     'repeat-each=i' => \$repeatEach,
367     'reset-results' => \$resetResults,
368     'results-directory|o=s' => \$testResultsDirectory,
369     'reverse' => \$reverseTests,
370     'root=s' => \$root,
371     'sample-on-timeout!' => \$runSample,
372     'singly|1' => sub { $testsPerDumpTool = 1; },
373     'skipped=s' => \&validateSkippedArg,
374     'slowest' => \$report10Slowest,
375     'strip-editing-callbacks!' => \$stripEditingCallbacks,
376     'threaded|t' => \$threaded,
377     'timeout=i' => \$timeoutSeconds,
378     'tolerance=f' => \$tolerance,
379     'use-remote-links-to-tests' => \$useRemoteLinksToTests,
380     'valgrind' => \$useValgrind,
381     'verbose|v' => \$verbose,
382     'webkit-test-runner|2' => \$useWebKitTestRunner,
383     # These arguments are ignored (but are used by new-run-webkit-tests).
384     'builder-name=s' => \$builderName,
385     'build-number=s' => \$buildNumber,
386     'master-name=s' => \$masterName,
387     'test-results-server=s' => \$testResultsServer,
388 );
389
390 if (!$getOptionsResult || $showHelp) {
391     print STDERR $usage;
392     exit 1;
393 }
394
395 if ($useWebKitTestRunner) {
396     if (isAppleMacWebKit()) {
397         $realPlatform = $platform;
398         $platform = "mac-wk2";
399     } elsif (isAppleWinWebKit()) {
400         $stripEditingCallbacks = 0 unless defined $stripEditingCallbacks;
401         $realPlatform = $platform;
402         $platform = "win-wk2";
403     } elsif (isQt()) {
404         $realPlatform = $platform;
405         $platform = "qt-wk2";
406     } elsif (isGtk()) {
407         $realPlatform = $platform;
408         $platform = "gtk-wk2";
409     }
410 }
411
412 $timeoutSeconds *= 10 if $guardMalloc;
413
414 $stripEditingCallbacks = isCygwin() unless defined $stripEditingCallbacks;
415
416 my $ignoreSkipped = $treatSkipped eq "ignore";
417 my $skippedOnly = $treatSkipped eq "only";
418
419 my $configuration = configuration();
420
421 # We need an environment variable to be able to enable the feature per-slave
422 $shouldWaitForHTTPD = $ENV{"WEBKIT_WAIT_FOR_HTTPD"} unless ($shouldWaitForHTTPD);
423 $verbose = 1 if $testsPerDumpTool == 1;
424
425 if ($shouldCheckLeaks && $testsPerDumpTool > 1000) {
426     print STDERR "\nWARNING: Running more than 1000 tests at a time with MallocStackLogging enabled may cause a crash.\n\n";
427 }
428
429 # Generating remote links causes a lot of unnecessary spew on GTK build bot
430 $useRemoteLinksToTests = 0 if isGtk();
431
432 setConfigurationProductDir(Cwd::abs_path($root)) if (defined($root));
433 my $productDir = productDir();
434 $productDir .= "/bin" if isQt();
435 $productDir .= "/Programs" if isGtk();
436
437 chdirWebKit();
438
439 if (!defined($root) && !$noBuildDumpTool) {
440     # FIXME: We build both DumpRenderTree and WebKitTestRunner for
441     # WebKitTestRunner runs becuase DumpRenderTree still includes
442     # the DumpRenderTreeSupport module and the TestNetscapePlugin.
443     # These two projects should be factored out into their own
444     # projects.
445     buildDumpTool("DumpRenderTree");
446     buildDumpTool("WebKitTestRunner") if $useWebKitTestRunner;
447 }
448
449 my $dumpToolName = $useWebKitTestRunner ? "WebKitTestRunner" : "DumpRenderTree";
450
451 if (isAppleWinWebKit()) {
452     $dumpToolName .= "_debug" if configurationForVisualStudio() eq "Debug_All";
453     $dumpToolName .= "_debug" if configurationForVisualStudio() eq "Debug_Cairo_CFLite";
454     $dumpToolName .= $Config{_exe};
455 }
456 my $dumpTool = File::Spec->catfile($productDir, $dumpToolName);
457 die "can't find executable $dumpToolName (looked in $productDir)\n" unless -x $dumpTool;
458
459 my $imageDiffTool = "$productDir/ImageDiff";
460 $imageDiffTool .= "_debug" if isCygwin() && configurationForVisualStudio() eq "Debug_All";
461 $imageDiffTool .= "_debug" if isCygwin() && configurationForVisualStudio() eq "Debug_Cairo_CFLite";
462 die "can't find executable $imageDiffTool (looked in $productDir)\n" if $pixelTests && !-x $imageDiffTool;
463
464 checkFrameworks() unless isCygwin();
465
466 if (isAppleMacWebKit()) {
467     push @INC, $productDir;
468     require DumpRenderTreeSupport;
469 }
470
471 my $layoutTestsName = "LayoutTests";
472 my $testDirectory = File::Spec->rel2abs($layoutTestsName);
473 my $expectedDirectory = $testDirectory;
474 my $platformBaseDirectory = catdir($testDirectory, "platform");
475 my $platformTestDirectory = catdir($platformBaseDirectory, $platform);
476 my @platformResultHierarchy = buildPlatformResultHierarchy();
477 my @platformTestHierarchy = buildPlatformTestHierarchy(@platformResultHierarchy);
478
479 $expectedDirectory = $ENV{"WebKitExpectedTestResultsDirectory"} if $ENV{"WebKitExpectedTestResultsDirectory"};
480
481 $testResultsDirectory = File::Spec->rel2abs($testResultsDirectory);
482 # $testResultsDirectory must be empty before testing.
483 rmtree $testResultsDirectory;
484 my $testResults = File::Spec->catfile($testResultsDirectory, "results.html");
485
486 if (isAppleMacWebKit()) {
487     print STDERR "Compiling Java tests\n";
488     my $javaTestsDirectory = catdir($testDirectory, "java");
489
490     if (system("/usr/bin/make", "-C", "$javaTestsDirectory")) {
491         exit 1;
492     }
493 } elsif (isCygwin()) {
494     setUpWindowsCrashLogSaving();
495 }
496
497 print "Running tests from $testDirectory\n";
498 if ($pixelTests) {
499     print "Enabling pixel tests with a tolerance of $tolerance%\n";
500     if (isDarwin()) {
501         if (!$useWebKitTestRunner) {
502             print "WARNING: Temporarily changing the main display color profile:\n";
503             print "\tThe colors on your screen will change for the duration of the testing.\n";
504             print "\tThis allows the pixel tests to have consistent color values across all machines.\n";
505         }
506
507         if (isPerianInstalled()) {
508             print "WARNING: Perian's QuickTime component is installed and this may affect pixel test results!\n";
509             print "\tYou should avoid generating new pixel results in this environment.\n";
510             print "\tSee https://bugs.webkit.org/show_bug.cgi?id=22615 for details.\n";
511         }
512     }
513 }
514
515 system "ln", "-s", $testDirectory, "/tmp/LayoutTests" unless -x "/tmp/LayoutTests";
516
517 my %ignoredFiles = ( "results.html" => 1 );
518 my %ignoredDirectories = map { $_ => 1 } qw(platform);
519 my %ignoredLocalDirectories = map { $_ => 1 } qw(.svn _svn resources script-tests);
520 my %supportedFileExtensions = map { $_ => 1 } qw(htm html shtml xml xhtml xhtmlmp pl php mht);
521
522 if (!checkWebCoreFeatureSupport("MathML", 0)) {
523     $ignoredDirectories{'mathml'} = 1;
524 }
525
526 if (!checkWebCoreFeatureSupport("MHTML", 0)) {
527     $ignoredDirectories{'mhtml'} = 1;
528 }
529
530 # FIXME: We should fix webkitperl/features.pm:hasFeature() to do the correct feature detection for Cygwin.
531 if (checkWebCoreFeatureSupport("SVG", 0)) {
532     $supportedFileExtensions{'svg'} = 1;
533 } elsif (isCygwin()) {
534     $supportedFileExtensions{'svg'} = 1;
535 } else {
536     $ignoredLocalDirectories{'svg'} = 1;
537 }
538
539 if (!$testHTTP) {
540     $ignoredDirectories{'http'} = 1;
541     $ignoredDirectories{'websocket'} = 1;
542 } elsif (!hasHTTPD()) {
543     print "\nNo httpd found. Cannot run http tests.\nPlease use --no-http if you do not want to run http tests.\n";
544     exit 1;
545 }
546
547 if (!$testWebSocket) {
548     $ignoredDirectories{'websocket'} = 1;
549 }
550
551 if (!$testMedia) {
552     $ignoredDirectories{'media'} = 1;
553     $ignoredDirectories{'http/tests/media'} = 1;
554 }
555
556 my $supportedFeaturesResult = "";
557
558 if (isCygwin()) {
559     # Collect supported features list
560     setPathForRunningWebKitApp(\%ENV);
561     my $supportedFeaturesCommand = "\"$dumpTool\" --print-supported-features 2>&1";
562     $supportedFeaturesResult = `$supportedFeaturesCommand 2>&1`;
563 }
564
565 my $hasAcceleratedCompositing = 0;
566 my $has3DRendering = 0;
567
568 if (isCygwin()) {
569     $hasAcceleratedCompositing = $supportedFeaturesResult =~ /AcceleratedCompositing/;
570     $has3DRendering = $supportedFeaturesResult =~ /3DRendering/;
571 } else {
572     $hasAcceleratedCompositing = checkWebCoreFeatureSupport("Accelerated Compositing", 0);
573     $has3DRendering = checkWebCoreFeatureSupport("3D Rendering", 0);
574 }
575
576 if (!$hasAcceleratedCompositing) {
577     $ignoredDirectories{'compositing'} = 1;
578
579     # This test has slightly different floating-point rounding when accelerated
580     # compositing is enabled.
581     $ignoredFiles{'svg/custom/use-on-symbol-inside-pattern.svg'} = 1;
582
583     # This test has an iframe that is put in a layer only in compositing mode.
584     $ignoredFiles{'media/media-document-audio-repaint.html'} = 1;
585
586     if (isAppleWebKit()) {
587         # In Apple's ports, the default controls for <video> contain a "full
588         # screen" button only if accelerated compositing is enabled.
589         $ignoredFiles{'media/controls-after-reload.html'} = 1;
590         $ignoredFiles{'media/controls-drag-timebar.html'} = 1;
591         $ignoredFiles{'media/controls-strict.html'} = 1;
592         $ignoredFiles{'media/controls-styling.html'} = 1;
593         $ignoredFiles{'media/controls-without-preload.html'} = 1;
594         $ignoredFiles{'media/video-controls-rendering.html'} = 1;
595         $ignoredFiles{'media/video-display-toggle.html'} = 1;
596         $ignoredFiles{'media/video-no-audio.html'} = 1;
597     }
598
599     # Here we're using !$hasAcceleratedCompositing as a proxy for "is a headless XP machine" (like
600     # our test slaves). Headless XP machines can neither support accelerated compositing nor pass
601     # this test, so skipping the test here is expedient, if a little sloppy. See
602     # <http://webkit.org/b/48333>.
603     $ignoredFiles{'platform/win/plugins/npn-invalidate-rect-invalidates-window.html'} = 1 if isAppleWinWebKit();
604 }
605
606 if (!$has3DRendering) {
607     $ignoredDirectories{'animations/3d'} = 1;
608     $ignoredDirectories{'transforms/3d'} = 1;
609
610     # These tests use the -webkit-transform-3d media query.
611     $ignoredFiles{'fast/media/mq-transform-02.html'} = 1;
612     $ignoredFiles{'fast/media/mq-transform-03.html'} = 1;
613 }
614
615 if (!checkWebCoreFeatureSupport("3D Canvas", 0)) {
616     $ignoredDirectories{'fast/canvas/webgl'} = 1;
617     $ignoredDirectories{'compositing/webgl'} = 1;
618     $ignoredDirectories{'http/tests/canvas/webgl'} = 1;
619 }
620
621 if (!checkWebCoreFeatureSupport("WCSS", 0)) {
622     $ignoredDirectories{'fast/wcss'} = 1;
623 }
624
625 if (!checkWebCoreFeatureSupport("XHTMLMP", 0)) {
626     $ignoredDirectories{'fast/xhtmlmp'} = 1;
627 }
628
629 if (isAppleMacWebKit() && $platform ne "mac-wk2" && osXVersion()->{minor} >= 6 && architecture() =~ /x86_64/) {
630     # This test relies on executing JavaScript during NPP_Destroy, which isn't supported with
631     # out-of-process plugins in WebKit1. See <http://webkit.org/b/58077>.
632     $ignoredFiles{'plugins/npp-set-window-called-during-destruction.html'} = 1;
633 }
634
635 processIgnoreTests(join(',', @ignoreTests), "ignore-tests") if @ignoreTests;
636 if (!$ignoreSkipped) {
637     if (!$skippedOnly || @ARGV == 0) {
638         readSkippedFiles("");
639     } else {
640         # Since readSkippedFiles() appends to @ARGV, we must use a foreach
641         # loop so that we only iterate over the original argument list.
642         foreach my $argnum (0 .. $#ARGV) {
643             readSkippedFiles(shift @ARGV);
644         }
645     }
646 }
647
648 my @tests = findTestsToRun();
649
650 die "no tests to run\n" if !@tests;
651
652 my %counts;
653 my %tests;
654 my %imagesPresent;
655 my %imageDifferences;
656 my %durations;
657 my $count = 0;
658 my $leaksOutputFileNumber = 1;
659 my $totalLeaks = 0;
660 my $stoppedRunningEarlyMessage;
661
662 my @toolArgs = ();
663 push @toolArgs, "--pixel-tests" if $pixelTests;
664 push @toolArgs, "--threaded" if $threaded;
665 push @toolArgs, "--complex-text" if $complexText;
666 push @toolArgs, "--gc-between-tests" if $gcBetweenTests;
667 push @toolArgs, "-";
668
669 my @diffToolArgs = ();
670 push @diffToolArgs, "--tolerance", $tolerance;
671
672 $| = 1;
673
674 my $dumpToolPID;
675 my $isDumpToolOpen = 0;
676 my $dumpToolCrashed = 0;
677 my $imageDiffToolPID;
678 my $isDiffToolOpen = 0;
679
680 my $atLineStart = 1;
681 my $lastDirectory = "";
682
683 my $isHttpdOpen = 0;
684 my $isWebSocketServerOpen = 0;
685 my $webSocketServerPidFile = 0;
686 my $failedToStartWebSocketServer = 0;
687 # wss is disabled until all platforms support pyOpenSSL.
688 # my $webSocketSecureServerPID = 0;
689
690 sub catch_pipe { $dumpToolCrashed = 1; }
691 $SIG{"PIPE"} = "catch_pipe";
692
693 print "Testing ", scalar @tests, " test cases";
694 print " $iterations times" if ($iterations > 1);
695 print ", repeating each test $repeatEach times" if ($repeatEach > 1);
696 print ".\n";
697
698 my $overallStartTime = time;
699
700 my %expectedResultPaths;
701
702 my @originalTests = @tests;
703 # Add individual test repetitions
704 if ($repeatEach > 1) {
705     @tests = ();
706     foreach my $test (@originalTests) {
707         for (my $i = 0; $i < $repeatEach; $i++) {
708             push(@tests, $test);
709         }
710     }
711 }
712 # Add test set repetitions
713 for (my $i = 1; $i < $iterations; $i++) {
714     push(@tests, @originalTests);
715 }
716
717 my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
718 open my $tests_run_fh, '>', "$absTestResultsDirectory/tests_run.txt" or die $!;
719
720 for my $test (@tests) {
721     my $newDumpTool = not $isDumpToolOpen;
722     openDumpTool();
723
724     my $base = stripExtension($test);
725     my $expectedExtension = ".txt";
726     
727     my $dir = $base;
728     $dir =~ s|/[^/]+$||;
729
730     if ($newDumpTool || $dir ne $lastDirectory) {
731         foreach my $logue (epiloguesAndPrologues($newDumpTool ? "" : $lastDirectory, $dir)) {
732             if (isCygwin()) {
733                 $logue = toWindowsPath($logue);
734             } else {
735                 $logue = canonpath($logue);
736             }
737             if ($verbose) {
738                 print "running epilogue or prologue $logue\n";
739             }
740             print OUT "$logue\n";
741             # Throw away output from DumpRenderTree.
742             # Once for the test output and once for pixel results (empty)
743             while (<IN>) {
744                 last if /#EOF/;
745             }
746             while (<IN>) {
747                 last if /#EOF/;
748             }
749         }
750     }
751
752     if ($verbose) {
753         print "running $test -> ";
754         $atLineStart = 0;
755     } elsif (!$quiet) {
756         if ($dir ne $lastDirectory) {
757             print "\n" unless $atLineStart;
758             print "$dir ";
759         }
760         print ".";
761         $atLineStart = 0;
762     }
763
764     $lastDirectory = $dir;
765
766     my $result;
767
768     my $startTime = time if $report10Slowest;
769
770     print $tests_run_fh "$test\n";
771
772     # Try to read expected hash file for pixel tests
773     my $suffixExpectedHash = "";
774     if ($pixelTests && !$resetResults) {
775         my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
776         if (my $expectedHash = readChecksumFromPng(File::Spec->catfile($expectedPixelDir, "$base-$expectedTag.png"))) {
777             # Format expected hash into a suffix string that is appended to the path / URL passed to DRT.
778             $suffixExpectedHash = "'$expectedHash";
779         }
780     }
781
782     if ($test =~ /^http\//) {
783         configureAndOpenHTTPDIfNeeded();
784         if ($test =~ /^http\/tests\/websocket\//) {
785             if ($test =~ /^websocket\/tests\/local\//) {
786                 my $testPath = "$testDirectory/$test";
787                 if (isCygwin()) {
788                     $testPath = toWindowsPath($testPath);
789                 } else {
790                     $testPath = canonpath($testPath);
791                 }
792                 print OUT "$testPath\n";
793             } else {
794                 if (openWebSocketServerIfNeeded()) {
795                     my $path = canonpath($test);
796                     if ($test =~ /^http\/tests\/websocket\/tests\/ssl\//) {
797                         # wss is disabled until all platforms support pyOpenSSL.
798                         print STDERR "Error: wss is disabled until all platforms support pyOpenSSL.";
799                     } else {
800                         $path =~ s/^http\/tests\///;
801                         print OUT "http://127.0.0.1:$httpdPort/$path\n";
802                     }
803                 } else {
804                     # We failed to launch the WebSocket server.  Display a useful error message rather than attempting
805                     # to run tests that expect the server to be available.
806                     my $errorMessagePath = "$testDirectory/http/tests/websocket/resources/server-failed-to-start.html";
807                     $errorMessagePath = isCygwin() ? toWindowsPath($errorMessagePath) : canonpath($errorMessagePath);
808                     print OUT "$errorMessagePath\n";
809                 }
810             }
811         } elsif ($test !~ /^http\/tests\/local\// && $test !~ /^http\/tests\/ssl\//) {
812             my $path = canonpath($test);
813             $path =~ s/^http\/tests\///;
814             print OUT "http://127.0.0.1:$httpdPort/$path$suffixExpectedHash\n";
815         } elsif ($test =~ /^http\/tests\/ssl\//) {
816             my $path = canonpath($test);
817             $path =~ s/^http\/tests\///;
818             print OUT "https://127.0.0.1:$httpdSSLPort/$path$suffixExpectedHash\n";
819         } else {
820             my $testPath = "$testDirectory/$test";
821             if (isCygwin()) {
822                 $testPath = toWindowsPath($testPath);
823             } else {
824                 $testPath = canonpath($testPath);
825             }
826             print OUT "$testPath$suffixExpectedHash\n";
827         }
828     } else {
829         my $testPath = "$testDirectory/$test";
830         if (isCygwin()) {
831             $testPath = toWindowsPath($testPath);
832         } else {
833             $testPath = canonpath($testPath);
834         }
835         print OUT "$testPath$suffixExpectedHash\n" if defined $testPath;
836     }
837
838     # DumpRenderTree is expected to dump two "blocks" to stdout for each test.
839     # Each block is terminated by a #EOF on a line by itself.
840     # The first block is the output of the test (in text, RenderTree or other formats).
841     # The second block is for optional pixel data in PNG format, and may be empty if
842     # pixel tests are not being run, or the test does not dump pixels (e.g. text tests).
843     my $readResults = readFromDumpToolWithTimer(IN, ERROR);
844
845     my $actual = $readResults->{output};
846     my $error = $readResults->{error};
847
848     $expectedExtension = $readResults->{extension};
849     my $expectedFileName = "$base-$expectedTag.$expectedExtension";
850
851     my $isText = isTextOnlyTest($actual);
852
853     my $expectedDir = expectedDirectoryForTest($base, $isText, $expectedExtension);
854     $expectedResultPaths{$base} = File::Spec->catfile($expectedDir, $expectedFileName);
855
856     unless ($readResults->{status} eq "success") {
857         my $crashed = $readResults->{status} eq "crashed";
858         my $webProcessCrashed = $readResults->{status} eq "webProcessCrashed";
859         testCrashedOrTimedOut($test, $base, $crashed, $webProcessCrashed, $actual, $error);
860         countFinishedTest($test, $base, $webProcessCrashed ? "webProcessCrash" : $crashed ? "crash" : "timedout", 0);
861         last if stopRunningTestsEarlyIfNeeded();
862         next;
863     }
864
865     $durations{$test} = time - $startTime if $report10Slowest;
866
867     my $expected;
868
869     if (!$resetResults && open EXPECTED, "<", $expectedResultPaths{$base}) {
870         $expected = "";
871         while (<EXPECTED>) {
872             next if $stripEditingCallbacks && $_ =~ /^EDITING DELEGATE:/;
873             $expected .= $_;
874         }
875         close EXPECTED;
876     }
877
878     if ($ignoreMetrics && !$isText && defined $expected) {
879         ($actual, $expected) = stripMetrics($actual, $expected);
880     }
881
882     if ($shouldCheckLeaks && $testsPerDumpTool == 1) {
883         print "        $test -> ";
884     }
885
886     my $actualPNG = "";
887     my $diffPNG = "";
888     my $diffPercentage = 0;
889     my $diffResult = "passed";
890
891     my $actualHash = "";
892     my $expectedHash = "";
893     my $actualPNGSize = 0;
894
895     while (<IN>) {
896         last if /#EOF/;
897         if (/ActualHash: ([a-f0-9]{32})/) {
898             $actualHash = $1;
899         } elsif (/ExpectedHash: ([a-f0-9]{32})/) {
900             $expectedHash = $1;
901         } elsif (/Content-Length: (\d+)\s*/) {
902             $actualPNGSize = $1;
903             read(IN, $actualPNG, $actualPNGSize);
904         }
905     }
906
907     if ($verbose && $pixelTests && !$resetResults && $actualPNGSize) {
908         if ($actualHash eq "" && $expectedHash eq "") {
909             printFailureMessageForTest($test, "WARNING: actual & expected pixel hashes are missing!");
910         } elsif ($actualHash eq "") {
911             printFailureMessageForTest($test, "WARNING: actual pixel hash is missing!");
912         } elsif ($expectedHash eq "") {
913             printFailureMessageForTest($test, "WARNING: expected pixel hash is missing!");
914         }
915     }
916
917     if ($actualPNGSize > 0) {
918         my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
919         my $expectedPNGPath = File::Spec->catfile($expectedPixelDir, "$base-$expectedTag.png");
920
921         if (!$resetResults && ($expectedHash ne $actualHash || ($actualHash eq "" && $expectedHash eq ""))) {
922             if (-f $expectedPNGPath) {
923                 my $expectedPNGSize = -s $expectedPNGPath;
924                 my $expectedPNG = "";
925                 open EXPECTEDPNG, $expectedPNGPath;
926                 read(EXPECTEDPNG, $expectedPNG, $expectedPNGSize);
927
928                 openDiffTool();
929                 print DIFFOUT "Content-Length: $actualPNGSize\n";
930                 print DIFFOUT $actualPNG;
931
932                 print DIFFOUT "Content-Length: $expectedPNGSize\n";
933                 print DIFFOUT $expectedPNG;
934
935                 while (<DIFFIN>) {
936                     last if /^error/ || /^diff:/;
937                     if (/Content-Length: (\d+)\s*/) {
938                         read(DIFFIN, $diffPNG, $1);
939                     }
940                 }
941
942                 if (/^diff: (.+)% (passed|failed)/) {
943                     $diffPercentage = $1 + 0;
944                     $imageDifferences{$base} = $diffPercentage;
945                     $diffResult = $2;
946                 }
947                 
948                 if (!$diffPercentage) {
949                     printFailureMessageForTest($test, "pixel hash failed (but pixel test still passes)");
950                 }
951             } elsif ($verbose) {
952                 printFailureMessageForTest($test, "WARNING: expected image is missing!");
953             }
954         }
955
956         if ($resetResults || !-f $expectedPNGPath) {
957             if (!$addPlatformExceptions) {
958                 mkpath catfile($expectedPixelDir, dirname($base)) if $testDirectory ne $expectedPixelDir;
959                 writeToFile($expectedPNGPath, $actualPNG);
960             } else {
961                 mkpath catfile($platformTestDirectory, dirname($base));
962                 writeToFile("$platformTestDirectory/$base-$expectedTag.png", $actualPNG);
963             }
964         }
965     }
966
967     if (dumpToolDidCrash()) {
968         $result = "crash";
969         testCrashedOrTimedOut($test, $base, 1, 0, $actual, $error);
970     } elsif (!defined $expected) {
971         if ($verbose) {
972             print "new " . ($resetResults ? "result" : "test");
973         }
974         $result = "new";
975
976         if ($generateNewResults || $resetResults) {
977             if (!$addPlatformExceptions) {
978                 mkpath catfile($expectedDir, dirname($base)) if $testDirectory ne $expectedDir;
979                 writeToFile("$expectedDir/$expectedFileName", $actual);
980             } else {
981                 mkpath catfile($platformTestDirectory, dirname($base));
982                 writeToFile("$platformTestDirectory/$expectedFileName", $actual);
983             }
984         }
985         deleteExpectedAndActualResults($base);
986         recordActualResultsAndDiff($base, $actual);
987         if (!$resetResults) {
988             # Always print the file name for new tests, as they will probably need some manual inspection.
989             # in verbose mode we already printed the test case, so no need to do it again.
990             unless ($verbose) {
991                 print "\n" unless $atLineStart;
992                 print "$test -> ";
993             }
994             my $resultsDir = catdir($expectedDir, dirname($base));
995             if (!$verbose) {
996                 print "new";
997             }
998             if ($generateNewResults) {
999                 print " (results generated in $resultsDir)";
1000             }
1001             print "\n" unless $atLineStart;
1002             $atLineStart = 1;
1003         }
1004     } elsif ($actual eq $expected && $diffResult eq "passed") {
1005         if ($verbose) {
1006             print "succeeded\n";
1007             $atLineStart = 1;
1008         }
1009         $result = "match";
1010         deleteExpectedAndActualResults($base);
1011     } else {
1012         $result = "mismatch";
1013
1014         my $pixelTestFailed = $pixelTests && $diffPNG && $diffPNG ne "";
1015         my $testFailed = $actual ne $expected;
1016
1017         my $message = !$testFailed ? "pixel test failed" : "failed";
1018
1019         if (($testFailed || $pixelTestFailed) && $addPlatformExceptions) {
1020             my $testBase = catfile($testDirectory, $base);
1021             my $expectedBase = catfile($expectedDir, $base);
1022             my $testIsMaximallyPlatformSpecific = $testBase =~ m|^\Q$platformTestDirectory\E/|;
1023             my $expectedResultIsMaximallyPlatformSpecific = $expectedBase =~ m|^\Q$platformTestDirectory\E/|;
1024             if (!$testIsMaximallyPlatformSpecific && !$expectedResultIsMaximallyPlatformSpecific) {
1025                 mkpath catfile($platformTestDirectory, dirname($base));
1026                 if ($testFailed) {
1027                     my $expectedFile = catfile($platformTestDirectory, "$expectedFileName");
1028                     writeToFile("$expectedFile", $actual);
1029                 }
1030                 if ($pixelTestFailed) {
1031                     my $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.png");
1032                     writeToFile("$expectedFile", $actualPNG);
1033                 }
1034                 $message .= " (results generated in $platformTestDirectory)";
1035             }
1036         }
1037
1038         printFailureMessageForTest($test, $message);
1039
1040         my $dir = "$testResultsDirectory/$base";
1041         $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
1042         my $testName = $1;
1043         mkpath $dir;
1044
1045         deleteExpectedAndActualResults($base);
1046         recordActualResultsAndDiff($base, $actual);
1047
1048         if ($pixelTestFailed) {
1049             $imagesPresent{$base} = 1;
1050
1051             writeToFile("$testResultsDirectory/$base-$actualTag.png", $actualPNG);
1052             writeToFile("$testResultsDirectory/$base-$diffsTag.png", $diffPNG);
1053
1054             my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
1055             copy("$expectedPixelDir/$base-$expectedTag.png", "$testResultsDirectory/$base-$expectedTag.png");
1056
1057             open DIFFHTML, ">$testResultsDirectory/$base-$diffsTag.html" or die;
1058             print DIFFHTML "<html>\n";
1059             print DIFFHTML "<head>\n";
1060             print DIFFHTML "<title>$base Image Compare</title>\n";
1061             print DIFFHTML "<script language=\"Javascript\" type=\"text/javascript\">\n";
1062             print DIFFHTML "var currentImage = 0;\n";
1063             print DIFFHTML "var imageNames = new Array(\"Actual\", \"Expected\");\n";
1064             print DIFFHTML "var imagePaths = new Array(\"$testName-$actualTag.png\", \"$testName-$expectedTag.png\");\n";
1065             if (-f "$testDirectory/$base-w3c.png") {
1066                 copy("$testDirectory/$base-w3c.png", "$testResultsDirectory/$base-w3c.png");
1067                 print DIFFHTML "imageNames.push(\"W3C\");\n";
1068                 print DIFFHTML "imagePaths.push(\"$testName-w3c.png\");\n";
1069             }
1070             print DIFFHTML "function animateImage() {\n";
1071             print DIFFHTML "    var image = document.getElementById(\"animatedImage\");\n";
1072             print DIFFHTML "    var imageText = document.getElementById(\"imageText\");\n";
1073             print DIFFHTML "    image.src = imagePaths[currentImage];\n";
1074             print DIFFHTML "    imageText.innerHTML = imageNames[currentImage] + \" Image\";\n";
1075             print DIFFHTML "    currentImage = (currentImage + 1) % imageNames.length;\n";
1076             print DIFFHTML "    setTimeout('animateImage()',2000);\n";
1077             print DIFFHTML "}\n";
1078             print DIFFHTML "</script>\n";
1079             print DIFFHTML "</head>\n";
1080             print DIFFHTML "<body onLoad=\"animateImage();\">\n";
1081             print DIFFHTML "<table>\n";
1082             if ($diffPercentage) {
1083                 print DIFFHTML "<tr>\n";
1084                 print DIFFHTML "<td>Difference between images: <a href=\"$testName-$diffsTag.png\">$diffPercentage%</a></td>\n";
1085                 print DIFFHTML "</tr>\n";
1086             }
1087             print DIFFHTML "<tr>\n";
1088             print DIFFHTML "<td><a href=\"" . toURL("$testDirectory/$test") . "\">test file</a></td>\n";
1089             print DIFFHTML "</tr>\n";
1090             print DIFFHTML "<tr>\n";
1091             print DIFFHTML "<td id=\"imageText\" style=\"text-weight: bold;\">Actual Image</td>\n";
1092             print DIFFHTML "</tr>\n";
1093             print DIFFHTML "<tr>\n";
1094             print DIFFHTML "<td><img src=\"$testName-$actualTag.png\" id=\"animatedImage\"></td>\n";
1095             print DIFFHTML "</tr>\n";
1096             print DIFFHTML "</table>\n";
1097             print DIFFHTML "</body>\n";
1098             print DIFFHTML "</html>\n";
1099         }
1100     }
1101
1102     if ($error) {
1103         my $dir = dirname(File::Spec->catdir($testResultsDirectory, $base));
1104         mkpath $dir;
1105         
1106         writeToFile(File::Spec->catfile($testResultsDirectory, "$base-$errorTag.txt"), $error);
1107         
1108         $counts{error}++;
1109         push @{$tests{error}}, $test;
1110     }
1111
1112     countFinishedTest($test, $base, $result, $isText);
1113     last if stopRunningTestsEarlyIfNeeded();
1114 }
1115
1116 close($tests_run_fh);
1117
1118 my $totalTestingTime = time - $overallStartTime;
1119 my $waitTime = getWaitTime();
1120 if ($waitTime > 0.1) {
1121     my $normalizedTestingTime = $totalTestingTime - $waitTime;
1122     printf "\n%0.2fs HTTPD waiting time\n", $waitTime . "";
1123     printf "%0.2fs normalized testing time", $normalizedTestingTime . "";
1124 }
1125 printf "\n%0.2fs total testing time\n", $totalTestingTime . "";
1126
1127 !$isDumpToolOpen || die "Failed to close $dumpToolName.\n";
1128
1129 $isHttpdOpen = !closeHTTPD();
1130 closeWebSocketServer();
1131
1132 # Because multiple instances of this script are running concurrently we cannot 
1133 # safely delete this symlink.
1134 # system "rm /tmp/LayoutTests";
1135
1136 # FIXME: Do we really want to check the image-comparison tool for leaks every time?
1137 if ($isDiffToolOpen && $shouldCheckLeaks) {
1138     $totalLeaks += countAndPrintLeaks("ImageDiff", $imageDiffToolPID, "$testResultsDirectory/ImageDiff-leaks.txt");
1139 }
1140
1141 if ($totalLeaks) {
1142     if ($mergeDepth) {
1143         parseLeaksandPrintUniqueLeaks();
1144     } else { 
1145         print "\nWARNING: $totalLeaks total leaks found!\n";
1146         print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
1147     }
1148 }
1149
1150 close IN;
1151 close OUT;
1152 close ERROR;
1153
1154 if ($report10Slowest) {
1155     print "\n\nThe 10 slowest tests:\n\n";
1156     my $count = 0;
1157     for my $test (sort slowestcmp keys %durations) {
1158         printf "%0.2f secs: %s\n", $durations{$test}, $test;
1159         last if ++$count == 10;
1160     }
1161 }
1162
1163 print "\n";
1164
1165 if ($skippedOnly && $counts{"match"}) {
1166     print "The following tests are in the Skipped file (" . File::Spec->abs2rel("$platformTestDirectory/Skipped", $testDirectory) . "), but succeeded:\n";
1167     foreach my $test (@{$tests{"match"}}) {
1168         print "  $test\n";
1169     }
1170 }
1171
1172 if ($resetResults || ($counts{match} && $counts{match} == $count)) {
1173     print "all $count test cases succeeded\n";
1174     unlink $testResults;
1175     exit;
1176 }
1177
1178 printResults();
1179
1180 mkpath $testResultsDirectory;
1181
1182 open HTML, ">", $testResults or die "Failed to open $testResults. $!";
1183 print HTML <<EOF;
1184 <html>
1185 <head>
1186 <title>Layout Test Results</title>
1187 <style>
1188 .stopped-running-early-message {
1189     border: 3px solid #d00;
1190     font-weight: bold;
1191 }
1192 </style>
1193 </head>
1194 </body>
1195 EOF
1196
1197 if ($ignoreMetrics) {
1198     print HTML "<h4>Tested with metrics ignored.</h4>";
1199 }
1200
1201 if ($stoppedRunningEarlyMessage) {
1202     print HTML "<p class='stopped-running-early-message'>$stoppedRunningEarlyMessage</p>";
1203 }
1204
1205 print HTML htmlForResultsSection(@{$tests{mismatch}}, "Tests where results did not match expected results", \&linksForMismatchTest);
1206 print HTML htmlForResultsSection(@{$tests{timedout}}, "Tests that timed out", \&linksForErrorTest);
1207 print HTML htmlForResultsSection(@{$tests{crash}}, "Tests that caused the DumpRenderTree tool to crash", \&linksForErrorTest);
1208 print HTML htmlForResultsSection(@{$tests{webProcessCrash}}, "Tests that caused the Web process to crash", \&linksForErrorTest);
1209 print HTML htmlForResultsSection(@{$tests{error}}, "Tests that had stderr output", \&linksForErrorTest);
1210 print HTML htmlForResultsSection(@{$tests{new}}, "Tests that had no expected results (probably new)", \&linksForNewTest);
1211
1212 print HTML "<p>httpd access log: <a href=\"access_log.txt\">access_log.txt</a></p>\n";
1213 print HTML "<p>httpd error log: <a href=\"error_log.txt\">error_log.txt</a></p>\n";
1214
1215 print HTML "</body>\n";
1216 print HTML "</html>\n";
1217 close HTML;
1218
1219 my @configurationArgs = argumentsForConfiguration();
1220
1221 if (isGtk()) {
1222   push(@configurationArgs, '-2') if $useWebKitTestRunner;
1223   system "Tools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
1224 } elsif (isQt()) {
1225   unshift @configurationArgs, qw(-graphicssystem raster -style windows);
1226   if (isCygwin()) {
1227     $testResults = "/" . toWindowsPath($testResults);
1228     $testResults =~ s/\\/\//g;
1229   }
1230   push(@configurationArgs, '-2') if $useWebKitTestRunner;
1231   system "Tools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
1232 } elsif (isCygwin()) {
1233   system "cygstart", $testResults if $launchSafari;
1234 } elsif (isWindows()) {
1235   system "start", $testResults if $launchSafari;
1236 } else {
1237   system "Tools/Scripts/run-safari", @configurationArgs, "-NSOpen", $testResults if $launchSafari;
1238 }
1239
1240 closeCygpaths() if isCygwin();
1241
1242 exit 1;
1243
1244 sub countAndPrintLeaks($$$)
1245 {
1246     my ($dumpToolName, $dumpToolPID, $leaksFilePath) = @_;
1247
1248     print "\n" unless $atLineStart;
1249     $atLineStart = 1;
1250
1251     # We are excluding the following reported leaks so they don't get in our way when looking for WebKit leaks:
1252     # This allows us ignore known leaks and only be alerted when new leaks occur. Some leaks are in the old
1253     # versions of the system frameworks that are being used by the leaks bots. Even though a leak has been
1254     # fixed, it will be listed here until the bot has been updated with the newer frameworks.
1255
1256     my @typesToExclude = (
1257     );
1258
1259     my @callStacksToExclude = (
1260         "Flash_EnforceLocalSecurity" # leaks in Flash plug-in code, rdar://problem/4449747
1261     );
1262
1263     if (isLeopard()) {
1264         # Leak list for the version of Leopard used on the build bot.
1265         push @callStacksToExclude, (
1266             "CFHTTPMessageAppendBytes", # leak in CFNetwork, rdar://problem/5435912
1267             "sendDidReceiveDataCallback", # leak in CFNetwork, rdar://problem/5441619
1268             "_CFHTTPReadStreamReadMark", # leak in CFNetwork, rdar://problem/5441468
1269             "httpProtocolStart", # leak in CFNetwork, rdar://problem/5468837
1270             "_CFURLConnectionSendCallbacks", # leak in CFNetwork, rdar://problem/5441600
1271             "DispatchQTMsg", # leak in QuickTime, PPC only, rdar://problem/5667132
1272             "QTMovieContentView createVisualContext", # leak in QuickTime, PPC only, rdar://problem/5667132
1273             "_CopyArchitecturesForJVMVersion", # leak in Java, rdar://problem/5910823
1274         );
1275     }
1276
1277     if (isSnowLeopard()) {
1278         push @callStacksToExclude, (
1279             "readMakerNoteProps", # <rdar://problem/7156432> leak in ImageIO
1280             "QTKitMovieControllerView completeUISetup", # <rdar://problem/7155156> leak in QTKit
1281             "getVMInitArgs", # <rdar://problem/7714444> leak in Java
1282             "Java_java_lang_System_initProperties", # <rdar://problem/7714465> leak in Java
1283             "glrCompExecuteKernel", # <rdar://problem/7815391> leak in graphics driver while using OpenGL
1284             "NSNumberFormatter getObjectValue:forString:errorDescription:", # <rdar://problem/7149350> Leak in NSNumberFormatter
1285         );
1286     }
1287
1288     my $leaksTool = sourceDir() . "/Tools/Scripts/run-leaks";
1289     my $excludeString = "--exclude-callstack '" . (join "' --exclude-callstack '", @callStacksToExclude) . "'";
1290     $excludeString .= " --exclude-type '" . (join "' --exclude-type '", @typesToExclude) . "'" if @typesToExclude;
1291
1292     print " ? checking for leaks in $dumpToolName\n";
1293     my $leaksOutput = `$leaksTool $excludeString $dumpToolPID`;
1294     my ($count, $bytes) = $leaksOutput =~ /Process $dumpToolPID: (\d+) leaks? for (\d+) total/;
1295     my ($excluded) = $leaksOutput =~ /(\d+) leaks? excluded/;
1296
1297     my $adjustedCount = $count;
1298     $adjustedCount -= $excluded if $excluded;
1299
1300     if (!$adjustedCount) {
1301         print " - no leaks found\n";
1302         unlink $leaksFilePath;
1303         return 0;
1304     } else {
1305         my $dir = $leaksFilePath;
1306         $dir =~ s|/[^/]+$|| or die;
1307         mkpath $dir;
1308
1309         if ($excluded) {
1310             print " + $adjustedCount leaks ($bytes bytes including $excluded excluded leaks) were found, details in $leaksFilePath\n";
1311         } else {
1312             print " + $count leaks ($bytes bytes) were found, details in $leaksFilePath\n";
1313         }
1314
1315         writeToFile($leaksFilePath, $leaksOutput);
1316         
1317         push @leaksFilenames, $leaksFilePath;
1318     }
1319
1320     return $adjustedCount;
1321 }
1322
1323 sub writeToFile($$)
1324 {
1325     my ($filePath, $contents) = @_;
1326     open NEWFILE, ">", "$filePath" or die "Could not create $filePath. $!\n";
1327     print NEWFILE $contents;
1328     close NEWFILE;
1329 }
1330
1331 # Break up a path into the directory (with slash) and base name.
1332 sub splitpath($)
1333 {
1334     my ($path) = @_;
1335
1336     my $pathSeparator = "/";
1337     my $dirname = dirname($path) . $pathSeparator;
1338     $dirname = "" if $dirname eq "." . $pathSeparator;
1339
1340     return ($dirname, basename($path));
1341 }
1342
1343 # Sort first by directory, then by file, so all paths in one directory are grouped
1344 # rather than being interspersed with items from subdirectories.
1345 # Use numericcmp to sort directory and filenames to make order logical.
1346 sub pathcmp($$)
1347 {
1348     my ($patha, $pathb) = @_;
1349
1350     my ($dira, $namea) = splitpath($patha);
1351     my ($dirb, $nameb) = splitpath($pathb);
1352
1353     return numericcmp($dira, $dirb) if $dira ne $dirb;
1354     return numericcmp($namea, $nameb);
1355 }
1356
1357 # Sort numeric parts of strings as numbers, other parts as strings.
1358 # Makes 1.33 come after 1.3, which is cool.
1359 sub numericcmp($$)
1360 {
1361     my ($aa, $bb) = @_;
1362
1363     my @a = split /(\d+)/, $aa;
1364     my @b = split /(\d+)/, $bb;
1365
1366     # Compare one chunk at a time.
1367     # Each chunk is either all numeric digits, or all not numeric digits.
1368     while (@a && @b) {
1369         my $a = shift @a;
1370         my $b = shift @b;
1371         
1372         # Use numeric comparison if chunks are non-equal numbers.
1373         return $a <=> $b if $a =~ /^\d/ && $b =~ /^\d/ && $a != $b;
1374
1375         # Use string comparison if chunks are any other kind of non-equal string.
1376         return $a cmp $b if $a ne $b;
1377     }
1378     
1379     # One of the two is now empty; compare lengths for result in this case.
1380     return @a <=> @b;
1381 }
1382
1383 # Sort slowest tests first.
1384 sub slowestcmp($$)
1385 {
1386     my ($testa, $testb) = @_;
1387
1388     my $dura = $durations{$testa};
1389     my $durb = $durations{$testb};
1390     return $durb <=> $dura if $dura != $durb;
1391     return pathcmp($testa, $testb);
1392 }
1393
1394 sub launchWithEnv(\@\%)
1395 {
1396     my ($args, $env) = @_;
1397
1398     # Dump the current environment as perl code and then put it in quotes so it is one parameter.
1399     my $environmentDumper = Data::Dumper->new([\%{$env}], [qw(*ENV)]);
1400     $environmentDumper->Indent(0);
1401     $environmentDumper->Purity(1);
1402     my $allEnvVars = $environmentDumper->Dump();
1403     unshift @{$args}, "\"$allEnvVars\"";
1404
1405     my $execScript = File::Spec->catfile(sourceDir(), qw(Tools Scripts execAppWithEnv));
1406     unshift @{$args}, $perlInterpreter, $execScript;
1407     return @{$args};
1408 }
1409
1410 sub resolveAndMakeTestResultsDirectory()
1411 {
1412     my $absTestResultsDirectory = File::Spec->rel2abs(glob $testResultsDirectory);
1413     mkpath $absTestResultsDirectory;
1414     return $absTestResultsDirectory;
1415 }
1416
1417 sub openDiffTool()
1418 {
1419     return if $isDiffToolOpen;
1420     return if !$pixelTests;
1421
1422     my %CLEAN_ENV;
1423     $CLEAN_ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
1424     $imageDiffToolPID = open2(\*DIFFIN, \*DIFFOUT, $imageDiffTool, launchWithEnv(@diffToolArgs, %CLEAN_ENV)) or die "unable to open $imageDiffTool\n";
1425     $isDiffToolOpen = 1;
1426 }
1427
1428 sub buildDumpTool($)
1429 {
1430     my ($dumpToolName) = @_;
1431
1432     my $dumpToolBuildScript =  "build-" . lc($dumpToolName);
1433     print STDERR "Running $dumpToolBuildScript\n";
1434
1435     local *DEVNULL;
1436     my ($childIn, $childOut, $childErr);
1437     if ($quiet) {
1438         open(DEVNULL, ">", File::Spec->devnull()) or die "Failed to open /dev/null";
1439         $childOut = ">&DEVNULL";
1440         $childErr = ">&DEVNULL";
1441     } else {
1442         # When not quiet, let the child use our stdout/stderr.
1443         $childOut = ">&STDOUT";
1444         $childErr = ">&STDERR";
1445     }
1446
1447     my @args = argumentsForConfiguration();
1448     my $buildProcess = open3($childIn, $childOut, $childErr, $perlInterpreter, File::Spec->catfile(qw(Tools Scripts), $dumpToolBuildScript), @args) or die "Failed to run build-dumprendertree";
1449     close($childIn);
1450     waitpid $buildProcess, 0;
1451     my $buildResult = $?;
1452     close($childOut);
1453     close($childErr);
1454
1455     close DEVNULL if ($quiet);
1456
1457     if ($buildResult) {
1458         print STDERR "Compiling $dumpToolName failed!\n";
1459         exit exitStatus($buildResult);
1460     }
1461 }
1462
1463 sub openDumpTool()
1464 {
1465     return if $isDumpToolOpen;
1466
1467     if ($verbose && $testsPerDumpTool != 1) {
1468         print "| Opening DumpTool |\n";
1469     }
1470
1471     my %CLEAN_ENV;
1472
1473     # Generic environment variables
1474     if (defined $ENV{'WEBKIT_TESTFONTS'}) {
1475         $CLEAN_ENV{WEBKIT_TESTFONTS} = $ENV{'WEBKIT_TESTFONTS'};
1476     }
1477
1478     # unique temporary directory for each DumpRendertree - needed for running more DumpRenderTree in parallel
1479     $CLEAN_ENV{DUMPRENDERTREE_TEMP} = File::Temp::tempdir('DumpRenderTree-XXXXXX', TMPDIR => 1, CLEANUP => 1);
1480     $CLEAN_ENV{XML_CATALOG_FILES} = ""; # work around missing /etc/catalog <rdar://problem/4292995>
1481
1482     # Platform spesifics
1483     if (isLinux()) {
1484         if (defined $ENV{'DISPLAY'}) {
1485             $CLEAN_ENV{DISPLAY} = $ENV{'DISPLAY'};
1486         } else {
1487             $CLEAN_ENV{DISPLAY} = ":1";
1488         }
1489         if (defined $ENV{'XAUTHORITY'}) {
1490             $CLEAN_ENV{XAUTHORITY} = $ENV{'XAUTHORITY'};
1491         }
1492
1493         $CLEAN_ENV{HOME} = $ENV{'HOME'};
1494         $CLEAN_ENV{LANG} = $ENV{'LANG'};
1495
1496         if (defined $ENV{'LD_LIBRARY_PATH'}) {
1497             $CLEAN_ENV{LD_LIBRARY_PATH} = $ENV{'LD_LIBRARY_PATH'};
1498         }
1499         if (defined $ENV{'DBUS_SESSION_BUS_ADDRESS'}) {
1500             $CLEAN_ENV{DBUS_SESSION_BUS_ADDRESS} = $ENV{'DBUS_SESSION_BUS_ADDRESS'};
1501         }
1502     } elsif (isDarwin()) {
1503         if (defined $ENV{'DYLD_LIBRARY_PATH'}) {
1504             $CLEAN_ENV{DYLD_LIBRARY_PATH} = $ENV{'DYLD_LIBRARY_PATH'};
1505         }
1506         if (defined $ENV{'HOME'}) {
1507             $CLEAN_ENV{HOME} = $ENV{'HOME'};
1508         }
1509
1510         $CLEAN_ENV{DYLD_FRAMEWORK_PATH} = $productDir;
1511         $CLEAN_ENV{DYLD_INSERT_LIBRARIES} = "/usr/lib/libgmalloc.dylib" if $guardMalloc;
1512     } elsif (isCygwin()) {
1513         $CLEAN_ENV{HOMEDRIVE} = $ENV{'HOMEDRIVE'};
1514         $CLEAN_ENV{HOMEPATH} = $ENV{'HOMEPATH'};
1515         $CLEAN_ENV{_NT_SYMBOL_PATH} = $ENV{_NT_SYMBOL_PATH};
1516
1517         setPathForRunningWebKitApp(\%CLEAN_ENV);
1518     }
1519
1520     # Port specifics
1521     if (isGtk()) {
1522         $CLEAN_ENV{LIBOVERLAY_SCROLLBAR} = "0";
1523         $CLEAN_ENV{GTK_MODULES} = "gail";
1524         $CLEAN_ENV{WEBKIT_INSPECTOR_PATH} = "$productDir/resources/inspector";
1525
1526         if ($useWebKitTestRunner) {
1527             my $injectedBundlePath = productDir() . "/Libraries/.libs/libTestRunnerInjectedBundle";
1528             $CLEAN_ENV{TEST_RUNNER_INJECTED_BUNDLE_FILENAME} = $injectedBundlePath;
1529             my $testPluginPath = productDir() . "/TestNetscapePlugin/.libs";
1530             $CLEAN_ENV{TEST_RUNNER_TEST_PLUGIN_PATH} = $testPluginPath;
1531         }
1532     }
1533
1534     if (isQt()) {
1535         $CLEAN_ENV{QTWEBKIT_PLUGIN_PATH} = productDir() . "/lib/plugins";
1536         $CLEAN_ENV{QT_DRT_WEBVIEW_MODE} = $ENV{"QT_DRT_WEBVIEW_MODE"};
1537     }
1538     
1539     my @args = ($dumpTool, @toolArgs);
1540     if (isAppleMacWebKit()) { 
1541         unshift @args, "arch", "-" . architecture();             
1542     }
1543
1544     if ($useValgrind) {
1545         unshift @args, "valgrind", "--suppressions=$platformBaseDirectory/qt/SuppressedValgrindErrors";
1546     } 
1547
1548     if ($useWebKitTestRunner) {
1549         # Make WebKitTestRunner use a similar timeout. We don't use the exact same timeout to avoid
1550         # race conditions.
1551         push @args, "--timeout", $timeoutSeconds - 5;
1552     }
1553
1554     $CLEAN_ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
1555
1556     $dumpToolPID = open3(\*OUT, \*IN, \*ERROR, launchWithEnv(@args, %CLEAN_ENV)) or die "Failed to start tool: $dumpTool\n";
1557     $isDumpToolOpen = 1;
1558     $dumpToolCrashed = 0;
1559 }
1560
1561 sub closeDumpTool()
1562 {
1563     return if !$isDumpToolOpen;
1564
1565     if ($verbose && $testsPerDumpTool != 1) {
1566         print "| Closing DumpTool |\n";
1567     }
1568
1569     close IN;
1570     close OUT;
1571     waitpid $dumpToolPID, 0;
1572     
1573     # check for WebCore counter leaks.
1574     if ($shouldCheckLeaks) {
1575         while (<ERROR>) {
1576             print;
1577         }
1578     }
1579     close ERROR;
1580     $isDumpToolOpen = 0;
1581 }
1582
1583 sub dumpToolDidCrash()
1584 {
1585     return 1 if $dumpToolCrashed;
1586     return 0 unless $isDumpToolOpen;
1587     my $pid = waitpid(-1, WNOHANG);
1588     return 1 if ($pid == $dumpToolPID);
1589
1590     # On Mac OS X, crashing may be significantly delayed by crash reporter.
1591     return 0 unless isAppleMacWebKit();
1592
1593     return DumpRenderTreeSupport::processIsCrashing($dumpToolPID);
1594 }
1595
1596 sub configureAndOpenHTTPDIfNeeded()
1597 {
1598     return if $isHttpdOpen;
1599     my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
1600     my $listen = "127.0.0.1:$httpdPort";
1601     my @args = (
1602         "-c", "CustomLog \"$absTestResultsDirectory/access_log.txt\" common",
1603         "-c", "ErrorLog \"$absTestResultsDirectory/error_log.txt\"",
1604         "-C", "Listen $listen"
1605     );
1606
1607     my @defaultArgs = getDefaultConfigForTestDirectory($testDirectory);
1608     @args = (@defaultArgs, @args);
1609
1610     waitForHTTPDLock() if $shouldWaitForHTTPD;
1611     $isHttpdOpen = openHTTPD(@args);
1612 }
1613
1614 sub checkPythonVersion()
1615 {
1616     # we have not chdir to sourceDir yet.
1617     system $perlInterpreter, File::Spec->catfile(sourceDir(), qw(Tools Scripts ensure-valid-python)), "--check-only";
1618     return exitStatus($?) == 0;
1619 }
1620
1621 sub openWebSocketServerIfNeeded()
1622 {
1623     return 1 if $isWebSocketServerOpen;
1624     return 0 if $failedToStartWebSocketServer;
1625
1626     my $webSocketHandlerDir = "$testDirectory";
1627     my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
1628     $webSocketServerPidFile = "$absTestResultsDirectory/websocket.pid";
1629
1630     my @args = (
1631         "Tools/Scripts/new-run-webkit-websocketserver",
1632         "--server", "start",
1633         "--port", "$webSocketPort",
1634         "--root", "$webSocketHandlerDir",
1635         "--output-dir", "$absTestResultsDirectory",
1636         "--pidfile", "$webSocketServerPidFile"
1637     );
1638     system "/usr/bin/python", @args;
1639
1640     $isWebSocketServerOpen = 1;
1641     return 1;
1642 }
1643
1644 sub closeWebSocketServer()
1645 {
1646     return if !$isWebSocketServerOpen;
1647
1648     my @args = (
1649         "Tools/Scripts/new-run-webkit-websocketserver",
1650         "--server", "stop",
1651         "--pidfile", "$webSocketServerPidFile"
1652     );
1653     system "/usr/bin/python", @args;
1654     unlink "$webSocketServerPidFile";
1655
1656     # wss is disabled until all platforms support pyOpenSSL.
1657     $isWebSocketServerOpen = 0;
1658 }
1659
1660 sub fileNameWithNumber($$)
1661 {
1662     my ($base, $number) = @_;
1663     return "$base$number" if ($number > 1);
1664     return $base;
1665 }
1666
1667 sub processIgnoreTests($$)
1668 {
1669     my @ignoreList = split(/\s*,\s*/, shift);
1670     my $listName = shift;
1671
1672     my $disabledSuffix = "-disabled";
1673
1674     my $addIgnoredDirectories = sub {
1675         return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
1676         $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)} = 1;
1677         return @_;
1678     };
1679     foreach my $item (@ignoreList) {
1680         my $path = catfile($testDirectory, $item); 
1681         if (-d $path) {
1682             $ignoredDirectories{$item} = 1;
1683             find({ preprocess => $addIgnoredDirectories, wanted => sub {} }, $path);
1684         }
1685         elsif (-f $path) {
1686             $ignoredFiles{$item} = 1;
1687         } elsif (-f $path . $disabledSuffix) {
1688             # The test is disabled, so do nothing.
1689         } else {
1690             print "$listName list contained '$item', but no file of that name could be found\n";
1691         }
1692     }
1693 }
1694
1695 sub stripExtension($)
1696 {
1697     my ($test) = @_;
1698
1699     $test =~ s/\.[a-zA-Z]+$//;
1700     return $test;
1701 }
1702
1703 sub isTextOnlyTest($)
1704 {
1705     my ($actual) = @_;
1706     my $isText;
1707     if ($actual =~ /^layer at/ms) {
1708         $isText = 0;
1709     } else {
1710         $isText = 1;
1711     }
1712     return $isText;
1713 }
1714
1715 sub expectedDirectoryForTest($;$;$)
1716 {
1717     my ($base, $isText, $expectedExtension) = @_;
1718
1719     my @directories = @platformResultHierarchy;
1720
1721     my @extraPlatforms = ();
1722     if (isAppleWinWebKit()) {
1723         push @extraPlatforms, "mac-wk2" if $platform eq "win-wk2";
1724         push @extraPlatforms, qw(mac-lion mac);
1725     }
1726   
1727     push @directories, map { catdir($platformBaseDirectory, $_) } @extraPlatforms;
1728     push @directories, $expectedDirectory;
1729
1730     # If we already have expected results, just return their location.
1731     foreach my $directory (@directories) {
1732         return $directory if -f File::Spec->catfile($directory, "$base-$expectedTag.$expectedExtension");
1733     }
1734
1735     # For cross-platform tests, text-only results should go in the cross-platform directory,
1736     # while render tree dumps should go in the least-specific platform directory.
1737     return $isText ? $expectedDirectory : $platformResultHierarchy[$#platformResultHierarchy];
1738 }
1739
1740 sub countFinishedTest($$$$)
1741 {
1742     my ($test, $base, $result, $isText) = @_;
1743
1744     if (($count + 1) % $testsPerDumpTool == 0 || $count == $#tests) {
1745         if ($shouldCheckLeaks) {
1746             my $fileName;
1747             if ($testsPerDumpTool == 1) {
1748                 $fileName = File::Spec->catfile($testResultsDirectory, "$base-leaks.txt");
1749             } else {
1750                 $fileName = File::Spec->catfile($testResultsDirectory, fileNameWithNumber($dumpToolName, $leaksOutputFileNumber) . "-leaks.txt");
1751             }
1752             my $leakCount = countAndPrintLeaks($dumpToolName, $dumpToolPID, $fileName);
1753             $totalLeaks += $leakCount;
1754             $leaksOutputFileNumber++ if ($leakCount);
1755         }
1756
1757         closeDumpTool();
1758     }
1759     
1760     $count++;
1761     $counts{$result}++;
1762     push @{$tests{$result}}, $test;
1763 }
1764
1765 sub testCrashedOrTimedOut($$$$$$)
1766 {
1767     my ($test, $base, $didCrash, $webProcessCrashed, $actual, $error) = @_;
1768
1769     printFailureMessageForTest($test, $webProcessCrashed ? "Web process crashed" : $didCrash ? "crashed" : "timed out");
1770
1771     sampleDumpTool() unless $didCrash || $webProcessCrashed;
1772
1773     my $dir = dirname(File::Spec->catdir($testResultsDirectory, $base));
1774     mkpath $dir;
1775
1776     deleteExpectedAndActualResults($base);
1777
1778     if (defined($error) && length($error)) {
1779         writeToFile(File::Spec->catfile($testResultsDirectory, "$base-$errorTag.txt"), $error);
1780     }
1781
1782     recordActualResultsAndDiff($base, $actual);
1783
1784     # There's no point in killing the dump tool when it's crashed. And it will kill itself when the
1785     # web process crashes.
1786     kill 9, $dumpToolPID unless $didCrash || $webProcessCrashed;
1787
1788     closeDumpTool();
1789
1790     captureSavedCrashLog($base, $webProcessCrashed) if $didCrash || $webProcessCrashed;
1791
1792     return unless isCygwin() && !$didCrash && $base =~ /^http/;
1793     # On Cygwin, http tests timing out can be a symptom of a non-responsive httpd.
1794     # If we timed out running an http test, try restarting httpd.
1795     $isHttpdOpen = !closeHTTPD();
1796     configureAndOpenHTTPDIfNeeded();
1797 }
1798
1799 sub captureSavedCrashLog($$)
1800 {
1801     my ($base, $webProcessCrashed) = @_;
1802
1803     my $crashLog;
1804
1805     my $glob;
1806     if (isCygwin()) {
1807         $glob = File::Spec->catfile($testResultsDirectory, $windowsCrashLogFilePrefix . "*.txt");
1808     } elsif (isAppleMacWebKit()) {
1809         my $crashLogDirectoryName;
1810         if (isLeopard()) {
1811             $crashLogDirectoryName = "CrashReporter";
1812         } else {
1813             $crashLogDirectoryName = "DiagnosticReports";
1814         }
1815
1816         $glob = File::Spec->catfile("~", "Library", "Logs", $crashLogDirectoryName, ($webProcessCrashed ? "WebProcess" : $dumpToolName) . "_*.crash");
1817
1818         # Even though the dump tool has exited, CrashReporter might still be running. We need to
1819         # wait for it to exit to ensure it has saved its crash log to disk. For simplicitly, we'll
1820         # assume that the ReportCrash process with the highest PID is the one we want.
1821         if (my @reportCrashPIDs = sort map { /^\s*(\d+)/; $1 } grep { /ReportCrash/ } `/bin/ps x`) {
1822             my $reportCrashPID = $reportCrashPIDs[$#reportCrashPIDs];
1823             # We use kill instead of waitpid because ReportCrash is not one of our child processes.
1824             usleep(250000) while kill(0, $reportCrashPID) > 0;
1825         }
1826     }
1827
1828     return unless $glob;
1829
1830     # We assume that the newest crash log in matching the glob is the one that corresponds to the crash that just occurred.
1831     if (my $newestCrashLog = findNewestFileMatchingGlob($glob)) {
1832         # The crash log must have been created after this script started running.
1833         $crashLog = $newestCrashLog if -M $newestCrashLog < 0;
1834     }
1835
1836     return unless $crashLog;
1837
1838     move($crashLog, File::Spec->catfile($testResultsDirectory, "$base-$crashLogTag.txt"));
1839 }
1840
1841 sub findNewestFileMatchingGlob($)
1842 {
1843     my ($glob) = @_;
1844
1845     my @paths = glob $glob;
1846     return unless scalar(@paths);
1847
1848     my @pathsAndTimes = map { [$_, -M $_] } @paths;
1849     @pathsAndTimes = sort { $b->[1] <=> $a->[1] } @pathsAndTimes;
1850     return $pathsAndTimes[$#pathsAndTimes]->[0];
1851 }
1852
1853 sub printFailureMessageForTest($$)
1854 {
1855     my ($test, $description) = @_;
1856
1857     unless ($verbose) {
1858         print "\n" unless $atLineStart;
1859         print "$test -> ";
1860     }
1861     print "$description\n";
1862     $atLineStart = 1;
1863 }
1864
1865 my %cygpaths = ();
1866
1867 sub openCygpathIfNeeded($)
1868 {
1869     my ($options) = @_;
1870
1871     return unless isCygwin();
1872     return $cygpaths{$options} if $cygpaths{$options} && $cygpaths{$options}->{"open"};
1873
1874     local (*CYGPATHIN, *CYGPATHOUT);
1875     my $pid = open2(\*CYGPATHIN, \*CYGPATHOUT, "cygpath -f - $options");
1876     my $cygpath =  {
1877         "pid" => $pid,
1878         "in" => *CYGPATHIN,
1879         "out" => *CYGPATHOUT,
1880         "open" => 1
1881     };
1882
1883     $cygpaths{$options} = $cygpath;
1884
1885     return $cygpath;
1886 }
1887
1888 sub closeCygpaths()
1889 {
1890     return unless isCygwin();
1891
1892     foreach my $cygpath (values(%cygpaths)) {
1893         close $cygpath->{"in"};
1894         close $cygpath->{"out"};
1895         waitpid($cygpath->{"pid"}, 0);
1896         $cygpath->{"open"} = 0;
1897
1898     }
1899 }
1900
1901 sub convertPathUsingCygpath($$)
1902 {
1903     my ($path, $options) = @_;
1904
1905     # cygpath -f (at least in Cygwin 1.7) converts spaces into newlines. We remove spaces here and
1906     # add them back in after conversion to work around this.
1907     my $spaceSubstitute = "__NOTASPACE__";
1908     $path =~ s/ /\Q$spaceSubstitute\E/g;
1909
1910     my $cygpath = openCygpathIfNeeded($options);
1911     local *inFH = $cygpath->{"in"};
1912     local *outFH = $cygpath->{"out"};
1913     print outFH $path . "\n";
1914     my $convertedPath = <inFH>;
1915     chomp($convertedPath) if defined $convertedPath;
1916
1917     $convertedPath =~ s/\Q$spaceSubstitute\E/ /g;
1918     return $convertedPath;
1919 }
1920
1921 sub toCygwinPath($)
1922 {
1923     my ($path) = @_;
1924     return unless isCygwin();
1925
1926     return convertPathUsingCygpath($path, "-u");
1927 }
1928
1929 sub toWindowsPath($)
1930 {
1931     my ($path) = @_;
1932     return unless isCygwin();
1933
1934     return convertPathUsingCygpath($path, "-w");
1935 }
1936
1937 sub toURL($)
1938 {
1939     my ($path) = @_;
1940
1941     if ($useRemoteLinksToTests) {
1942         my $relativePath = File::Spec->abs2rel($path, $testDirectory);
1943
1944         # If the file is below the test directory then convert it into a link to the file in SVN
1945         if ($relativePath !~ /^\.\.\//) {
1946             my $revision = svnRevisionForDirectory($testDirectory);
1947             my $svnPath = pathRelativeToSVNRepositoryRootForPath($path);
1948             return "http://trac.webkit.org/export/$revision/$svnPath";
1949         }
1950     }
1951
1952     return $path unless isCygwin();
1953
1954     return "file:///" . convertPathUsingCygpath($path, "-m");
1955 }
1956
1957 sub validateSkippedArg($$;$)
1958 {
1959     my ($option, $value, $value2) = @_;
1960     my %validSkippedValues = map { $_ => 1 } qw(default ignore only);
1961     $value = lc($value);
1962     die "Invalid argument '" . $value . "' for option $option" unless $validSkippedValues{$value};
1963     $treatSkipped = $value;
1964 }
1965
1966 sub htmlForResultsSection(\@$&)
1967 {
1968     my ($tests, $description, $linkGetter) = @_;
1969
1970     my @html = ();
1971     return join("\n", @html) unless @{$tests};
1972
1973     push @html, "<p>$description:</p>";
1974     push @html, "<table>";
1975     foreach my $test (@{$tests}) {
1976         push @html, "<tr>";
1977         push @html, "<td><a href=\"" . toURL("$testDirectory/$test") . "\">$test</a></td>";
1978         foreach my $link (@{&{$linkGetter}($test)}) {
1979             push @html, "<td>";
1980             push @html, "<a href=\"$link->{href}\">$link->{text}</a>" if -f File::Spec->catfile($testResultsDirectory, $link->{href});
1981             push @html, "</td>";
1982         }
1983         push @html, "</tr>";
1984     }
1985     push @html, "</table>";
1986
1987     return join("\n", @html);
1988 }
1989
1990 sub linksForExpectedAndActualResults($)
1991 {
1992     my ($base) = @_;
1993
1994     my @links = ();
1995
1996     return \@links unless -s "$testResultsDirectory/$base-$diffsTag.txt";
1997     
1998     my $expectedResultPath = $expectedResultPaths{$base};
1999     my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
2000
2001     push @links, { href => "$base-$expectedTag$expectedResultExtension", text => "expected" };
2002     push @links, { href => "$base-$actualTag$expectedResultExtension", text => "actual" };
2003     push @links, { href => "$base-$diffsTag.txt", text => "diff" };
2004     push @links, { href => "$base-$prettyDiffTag.html", text => "pretty diff" };
2005
2006     return \@links;
2007 }
2008
2009 sub linksForMismatchTest
2010 {
2011     my ($test) = @_;
2012
2013     my @links = ();
2014
2015     my $base = stripExtension($test);
2016
2017     push @links, @{linksForExpectedAndActualResults($base)};
2018     return \@links unless $pixelTests && $imagesPresent{$base};
2019
2020     push @links, { href => "$base-$expectedTag.png", text => "expected image" };
2021     push @links, { href => "$base-$diffsTag.html", text => "image diffs" };
2022     push @links, { href => "$base-$diffsTag.png", text => "$imageDifferences{$base}%" };
2023
2024     return \@links;
2025 }
2026
2027 sub crashLocation($)
2028 {
2029     my ($base) = @_;
2030
2031     my $crashLogFile = File::Spec->catfile($testResultsDirectory, "$base-$crashLogTag.txt");
2032
2033     if (isCygwin()) {
2034         # We're looking for the following text:
2035         #
2036         # FOLLOWUP_IP:
2037         # module!function+offset [file:line]
2038         #
2039         # The second contains the function that crashed (or the function that ended up jumping to a bad
2040         # address, as in the case of a null function pointer).
2041
2042         open LOG, "<", $crashLogFile or return;
2043         while (my $line = <LOG>) {
2044             last if $line =~ /^FOLLOWUP_IP:/;
2045         }
2046         my $desiredLine = <LOG>;
2047         close LOG;
2048
2049         return unless $desiredLine;
2050
2051         # Just take everything up to the first space (which is where the file/line information should
2052         # start).
2053         $desiredLine =~ /^(\S+)/;
2054         return $1;
2055     }
2056
2057     if (isAppleMacWebKit()) {
2058         # We're looking for the following text:
2059         #
2060         # Thread M Crashed:
2061         # N   module                              address function + offset (file:line)
2062         #
2063         # Some lines might have a module of "???" if we've jumped to a bad address. We should skip
2064         # past those.
2065
2066         open LOG, "<", $crashLogFile or return;
2067         while (my $line = <LOG>) {
2068             last if $line =~ /^Thread \d+ Crashed:/;
2069         }
2070         my $location;
2071         while (my $line = <LOG>) {
2072             $line =~ /^\d+\s+(\S+)\s+\S+ (.* \+ \d+)/ or next;
2073             my $module = $1;
2074             my $functionAndOffset = $2;
2075             next if $module eq "???";
2076             $location = "$module: $functionAndOffset";
2077             last;
2078         }
2079         close LOG;
2080         return $location;
2081     }
2082 }
2083
2084 sub linksForErrorTest
2085 {
2086     my ($test) = @_;
2087
2088     my @links = ();
2089
2090     my $base = stripExtension($test);
2091
2092     my $crashLogText = "crash log";
2093     if (my $crashLocation = crashLocation($base)) {
2094         $crashLogText .= " (<code>" . CGI::escapeHTML($crashLocation) . "</code>)";
2095     }
2096
2097     push @links, @{linksForExpectedAndActualResults($base)};
2098     push @links, { href => "$base-$errorTag.txt", text => "stderr" };
2099     push @links, { href => "$base-$crashLogTag.txt", text => $crashLogText };
2100
2101     return \@links;
2102 }
2103
2104 sub linksForNewTest
2105 {
2106     my ($test) = @_;
2107
2108     my @links = ();
2109
2110     my $base = stripExtension($test);
2111
2112     my $expectedResultPath = $expectedResultPaths{$base};
2113     my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
2114
2115     push @links, { href => "$base-$actualTag$expectedResultExtension", text => "result" };
2116     if ($pixelTests && $imagesPresent{$base}) {
2117         push @links, { href => "$base-$expectedTag.png", text => "image" };
2118     }
2119
2120     return \@links;
2121 }
2122
2123 sub deleteExpectedAndActualResults($)
2124 {
2125     my ($base) = @_;
2126
2127     unlink "$testResultsDirectory/$base-$actualTag.txt";
2128     unlink "$testResultsDirectory/$base-$diffsTag.txt";
2129     unlink "$testResultsDirectory/$base-$errorTag.txt";
2130     unlink "$testResultsDirectory/$base-$crashLogTag.txt";
2131 }
2132
2133 sub recordActualResultsAndDiff($$)
2134 {
2135     my ($base, $actualResults) = @_;
2136
2137     return unless defined($actualResults) && length($actualResults);
2138
2139     my $expectedResultPath = $expectedResultPaths{$base};
2140     my ($expectedResultFileNameMinusExtension, $expectedResultDirectoryPath, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
2141     my $actualResultsPath = File::Spec->catfile($testResultsDirectory, "$base-$actualTag$expectedResultExtension");
2142     my $copiedExpectedResultsPath = File::Spec->catfile($testResultsDirectory, "$base-$expectedTag$expectedResultExtension");
2143
2144     mkpath(dirname($actualResultsPath));
2145     writeToFile("$actualResultsPath", $actualResults);
2146
2147     # We don't need diff and pretty diff for tests without expected file.
2148     if ( !-f $expectedResultPath) {
2149         return;
2150     }
2151
2152     copy("$expectedResultPath", "$copiedExpectedResultsPath");
2153
2154     my $diffOuputBasePath = File::Spec->catfile($testResultsDirectory, $base);
2155     my $diffOutputPath = "$diffOuputBasePath-$diffsTag.txt";
2156     system "diff -u \"$copiedExpectedResultsPath\" \"$actualResultsPath\" > \"$diffOutputPath\"";
2157
2158     my $prettyDiffOutputPath = "$diffOuputBasePath-$prettyDiffTag.html";
2159     my $prettyPatchPath = "Websites/bugs.webkit.org/PrettyPatch/";
2160     my $prettifyPath = "$prettyPatchPath/prettify.rb";
2161     system "ruby -I \"$prettyPatchPath\" \"$prettifyPath\" \"$diffOutputPath\" > \"$prettyDiffOutputPath\"";
2162 }
2163
2164 sub buildPlatformResultHierarchy()
2165 {
2166     mkpath($platformTestDirectory) if ($platform eq "undefined" && !-d "$platformTestDirectory");
2167
2168     my @platforms;
2169     
2170     my $isMac = $platform =~ /^mac/;
2171     my $isWin = $platform =~ /^win/;
2172     if ($isMac || $isWin) {
2173         my $effectivePlatform = $platform;
2174         if ($platform eq "mac-wk2" || $platform eq "win-wk2") {
2175             push @platforms, $platform;
2176             $effectivePlatform = $realPlatform;
2177         }
2178
2179         my @platformList = $isMac ? @macPlatforms : @winPlatforms;
2180         my $i;
2181         for ($i = 0; $i < @platformList; $i++) {
2182             last if $platformList[$i] eq $effectivePlatform;
2183         }
2184         for (; $i < @platformList; $i++) {
2185             push @platforms, $platformList[$i];
2186         }
2187     } elsif ($platform =~ /^qt-/) {
2188         push @platforms, $platform;
2189         push @platforms, "qt";
2190     } elsif ($platform =~ /^gtk-/) {
2191         push @platforms, $platform;
2192         push @platforms, "gtk";
2193     } else {
2194         @platforms = $platform;
2195     }
2196
2197     my @hierarchy;
2198     for (my $i = 0; $i < @platforms; $i++) {
2199         my $scoped = catdir($platformBaseDirectory, $platforms[$i]);
2200         push(@hierarchy, $scoped) if (-d $scoped);
2201     }
2202     
2203     unshift @hierarchy, grep { -d $_ } @additionalPlatformDirectories;
2204
2205     return @hierarchy;
2206 }
2207
2208 sub buildPlatformTestHierarchy(@)
2209 {
2210     my (@platformHierarchy) = @_;
2211
2212     my $wk2Platform;
2213     for (my $i = 0; $i < @platformHierarchy; ++$i) {
2214         if ($platformHierarchy[$i] =~ /-wk2/) {
2215             $wk2Platform = splice @platformHierarchy, $i, 1;
2216             last;
2217         }
2218     }
2219
2220     my @result;
2221     push @result, $platformHierarchy[0];
2222     push @result, $wk2Platform if defined $wk2Platform;
2223     push @result, $platformHierarchy[$#platformHierarchy] if @platformHierarchy >= 2;
2224
2225     return @result;
2226 }
2227
2228 sub epiloguesAndPrologues($$)
2229 {
2230     my ($lastDirectory, $directory) = @_;
2231     my @lastComponents = split('/', $lastDirectory);
2232     my @components = split('/', $directory);
2233
2234     while (@lastComponents) {
2235         if (!defined($components[0]) || $lastComponents[0] ne $components[0]) {
2236             last;
2237         }
2238         shift @components;
2239         shift @lastComponents;
2240     }
2241
2242     my @result;
2243     my $leaving = $lastDirectory;
2244     foreach (@lastComponents) {
2245         my $epilogue = $leaving . "/resources/run-webkit-tests-epilogue.html";
2246         foreach (@platformResultHierarchy) {
2247             push @result, catdir($_, $epilogue) if (stat(catdir($_, $epilogue)));
2248         }
2249         push @result, catdir($testDirectory, $epilogue) if (stat(catdir($testDirectory, $epilogue)));
2250         $leaving =~ s|(^\|/)[^/]+$||;
2251     }
2252
2253     my $entering = $leaving;
2254     foreach (@components) {
2255         $entering .= '/' . $_;
2256         my $prologue = $entering . "/resources/run-webkit-tests-prologue.html";
2257         push @result, catdir($testDirectory, $prologue) if (stat(catdir($testDirectory, $prologue)));
2258         foreach (reverse @platformResultHierarchy) {
2259             push @result, catdir($_, $prologue) if (stat(catdir($_, $prologue)));
2260         }
2261     }
2262     return @result;
2263 }
2264     
2265 sub parseLeaksandPrintUniqueLeaks()
2266 {
2267     return unless @leaksFilenames;
2268
2269     my $mergedFilenames = join " ", @leaksFilenames;
2270     my $parseMallocHistoryTool = sourceDir() . "/Tools/Scripts/parse-malloc-history";
2271     
2272     open MERGED_LEAKS, "cat $mergedFilenames | $parseMallocHistoryTool --merge-depth $mergeDepth  - |" ;
2273     my @leakLines = <MERGED_LEAKS>;
2274     close MERGED_LEAKS;
2275     
2276     my $uniqueLeakCount = 0;
2277     my $totalBytes;
2278     foreach my $line (@leakLines) {
2279         ++$uniqueLeakCount if ($line =~ /^(\d*)\scalls/);
2280         $totalBytes = $1 if $line =~ /^total\:\s(.*)\s\(/;
2281     }
2282     
2283     print "\nWARNING: $totalLeaks total leaks found for a total of $totalBytes!\n";
2284     print "WARNING: $uniqueLeakCount unique leaks found!\n";
2285     print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
2286     
2287 }
2288
2289 sub extensionForMimeType($)
2290 {
2291     my ($mimeType) = @_;
2292
2293     if ($mimeType eq "application/x-webarchive") {
2294         return "webarchive";
2295     } elsif ($mimeType eq "application/pdf") {
2296         return "pdf";
2297     } elsif ($mimeType eq "audio/wav") {
2298         return "wav";
2299     }
2300     return "txt";
2301 }
2302
2303 # Read up to the first #EOF (the content block of the test), or until detecting crashes or timeouts.
2304 sub readFromDumpToolWithTimer(**)
2305 {
2306     my ($fhIn, $fhError) = @_;
2307
2308     setFileHandleNonBlocking($fhIn, 1);
2309     setFileHandleNonBlocking($fhError, 1);
2310
2311     my $maximumSecondsWithoutOutput = $timeoutSeconds;
2312     my $microsecondsToWaitBeforeReadingAgain = 1000;
2313
2314     my $timeOfLastSuccessfulRead = time;
2315
2316     my @output = ();
2317     my @error = ();
2318     my $status = "success";
2319     my $mimeType = "text/plain";
2320     my $encoding = "";
2321     # We don't have a very good way to know when the "headers" stop
2322     # and the content starts, so we use this as a hack:
2323     my $haveSeenContentType = 0;
2324     my $haveSeenContentTransferEncoding = 0;
2325     my $haveSeenEofIn = 0;
2326     my $haveSeenEofError = 0;
2327
2328     while (1) {
2329         if (time - $timeOfLastSuccessfulRead > $maximumSecondsWithoutOutput) {
2330             $status = dumpToolDidCrash() ? "crashed" : "timedOut";
2331             last;
2332         }
2333
2334         # Once we've seen the EOF, we must not read anymore.
2335         my $lineIn = readline($fhIn) unless $haveSeenEofIn;
2336         my $lineError = readline($fhError) unless $haveSeenEofError;
2337         if (!defined($lineIn) && !defined($lineError)) {
2338             last if ($haveSeenEofIn && $haveSeenEofError);
2339
2340             if ($! != EAGAIN) {
2341                 $status = "crashed";
2342                 last;
2343             }
2344
2345             # No data ready
2346             usleep($microsecondsToWaitBeforeReadingAgain);
2347             next;
2348         }
2349
2350         $timeOfLastSuccessfulRead = time;
2351
2352         if (defined($lineIn)) {
2353             if (!$haveSeenContentType && $lineIn =~ /^Content-Type: (\S+)$/) {
2354                 $mimeType = $1;
2355                 $haveSeenContentType = 1;
2356             } elsif (!$haveSeenContentTransferEncoding && $lineIn =~ /^Content-Transfer-Encoding: (\S+)$/) {
2357                 $encoding = $1;
2358                 $haveSeenContentTransferEncoding = 1;
2359             } elsif ($lineIn =~ /(.*)#EOF$/) {
2360                 if ($1 ne "") {
2361                     push @output, $1;
2362                 }
2363                 $haveSeenEofIn = 1;
2364             } else {
2365                 push @output, $lineIn;
2366             }
2367         }
2368         if (defined($lineError)) {
2369             if ($lineError =~ /#CRASHED - WebProcess/) {
2370                 $status = "webProcessCrashed";
2371                 last;
2372             }
2373             if ($lineError =~ /#CRASHED/) {
2374                 $status = "crashed";
2375                 last;
2376             }
2377             if ($lineError =~ /#EOF/) {
2378                 $haveSeenEofError = 1;
2379             } else {
2380                 push @error, $lineError;
2381             }
2382         }
2383     }
2384
2385     setFileHandleNonBlocking($fhIn, 0);
2386     setFileHandleNonBlocking($fhError, 0);
2387     my $joined_output = join("", @output);
2388     if ($encoding eq "base64") {
2389         $joined_output = decode_base64($joined_output);
2390     }
2391     return {
2392         output => $joined_output,
2393         error => join("", @error),
2394         status => $status,
2395         mimeType => $mimeType,
2396         extension => extensionForMimeType($mimeType)
2397     };
2398 }
2399
2400 sub setFileHandleNonBlocking(*$)
2401 {
2402     my ($fh, $nonBlocking) = @_;
2403
2404     my $flags = fcntl($fh, F_GETFL, 0) or die "Couldn't get filehandle flags";
2405
2406     if ($nonBlocking) {
2407         $flags |= O_NONBLOCK;
2408     } else {
2409         $flags &= ~O_NONBLOCK;
2410     }
2411
2412     fcntl($fh, F_SETFL, $flags) or die "Couldn't set filehandle flags";
2413
2414     return 1;
2415 }
2416
2417 sub sampleDumpTool()
2418 {
2419     return unless isAppleMacWebKit();
2420     return unless $runSample;
2421
2422     my $outputDirectory = "$ENV{HOME}/Library/Logs/DumpRenderTree";
2423     -d $outputDirectory or mkdir $outputDirectory;
2424
2425     my $outputFile = "$outputDirectory/HangReport.txt";
2426     system "/usr/bin/sample", $dumpToolPID, qw(10 10 -file), $outputFile;
2427 }
2428
2429 sub stripMetrics($$)
2430 {
2431     my ($actual, $expected) = @_;
2432
2433     foreach my $result ($actual, $expected) {
2434         $result =~ s/at \(-?[0-9]+,-?[0-9]+\) *//g;
2435         $result =~ s/size -?[0-9]+x-?[0-9]+ *//g;
2436         $result =~ s/text run width -?[0-9]+: //g;
2437         $result =~ s/text run width -?[0-9]+ [a-zA-Z ]+: //g;
2438         $result =~ s/RenderButton {BUTTON} .*/RenderButton {BUTTON}/g;
2439         $result =~ s/RenderImage {INPUT} .*/RenderImage {INPUT}/g;
2440         $result =~ s/RenderBlock {INPUT} .*/RenderBlock {INPUT}/g;
2441         $result =~ s/RenderTextControl {INPUT} .*/RenderTextControl {INPUT}/g;
2442         $result =~ s/\([0-9]+px/px/g;
2443         $result =~ s/ *" *\n +" */ /g;
2444         $result =~ s/" +$/"/g;
2445
2446         $result =~ s/- /-/g;
2447         $result =~ s/\n( *)"\s+/\n$1"/g;
2448         $result =~ s/\s+"\n/"\n/g;
2449         $result =~ s/scrollWidth [0-9]+/scrollWidth/g;
2450         $result =~ s/scrollHeight [0-9]+/scrollHeight/g;
2451     }
2452
2453     return ($actual, $expected);
2454 }
2455
2456 sub fileShouldBeIgnored
2457 {
2458     my ($filePath) = @_;
2459     foreach my $ignoredDir (keys %ignoredDirectories) {
2460         if ($filePath =~ m/^$ignoredDir/) {
2461             return 1;
2462         }
2463     }
2464     return 0;
2465 }
2466
2467 sub readSkippedFiles($)
2468 {
2469     my ($constraintPath) = @_;
2470
2471     my @skippedFileDirectories = @platformTestHierarchy;
2472
2473     # Because nearly all of the skipped tests for WebKit 2 on Mac are due to
2474     # cross-platform issues, the Windows and Qt ports use the Mac skipped list
2475     # additionally to their own to avoid maintaining separate lists.
2476     push(@skippedFileDirectories, catdir($platformBaseDirectory, "wk2")) if ($platform eq "win-wk2" || $platform eq "qt-wk2" || $platform eq "mac-wk2");
2477
2478     foreach my $level (@skippedFileDirectories) {
2479         if (open SKIPPED, "<", "$level/Skipped") {
2480             if ($verbose) {
2481                 my ($dir, $name) = splitpath($level);
2482                 print "Skipped tests in $name:\n";
2483             }
2484
2485             while (<SKIPPED>) {
2486                 my $skipped = $_;
2487                 chomp $skipped;
2488                 $skipped =~ s/^[ \n\r]+//;
2489                 $skipped =~ s/[ \n\r]+$//;
2490                 if ($skipped && $skipped !~ /^#/) {
2491                     if ($skippedOnly) {
2492                         if (!fileShouldBeIgnored($skipped)) {
2493                             if (!$constraintPath) {
2494                                 # Always add $skipped since no constraint path was specified on the command line.
2495                                 push(@ARGV, $skipped);
2496                             } elsif ($skipped =~ /^($constraintPath)/ || ("LayoutTests/".$skipped) =~ /^($constraintPath)/ ) {
2497                                 # Add $skipped only if it matches the current path constraint, e.g.,
2498                                 # "--skipped=only dir1" with "dir1/file1.html" on the skipped list or
2499                                 # "--skipped=only LayoutTests/dir1" with "dir1/file1.html" on the skipped list
2500                                 push(@ARGV, $skipped);
2501                             } elsif ($constraintPath =~ /^("LayoutTests\/".$skipped)/ || $constraintPath =~ /^($skipped)/) {
2502                                 # Add current path constraint if it is more specific than the skip list entry,
2503                                 # e.g., "--skipped=only dir1/dir2/dir3" with "dir1" on the skipped list or
2504                                 # e.g., "--skipped=only LayoutTests/dir1/dir2/dir3" with "dir1" on the skipped list.
2505                                 push(@ARGV, $constraintPath);
2506                             }
2507                         } elsif ($verbose) {
2508                             print "    $skipped\n";
2509                         }
2510                     } else {
2511                         if ($verbose) {
2512                             print "    $skipped\n";
2513                         }
2514                         processIgnoreTests($skipped, "Skipped");
2515                     }
2516                 }
2517             }
2518             close SKIPPED;
2519         }
2520     }
2521 }
2522
2523 sub readChecksumFromPng($)
2524 {
2525     my ($path) = @_;
2526     my $data;
2527     if (open(PNGFILE, $path) && read(PNGFILE, $data, 2048) && $data =~ /tEXtchecksum\0([a-fA-F0-9]{32})/) {
2528         return $1;
2529     }
2530 }
2531
2532 my @testsFound;
2533
2534 sub isUsedInReftest
2535 {
2536     my $filename = $_;
2537     if ($filename =~ /-$expectedTag(-$mismatchTag)?\.html$/) {
2538         return 1;
2539     }
2540     my $base = stripExtension($filename);
2541     return (-f "$base-$expectedTag.html" || -f "$base-$expectedTag-$mismatchTag.html");
2542 }
2543
2544 sub directoryFilter
2545 {
2546     return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
2547     return () if exists $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)};
2548     return @_;
2549 }
2550
2551 sub fileFilter
2552 {
2553     my $filename = $_;
2554     if ($filename =~ /\.([^.]+)$/) {
2555         my $extension = $1;
2556         if (exists $supportedFileExtensions{$extension} && !isUsedInReftest($filename)) {
2557             my $path = File::Spec->abs2rel(catfile($File::Find::dir, $filename), $testDirectory);
2558             push @testsFound, $path if !exists $ignoredFiles{$path};
2559         }
2560     }
2561 }
2562
2563 sub findTestsToRun
2564 {
2565     my @testsToRun = ();
2566
2567     for my $test (@ARGV) {
2568         $test =~ s/^(\Q$layoutTestsName\E|\Q$testDirectory\E)\///;
2569         my $fullPath = catfile($testDirectory, $test);
2570         if (file_name_is_absolute($test)) {
2571             print "can't run test $test outside $testDirectory\n";
2572         } elsif (-f $fullPath) {
2573             my ($filename, $pathname, $fileExtension) = fileparse($test, qr{\.[^.]+$});
2574             if (!exists $supportedFileExtensions{substr($fileExtension, 1)}) {
2575                 print "test $test does not have a supported extension\n";
2576             } elsif ($testHTTP || $pathname !~ /^http\//) {
2577                 push @testsToRun, $test;
2578             }
2579         } elsif (-d $fullPath) {
2580             @testsFound = ();
2581             find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $fullPath);
2582             for my $level (@platformTestHierarchy) {
2583                 my $platformPath = catfile($level, $test);
2584                 find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $platformPath) if (-d $platformPath);
2585             }
2586             push @testsToRun, sort pathcmp @testsFound;
2587             @testsFound = ();
2588         } else {
2589             print "test $test not found\n";
2590         }
2591     }
2592
2593     if (!scalar @ARGV) {
2594         @testsFound = ();
2595         find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $testDirectory);
2596         for my $level (@platformTestHierarchy) {
2597             find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $level);
2598         }
2599         push @testsToRun, sort pathcmp @testsFound;
2600         @testsFound = ();
2601
2602         # We need to minimize the time when Apache and WebSocketServer is locked by tests
2603         # so run them last if no explicit order was specified in the argument list.
2604         my @httpTests;
2605         my @websocketTests;
2606         my @otherTests;
2607         foreach my $test (@testsToRun) {
2608             if ($test =~ /^http\//) {
2609                 push(@httpTests, $test);
2610             } elsif ($test =~ /^websocket\//) {
2611                 push(@websocketTests, $test);
2612             } else {
2613                 push(@otherTests, $test);
2614             }
2615         }
2616         @testsToRun = (@otherTests, @httpTests, @websocketTests);
2617     }
2618
2619     # Reverse the tests
2620     @testsToRun = reverse @testsToRun if $reverseTests;
2621
2622     # Shuffle the array
2623     @testsToRun = shuffle(@testsToRun) if $randomizeTests;
2624
2625     return @testsToRun;
2626 }
2627
2628 sub printResults
2629 {
2630     my %text = (
2631         match => "succeeded",
2632         mismatch => "had incorrect layout",
2633         new => "were new",
2634         timedout => "timed out",
2635         crash => "crashed",
2636         webProcessCrash => "Web process crashed",
2637         error => "had stderr output"
2638     );
2639
2640     for my $type ("match", "mismatch", "new", "timedout", "crash", "webProcessCrash", "error") {
2641         my $typeCount = $counts{$type};
2642         next unless $typeCount;
2643         my $typeText = $text{$type};
2644         my $message;
2645         if ($typeCount == 1) {
2646             $typeText =~ s/were/was/;
2647             $message = sprintf "1 test case (%d%%) %s\n", 1 * 100 / $count, $typeText;
2648         } else {
2649             $message = sprintf "%d test cases (%d%%) %s\n", $typeCount, $typeCount * 100 / $count, $typeText;
2650         }
2651         $message =~ s-\(0%\)-(<1%)-;
2652         print $message;
2653     }
2654 }
2655
2656 sub stopRunningTestsEarlyIfNeeded()
2657 {
2658     # --reset-results does not check pass vs. fail, so exitAfterNFailures makes no sense with --reset-results.
2659     return 0 if $resetResults;
2660
2661     my $passCount = $counts{match} || 0; # $counts{match} will be undefined if we've not yet passed a test (e.g. the first test fails).
2662     my $newCount = $counts{new} || 0;
2663     my $failureCount = $count - $passCount - $newCount; # "Failure" here includes timeouts, crashes, etc.
2664     if ($exitAfterNFailures && $failureCount >= $exitAfterNFailures) {
2665         $stoppedRunningEarlyMessage = "Exiting early after $failureCount failures. $count tests run.";
2666         print "\n", $stoppedRunningEarlyMessage;
2667         closeDumpTool();
2668         return 1;
2669     }
2670
2671     my $crashCount = $counts{crash} || 0;
2672     my $webProcessCrashCount = $counts{webProcessCrash} || 0;
2673     my $timeoutCount = $counts{timedout} || 0;
2674     if ($exitAfterNCrashesOrTimeouts && $crashCount + $webProcessCrashCount + $timeoutCount >= $exitAfterNCrashesOrTimeouts) {
2675         $stoppedRunningEarlyMessage = "Exiting early after $crashCount crashes, $webProcessCrashCount web process crashes, and $timeoutCount timeouts. $count tests run.";
2676         print "\n", $stoppedRunningEarlyMessage;
2677         closeDumpTool();
2678         return 1;
2679     }
2680
2681     return 0;
2682 }
2683
2684 # Store this at global scope so it won't be GCed (and thus unlinked) until the program exits.
2685 my $debuggerTempDirectory;
2686
2687 sub createDebuggerCommandFile()
2688 {
2689     return unless isCygwin();
2690
2691     my @commands = (
2692         '.logopen /t "' . toWindowsPath($testResultsDirectory) . "\\" . $windowsCrashLogFilePrefix . '.txt"',
2693         '.srcpath "' . toWindowsPath(sourceDir()) . '"',
2694         '!analyze -vv',
2695         '~*kpn',
2696         'q',
2697     );
2698
2699     $debuggerTempDirectory = File::Temp->newdir;
2700
2701     my $commandFile = File::Spec->catfile($debuggerTempDirectory, "debugger-commands.txt");
2702     unless (open COMMANDS, '>', $commandFile) {
2703         print "Failed to open $commandFile. Crash logs will not be saved.\n";
2704         return;
2705     }
2706     print COMMANDS join("\n", @commands), "\n";
2707     unless (close COMMANDS) {
2708         print "Failed to write to $commandFile. Crash logs will not be saved.\n";
2709         return;
2710     }
2711
2712     return $commandFile;
2713 }
2714
2715 sub readRegistryString($)
2716 {
2717     my ($valueName) = @_;
2718     chomp(my $string = `regtool --wow32 get "$valueName"`);
2719     return $string;
2720 }
2721
2722 sub writeRegistryString($$)
2723 {
2724     my ($valueName, $string) = @_;
2725
2726     my $error = system "regtool", "--wow32", "set", "-s", $valueName, $string;
2727
2728     # On Windows Vista/7 with UAC enabled, regtool will fail to modify the registry, but will still
2729     # return a successful exit code. So we double-check here that the value we tried to write to the
2730     # registry was really written.
2731     return !$error && readRegistryString($valueName) eq $string;
2732 }
2733
2734 sub setUpWindowsCrashLogSaving()
2735 {
2736     return unless isCygwin();
2737
2738     unless (defined $ENV{_NT_SYMBOL_PATH}) {
2739         print "The _NT_SYMBOL_PATH environment variable is not set. Crash logs will not be saved.\nSee <http://trac.webkit.org/wiki/BuildingOnWindows#GettingCrashLogs>.\n";
2740         return;
2741     }
2742
2743     my $ntsdPath = File::Spec->catfile(toCygwinPath($ENV{PROGRAMFILES}), "Debugging Tools for Windows (x86)", "ntsd.exe");
2744     unless (-f $ntsdPath) {
2745         $ntsdPath = File::Spec->catfile(toCygwinPath($ENV{ProgramW6432}), "Debugging Tools for Windows (x64)", "ntsd.exe");
2746         unless (-f $ntsdPath) {
2747             $ntsdPath = File::Spec->catfile(toCygwinPath($ENV{SYSTEMROOT}), "system32", "ntsd.exe");
2748             unless (-f $ntsdPath) {
2749                 print STDERR "Can't find ntsd.exe. Crash logs will not be saved.\nSee <http://trac.webkit.org/wiki/BuildingOnWindows#GettingCrashLogs>.\n";
2750                 return;
2751             }
2752         }
2753     }
2754
2755     # If we used -c (instead of -cf) we could pass the commands directly on the command line. But
2756     # when the commands include multiple quoted paths (e.g., for .logopen and .srcpath), Windows
2757     # fails to invoke the post-mortem debugger at all (perhaps due to a bug in Windows's command
2758     # line parsing). So we save the commands to a file instead and tell the debugger to execute them
2759     # using -cf.
2760     my $commandFile = createDebuggerCommandFile() or return;
2761
2762     my @options = (
2763         '-p %ld',
2764         '-e %ld',
2765         '-g',
2766         '-lines',
2767         '-cf "' . toWindowsPath($commandFile) . '"',
2768     );
2769
2770     my %values = (
2771         Debugger => '"' . toWindowsPath($ntsdPath) . '" ' . join(' ', @options),
2772         Auto => 1
2773     );
2774
2775     foreach my $value (keys %values) {
2776         $previousWindowsPostMortemDebuggerValues{$value} = readRegistryString("$windowsPostMortemDebuggerKey/$value");
2777         next if writeRegistryString("$windowsPostMortemDebuggerKey/$value", $values{$value});
2778
2779         print "Failed to set \"$windowsPostMortemDebuggerKey/$value\". Crash logs will not be saved.\nSee <http://trac.webkit.org/wiki/BuildingOnWindows#GettingCrashLogs>.\n";
2780         return;
2781     }
2782
2783     print "Crash logs will be saved to $testResultsDirectory.\n";
2784 }
2785
2786 END {
2787     return unless isCygwin();
2788
2789     foreach my $value (keys %previousWindowsPostMortemDebuggerValues) {
2790         next if writeRegistryString("$windowsPostMortemDebuggerKey/$value", $previousWindowsPostMortemDebuggerValues{$value});
2791         print "Failed to restore \"$windowsPostMortemDebuggerKey/$value\" to its previous value \"$previousWindowsPostMortemDebuggerValues{$value}\"\n.";
2792     }
2793 }