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