OSDN Git Service

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