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