summaryrefslogtreecommitdiffstats
path: root/Tools/Scripts/old-run-webkit-tests
blob: c56cb1c21b2a90199271a94998677e2f190779da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
#!/usr/bin/perl

# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
# Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
# Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com)
# Copyright (C) 2007 Eric Seidel <eric@webkit.org>
# Copyright (C) 2009 Google Inc. All rights reserved.
# Copyright (C) 2009 Andras Becsi (becsi.andras@stud.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1.  Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer. 
# 2.  Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution. 
# 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
#     its contributors may be used to endorse or promote products derived
#     from this software without specific prior written permission. 
#
# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Script to run the WebKit Open Source Project layout tests.

# Run all the tests passed in on the command line.
# If no tests are passed, find all the .html, .shtml, .xml, .xhtml, .xhtmlmp, .pl, .php (and svg) files in the test directory.

# Run each text.
# Compare against the existing file xxx-expected.txt.
# If there is a mismatch, generate xxx-actual.txt and xxx-diffs.txt.

# At the end, report:
#   the number of tests that got the expected results
#   the number of tests that ran, but did not get the expected results
#   the number of tests that failed to run
#   the number of tests that were run but had no expected results to compare against

use strict;
use warnings;

use Config;
use Cwd;
use Data::Dumper;
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
use File::Basename;
use File::Copy;
use File::Find;
use File::Path;
use File::Spec;
use File::Spec::Functions;
use File::Temp;
use FindBin;
use Getopt::Long;
use IPC::Open2;
use IPC::Open3;
use Time::HiRes qw(time usleep);

use List::Util 'shuffle';

use lib $FindBin::Bin;
use webkitperl::features;
use webkitperl::httpd;
use webkitdirs;
use VCSUtils;
use POSIX;

sub buildPlatformResultHierarchy();
sub buildPlatformTestHierarchy(@);
sub captureSavedCrashLog($);
sub checkPythonVersion();
sub closeCygpaths();
sub closeDumpTool();
sub closeWebSocketServer();
sub configureAndOpenHTTPDIfNeeded();
sub countAndPrintLeaks($$$);
sub countFinishedTest($$$$);
sub deleteExpectedAndActualResults($);
sub dumpToolDidCrash();
sub epiloguesAndPrologues($$);
sub expectedDirectoryForTest($;$;$);
sub fileNameWithNumber($$);
sub findNewestFileMatchingGlob($);
sub htmlForResultsSection(\@$&);
sub isTextOnlyTest($);
sub launchWithEnv(\@\%);
sub resolveAndMakeTestResultsDirectory();
sub numericcmp($$);
sub openDiffTool();
sub buildDumpTool($);
sub openDumpTool();
sub parseLeaksandPrintUniqueLeaks();
sub openWebSocketServerIfNeeded();
sub pathcmp($$);
sub printFailureMessageForTest($$);
sub processIgnoreTests($$);
sub readFromDumpToolWithTimer(**);
sub readSkippedFiles($);
sub recordActualResultsAndDiff($$);
sub sampleDumpTool();
sub setFileHandleNonBlocking(*$);
sub setUpWindowsCrashLogSaving();
sub slowestcmp($$);
sub splitpath($);
sub stopRunningTestsEarlyIfNeeded();
sub stripExtension($);
sub stripMetrics($$);
sub testCrashedOrTimedOut($$$$$$);
sub toCygwinPath($);
sub toURL($);
sub toWindowsPath($);
sub validateSkippedArg($$;$);
sub writeToFile($$);

# Argument handling
my $addPlatformExceptions = 0;
my $complexText = 0;
my $exitAfterNFailures = 0;
my $exitAfterNCrashesOrTimeouts = 0;
my $generateNewResults = isAppleMacWebKit() ? 1 : 0;
my $guardMalloc = '';
# FIXME: Dynamic HTTP-port configuration in this file is wrong.  The various
# apache config files in LayoutTests/http/config govern the port numbers.
# Dynamic configuration as-written will also cause random failures in
# an IPv6 environment.  See https://bugs.webkit.org/show_bug.cgi?id=37104.
my $httpdPort = 8000;
my $httpdSSLPort = 8443;
my $ignoreMetrics = 0;
my $webSocketPort = 8880;
# wss is disabled until all platforms support pyOpenSSL.
# my $webSocketSecurePort = 9323;
my $ignoreTests = '';
my $iterations = 1;
my $launchSafari = 1;
my $mergeDepth;
my $pixelTests = '';
my $platform;
my $quiet = '';
my $randomizeTests = 0;
my $repeatEach = 1;
my $report10Slowest = 0;
my $resetResults = 0;
my $reverseTests = 0;
my $root;
my $runSample = 1;
my $shouldCheckLeaks = 0;
my $showHelp = 0;
my $stripEditingCallbacks;
my $testHTTP = 1;
my $testWebSocket = 1;
my $testMedia = 1;
my $tmpDir = "/tmp";
my $testResultsDirectory = File::Spec->catdir($tmpDir, "layout-test-results");
my $testsPerDumpTool = 1000;
my $threaded = 0;
# DumpRenderTree has an internal timeout of 30 seconds, so this must be > 30.
my $timeoutSeconds = 35;
my $tolerance = 0;
my $treatSkipped = "default";
my $useRemoteLinksToTests = 0;
my $useValgrind = 0;
my $verbose = 0;
my $shouldWaitForHTTPD = 0;
my $useWebKitTestRunner = 0;
my $noBuildDumpTool = 0;

my @leaksFilenames;

if (isWindows() || isMsys()) {
    print "This script has to be run under Cygwin to function correctly.\n";
    exit 1;
}

# Default to --no-http for wx for now.
$testHTTP = 0 if (isWx());

my $perlInterpreter = "perl";

my $expectedTag = "expected";
my $actualTag = "actual";
my $prettyDiffTag = "pretty-diff";
my $diffsTag = "diffs";
my $errorTag = "stderr";
my $crashLogTag = "crash-log";

my $windowsCrashLogFilePrefix = "CrashLog";

# These are defined here instead of closer to where they are used so that they
# will always be accessible from the END block that uses them, even if the user
# presses Ctrl-C before Perl has finished evaluating this whole file.
my $windowsPostMortemDebuggerKey = "/HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/AeDebug";
my %previousWindowsPostMortemDebuggerValues;

my $realPlatform;

my @macPlatforms = ("mac-tiger", "mac-leopard", "mac-snowleopard", "mac");
my @winPlatforms = ("win-xp", "win-vista", "win-7", "win");

if (isAppleMacWebKit()) {
    if (isTiger()) {
        $platform = "mac-tiger";
        $tolerance = 1.0;
    } elsif (isLeopard()) {
        $platform = "mac-leopard";
        $tolerance = 0.1;
    } elsif (isSnowLeopard()) {
        $platform = "mac-snowleopard";
        $tolerance = 0.1;
    } else {
        $platform = "mac";
    }
} elsif (isQt()) {
    if (isDarwin()) {
        $platform = "qt-mac";
    } elsif (isLinux()) {
        $platform = "qt-linux";
    } elsif (isWindows() || isCygwin()) {
        $platform = "qt-win";
    } else {
        $platform = "qt";
    }
} elsif (isGtk()) {
    $platform = "gtk";
} elsif (isWx()) {
    $platform = "wx";
} elsif (isCygwin() || isWindows()) {
    if (isWindowsXP()) {
        $platform = "win-xp";
    } elsif (isWindowsVista()) {
        $platform = "win-vista";
    } elsif (isWindows7()) {
        $platform = "win-7";
    } else {
        $platform = "win";
    }
}

if (isQt() || isAppleWinWebKit()) {
    my $testfontPath = $ENV{"WEBKIT_TESTFONTS"};
    if (!$testfontPath || !-d "$testfontPath") {
        print "The WEBKIT_TESTFONTS environment variable is not defined or not set properly\n";
        print "You must set it before running the tests.\n";
        print "Use git to grab the actual fonts from http://gitorious.org/qtwebkit/testfonts\n";
        exit 1;
    }
}

if (!defined($platform)) {
    print "WARNING: Your platform is not recognized. Any platform-specific results will be generated in platform/undefined.\n";
    $platform = "undefined";
}

if (!checkPythonVersion()) {
    print "WARNING: Your platform does not have Python 2.5+, which is required to run websocket server, so disabling websocket/tests.\n";
    $testWebSocket = 0;
}

my $programName = basename($0);
my $launchSafariDefault = $launchSafari ? "launch" : "do not launch";
my $httpDefault = $testHTTP ? "run" : "do not run";
my $sampleDefault = $runSample ? "run" : "do not run";

my $usage = <<EOF;
Usage: $programName [options] [testdir|testpath ...]
  --add-platform-exceptions       Put new results for non-platform-specific failing tests into the platform-specific results directory
  --complex-text                  Use the complex text code path for all text (Mac OS X and Windows only)
  -c|--configuration config       Set DumpRenderTree build configuration
  -g|--guard-malloc               Enable malloc guard
  --exit-after-n-failures N       Exit after the first N failures (includes crashes) instead of running all tests
  --exit-after-n-crashes-or-timeouts N
                                  Exit after the first N crashes instead of running all tests
  -h|--help                       Show this help message
  --[no-]http                     Run (or do not run) http tests (default: $httpDefault)
  --[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) 
  -i|--ignore-tests               Comma-separated list of directories or tests to ignore
  --iterations n                  Number of times to run the set of tests (e.g. ABCABCABC)
  --[no-]launch-safari            Launch (or do not launch) Safari to display test results (default: $launchSafariDefault)
  -l|--leaks                      Enable leaks checking
  --[no-]new-test-results         Generate results for new tests
  --nthly n                       Restart DumpRenderTree every n tests (default: $testsPerDumpTool)
  -p|--pixel-tests                Enable pixel tests
  --tolerance t                   Ignore image differences less than this percentage (default: $tolerance)
  --platform                      Override the detected platform to use for tests and results (default: $platform)
  --port                          Web server port to use with http tests
  -q|--quiet                      Less verbose output
  --reset-results                 Reset ALL results (including pixel tests if --pixel-tests is set)
  -o|--results-directory          Output results directory (default: $testResultsDirectory)
  --random                        Run the tests in a random order
  --repeat-each n                 Number of times to run each test (e.g. AAABBBCCC)
  --reverse                       Run the tests in reverse alphabetical order
  --root                          Path to root tools build
  --[no-]sample-on-timeout        Run sample on timeout (default: $sampleDefault) (Mac OS X only)
  -1|--singly                     Isolate each test case run (implies --nthly 1 --verbose)
  --skipped=[default|ignore|only] Specifies how to treat the Skipped file
                                     default: Tests/directories listed in the Skipped file are not tested
                                     ignore:  The Skipped file is ignored
                                     only:    Only those tests/directories listed in the Skipped file will be run
  --slowest                       Report the 10 slowest tests
  --ignore-metrics                Ignore metrics in tests
  --[no-]strip-editing-callbacks  Remove editing callbacks from expected results
  -t|--threaded                   Run a concurrent JavaScript thead with each test
  --timeout t                     Sets the number of seconds before a test times out (default: $timeoutSeconds)
  --valgrind                      Run DumpRenderTree inside valgrind (Qt/Linux only)
  -v|--verbose                    More verbose output (overrides --quiet)
  -m|--merge-leak-depth arg       Merges leak callStacks and prints the number of unique leaks beneath a callstack depth of arg.  Defaults to 5.
  --use-remote-links-to-tests     Link to test files within the SVN repository in the results.
  -2|--webkit-test-runner         Use WebKitTestRunner rather than DumpRenderTree.
EOF

setConfiguration();

my $getOptionsResult = GetOptions(
    'add-platform-exceptions' => \$addPlatformExceptions,
    'complex-text' => \$complexText,
    'exit-after-n-failures=i' => \$exitAfterNFailures,
    'exit-after-n-crashes-or-timeouts=i' => \$exitAfterNCrashesOrTimeouts,
    'guard-malloc|g' => \$guardMalloc,
    'help|h' => \$showHelp,
    'http!' => \$testHTTP,
    'wait-for-httpd!' => \$shouldWaitForHTTPD,
    'ignore-metrics!' => \$ignoreMetrics,
    'ignore-tests|i=s' => \$ignoreTests,
    'iterations=i' => \$iterations,
    'launch-safari!' => \$launchSafari,
    'leaks|l' => \$shouldCheckLeaks,
    'merge-leak-depth|m:5' => \$mergeDepth,
    'new-test-results!' => \$generateNewResults,
    'no-build' => \$noBuildDumpTool,
    'nthly=i' => \$testsPerDumpTool,
    'pixel-tests|p' => \$pixelTests,
    'platform=s' => \$platform,
    'port=i' => \$httpdPort,
    'quiet|q' => \$quiet,
    'random' => \$randomizeTests,
    'repeat-each=i' => \$repeatEach,
    'reset-results' => \$resetResults,
    'results-directory|o=s' => \$testResultsDirectory,
    'reverse' => \$reverseTests,
    'root=s' => \$root,
    'sample-on-timeout!' => \$runSample,
    'singly|1' => sub { $testsPerDumpTool = 1; },
    'skipped=s' => \&validateSkippedArg,
    'slowest' => \$report10Slowest,
    'strip-editing-callbacks!' => \$stripEditingCallbacks,
    'threaded|t' => \$threaded,
    'timeout=i' => \$timeoutSeconds,
    'tolerance=f' => \$tolerance,
    'use-remote-links-to-tests' => \$useRemoteLinksToTests,
    'valgrind' => \$useValgrind,
    'verbose|v' => \$verbose,
    'webkit-test-runner|2' => \$useWebKitTestRunner,
);

if (!$getOptionsResult || $showHelp) {
    print STDERR $usage;
    exit 1;
}

if ($useWebKitTestRunner) {
    if (isAppleMacWebKit()) {
        $realPlatform = $platform;
        $platform = "mac-wk2";
    } elsif (isAppleWinWebKit()) {
        $stripEditingCallbacks = 0 unless defined $stripEditingCallbacks;
        $realPlatform = $platform;
        $platform = "win-wk2";
    } elsif (isQt()) {
        $realPlatform = $platform;
        $platform = "qt-wk2";
    }
}

$timeoutSeconds *= 10 if $guardMalloc;

$stripEditingCallbacks = isCygwin() unless defined $stripEditingCallbacks;

my $ignoreSkipped = $treatSkipped eq "ignore";
my $skippedOnly = $treatSkipped eq "only";

my $configuration = configuration();

# We need an environment variable to be able to enable the feature per-slave
$shouldWaitForHTTPD = $ENV{"WEBKIT_WAIT_FOR_HTTPD"} unless ($shouldWaitForHTTPD);
$verbose = 1 if $testsPerDumpTool == 1;

if ($shouldCheckLeaks && $testsPerDumpTool > 1000) {
    print STDERR "\nWARNING: Running more than 1000 tests at a time with MallocStackLogging enabled may cause a crash.\n\n";
}

# Stack logging does not play well with QuickTime on Tiger (rdar://problem/5537157)
$testMedia = 0 if $shouldCheckLeaks && isTiger();

# Generating remote links causes a lot of unnecessary spew on GTK build bot
$useRemoteLinksToTests = 0 if isGtk();

setUpWindowsCrashLogSaving() if isCygwin();

setConfigurationProductDir(Cwd::abs_path($root)) if (defined($root));
my $productDir = productDir();
$productDir .= "/bin" if isQt();
$productDir .= "/Programs" if isGtk();

chdirWebKit();

if (!defined($root) && !$noBuildDumpTool) {
    # FIXME: We build both DumpRenderTree and WebKitTestRunner for
    # WebKitTestRunner runs becuase DumpRenderTree still includes
    # the DumpRenderTreeSupport module and the TestNetscapePlugin.
    # These two projects should be factored out into their own
    # projects.
    buildDumpTool("DumpRenderTree");
    buildDumpTool("WebKitTestRunner") if $useWebKitTestRunner;
}

my $dumpToolName = $useWebKitTestRunner ? "WebKitTestRunner" : "DumpRenderTree";

if (isAppleWinWebKit()) {
    $dumpToolName .= "_debug" if configurationForVisualStudio() eq "Debug_All";
    $dumpToolName .= $Config{_exe};
}
my $dumpTool = File::Spec->catfile($productDir, $dumpToolName);
die "can't find executable $dumpToolName (looked in $productDir)\n" unless -x $dumpTool;

my $imageDiffTool = "$productDir/ImageDiff";
$imageDiffTool .= "_debug" if isCygwin() && configurationForVisualStudio() eq "Debug_All";
die "can't find executable $imageDiffTool (looked in $productDir)\n" if $pixelTests && !-x $imageDiffTool;

checkFrameworks() unless isCygwin();

if (isAppleMacWebKit()) {
    push @INC, $productDir;
    require DumpRenderTreeSupport;
}

my $layoutTestsName = "LayoutTests";
my $testDirectory = File::Spec->rel2abs($layoutTestsName);
my $expectedDirectory = $testDirectory;
my $platformBaseDirectory = catdir($testDirectory, "platform");
my $platformTestDirectory = catdir($platformBaseDirectory, $platform);
my @platformResultHierarchy = buildPlatformResultHierarchy();
my @platformTestHierarchy = buildPlatformTestHierarchy(@platformResultHierarchy);

$expectedDirectory = $ENV{"WebKitExpectedTestResultsDirectory"} if $ENV{"WebKitExpectedTestResultsDirectory"};

$testResultsDirectory = File::Spec->rel2abs($testResultsDirectory);
# $testResultsDirectory must be empty before testing.
rmtree $testResultsDirectory;
my $testResults = File::Spec->catfile($testResultsDirectory, "results.html");

if (isAppleMacWebKit()) {
    print STDERR "Compiling Java tests\n";
    my $javaTestsDirectory = catdir($testDirectory, "java");

    if (system("/usr/bin/make", "-C", "$javaTestsDirectory")) {
        exit 1;
    }
}


print "Running tests from $testDirectory\n";
if ($pixelTests) {
    print "Enabling pixel tests with a tolerance of $tolerance%\n";
    if (isDarwin()) {
        print "WARNING: Temporarily changing the main display color profile:\n";
        print "\tThe colors on your screen will change for the duration of the testing.\n";
        print "\tThis allows the pixel tests to have consistent color values across all machines.\n";
        
        if (isPerianInstalled()) {
            print "WARNING: Perian's QuickTime component is installed and this may affect pixel test results!\n";
            print "\tYou should avoid generating new pixel results in this environment.\n";
            print "\tSee https://bugs.webkit.org/show_bug.cgi?id=22615 for details.\n";
        }
    }
}

system "ln", "-s", $testDirectory, "/tmp/LayoutTests" unless -x "/tmp/LayoutTests";

my %ignoredFiles = ( "results.html" => 1 );
my %ignoredDirectories = map { $_ => 1 } qw(platform);
my %ignoredLocalDirectories = map { $_ => 1 } qw(.svn _svn resources script-tests);
my %supportedFileExtensions = map { $_ => 1 } qw(html shtml xml xhtml xhtmlmp pl php);

if (!checkWebCoreFeatureSupport("MathML", 0)) {
    $ignoredDirectories{'mathml'} = 1;
}

# FIXME: We should fix webkitperl/features.pm:hasFeature() to do the correct feature detection for Cygwin.
if (checkWebCoreFeatureSupport("SVG", 0)) {
    $supportedFileExtensions{'svg'} = 1;
} elsif (isCygwin()) {
    $supportedFileExtensions{'svg'} = 1;
} else {
    $ignoredLocalDirectories{'svg'} = 1;
}

if (!$testHTTP) {
    $ignoredDirectories{'http'} = 1;
    $ignoredDirectories{'websocket'} = 1;
}
if (!$testWebSocket) {
    $ignoredDirectories{'websocket'} = 1;
}

if (!$testMedia) {
    $ignoredDirectories{'media'} = 1;
    $ignoredDirectories{'http/tests/media'} = 1;
}

my $supportedFeaturesResult = "";

if (isCygwin()) {
    # Collect supported features list
    setPathForRunningWebKitApp(\%ENV);
    my $supportedFeaturesCommand = "\"$dumpTool\" --print-supported-features 2>&1";
    $supportedFeaturesResult = `$supportedFeaturesCommand 2>&1`;
}

my $hasAcceleratedCompositing = 0;
my $has3DRendering = 0;

if (isCygwin()) {
    $hasAcceleratedCompositing = $supportedFeaturesResult =~ /AcceleratedCompositing/;
    $has3DRendering = $supportedFeaturesResult =~ /3DRendering/;
} else {
    $hasAcceleratedCompositing = checkWebCoreFeatureSupport("Accelerated Compositing", 0);
    $has3DRendering = checkWebCoreFeatureSupport("3D Rendering", 0);
}

if (!$hasAcceleratedCompositing) {
    $ignoredDirectories{'compositing'} = 1;

    # This test has slightly different floating-point rounding when accelerated
    # compositing is enabled.
    $ignoredFiles{'svg/custom/use-on-symbol-inside-pattern.svg'} = 1;

    if (isAppleWebKit()) {
        # In Apple's ports, the default controls for <video> contain a "full
        # screen" button only if accelerated compositing is enabled.
        $ignoredFiles{'media/controls-after-reload.html'} = 1;
        $ignoredFiles{'media/controls-drag-timebar.html'} = 1;
        $ignoredFiles{'media/controls-strict.html'} = 1;
        $ignoredFiles{'media/controls-styling.html'} = 1;
        $ignoredFiles{'media/video-controls-rendering.html'} = 1;
        $ignoredFiles{'media/video-display-toggle.html'} = 1;
        $ignoredFiles{'media/video-no-audio.html'} = 1;
    }

    # Here we're using !$hasAcceleratedCompositing as a proxy for "is a headless XP machine" (like
    # our test slaves). Headless XP machines can neither support accelerated compositing nor pass
    # this test, so skipping the test here is expedient, if a little sloppy. See
    # <http://webkit.org/b/48333>.
    $ignoredFiles{'platform/win/plugins/npn-invalidate-rect-invalidates-window.html'} = 1 if isAppleWinWebKit();
}

if (!$has3DRendering) {
    $ignoredDirectories{'animations/3d'} = 1;
    $ignoredDirectories{'transforms/3d'} = 1;

    # These tests use the -webkit-transform-3d media query.
    $ignoredFiles{'fast/media/mq-transform-02.html'} = 1;
    $ignoredFiles{'fast/media/mq-transform-03.html'} = 1;
}

if (!checkWebCoreFeatureSupport("3D Canvas", 0)) {
    $ignoredDirectories{'fast/canvas/webgl'} = 1;
    $ignoredDirectories{'compositing/webgl'} = 1;
    $ignoredDirectories{'http/tests/canvas/webgl'} = 1;
}

if (checkWebCoreFeatureSupport("WML", 0)) {
    $supportedFileExtensions{'wml'} = 1;
} else {
    $ignoredDirectories{'http/tests/wml'} = 1;
    $ignoredDirectories{'fast/wml'} = 1;
    $ignoredDirectories{'wml'} = 1;
}

if (!checkWebCoreFeatureSupport("WCSS", 0)) {
    $ignoredDirectories{'fast/wcss'} = 1;
}

if (!checkWebCoreFeatureSupport("XHTMLMP", 0)) {
    $ignoredDirectories{'fast/xhtmlmp'} = 1;
}

processIgnoreTests($ignoreTests, "ignore-tests") if $ignoreTests;
if (!$ignoreSkipped) {
    if (!$skippedOnly || @ARGV == 0) {
        readSkippedFiles("");
    } else {
        # Since readSkippedFiles() appends to @ARGV, we must use a foreach
        # loop so that we only iterate over the original argument list.
        foreach my $argnum (0 .. $#ARGV) {
            readSkippedFiles(shift @ARGV);
        }
    }
}

my @tests = findTestsToRun();

die "no tests to run\n" if !@tests;

my %counts;
my %tests;
my %imagesPresent;
my %imageDifferences;
my %durations;
my $count = 0;
my $leaksOutputFileNumber = 1;
my $totalLeaks = 0;

my @toolArgs = ();
push @toolArgs, "--pixel-tests" if $pixelTests;
push @toolArgs, "--threaded" if $threaded;
push @toolArgs, "--complex-text" if $complexText;
push @toolArgs, "-";

my @diffToolArgs = ();
push @diffToolArgs, "--tolerance", $tolerance;

$| = 1;

my $dumpToolPID;
my $isDumpToolOpen = 0;
my $dumpToolCrashed = 0;
my $imageDiffToolPID;
my $isDiffToolOpen = 0;

my $atLineStart = 1;
my $lastDirectory = "";

my $isHttpdOpen = 0;
my $isWebSocketServerOpen = 0;
my $webSocketServerPidFile = 0;
my $failedToStartWebSocketServer = 0;
# wss is disabled until all platforms support pyOpenSSL.
# my $webSocketSecureServerPID = 0;

sub catch_pipe { $dumpToolCrashed = 1; }
$SIG{"PIPE"} = "catch_pipe";

print "Testing ", scalar @tests, " test cases";
print " $iterations times" if ($iterations > 1);
print ", repeating each test $repeatEach times" if ($repeatEach > 1);
print ".\n";

my $overallStartTime = time;

my %expectedResultPaths;

my @originalTests = @tests;
# Add individual test repetitions
if ($repeatEach > 1) {
    @tests = ();
    foreach my $test (@originalTests) {
        for (my $i = 0; $i < $repeatEach; $i++) {
            push(@tests, $test);
        }
    }
}
# Add test set repetitions
for (my $i = 1; $i < $iterations; $i++) {
    push(@tests, @originalTests);
}

for my $test (@tests) {
    my $newDumpTool = not $isDumpToolOpen;
    openDumpTool();

    my $base = stripExtension($test);
    my $expectedExtension = ".txt";
    
    my $dir = $base;
    $dir =~ s|/[^/]+$||;

    if ($newDumpTool || $dir ne $lastDirectory) {
        foreach my $logue (epiloguesAndPrologues($newDumpTool ? "" : $lastDirectory, $dir)) {
            if (isCygwin()) {
                $logue = toWindowsPath($logue);
            } else {
                $logue = canonpath($logue);
            }
            if ($verbose) {
                print "running epilogue or prologue $logue\n";
            }
            print OUT "$logue\n";
            # Throw away output from DumpRenderTree.
            # Once for the test output and once for pixel results (empty)
            while (<IN>) {
                last if /#EOF/;
            }
            while (<IN>) {
                last if /#EOF/;
            }
        }
    }

    if ($verbose) {
        print "running $test -> ";
        $atLineStart = 0;
    } elsif (!$quiet) {
        if ($dir ne $lastDirectory) {
            print "\n" unless $atLineStart;
            print "$dir ";
        }
        print ".";
        $atLineStart = 0;
    }

    $lastDirectory = $dir;

    my $result;

    my $startTime = time if $report10Slowest;

    # Try to read expected hash file for pixel tests
    my $suffixExpectedHash = "";
    if ($pixelTests && !$resetResults) {
        my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
        if (open EXPECTEDHASH, File::Spec->catfile($expectedPixelDir, "$base-$expectedTag.checksum")) {
            my $expectedHash = <EXPECTEDHASH>;
            chomp($expectedHash);
            close EXPECTEDHASH;
            
            # Format expected hash into a suffix string that is appended to the path / URL passed to DRT
            $suffixExpectedHash = "'$expectedHash";
        }
    }

    if ($test =~ /^http\//) {
        configureAndOpenHTTPDIfNeeded();
        if ($test =~ /^http\/tests\/websocket\//) {
            if ($test =~ /^websocket\/tests\/local\//) {
                my $testPath = "$testDirectory/$test";
                if (isCygwin()) {
                    $testPath = toWindowsPath($testPath);
                } else {
                    $testPath = canonpath($testPath);
                }
                print OUT "$testPath\n";
            } else {
                if (openWebSocketServerIfNeeded()) {
                    my $path = canonpath($test);
                    if ($test =~ /^http\/tests\/websocket\/tests\/ssl\//) {
                        # wss is disabled until all platforms support pyOpenSSL.
                        print STDERR "Error: wss is disabled until all platforms support pyOpenSSL.";
                    } else {
                        $path =~ s/^http\/tests\///;
                        print OUT "http://127.0.0.1:$httpdPort/$path\n";
                    }
                } else {
                    # We failed to launch the WebSocket server.  Display a useful error message rather than attempting
                    # to run tests that expect the server to be available.
                    my $errorMessagePath = "$testDirectory/http/tests/websocket/resources/server-failed-to-start.html";
                    $errorMessagePath = isCygwin() ? toWindowsPath($errorMessagePath) : canonpath($errorMessagePath);
                    print OUT "$errorMessagePath\n";
                }
            }
        } elsif ($test !~ /^http\/tests\/local\// && $test !~ /^http\/tests\/ssl\// && $test !~ /^http\/tests\/wml\// && $test !~ /^http\/tests\/media\//) {
            my $path = canonpath($test);
            $path =~ s/^http\/tests\///;
            print OUT "http://127.0.0.1:$httpdPort/$path$suffixExpectedHash\n";
        } elsif ($test =~ /^http\/tests\/ssl\//) {
            my $path = canonpath($test);
            $path =~ s/^http\/tests\///;
            print OUT "https://127.0.0.1:$httpdSSLPort/$path$suffixExpectedHash\n";
        } else {
            my $testPath = "$testDirectory/$test";
            if (isCygwin()) {
                $testPath = toWindowsPath($testPath);
            } else {
                $testPath = canonpath($testPath);
            }
            print OUT "$testPath$suffixExpectedHash\n";
        }
    } else {
        my $testPath = "$testDirectory/$test";
        if (isCygwin()) {
            $testPath = toWindowsPath($testPath);
        } else {
            $testPath = canonpath($testPath);
        }
        print OUT "$testPath$suffixExpectedHash\n" if defined $testPath;
    }

    # DumpRenderTree is expected to dump two "blocks" to stdout for each test.
    # Each block is terminated by a #EOF on a line by itself.
    # The first block is the output of the test (in text, RenderTree or other formats).
    # The second block is for optional pixel data in PNG format, and may be empty if
    # pixel tests are not being run, or the test does not dump pixels (e.g. text tests).
    my $readResults = readFromDumpToolWithTimer(IN, ERROR);

    my $actual = $readResults->{output};
    my $error = $readResults->{error};

    $expectedExtension = $readResults->{extension};
    my $expectedFileName = "$base-$expectedTag.$expectedExtension";

    my $isText = isTextOnlyTest($actual);

    my $expectedDir = expectedDirectoryForTest($base, $isText, $expectedExtension);
    $expectedResultPaths{$base} = File::Spec->catfile($expectedDir, $expectedFileName);

    unless ($readResults->{status} eq "success") {
        my $crashed = $readResults->{status} eq "crashed";
        my $webProcessCrashed = $readResults->{status} eq "webProcessCrashed";
        testCrashedOrTimedOut($test, $base, $crashed, $webProcessCrashed, $actual, $error);
        countFinishedTest($test, $base, $webProcessCrashed ? "webProcessCrash" : $crashed ? "crash" : "timedout", 0);
        last if stopRunningTestsEarlyIfNeeded();
        next;
    }

    $durations{$test} = time - $startTime if $report10Slowest;

    my $expected;

    if (!$resetResults && open EXPECTED, "<", $expectedResultPaths{$base}) {
        $expected = "";
        while (<EXPECTED>) {
            next if $stripEditingCallbacks && $_ =~ /^EDITING DELEGATE:/;
            $expected .= $_;
        }
        close EXPECTED;
    }

    if ($ignoreMetrics && !$isText && defined $expected) {
        ($actual, $expected) = stripMetrics($actual, $expected);
    }

    if ($shouldCheckLeaks && $testsPerDumpTool == 1) {
        print "        $test -> ";
    }

    my $actualPNG = "";
    my $diffPNG = "";
    my $diffPercentage = 0;
    my $diffResult = "passed";

    my $actualHash = "";
    my $expectedHash = "";
    my $actualPNGSize = 0;

    while (<IN>) {
        last if /#EOF/;
        if (/ActualHash: ([a-f0-9]{32})/) {
            $actualHash = $1;
        } elsif (/ExpectedHash: ([a-f0-9]{32})/) {
            $expectedHash = $1;
        } elsif (/Content-Length: (\d+)\s*/) {
            $actualPNGSize = $1;
            read(IN, $actualPNG, $actualPNGSize);
        }
    }

    if ($verbose && $pixelTests && !$resetResults && $actualPNGSize) {
        if ($actualHash eq "" && $expectedHash eq "") {
            printFailureMessageForTest($test, "WARNING: actual & expected pixel hashes are missing!");
        } elsif ($actualHash eq "") {
            printFailureMessageForTest($test, "WARNING: actual pixel hash is missing!");
        } elsif ($expectedHash eq "") {
            printFailureMessageForTest($test, "WARNING: expected pixel hash is missing!");
        }
    }

    if ($actualPNGSize > 0) {
        my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
        my $expectedPNGPath = File::Spec->catfile($expectedPixelDir, "$base-$expectedTag.png");

        if (!$resetResults && ($expectedHash ne $actualHash || ($actualHash eq "" && $expectedHash eq ""))) {
            if (-f $expectedPNGPath) {
                my $expectedPNGSize = -s $expectedPNGPath;
                my $expectedPNG = "";
                open EXPECTEDPNG, $expectedPNGPath;
                read(EXPECTEDPNG, $expectedPNG, $expectedPNGSize);

                openDiffTool();
                print DIFFOUT "Content-Length: $actualPNGSize\n";
                print DIFFOUT $actualPNG;

                print DIFFOUT "Content-Length: $expectedPNGSize\n";
                print DIFFOUT $expectedPNG;

                while (<DIFFIN>) {
                    last if /^error/ || /^diff:/;
                    if (/Content-Length: (\d+)\s*/) {
                        read(DIFFIN, $diffPNG, $1);
                    }
                }

                if (/^diff: (.+)% (passed|failed)/) {
                    $diffPercentage = $1 + 0;
                    $imageDifferences{$base} = $diffPercentage;
                    $diffResult = $2;
                }
                
                if (!$diffPercentage) {
                    printFailureMessageForTest($test, "pixel hash failed (but pixel test still passes)");
                }
            } elsif ($verbose) {
                printFailureMessageForTest($test, "WARNING: expected image is missing!");
            }
        }

        if ($resetResults || !-f $expectedPNGPath) {
            mkpath catfile($expectedPixelDir, dirname($base)) if $testDirectory ne $expectedPixelDir;
            writeToFile($expectedPNGPath, $actualPNG);
        }

        my $expectedChecksumPath = File::Spec->catfile($expectedPixelDir, "$base-$expectedTag.checksum");
        if ($actualHash ne "" && ($resetResults || !-f $expectedChecksumPath)) {
            writeToFile($expectedChecksumPath, $actualHash);
        }
    }

    if (dumpToolDidCrash()) {
        $result = "crash";
        testCrashedOrTimedOut($test, $base, 1, 0, $actual, $error);
    } elsif (!defined $expected) {
        if ($verbose) {
            print "new " . ($resetResults ? "result" : "test");
        }
        $result = "new";

        if ($generateNewResults || $resetResults) {
            mkpath catfile($expectedDir, dirname($base)) if $testDirectory ne $expectedDir;
            writeToFile("$expectedDir/$expectedFileName", $actual);
        }
        deleteExpectedAndActualResults($base);
        recordActualResultsAndDiff($base, $actual);
        if (!$resetResults) {
            # Always print the file name for new tests, as they will probably need some manual inspection.
            # in verbose mode we already printed the test case, so no need to do it again.
            unless ($verbose) {
                print "\n" unless $atLineStart;
                print "$test -> ";
            }
            my $resultsDir = catdir($expectedDir, dirname($base));
            if (!$verbose) {
                print "new";
            }
            if ($generateNewResults) {
                print " (results generated in $resultsDir)";
            }
            print "\n" unless $atLineStart;
            $atLineStart = 1;
        }
    } elsif ($actual eq $expected && $diffResult eq "passed") {
        if ($verbose) {
            print "succeeded\n";
            $atLineStart = 1;
        }
        $result = "match";
        deleteExpectedAndActualResults($base);
    } else {
        $result = "mismatch";

        my $pixelTestFailed = $pixelTests && $diffPNG && $diffPNG ne "";
        my $testFailed = $actual ne $expected;

        my $message = !$testFailed ? "pixel test failed" : "failed";

        if (($testFailed || $pixelTestFailed) && $addPlatformExceptions) {
            my $testBase = catfile($testDirectory, $base);
            my $expectedBase = catfile($expectedDir, $base);
            my $testIsMaximallyPlatformSpecific = $testBase =~ m|^\Q$platformTestDirectory\E/|;
            my $expectedResultIsMaximallyPlatformSpecific = $expectedBase =~ m|^\Q$platformTestDirectory\E/|;
            if (!$testIsMaximallyPlatformSpecific && !$expectedResultIsMaximallyPlatformSpecific) {
                mkpath catfile($platformTestDirectory, dirname($base));
                if ($testFailed) {
                    my $expectedFile = catfile($platformTestDirectory, "$expectedFileName");
                    writeToFile("$expectedFile", $actual);
                }
                if ($pixelTestFailed) {
                    my $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.checksum");
                    writeToFile("$expectedFile", $actualHash);

                    $expectedFile = catfile($platformTestDirectory, "$base-$expectedTag.png");
                    writeToFile("$expectedFile", $actualPNG);
                }
                $message .= " (results generated in $platformTestDirectory)";
            }
        }

        printFailureMessageForTest($test, $message);

        my $dir = "$testResultsDirectory/$base";
        $dir =~ s|/([^/]+)$|| or die "Failed to find test name from base\n";
        my $testName = $1;
        mkpath $dir;

        deleteExpectedAndActualResults($base);
        recordActualResultsAndDiff($base, $actual);

        if ($pixelTestFailed) {
            $imagesPresent{$base} = 1;

            writeToFile("$testResultsDirectory/$base-$actualTag.png", $actualPNG);
            writeToFile("$testResultsDirectory/$base-$diffsTag.png", $diffPNG);

            my $expectedPixelDir = expectedDirectoryForTest($base, 0, "png");
            copy("$expectedPixelDir/$base-$expectedTag.png", "$testResultsDirectory/$base-$expectedTag.png");

            open DIFFHTML, ">$testResultsDirectory/$base-$diffsTag.html" or die;
            print DIFFHTML "<html>\n";
            print DIFFHTML "<head>\n";
            print DIFFHTML "<title>$base Image Compare</title>\n";
            print DIFFHTML "<script language=\"Javascript\" type=\"text/javascript\">\n";
            print DIFFHTML "var currentImage = 0;\n";
            print DIFFHTML "var imageNames = new Array(\"Actual\", \"Expected\");\n";
            print DIFFHTML "var imagePaths = new Array(\"$testName-$actualTag.png\", \"$testName-$expectedTag.png\");\n";
            if (-f "$testDirectory/$base-w3c.png") {
                copy("$testDirectory/$base-w3c.png", "$testResultsDirectory/$base-w3c.png");
                print DIFFHTML "imageNames.push(\"W3C\");\n";
                print DIFFHTML "imagePaths.push(\"$testName-w3c.png\");\n";
            }
            print DIFFHTML "function animateImage() {\n";
            print DIFFHTML "    var image = document.getElementById(\"animatedImage\");\n";
            print DIFFHTML "    var imageText = document.getElementById(\"imageText\");\n";
            print DIFFHTML "    image.src = imagePaths[currentImage];\n";
            print DIFFHTML "    imageText.innerHTML = imageNames[currentImage] + \" Image\";\n";
            print DIFFHTML "    currentImage = (currentImage + 1) % imageNames.length;\n";
            print DIFFHTML "    setTimeout('animateImage()',2000);\n";
            print DIFFHTML "}\n";
            print DIFFHTML "</script>\n";
            print DIFFHTML "</head>\n";
            print DIFFHTML "<body onLoad=\"animateImage();\">\n";
            print DIFFHTML "<table>\n";
            if ($diffPercentage) {
                print DIFFHTML "<tr>\n";
                print DIFFHTML "<td>Difference between images: <a href=\"$testName-$diffsTag.png\">$diffPercentage%</a></td>\n";
                print DIFFHTML "</tr>\n";
            }
            print DIFFHTML "<tr>\n";
            print DIFFHTML "<td><a href=\"" . toURL("$testDirectory/$test") . "\">test file</a></td>\n";
            print DIFFHTML "</tr>\n";
            print DIFFHTML "<tr>\n";
            print DIFFHTML "<td id=\"imageText\" style=\"text-weight: bold;\">Actual Image</td>\n";
            print DIFFHTML "</tr>\n";
            print DIFFHTML "<tr>\n";
            print DIFFHTML "<td><img src=\"$testName-$actualTag.png\" id=\"animatedImage\"></td>\n";
            print DIFFHTML "</tr>\n";
            print DIFFHTML "</table>\n";
            print DIFFHTML "</body>\n";
            print DIFFHTML "</html>\n";
        }
    }

    if ($error) {
        my $dir = dirname(File::Spec->catdir($testResultsDirectory, $base));
        mkpath $dir;
        
        writeToFile(File::Spec->catfile($testResultsDirectory, "$base-$errorTag.txt"), $error);
        
        $counts{error}++;
        push @{$tests{error}}, $test;
    }

    countFinishedTest($test, $base, $result, $isText);
    last if stopRunningTestsEarlyIfNeeded();
}

my $totalTestingTime = time - $overallStartTime;
my $waitTime = getWaitTime();
if ($waitTime > 0.1) {
    my $normalizedTestingTime = $totalTestingTime - $waitTime;
    printf "\n%0.2fs HTTPD waiting time\n", $waitTime . "";
    printf "%0.2fs normalized testing time", $normalizedTestingTime . "";
}
printf "\n%0.2fs total testing time\n", $totalTestingTime . "";

!$isDumpToolOpen || die "Failed to close $dumpToolName.\n";

$isHttpdOpen = !closeHTTPD();
closeWebSocketServer();

# Because multiple instances of this script are running concurrently we cannot 
# safely delete this symlink.
# system "rm /tmp/LayoutTests";

# FIXME: Do we really want to check the image-comparison tool for leaks every time?
if ($isDiffToolOpen && $shouldCheckLeaks) {
    $totalLeaks += countAndPrintLeaks("ImageDiff", $imageDiffToolPID, "$testResultsDirectory/ImageDiff-leaks.txt");
}

if ($totalLeaks) {
    if ($mergeDepth) {
        parseLeaksandPrintUniqueLeaks();
    } else { 
        print "\nWARNING: $totalLeaks total leaks found!\n";
        print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
    }
}

close IN;
close OUT;
close ERROR;

if ($report10Slowest) {
    print "\n\nThe 10 slowest tests:\n\n";
    my $count = 0;
    for my $test (sort slowestcmp keys %durations) {
        printf "%0.2f secs: %s\n", $durations{$test}, $test;
        last if ++$count == 10;
    }
}

print "\n";

if ($skippedOnly && $counts{"match"}) {
    print "The following tests are in the Skipped file (" . File::Spec->abs2rel("$platformTestDirectory/Skipped", $testDirectory) . "), but succeeded:\n";
    foreach my $test (@{$tests{"match"}}) {
        print "  $test\n";
    }
}

if ($resetResults || ($counts{match} && $counts{match} == $count)) {
    print "all $count test cases succeeded\n";
    unlink $testResults;
    exit;
}

printResults();

mkpath $testResultsDirectory;

open HTML, ">", $testResults or die "Failed to open $testResults. $!";
print HTML "<html>\n";
print HTML "<head>\n";
print HTML "<title>Layout Test Results</title>\n";
print HTML "</head>\n";
print HTML "<body>\n";

if ($ignoreMetrics) {
    print HTML "<h4>Tested with metrics ignored.</h4>";
}

print HTML htmlForResultsSection(@{$tests{mismatch}}, "Tests where results did not match expected results", \&linksForMismatchTest);
print HTML htmlForResultsSection(@{$tests{timedout}}, "Tests that timed out", \&linksForErrorTest);
print HTML htmlForResultsSection(@{$tests{crash}}, "Tests that caused the DumpRenderTree tool to crash", \&linksForErrorTest);
print HTML htmlForResultsSection(@{$tests{webProcessCrash}}, "Tests that caused the Web process to crash", \&linksForErrorTest);
print HTML htmlForResultsSection(@{$tests{error}}, "Tests that had stderr output", \&linksForErrorTest);
print HTML htmlForResultsSection(@{$tests{new}}, "Tests that had no expected results (probably new)", \&linksForNewTest);

print HTML "</body>\n";
print HTML "</html>\n";
close HTML;

my @configurationArgs = argumentsForConfiguration();

if (isGtk()) {
  system "Tools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
} elsif (isQt()) {
  unshift @configurationArgs, qw(-graphicssystem raster -style windows);
  if (isCygwin()) {
    $testResults = "/" . toWindowsPath($testResults);
    $testResults =~ s/\\/\//g;
  }
  system "Tools/Scripts/run-launcher", @configurationArgs, "file://".$testResults if $launchSafari;
} elsif (isCygwin()) {
  system "cygstart", $testResults if $launchSafari;
} elsif (isWindows()) {
  system "start", $testResults if $launchSafari;
} else {
  system "Tools/Scripts/run-safari", @configurationArgs, "-NSOpen", $testResults if $launchSafari;
}

closeCygpaths() if isCygwin();

exit 1;

sub countAndPrintLeaks($$$)
{
    my ($dumpToolName, $dumpToolPID, $leaksFilePath) = @_;

    print "\n" unless $atLineStart;
    $atLineStart = 1;

    # We are excluding the following reported leaks so they don't get in our way when looking for WebKit leaks:
    # This allows us ignore known leaks and only be alerted when new leaks occur. Some leaks are in the old
    # versions of the system frameworks that are being used by the leaks bots. Even though a leak has been
    # fixed, it will be listed here until the bot has been updated with the newer frameworks.

    my @typesToExclude = (
    );

    my @callStacksToExclude = (
        "Flash_EnforceLocalSecurity" # leaks in Flash plug-in code, rdar://problem/4449747
    );

    if (isTiger()) {
        # Leak list for the version of Tiger used on the build bot.
        push @callStacksToExclude, (
            "CFRunLoopRunSpecific \\| malloc_zone_malloc", "CFRunLoopRunSpecific \\| CFAllocatorAllocate ", # leak in CFRunLoopRunSpecific, rdar://problem/4670839
            "CGImageSourceGetPropertiesAtIndex", # leak in ImageIO, rdar://problem/4628809
            "FOGetCoveredUnicodeChars", # leak in ATS, rdar://problem/3943604
            "GetLineDirectionPreference", "InitUnicodeUtilities", # leaks tool falsely reporting leak in CFNotificationCenterAddObserver, rdar://problem/4964790
            "ICCFPrefWrapper::GetPrefDictionary", # leaks in Internet Config. code, rdar://problem/4449794
            "NSHTTPURLProtocol setResponseHeader:", # leak in multipart/mixed-replace handling in Foundation, no Radar, but fixed in Leopard
            "NSURLCache cachedResponseForRequest", # leak in CFURL cache, rdar://problem/4768430
            "PCFragPrepareClosureFromFile", # leak in Code Fragment Manager, rdar://problem/3426998
            "WebCore::Selection::toRange", # bug in 'leaks', rdar://problem/4967949
            "WebCore::SubresourceLoader::create", # bug in 'leaks', rdar://problem/4985806
            "_CFPreferencesDomainDeepCopyDictionary", # leak in CFPreferences, rdar://problem/4220786
            "_objc_msgForward", # leak in NSSpellChecker, rdar://problem/4965278
            "gldGetString", # leak in OpenGL, rdar://problem/5013699
            "_setDefaultUserInfoFromURL", # leak in NSHTTPAuthenticator, rdar://problem/5546453 
            "SSLHandshake", # leak in SSL, rdar://problem/5546440 
            "SecCertificateCreateFromData", # leak in SSL code, rdar://problem/4464397
        );
        push @typesToExclude, (
            "THRD", # bug in 'leaks', rdar://problem/3387783
            "DRHT", # ditto (endian little hate i)
        );
    }

    if (isLeopard()) {
        # Leak list for the version of Leopard used on the build bot.
        push @callStacksToExclude, (
            "CFHTTPMessageAppendBytes", # leak in CFNetwork, rdar://problem/5435912
            "sendDidReceiveDataCallback", # leak in CFNetwork, rdar://problem/5441619
            "_CFHTTPReadStreamReadMark", # leak in CFNetwork, rdar://problem/5441468
            "httpProtocolStart", # leak in CFNetwork, rdar://problem/5468837
            "_CFURLConnectionSendCallbacks", # leak in CFNetwork, rdar://problem/5441600
            "DispatchQTMsg", # leak in QuickTime, PPC only, rdar://problem/5667132
            "QTMovieContentView createVisualContext", # leak in QuickTime, PPC only, rdar://problem/5667132
            "_CopyArchitecturesForJVMVersion", # leak in Java, rdar://problem/5910823
        );
    }

    if (isSnowLeopard()) {
        push @callStacksToExclude, (
            "readMakerNoteProps", # <rdar://problem/7156432> leak in ImageIO
            "QTKitMovieControllerView completeUISetup", # <rdar://problem/7155156> leak in QTKit
            "getVMInitArgs", # <rdar://problem/7714444> leak in Java
            "Java_java_lang_System_initProperties", # <rdar://problem/7714465> leak in Java
            "glrCompExecuteKernel", # <rdar://problem/7815391> leak in graphics driver while using OpenGL
        );
    }

    if (isDarwin() && !isTiger() && !isLeopard() && !isSnowLeopard()) {
        push @callStacksToExclude, (
            "CGGradientCreateWithColorComponents", # leak in CoreGraphics, <rdar://problem/7888492>
        );
    }

    my $leaksTool = sourceDir() . "/Tools/Scripts/run-leaks";
    my $excludeString = "--exclude-callstack '" . (join "' --exclude-callstack '", @callStacksToExclude) . "'";
    $excludeString .= " --exclude-type '" . (join "' --exclude-type '", @typesToExclude) . "'" if @typesToExclude;

    print " ? checking for leaks in $dumpToolName\n";
    my $leaksOutput = `$leaksTool $excludeString $dumpToolPID`;
    my ($count, $bytes) = $leaksOutput =~ /Process $dumpToolPID: (\d+) leaks? for (\d+) total/;
    my ($excluded) = $leaksOutput =~ /(\d+) leaks? excluded/;

    my $adjustedCount = $count;
    $adjustedCount -= $excluded if $excluded;

    if (!$adjustedCount) {
        print " - no leaks found\n";
        unlink $leaksFilePath;
        return 0;
    } else {
        my $dir = $leaksFilePath;
        $dir =~ s|/[^/]+$|| or die;
        mkpath $dir;

        if ($excluded) {
            print " + $adjustedCount leaks ($bytes bytes including $excluded excluded leaks) were found, details in $leaksFilePath\n";
        } else {
            print " + $count leaks ($bytes bytes) were found, details in $leaksFilePath\n";
        }

        writeToFile($leaksFilePath, $leaksOutput);
        
        push @leaksFilenames, $leaksFilePath;
    }

    return $adjustedCount;
}

sub writeToFile($$)
{
    my ($filePath, $contents) = @_;
    open NEWFILE, ">", "$filePath" or die "Could not create $filePath. $!\n";
    print NEWFILE $contents;
    close NEWFILE;
}

# Break up a path into the directory (with slash) and base name.
sub splitpath($)
{
    my ($path) = @_;

    my $pathSeparator = "/";
    my $dirname = dirname($path) . $pathSeparator;
    $dirname = "" if $dirname eq "." . $pathSeparator;

    return ($dirname, basename($path));
}

# Sort first by directory, then by file, so all paths in one directory are grouped
# rather than being interspersed with items from subdirectories.
# Use numericcmp to sort directory and filenames to make order logical.
sub pathcmp($$)
{
    my ($patha, $pathb) = @_;

    my ($dira, $namea) = splitpath($patha);
    my ($dirb, $nameb) = splitpath($pathb);

    return numericcmp($dira, $dirb) if $dira ne $dirb;
    return numericcmp($namea, $nameb);
}

# Sort numeric parts of strings as numbers, other parts as strings.
# Makes 1.33 come after 1.3, which is cool.
sub numericcmp($$)
{
    my ($aa, $bb) = @_;

    my @a = split /(\d+)/, $aa;
    my @b = split /(\d+)/, $bb;

    # Compare one chunk at a time.
    # Each chunk is either all numeric digits, or all not numeric digits.
    while (@a && @b) {
        my $a = shift @a;
        my $b = shift @b;
        
        # Use numeric comparison if chunks are non-equal numbers.
        return $a <=> $b if $a =~ /^\d/ && $b =~ /^\d/ && $a != $b;

        # Use string comparison if chunks are any other kind of non-equal string.
        return $a cmp $b if $a ne $b;
    }
    
    # One of the two is now empty; compare lengths for result in this case.
    return @a <=> @b;
}

# Sort slowest tests first.
sub slowestcmp($$)
{
    my ($testa, $testb) = @_;

    my $dura = $durations{$testa};
    my $durb = $durations{$testb};
    return $durb <=> $dura if $dura != $durb;
    return pathcmp($testa, $testb);
}

sub launchWithEnv(\@\%)
{
    my ($args, $env) = @_;

    # Dump the current environment as perl code and then put it in quotes so it is one parameter.
    my $environmentDumper = Data::Dumper->new([\%{$env}], [qw(*ENV)]);
    $environmentDumper->Indent(0);
    $environmentDumper->Purity(1);
    my $allEnvVars = $environmentDumper->Dump();
    unshift @{$args}, "\"$allEnvVars\"";

    my $execScript = File::Spec->catfile(sourceDir(), qw(Tools Scripts execAppWithEnv));
    unshift @{$args}, $perlInterpreter, $execScript;
    return @{$args};
}

sub resolveAndMakeTestResultsDirectory()
{
    my $absTestResultsDirectory = File::Spec->rel2abs(glob $testResultsDirectory);
    mkpath $absTestResultsDirectory;
    return $absTestResultsDirectory;
}

sub openDiffTool()
{
    return if $isDiffToolOpen;
    return if !$pixelTests;

    my %CLEAN_ENV;
    $CLEAN_ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;
    $imageDiffToolPID = open2(\*DIFFIN, \*DIFFOUT, $imageDiffTool, launchWithEnv(@diffToolArgs, %CLEAN_ENV)) or die "unable to open $imageDiffTool\n";
    $isDiffToolOpen = 1;
}

sub buildDumpTool($)
{
    my ($dumpToolName) = @_;

    my $dumpToolBuildScript =  "build-" . lc($dumpToolName);
    print STDERR "Running $dumpToolBuildScript\n";

    local *DEVNULL;
    my ($childIn, $childOut, $childErr);
    if ($quiet) {
        open(DEVNULL, ">", File::Spec->devnull()) or die "Failed to open /dev/null";
        $childOut = ">&DEVNULL";
        $childErr = ">&DEVNULL";
    } else {
        # When not quiet, let the child use our stdout/stderr.
        $childOut = ">&STDOUT";
        $childErr = ">&STDERR";
    }

    my @args = argumentsForConfiguration();
    my $buildProcess = open3($childIn, $childOut, $childErr, $perlInterpreter, File::Spec->catfile(qw(Tools Scripts), $dumpToolBuildScript), @args) or die "Failed to run build-dumprendertree";
    close($childIn);
    waitpid $buildProcess, 0;
    my $buildResult = $?;
    close($childOut);
    close($childErr);

    close DEVNULL if ($quiet);

    if ($buildResult) {
        print STDERR "Compiling $dumpToolName failed!\n";
        exit exitStatus($buildResult);
    }
}

sub openDumpTool()
{
    return if $isDumpToolOpen;

    if ($verbose && $testsPerDumpTool != 1) {
        print "| Opening DumpTool |\n";
    }

    my %CLEAN_ENV;

    # Generic environment variables
    if (defined $ENV{'WEBKIT_TESTFONTS'}) {
        $CLEAN_ENV{WEBKIT_TESTFONTS} = $ENV{'WEBKIT_TESTFONTS'};
    }

    # unique temporary directory for each DumpRendertree - needed for running more DumpRenderTree in parallel
    $CLEAN_ENV{DUMPRENDERTREE_TEMP} = File::Temp::tempdir('DumpRenderTree-XXXXXX', TMPDIR => 1, CLEANUP => 1);
    $CLEAN_ENV{XML_CATALOG_FILES} = ""; # work around missing /etc/catalog <rdar://problem/4292995>

    # Platform spesifics
    if (isLinux()) {
        if (defined $ENV{'DISPLAY'}) {
            $CLEAN_ENV{DISPLAY} = $ENV{'DISPLAY'};
        } else {
            $CLEAN_ENV{DISPLAY} = ":1";
        }
        if (defined $ENV{'XAUTHORITY'}) {
            $CLEAN_ENV{XAUTHORITY} = $ENV{'XAUTHORITY'};
        }

        $CLEAN_ENV{HOME} = $ENV{'HOME'};

        if (defined $ENV{'LD_LIBRARY_PATH'}) {
            $CLEAN_ENV{LD_LIBRARY_PATH} = $ENV{'LD_LIBRARY_PATH'};
        }
        if (defined $ENV{'DBUS_SESSION_BUS_ADDRESS'}) {
            $CLEAN_ENV{DBUS_SESSION_BUS_ADDRESS} = $ENV{'DBUS_SESSION_BUS_ADDRESS'};
        }
    } elsif (isDarwin()) {
        if (defined $ENV{'DYLD_LIBRARY_PATH'}) {
            $CLEAN_ENV{DYLD_LIBRARY_PATH} = $ENV{'DYLD_LIBRARY_PATH'};
        }
        if (defined $ENV{'HOME'}) {
            $CLEAN_ENV{HOME} = $ENV{'HOME'};
        }

        $CLEAN_ENV{DYLD_FRAMEWORK_PATH} = $productDir;
        $CLEAN_ENV{DYLD_INSERT_LIBRARIES} = "/usr/lib/libgmalloc.dylib" if $guardMalloc;
    } elsif (isCygwin()) {
        $CLEAN_ENV{HOMEDRIVE} = $ENV{'HOMEDRIVE'};
        $CLEAN_ENV{HOMEPATH} = $ENV{'HOMEPATH'};
        $CLEAN_ENV{_NT_SYMBOL_PATH} = $ENV{_NT_SYMBOL_PATH};

        setPathForRunningWebKitApp(\%CLEAN_ENV);
    }

    # Port specifics
    if (isGtk()) {
        $CLEAN_ENV{GTK_MODULES} = "gail";
        $CLEAN_ENV{WEBKIT_INSPECTOR_PATH} = "$productDir/resources/inspector";
    }

    if (isQt()) {
        $CLEAN_ENV{QTWEBKIT_PLUGIN_PATH} = productDir() . "/lib/plugins";
        $CLEAN_ENV{QT_DRT_WEBVIEW_MODE} = $ENV{"QT_DRT_WEBVIEW_MODE"};
    }
    
    my @args = ($dumpTool, @toolArgs);
    if (isAppleMacWebKit() and !isTiger()) { 
        unshift @args, "arch", "-" . architecture();             
    }

    if ($useValgrind) {
        unshift @args, "valgrind", "--suppressions=$platformBaseDirectory/qt/SuppressedValgrindErrors";
    } 

    if ($useWebKitTestRunner) {
        # Make WebKitTestRunner use a similar timeout. We don't use the exact same timeout to avoid
        # race conditions.
        push @args, "--timeout", $timeoutSeconds - 5;
    }

    $CLEAN_ENV{MallocStackLogging} = 1 if $shouldCheckLeaks;

    $dumpToolPID = open3(\*OUT, \*IN, \*ERROR, launchWithEnv(@args, %CLEAN_ENV)) or die "Failed to start tool: $dumpTool\n";
    $isDumpToolOpen = 1;
    $dumpToolCrashed = 0;
}

sub closeDumpTool()
{
    return if !$isDumpToolOpen;

    if ($verbose && $testsPerDumpTool != 1) {
        print "| Closing DumpTool |\n";
    }

    close IN;
    close OUT;
    waitpid $dumpToolPID, 0;
    
    # check for WebCore counter leaks.
    if ($shouldCheckLeaks) {
        while (<ERROR>) {
            print;
        }
    }
    close ERROR;
    $isDumpToolOpen = 0;
}

sub dumpToolDidCrash()
{
    return 1 if $dumpToolCrashed;
    return 0 unless $isDumpToolOpen;
    my $pid = waitpid(-1, WNOHANG);
    return 1 if ($pid == $dumpToolPID);

    # On Mac OS X, crashing may be significantly delayed by crash reporter.
    return 0 unless isAppleMacWebKit();

    return DumpRenderTreeSupport::processIsCrashing($dumpToolPID);
}

sub configureAndOpenHTTPDIfNeeded()
{
    return if $isHttpdOpen;
    my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
    my $listen = "127.0.0.1:$httpdPort";
    my @args = (
        "-c", "CustomLog \"$absTestResultsDirectory/access_log.txt\" common",
        "-c", "ErrorLog \"$absTestResultsDirectory/error_log.txt\"",
        "-C", "Listen $listen"
    );

    my @defaultArgs = getDefaultConfigForTestDirectory($testDirectory);
    @args = (@defaultArgs, @args);

    waitForHTTPDLock() if $shouldWaitForHTTPD;
    $isHttpdOpen = openHTTPD(@args);
}

sub checkPythonVersion()
{
    # we have not chdir to sourceDir yet.
    system $perlInterpreter, File::Spec->catfile(sourceDir(), qw(Tools Scripts ensure-valid-python)), "--check-only";
    return exitStatus($?) == 0;
}

sub openWebSocketServerIfNeeded()
{
    return 1 if $isWebSocketServerOpen;
    return 0 if $failedToStartWebSocketServer;

    my $webSocketHandlerDir = "$testDirectory";
    my $absTestResultsDirectory = resolveAndMakeTestResultsDirectory();
    $webSocketServerPidFile = "$absTestResultsDirectory/websocket.pid";

    my @args = (
        "Tools/Scripts/new-run-webkit-websocketserver",
        "--server", "start",
        "--port", "$webSocketPort",
        "--root", "$webSocketHandlerDir",
        "--output-dir", "$absTestResultsDirectory",
        "--pidfile", "$webSocketServerPidFile"
    );
    system "/usr/bin/python", @args;

    $isWebSocketServerOpen = 1;
    return 1;
}

sub closeWebSocketServer()
{
    return if !$isWebSocketServerOpen;

    my @args = (
        "Tools/Scripts/new-run-webkit-websocketserver",
        "--server", "stop",
        "--pidfile", "$webSocketServerPidFile"
    );
    system "/usr/bin/python", @args;
    unlink "$webSocketServerPidFile";

    # wss is disabled until all platforms support pyOpenSSL.
    $isWebSocketServerOpen = 0;
}

sub fileNameWithNumber($$)
{
    my ($base, $number) = @_;
    return "$base$number" if ($number > 1);
    return $base;
}

sub processIgnoreTests($$)
{
    my @ignoreList = split(/\s*,\s*/, shift);
    my $listName = shift;

    my $disabledSuffix = "-disabled";

    my $addIgnoredDirectories = sub {
        return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
        $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)} = 1;
        return @_;
    };
    foreach my $item (@ignoreList) {
        my $path = catfile($testDirectory, $item); 
        if (-d $path) {
            $ignoredDirectories{$item} = 1;
            find({ preprocess => $addIgnoredDirectories, wanted => sub {} }, $path);
        }
        elsif (-f $path) {
            $ignoredFiles{$item} = 1;
        } elsif (-f $path . $disabledSuffix) {
            # The test is disabled, so do nothing.
        } else {
            print "$listName list contained '$item', but no file of that name could be found\n";
        }
    }
}

sub stripExtension($)
{
    my ($test) = @_;

    $test =~ s/\.[a-zA-Z]+$//;
    return $test;
}

sub isTextOnlyTest($)
{
    my ($actual) = @_;
    my $isText;
    if ($actual =~ /^layer at/ms) {
        $isText = 0;
    } else {
        $isText = 1;
    }
    return $isText;
}

sub expectedDirectoryForTest($;$;$)
{
    my ($base, $isText, $expectedExtension) = @_;

    my @directories = @platformResultHierarchy;
    push @directories, map { catdir($platformBaseDirectory, $_) } qw(mac-snowleopard mac) if isAppleWinWebKit();
    push @directories, $expectedDirectory;

    # If we already have expected results, just return their location.
    foreach my $directory (@directories) {
        return $directory if -f File::Spec->catfile($directory, "$base-$expectedTag.$expectedExtension");
    }

    # For cross-platform tests, text-only results should go in the cross-platform directory,
    # while render tree dumps should go in the least-specific platform directory.
    return $isText ? $expectedDirectory : $platformResultHierarchy[$#platformResultHierarchy];
}

sub countFinishedTest($$$$)
{
    my ($test, $base, $result, $isText) = @_;

    if (($count + 1) % $testsPerDumpTool == 0 || $count == $#tests) {
        if ($shouldCheckLeaks) {
            my $fileName;
            if ($testsPerDumpTool == 1) {
                $fileName = File::Spec->catfile($testResultsDirectory, "$base-leaks.txt");
            } else {
                $fileName = File::Spec->catfile($testResultsDirectory, fileNameWithNumber($dumpToolName, $leaksOutputFileNumber) . "-leaks.txt");
            }
            my $leakCount = countAndPrintLeaks($dumpToolName, $dumpToolPID, $fileName);
            $totalLeaks += $leakCount;
            $leaksOutputFileNumber++ if ($leakCount);
        }

        closeDumpTool();
    }
    
    $count++;
    $counts{$result}++;
    push @{$tests{$result}}, $test;
}

sub testCrashedOrTimedOut($$$$$$)
{
    my ($test, $base, $didCrash, $webProcessCrashed, $actual, $error) = @_;

    printFailureMessageForTest($test, $webProcessCrashed ? "Web process crashed" : $didCrash ? "crashed" : "timed out");

    sampleDumpTool() unless $didCrash || $webProcessCrashed;

    my $dir = dirname(File::Spec->catdir($testResultsDirectory, $base));
    mkpath $dir;

    deleteExpectedAndActualResults($base);

    if (defined($error) && length($error)) {
        writeToFile(File::Spec->catfile($testResultsDirectory, "$base-$errorTag.txt"), $error);
    }

    recordActualResultsAndDiff($base, $actual);

    kill 9, $dumpToolPID unless $didCrash;

    closeDumpTool();

    captureSavedCrashLog($base) if $didCrash;

    return unless isCygwin() && !$didCrash && $base =~ /^http/;
    # On Cygwin, http tests timing out can be a symptom of a non-responsive httpd.
    # If we timed out running an http test, try restarting httpd.
    $isHttpdOpen = !closeHTTPD();
    configureAndOpenHTTPDIfNeeded();
}

sub captureSavedCrashLog($)
{
    my ($base) = @_;

    my $crashLog;

    my $glob;
    if (isCygwin()) {
        $glob = File::Spec->catfile($testResultsDirectory, $windowsCrashLogFilePrefix . "*.txt");
    } elsif (isAppleMacWebKit()) {
        $glob = File::Spec->catfile("~", "Library", "Logs", "CrashReporter", $dumpToolName . "_*.crash");

        # Even though the dump tool has exited, CrashReporter might still be running. We need to
        # wait for it to exit to ensure it has saved its crash log to disk. For simplicitly, we'll
        # assume that the ReportCrash process with the highest PID is the one we want.
        if (my @reportCrashPIDs = sort map { /^\s*(\d+)/; $1 } grep { /ReportCrash/ } `/bin/ps x`) {
            my $reportCrashPID = $reportCrashPIDs[$#reportCrashPIDs];
            # We use kill instead of waitpid because ReportCrash is not one of our child processes.
            usleep(250000) while kill(0, $reportCrashPID) > 0;
        }
    }

    # We assume that the newest crash log in matching the glob is the one that corresponds to the crash that just occurred.
    if (my $newestCrashLog = findNewestFileMatchingGlob($glob)) {
        # The crash log must have been created after this script started running.
        $crashLog = $newestCrashLog if -M $newestCrashLog < 0;
    }

    return unless $crashLog;

    move($crashLog, File::Spec->catfile($testResultsDirectory, "$base-$crashLogTag.txt"));
}

sub findNewestFileMatchingGlob($)
{
    my ($glob) = @_;

    my @paths = glob $glob;
    return unless @paths;

    my @pathsAndTimes = map { [$_, -M $_] } @paths;
    @pathsAndTimes = sort { $b->[1] <=> $a->[1] } @pathsAndTimes;
    return $pathsAndTimes[$#pathsAndTimes]->[0];
}

sub printFailureMessageForTest($$)
{
    my ($test, $description) = @_;

    unless ($verbose) {
        print "\n" unless $atLineStart;
        print "$test -> ";
    }
    print "$description\n";
    $atLineStart = 1;
}

my %cygpaths = ();

sub openCygpathIfNeeded($)
{
    my ($options) = @_;

    return unless isCygwin();
    return $cygpaths{$options} if $cygpaths{$options} && $cygpaths{$options}->{"open"};

    local (*CYGPATHIN, *CYGPATHOUT);
    my $pid = open2(\*CYGPATHIN, \*CYGPATHOUT, "cygpath -f - $options");
    my $cygpath =  {
        "pid" => $pid,
        "in" => *CYGPATHIN,
        "out" => *CYGPATHOUT,
        "open" => 1
    };

    $cygpaths{$options} = $cygpath;

    return $cygpath;
}

sub closeCygpaths()
{
    return unless isCygwin();

    foreach my $cygpath (values(%cygpaths)) {
        close $cygpath->{"in"};
        close $cygpath->{"out"};
        waitpid($cygpath->{"pid"}, 0);
        $cygpath->{"open"} = 0;

    }
}

sub convertPathUsingCygpath($$)
{
    my ($path, $options) = @_;

    # cygpath -f (at least in Cygwin 1.7) converts spaces into newlines. We remove spaces here and
    # add them back in after conversion to work around this.
    my $spaceSubstitute = "__NOTASPACE__";
    $path =~ s/ /\Q$spaceSubstitute\E/g;

    my $cygpath = openCygpathIfNeeded($options);
    local *inFH = $cygpath->{"in"};
    local *outFH = $cygpath->{"out"};
    print outFH $path . "\n";
    my $convertedPath = <inFH>;
    chomp($convertedPath) if defined $convertedPath;

    $convertedPath =~ s/\Q$spaceSubstitute\E/ /g;
    return $convertedPath;
}

sub toCygwinPath($)
{
    my ($path) = @_;
    return unless isCygwin();

    return convertPathUsingCygpath($path, "-u");
}

sub toWindowsPath($)
{
    my ($path) = @_;
    return unless isCygwin();

    return convertPathUsingCygpath($path, "-w");
}

sub toURL($)
{
    my ($path) = @_;

    if ($useRemoteLinksToTests) {
        my $relativePath = File::Spec->abs2rel($path, $testDirectory);

        # If the file is below the test directory then convert it into a link to the file in SVN
        if ($relativePath !~ /^\.\.\//) {
            my $revision = svnRevisionForDirectory($testDirectory);
            my $svnPath = pathRelativeToSVNRepositoryRootForPath($path);
            return "http://trac.webkit.org/export/$revision/$svnPath";
        }
    }

    return $path unless isCygwin();

    return "file:///" . convertPathUsingCygpath($path, "-m");
}

sub validateSkippedArg($$;$)
{
    my ($option, $value, $value2) = @_;
    my %validSkippedValues = map { $_ => 1 } qw(default ignore only);
    $value = lc($value);
    die "Invalid argument '" . $value . "' for option $option" unless $validSkippedValues{$value};
    $treatSkipped = $value;
}

sub htmlForResultsSection(\@$&)
{
    my ($tests, $description, $linkGetter) = @_;

    my @html = ();
    return join("\n", @html) unless @{$tests};

    push @html, "<p>$description:</p>";
    push @html, "<table>";
    foreach my $test (@{$tests}) {
        push @html, "<tr>";
        push @html, "<td><a href=\"" . toURL("$testDirectory/$test") . "\">$test</a></td>";
        foreach my $link (@{&{$linkGetter}($test)}) {
            push @html, "<td>";
            push @html, "<a href=\"$link->{href}\">$link->{text}</a>" if -f File::Spec->catfile($testResultsDirectory, $link->{href});
            push @html, "</td>";
        }
        push @html, "</tr>";
    }
    push @html, "</table>";

    return join("\n", @html);
}

sub linksForExpectedAndActualResults($)
{
    my ($base) = @_;

    my @links = ();

    return \@links unless -s "$testResultsDirectory/$base-$diffsTag.txt";
    
    my $expectedResultPath = $expectedResultPaths{$base};
    my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});

    push @links, { href => "$base-$expectedTag$expectedResultExtension", text => "expected" };
    push @links, { href => "$base-$actualTag$expectedResultExtension", text => "actual" };
    push @links, { href => "$base-$diffsTag.txt", text => "diff" };
    push @links, { href => "$base-$prettyDiffTag.html", text => "pretty diff" };

    return \@links;
}

sub linksForMismatchTest
{
    my ($test) = @_;

    my @links = ();

    my $base = stripExtension($test);

    push @links, @{linksForExpectedAndActualResults($base)};
    return \@links unless $pixelTests && $imagesPresent{$base};

    push @links, { href => "$base-$expectedTag.png", text => "expected image" };
    push @links, { href => "$base-$diffsTag.html", text => "image diffs" };
    push @links, { href => "$base-$diffsTag.png", text => "$imageDifferences{$base}%" };

    return \@links;
}

sub crashLocation($)
{
    my ($base) = @_;

    my $crashLogFile = File::Spec->catfile($testResultsDirectory, "$base-$crashLogTag.txt");

    if (isCygwin()) {
        # We're looking for the following text:
        #
        # FOLLOWUP_IP:
        # module!function+offset [file:line]
        #
        # The second contains the function that crashed (or the function that ended up jumping to a bad
        # address, as in the case of a null function pointer).

        open LOG, "<", $crashLogFile or return;
        while (my $line = <LOG>) {
            last if $line =~ /^FOLLOWUP_IP:/;
        }
        my $desiredLine = <LOG>;
        close LOG;

        return unless $desiredLine;

        # Just take everything up to the first space (which is where the file/line information should
        # start).
        $desiredLine =~ /^(\S+)/;
        return $1;
    }

    if (isAppleMacWebKit()) {
        # We're looking for the following text:
        #
        # Thread M Crashed:
        # N   module                              address function + offset (file:line)
        #
        # Some lines might have a module of "???" if we've jumped to a bad address. We should skip
        # past those.

        open LOG, "<", $crashLogFile or return;
        while (my $line = <LOG>) {
            last if $line =~ /^Thread \d+ Crashed:/;
        }
        my $location;
        while (my $line = <LOG>) {
            $line =~ /^\d+\s+(\S+)\s+\S+ (.* \+ \d+)/ or next;
            my $module = $1;
            my $functionAndOffset = $2;
            next if $module eq "???";
            $location = "$module: $functionAndOffset";
            last;
        }
        close LOG;
        return $location;
    }
}

sub linksForErrorTest
{
    my ($test) = @_;

    my @links = ();

    my $base = stripExtension($test);

    my $crashLogText = "crash log";
    if (my $crashLocation = crashLocation($base)) {
        $crashLogText .= " (<code>" . $crashLocation . "</code>)";
    }

    push @links, @{linksForExpectedAndActualResults($base)};
    push @links, { href => "$base-$errorTag.txt", text => "stderr" };
    push @links, { href => "$base-$crashLogTag.txt", text => $crashLogText };

    return \@links;
}

sub linksForNewTest
{
    my ($test) = @_;

    my @links = ();

    my $base = stripExtension($test);

    my $expectedResultPath = $expectedResultPaths{$base};
    my ($expectedResultFileName, $expectedResultsDirectory, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});

    push @links, { href => "$base-$actualTag$expectedResultExtension", text => "result" };
    if ($pixelTests && $imagesPresent{$base}) {
        push @links, { href => "$base-$expectedTag.png", text => "image" };
    }

    return \@links;
}

sub deleteExpectedAndActualResults($)
{
    my ($base) = @_;

    unlink "$testResultsDirectory/$base-$actualTag.txt";
    unlink "$testResultsDirectory/$base-$diffsTag.txt";
    unlink "$testResultsDirectory/$base-$errorTag.txt";
    unlink "$testResultsDirectory/$base-$crashLogTag.txt";
}

sub recordActualResultsAndDiff($$)
{
    my ($base, $actualResults) = @_;

    return unless defined($actualResults) && length($actualResults);

    my $expectedResultPath = $expectedResultPaths{$base};
    my ($expectedResultFileNameMinusExtension, $expectedResultDirectoryPath, $expectedResultExtension) = fileparse($expectedResultPath, qr{\.[^.]+$});
    my $actualResultsPath = File::Spec->catfile($testResultsDirectory, "$base-$actualTag$expectedResultExtension");
    my $copiedExpectedResultsPath = File::Spec->catfile($testResultsDirectory, "$base-$expectedTag$expectedResultExtension");

    mkpath(dirname($actualResultsPath));
    writeToFile("$actualResultsPath", $actualResults);

    if (-f $expectedResultPath) {
        copy("$expectedResultPath", "$copiedExpectedResultsPath");
    } else {
        open EMPTY, ">$copiedExpectedResultsPath";
        close EMPTY;
    }

    my $diffOuputBasePath = File::Spec->catfile($testResultsDirectory, $base);
    my $diffOutputPath = "$diffOuputBasePath-$diffsTag.txt";
    system "diff -u \"$copiedExpectedResultsPath\" \"$actualResultsPath\" > \"$diffOutputPath\"";

    my $prettyDiffOutputPath = "$diffOuputBasePath-$prettyDiffTag.html";
    my $prettyPatchPath = "Websites/bugs.webkit.org/PrettyPatch/";
    my $prettifyPath = "$prettyPatchPath/prettify.rb";
    system "ruby -I \"$prettyPatchPath\" \"$prettifyPath\" \"$diffOutputPath\" > \"$prettyDiffOutputPath\"";
}

sub buildPlatformResultHierarchy()
{
    mkpath($platformTestDirectory) if ($platform eq "undefined" && !-d "$platformTestDirectory");

    my @platforms;
    
    my $isMac = $platform =~ /^mac/;
    my $isWin = $platform =~ /^win/;
    if ($isMac || $isWin) {
        my $effectivePlatform = $platform;
        if ($platform eq "mac-wk2" || $platform eq "win-wk2") {
            push @platforms, $platform;
            $effectivePlatform = $realPlatform;
        }

        my @platformList = $isMac ? @macPlatforms : @winPlatforms;
        my $i;
        for ($i = 0; $i < @platformList; $i++) {
            last if $platformList[$i] eq $effectivePlatform;
        }
        for (; $i < @platformList; $i++) {
            push @platforms, $platformList[$i];
        }
    } elsif ($platform =~ /^qt-/) {
        push @platforms, $platform;
        push @platforms, "qt";
    } else {
        @platforms = $platform;
    }

    my @hierarchy;
    for (my $i = 0; $i < @platforms; $i++) {
        my $scoped = catdir($platformBaseDirectory, $platforms[$i]);
        push(@hierarchy, $scoped) if (-d $scoped);
    }
    
    return @hierarchy;
}

sub buildPlatformTestHierarchy(@)
{
    my (@platformHierarchy) = @_;
    return @platformHierarchy if (@platformHierarchy < 2);
    if ($platformHierarchy[0] =~ /mac-wk2/) {
        return ($platformHierarchy[0], $platformHierarchy[1], $platformHierarchy[$#platformHierarchy]);
    }
    return ($platformHierarchy[0], $platformHierarchy[$#platformHierarchy]);
}

sub epiloguesAndPrologues($$)
{
    my ($lastDirectory, $directory) = @_;
    my @lastComponents = split('/', $lastDirectory);
    my @components = split('/', $directory);

    while (@lastComponents) {
        if (!defined($components[0]) || $lastComponents[0] ne $components[0]) {
            last;
        }
        shift @components;
        shift @lastComponents;
    }

    my @result;
    my $leaving = $lastDirectory;
    foreach (@lastComponents) {
        my $epilogue = $leaving . "/resources/run-webkit-tests-epilogue.html";
        foreach (@platformResultHierarchy) {
            push @result, catdir($_, $epilogue) if (stat(catdir($_, $epilogue)));
        }
        push @result, catdir($testDirectory, $epilogue) if (stat(catdir($testDirectory, $epilogue)));
        $leaving =~ s|(^\|/)[^/]+$||;
    }

    my $entering = $leaving;
    foreach (@components) {
        $entering .= '/' . $_;
        my $prologue = $entering . "/resources/run-webkit-tests-prologue.html";
        push @result, catdir($testDirectory, $prologue) if (stat(catdir($testDirectory, $prologue)));
        foreach (reverse @platformResultHierarchy) {
            push @result, catdir($_, $prologue) if (stat(catdir($_, $prologue)));
        }
    }
    return @result;
}
    
sub parseLeaksandPrintUniqueLeaks()
{
    return unless @leaksFilenames;
     
    my $mergedFilenames = join " ", @leaksFilenames;
    my $parseMallocHistoryTool = sourceDir() . "/Tools/Scripts/parse-malloc-history";
    
    open MERGED_LEAKS, "cat $mergedFilenames | $parseMallocHistoryTool --merge-depth $mergeDepth  - |" ;
    my @leakLines = <MERGED_LEAKS>;
    close MERGED_LEAKS;
    
    my $uniqueLeakCount = 0;
    my $totalBytes;
    foreach my $line (@leakLines) {
        ++$uniqueLeakCount if ($line =~ /^(\d*)\scalls/);
        $totalBytes = $1 if $line =~ /^total\:\s(.*)\s\(/;
    }
    
    print "\nWARNING: $totalLeaks total leaks found for a total of $totalBytes!\n";
    print "WARNING: $uniqueLeakCount unique leaks found!\n";
    print "See above for individual leaks results.\n" if ($leaksOutputFileNumber > 2);
    
}

sub extensionForMimeType($)
{
    my ($mimeType) = @_;

    if ($mimeType eq "application/x-webarchive") {
        return "webarchive";
    } elsif ($mimeType eq "application/pdf") {
        return "pdf";
    }
    return "txt";
}

# Read up to the first #EOF (the content block of the test), or until detecting crashes or timeouts.
sub readFromDumpToolWithTimer(**)
{
    my ($fhIn, $fhError) = @_;

    setFileHandleNonBlocking($fhIn, 1);
    setFileHandleNonBlocking($fhError, 1);

    my $maximumSecondsWithoutOutput = $timeoutSeconds;
    my $microsecondsToWaitBeforeReadingAgain = 1000;

    my $timeOfLastSuccessfulRead = time;

    my @output = ();
    my @error = ();
    my $status = "success";
    my $mimeType = "text/plain";
    # We don't have a very good way to know when the "headers" stop
    # and the content starts, so we use this as a hack:
    my $haveSeenContentType = 0;
    my $haveSeenEofIn = 0;
    my $haveSeenEofError = 0;

    while (1) {
        if (time - $timeOfLastSuccessfulRead > $maximumSecondsWithoutOutput) {
            $status = dumpToolDidCrash() ? "crashed" : "timedOut";
            last;
        }

        # Once we've seen the EOF, we must not read anymore.
        my $lineIn = readline($fhIn) unless $haveSeenEofIn;
        my $lineError = readline($fhError) unless $haveSeenEofError;
        if (!defined($lineIn) && !defined($lineError)) {
            last if ($haveSeenEofIn && $haveSeenEofError);

            if ($! != EAGAIN) {
                $status = "crashed";
                last;
            }

            # No data ready
            usleep($microsecondsToWaitBeforeReadingAgain);
            next;
        }

        $timeOfLastSuccessfulRead = time;

        if (defined($lineIn)) {
            if (!$haveSeenContentType && $lineIn =~ /^Content-Type: (\S+)$/) {
                $mimeType = $1;
                $haveSeenContentType = 1;
            } elsif ($lineIn =~ /#EOF/) {
                $haveSeenEofIn = 1;
            } else {
                push @output, $lineIn;
            }
        }
        if (defined($lineError)) {
            if ($lineError =~ /#CRASHED - WebProcess/) {
                $status = "webProcessCrashed";
                last;
            }
            if ($lineError =~ /#CRASHED/) {
                $status = "crashed";
                last;
            }
            if ($lineError =~ /#EOF/) {
                $haveSeenEofError = 1;
            } else {
                push @error, $lineError;
            }
        }
    }

    setFileHandleNonBlocking($fhIn, 0);
    setFileHandleNonBlocking($fhError, 0);
    return {
        output => join("", @output),
        error => join("", @error),
        status => $status,
        mimeType => $mimeType,
        extension => extensionForMimeType($mimeType)
    };
}

sub setFileHandleNonBlocking(*$)
{
    my ($fh, $nonBlocking) = @_;

    my $flags = fcntl($fh, F_GETFL, 0) or die "Couldn't get filehandle flags";

    if ($nonBlocking) {
        $flags |= O_NONBLOCK;
    } else {
        $flags &= ~O_NONBLOCK;
    }

    fcntl($fh, F_SETFL, $flags) or die "Couldn't set filehandle flags";

    return 1;
}

sub sampleDumpTool()
{
    return unless isAppleMacWebKit();
    return unless $runSample;

    my $outputDirectory = "$ENV{HOME}/Library/Logs/DumpRenderTree";
    -d $outputDirectory or mkdir $outputDirectory;

    my $outputFile = "$outputDirectory/HangReport.txt";
    system "/usr/bin/sample", $dumpToolPID, qw(10 10 -file), $outputFile;
}

sub stripMetrics($$)
{
    my ($actual, $expected) = @_;

    foreach my $result ($actual, $expected) {
        $result =~ s/at \(-?[0-9]+,-?[0-9]+\) *//g;
        $result =~ s/size -?[0-9]+x-?[0-9]+ *//g;
        $result =~ s/text run width -?[0-9]+: //g;
        $result =~ s/text run width -?[0-9]+ [a-zA-Z ]+: //g;
        $result =~ s/RenderButton {BUTTON} .*/RenderButton {BUTTON}/g;
        $result =~ s/RenderImage {INPUT} .*/RenderImage {INPUT}/g;
        $result =~ s/RenderBlock {INPUT} .*/RenderBlock {INPUT}/g;
        $result =~ s/RenderTextControl {INPUT} .*/RenderTextControl {INPUT}/g;
        $result =~ s/\([0-9]+px/px/g;
        $result =~ s/ *" *\n +" */ /g;
        $result =~ s/" +$/"/g;

        $result =~ s/- /-/g;
        $result =~ s/\n( *)"\s+/\n$1"/g;
        $result =~ s/\s+"\n/"\n/g;
        $result =~ s/scrollWidth [0-9]+/scrollWidth/g;
        $result =~ s/scrollHeight [0-9]+/scrollHeight/g;
    }

    return ($actual, $expected);
}

sub fileShouldBeIgnored
{
    my ($filePath) = @_;
    foreach my $ignoredDir (keys %ignoredDirectories) {
        if ($filePath =~ m/^$ignoredDir/) {
            return 1;
        }
    }
    return 0;
}

sub readSkippedFiles($)
{
    my ($constraintPath) = @_;

    my @skippedFileDirectories = @platformTestHierarchy;

    # Because nearly all of the skipped tests for WebKit 2 on Mac are due to
    # cross-platform issues, Windows will use both the Mac and Windows skipped
    # lists to avoid maintaining separate lists.
    push(@skippedFileDirectories, catdir($platformBaseDirectory, "mac-wk2")) if $platform eq "win-wk2";

    foreach my $level (@skippedFileDirectories) {
        if (open SKIPPED, "<", "$level/Skipped") {
            if ($verbose) {
                my ($dir, $name) = splitpath($level);
                print "Skipped tests in $name:\n";
            }

            while (<SKIPPED>) {
                my $skipped = $_;
                chomp $skipped;
                $skipped =~ s/^[ \n\r]+//;
                $skipped =~ s/[ \n\r]+$//;
                if ($skipped && $skipped !~ /^#/) {
                    if ($skippedOnly) {
                        if (!fileShouldBeIgnored($skipped)) {
                            if (!$constraintPath) {
                                # Always add $skipped since no constraint path was specified on the command line.
                                push(@ARGV, $skipped);
                            } elsif ($skipped =~ /^($constraintPath)/) {
                                # Add $skipped only if it matches the current path constraint, e.g.,
                                # "--skipped=only dir1" with "dir1/file1.html" on the skipped list.
                                push(@ARGV, $skipped);
                            } elsif ($constraintPath =~ /^($skipped)/) {
                                # Add current path constraint if it is more specific than the skip list entry,
                                # e.g., "--skipped=only dir1/dir2/dir3" with "dir1" on the skipped list.
                                push(@ARGV, $constraintPath);
                            }
                        } elsif ($verbose) {
                            print "    $skipped\n";
                        }
                    } else {
                        if ($verbose) {
                            print "    $skipped\n";
                        }
                        processIgnoreTests($skipped, "Skipped");
                    }
                }
            }
            close SKIPPED;
        }
    }
}

my @testsFound;

sub directoryFilter
{
    return () if exists $ignoredLocalDirectories{basename($File::Find::dir)};
    return () if exists $ignoredDirectories{File::Spec->abs2rel($File::Find::dir, $testDirectory)};
    return @_;
}

sub fileFilter
{
    my $filename = $_;
    if ($filename =~ /\.([^.]+)$/) {
        if (exists $supportedFileExtensions{$1}) {
            my $path = File::Spec->abs2rel(catfile($File::Find::dir, $filename), $testDirectory);
            push @testsFound, $path if !exists $ignoredFiles{$path};
        }
    }
}

sub findTestsToRun
{
    my @testsToRun = ();

    for my $test (@ARGV) {
        $test =~ s/^(\Q$layoutTestsName\E|\Q$testDirectory\E)\///;
        my $fullPath = catfile($testDirectory, $test);
        if (file_name_is_absolute($test)) {
            print "can't run test $test outside $testDirectory\n";
        } elsif (-f $fullPath) {
            my ($filename, $pathname, $fileExtension) = fileparse($test, qr{\.[^.]+$});
            if (!exists $supportedFileExtensions{substr($fileExtension, 1)}) {
                print "test $test does not have a supported extension\n";
            } elsif ($testHTTP || $pathname !~ /^http\//) {
                push @testsToRun, $test;
            }
        } elsif (-d $fullPath) {
            @testsFound = ();
            find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $fullPath);
            for my $level (@platformTestHierarchy) {
                my $platformPath = catfile($level, $test);
                find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $platformPath) if (-d $platformPath);
            }
            push @testsToRun, sort pathcmp @testsFound;
            @testsFound = ();
        } else {
            print "test $test not found\n";
        }
    }

    if (!scalar @ARGV) {
        @testsFound = ();
        find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $testDirectory);
        for my $level (@platformTestHierarchy) {
            find({ preprocess => \&directoryFilter, wanted => \&fileFilter }, $level);
        }
        push @testsToRun, sort pathcmp @testsFound;
        @testsFound = ();

        # We need to minimize the time when Apache and WebSocketServer is locked by tests
        # so run them last if no explicit order was specified in the argument list.
        my @httpTests;
        my @websocketTests;
        my @otherTests;
        foreach my $test (@testsToRun) {
            if ($test =~ /^http\//) {
                push(@httpTests, $test);
            } elsif ($test =~ /^websocket\//) {
                push(@websocketTests, $test);
            } else {
                push(@otherTests, $test);
            }
        }
        @testsToRun = (@otherTests, @httpTests, @websocketTests);
    }

    # Reverse the tests
    @testsToRun = reverse @testsToRun if $reverseTests;

    # Shuffle the array
    @testsToRun = shuffle(@testsToRun) if $randomizeTests;

    return @testsToRun;
}

sub printResults
{
    my %text = (
        match => "succeeded",
        mismatch => "had incorrect layout",
        new => "were new",
        timedout => "timed out",
        crash => "crashed",
        webProcessCrash => "Web process crashed",
        error => "had stderr output"
    );

    for my $type ("match", "mismatch", "new", "timedout", "crash", "webProcessCrash", "error") {
        my $typeCount = $counts{$type};
        next unless $typeCount;
        my $typeText = $text{$type};
        my $message;
        if ($typeCount == 1) {
            $typeText =~ s/were/was/;
            $message = sprintf "1 test case (%d%%) %s\n", 1 * 100 / $count, $typeText;
        } else {
            $message = sprintf "%d test cases (%d%%) %s\n", $typeCount, $typeCount * 100 / $count, $typeText;
        }
        $message =~ s-\(0%\)-(<1%)-;
        print $message;
    }
}

sub stopRunningTestsEarlyIfNeeded()
{
    # --reset-results does not check pass vs. fail, so exitAfterNFailures makes no sense with --reset-results.
    return 0 if $resetResults;

    my $passCount = $counts{match} || 0; # $counts{match} will be undefined if we've not yet passed a test (e.g. the first test fails).
    my $newCount = $counts{new} || 0;
    my $failureCount = $count - $passCount - $newCount; # "Failure" here includes timeouts, crashes, etc.
    if ($exitAfterNFailures && $failureCount >= $exitAfterNFailures) {
        print "\nExiting early after $failureCount failures. $count tests run.";
        closeDumpTool();
        return 1;
    }

    my $crashCount = $counts{crash} || 0;
    my $timeoutCount = $counts{timedout} || 0;
    if ($exitAfterNCrashesOrTimeouts && $crashCount + $timeoutCount >= $exitAfterNCrashesOrTimeouts) {
        print "\nExiting early after $crashCount crashes and $timeoutCount timeouts. $count tests run.";
        closeDumpTool();
        return 1;
    }

    return 0;
}

# Store this at global scope so it won't be GCed (and thus unlinked) until the program exits.
my $debuggerTempDirectory;

sub createDebuggerCommandFile()
{
    return unless isCygwin();

    my @commands = (
        '.logopen /t "' . toWindowsPath($testResultsDirectory) . "\\" . $windowsCrashLogFilePrefix . '.txt"',
        '.srcpath "' . toWindowsPath(sourceDir()) . '"',
        '!analyze -vv',
        '~*kpn',
        'q',
    );

    $debuggerTempDirectory = File::Temp->newdir;

    my $commandFile = File::Spec->catfile($debuggerTempDirectory, "debugger-commands.txt");
    unless (open COMMANDS, '>', $commandFile) {
        print "Failed to open $commandFile. Crash logs will not be saved.\n";
        return;
    }
    print COMMANDS join("\n", @commands), "\n";
    unless (close COMMANDS) {
        print "Failed to write to $commandFile. Crash logs will not be saved.\n";
        return;
    }

    return $commandFile;
}

sub setUpWindowsCrashLogSaving()
{
    return unless isCygwin();

    unless (defined $ENV{_NT_SYMBOL_PATH}) {
        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";
        return;
    }

    my $ntsdPath = File::Spec->catfile(toCygwinPath($ENV{PROGRAMFILES}), "Debugging Tools for Windows (x86)", "ntsd.exe");
    unless (-f $ntsdPath) {
        $ntsdPath = File::Spec->catfile(toCygwinPath($ENV{SYSTEMROOT}), "system32", "ntsd.exe");
        unless (-f $ntsdPath) {
            print STDERR "Can't find ntsd.exe. Crash logs will not be saved.\nSee <http://trac.webkit.org/wiki/BuildingOnWindows#GettingCrashLogs>.\n";
            return;
        }
    }

    # If we used -c (instead of -cf) we could pass the commands directly on the command line. But
    # when the commands include multiple quoted paths (e.g., for .logopen and .srcpath), Windows
    # fails to invoke the post-mortem debugger at all (perhaps due to a bug in Windows's command
    # line parsing). So we save the commands to a file instead and tell the debugger to execute them
    # using -cf.
    my $commandFile = createDebuggerCommandFile() or return;

    my @options = (
        '-p %ld',
        '-e %ld',
        '-g',
        '-lines',
        '-cf "' . toWindowsPath($commandFile) . '"',
    );

    my %values = (
        Debugger => '"' . toWindowsPath($ntsdPath) . '" ' . join(' ', @options),
        Auto => 1
    );

    foreach my $value (keys %values) {
        chomp($previousWindowsPostMortemDebuggerValues{$value} = `regtool get "$windowsPostMortemDebuggerKey/$value"`);
        my $result = system "regtool", "set", "-s", "$windowsPostMortemDebuggerKey/$value", $values{$value};
        next unless $result;

        print "Failed to set \"$windowsPostMortemDebuggerKey/$value\". Crash logs will not be saved.\nSee <http://trac.webkit.org/wiki/BuildingOnWindows#GettingCrashLogs>.\n";
        return;
    }

    print "Crash logs will be saved to $testResultsDirectory.\n";
}

END {
    return unless isCygwin();

    foreach my $value (keys %previousWindowsPostMortemDebuggerValues) {
        my $result = system "regtool", "set", "-s", "$windowsPostMortemDebuggerKey/$value", $previousWindowsPostMortemDebuggerValues{$value};
        !$result or print "Failed to restore \"$windowsPostMortemDebuggerKey/$value\" to its previous value \"$previousWindowsPostMortemDebuggerValues{$value}\"\n.";
    }
}