Add User Timing Experimental Feature
[WebKit-https.git] / Tools / DumpRenderTree / mac / DumpRenderTree.mm
1 /*
2  * Copyright (C) 2005-2016 Apple Inc. All rights reserved.
3  *           (C) 2007 Graham Dennis (graham.dennis@gmail.com)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #import "config.h"
31 #import "DumpRenderTree.h"
32
33 #import "AccessibilityController.h"
34 #import "DefaultPolicyDelegate.h"
35 #import "DumpRenderTreeDraggingInfo.h"
36 #import "DumpRenderTreePasteboard.h"
37 #import "DumpRenderTreeSpellChecker.h"
38 #import "DumpRenderTreeWindow.h"
39 #import "EditingDelegate.h"
40 #import "EventSendingController.h"
41 #import "FrameLoadDelegate.h"
42 #import "HistoryDelegate.h"
43 #import "JavaScriptThreading.h"
44 #import "MockGeolocationProvider.h"
45 #import "MockWebNotificationProvider.h"
46 #import "NavigationController.h"
47 #import "ObjCPlugin.h"
48 #import "ObjCPluginFunction.h"
49 #import "PixelDumpSupport.h"
50 #import "PolicyDelegate.h"
51 #import "ResourceLoadDelegate.h"
52 #import "TestOptions.h"
53 #import "TestRunner.h"
54 #import "UIDelegate.h"
55 #import "WebArchiveDumpSupport.h"
56 #import "WebCoreTestSupport.h"
57 #import "WorkQueue.h"
58 #import "WorkQueueItem.h"
59 #import <CoreFoundation/CoreFoundation.h>
60 #import <JavaScriptCore/TestRunnerUtils.h>
61 #import <WebCore/LogInitialization.h>
62 #import <WebKit/DOMElement.h>
63 #import <WebKit/DOMExtensions.h>
64 #import <WebKit/DOMRange.h>
65 #import <WebKit/WKRetainPtr.h>
66 #import <WebKit/WKString.h>
67 #import <WebKit/WKStringCF.h>
68 #import <WebKit/WebArchive.h>
69 #import <WebKit/WebBackForwardList.h>
70 #import <WebKit/WebCache.h>
71 #import <WebKit/WebCoreStatistics.h>
72 #import <WebKit/WebDataSourcePrivate.h>
73 #import <WebKit/WebDatabaseManagerPrivate.h>
74 #import <WebKit/WebDeviceOrientationProviderMock.h>
75 #import <WebKit/WebDocumentPrivate.h>
76 #import <WebKit/WebEditingDelegate.h>
77 #import <WebKit/WebFrameView.h>
78 #import <WebKit/WebHistory.h>
79 #import <WebKit/WebHistoryItemPrivate.h>
80 #import <WebKit/WebInspector.h>
81 #import <WebKit/WebKitNSStringExtras.h>
82 #import <WebKit/WebPluginDatabase.h>
83 #import <WebKit/WebPreferenceKeysPrivate.h>
84 #import <WebKit/WebPreferences.h>
85 #import <WebKit/WebPreferencesPrivate.h>
86 #import <WebKit/WebResourceLoadDelegate.h>
87 #import <WebKit/WebStorageManagerPrivate.h>
88 #import <WebKit/WebViewPrivate.h>
89 #import <WebKitSystemInterface.h>
90 #import <getopt.h>
91 #import <wtf/Assertions.h>
92 #import <wtf/FastMalloc.h>
93 #import <wtf/LoggingAccumulator.h>
94 #import <wtf/ObjcRuntimeExtras.h>
95 #import <wtf/RetainPtr.h>
96 #import <wtf/Threading.h>
97 #import <wtf/text/WTFString.h>
98
99 #if !PLATFORM(IOS)
100 #import <Carbon/Carbon.h>
101 #import <WebKit/WebDynamicScrollBarsView.h>
102 #endif
103
104 #if PLATFORM(IOS)
105 #import "DumpRenderTreeBrowserView.h"
106 #import "UIKitSPI.h"
107 #import <QuartzCore/QuartzCore.h>
108 #import <WebCore/CoreGraphicsSPI.h>
109 #import <WebKit/WAKWindow.h>
110 #import <WebKit/WebCoreThread.h>
111 #import <WebKit/WebCoreThreadRun.h>
112 #import <WebKit/WebDOMOperations.h>
113 #import <fcntl.h>
114 #endif
115
116 extern "C" {
117 #import <mach-o/getsect.h>
118 }
119
120 using namespace std;
121
122 #if !PLATFORM(IOS)
123 @interface DumpRenderTreeApplication : NSApplication
124 @end
125
126 @interface DumpRenderTreeEvent : NSEvent
127 @end
128 #else
129 @interface ScrollViewResizerDelegate : NSObject
130 @end
131
132 @implementation ScrollViewResizerDelegate
133 - (void)view:(UIWebDocumentView *)view didSetFrame:(CGRect)newFrame oldFrame:(CGRect)oldFrame asResultOfZoom:(BOOL)wasResultOfZoom
134 {
135     UIView *scrollView = [view superview];
136     while (![scrollView isKindOfClass:[UIWebScrollView class]])
137         scrollView = [scrollView superview];
138
139     ASSERT(scrollView && [scrollView isKindOfClass:[UIWebScrollView class]]);
140     const CGSize scrollViewSize = [scrollView bounds].size;
141     CGSize contentSize = newFrame.size;
142     contentSize.height = CGRound(max(CGRectGetMaxY(newFrame), scrollViewSize.height));
143     [(UIWebScrollView *)scrollView setContentSize:contentSize];
144 }
145 @end
146 #endif
147
148 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
149 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
150 @end
151
152 #if USE(APPKIT)
153 @interface NSSound ()
154 + (void)_setAlertType:(NSUInteger)alertType;
155 @end
156 #endif
157
158 @interface WebView ()
159 - (BOOL)_flushCompositingChanges;
160 @end
161
162 #if !PLATFORM(IOS)
163 @interface WebView (WebViewInternalForTesting)
164 - (WebCore::Frame*)_mainCoreFrame;
165 @end
166 #endif
167
168 static void runTest(const string& testURL);
169
170 // Deciding when it's OK to dump out the state is a bit tricky.  All these must be true:
171 // - There is no load in progress
172 // - There is no work queued up (see workQueue var, below)
173 // - waitToDump==NO.  This means either waitUntilDone was never called, or it was called
174 //       and notifyDone was called subsequently.
175 // Note that the call to notifyDone and the end of the load can happen in either order.
176
177 volatile bool done;
178
179 NavigationController* gNavigationController = nullptr;
180 RefPtr<TestRunner> gTestRunner;
181
182 WebFrame *mainFrame = nullptr;
183 // This is the topmost frame that is loading, during a given load, or nil when no load is 
184 // in progress.  Usually this is the same as the main frame, but not always.  In the case
185 // where a frameset is loaded, and then new content is loaded into one of the child frames,
186 // that child frame is the "topmost frame that is loading".
187 WebFrame *topLoadingFrame = nullptr; // !nil iff a load is in progress
188
189
190 CFMutableSetRef disallowedURLs= nullptr;
191 static CFRunLoopTimerRef waitToDumpWatchdog;
192
193 // Delegates
194 static FrameLoadDelegate *frameLoadDelegate;
195 static UIDelegate *uiDelegate;
196 static EditingDelegate *editingDelegate;
197 static ResourceLoadDelegate *resourceLoadDelegate;
198 static HistoryDelegate *historyDelegate;
199 PolicyDelegate *policyDelegate = nullptr;
200 DefaultPolicyDelegate *defaultPolicyDelegate = nullptr;
201 #if PLATFORM(IOS)
202 static ScrollViewResizerDelegate *scrollViewResizerDelegate;
203 #endif
204
205 static int dumpPixelsForAllTests;
206 static bool dumpPixelsForCurrentTest;
207 static int threaded;
208 static int dumpTree = YES;
209 static int useTimeoutWatchdog = YES;
210 static int forceComplexText;
211 static int useAcceleratedDrawing;
212 static int gcBetweenTests;
213 static int showWebView;
214 static int printTestCount;
215 static BOOL printSeparators;
216 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
217 static std::set<std::string> allowedHosts;
218
219 static WebHistoryItem *prevTestBFItem; // current b/f item at the end of the previous test
220
221 #if PLATFORM(IOS)
222 const CGRect layoutTestViewportRect = { {0, 0}, {static_cast<CGFloat>(TestRunner::viewWidth), static_cast<CGFloat>(TestRunner::viewHeight)} };
223 DumpRenderTreeBrowserView *gWebBrowserView = nil;
224 DumpRenderTreeWebScrollView *gWebScrollView = nil;
225 DumpRenderTreeWindow *gDrtWindow = nil;
226 #endif
227
228 #ifdef __OBJC2__
229 static void swizzleAllMethods(Class imposter, Class original)
230 {
231     unsigned int imposterMethodCount;
232     Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
233
234     unsigned int originalMethodCount;
235     Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
236
237     for (unsigned int i = 0; i < imposterMethodCount; i++) {
238         SEL imposterMethodName = method_getName(imposterMethods[i]);
239
240         // Attempt to add the method to the original class.  If it fails, the method already exists and we should
241         // instead exchange the implementations.
242         if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
243             continue;
244
245         unsigned int j = 0;
246         for (; j < originalMethodCount; j++) {
247             SEL originalMethodName = method_getName(originalMethods[j]);
248             if (sel_isEqual(imposterMethodName, originalMethodName))
249                 break;
250         }
251
252         // If class_addMethod failed above then the method must exist on the original class.
253         ASSERT(j < originalMethodCount);
254         method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
255     }
256
257     free(imposterMethods);
258     free(originalMethods);
259 }
260 #endif
261
262 static void poseAsClass(const char* imposter, const char* original)
263 {
264     Class imposterClass = objc_getClass(imposter);
265     Class originalClass = objc_getClass(original);
266
267 #ifndef __OBJC2__
268     class_poseAs(imposterClass, originalClass);
269 #else
270
271     // Swizzle instance methods
272     swizzleAllMethods(imposterClass, originalClass);
273     // and then class methods
274     swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
275 #endif
276 }
277
278 void setPersistentUserStyleSheetLocation(CFStringRef url)
279 {
280     persistentUserStyleSheetLocation = url;
281 }
282
283 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
284 {
285     static char* const ignoreSet[] = {
286         // Keeping this infrastructure around in case we ever need it again.
287     };
288     static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
289     
290     for (int i = 0; i < ignoreSetCount; i++) {
291         // FIXME: ignore case
292         string curIgnore(ignoreSet[i]);
293         // Match at the end of the URLString
294         if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
295             return true;
296     }
297     return false;
298 }
299
300 #if !PLATFORM(IOS)
301 static NSSet *allowedFontFamilySet()
302 {
303     static NSSet *fontFamilySet = [[NSSet setWithObjects:
304         @"Ahem",
305         @"Al Bayan",
306         @"American Typewriter",
307         @"Andale Mono",
308         @"Apple Braille",
309         @"Apple Color Emoji",
310         @"Apple Chancery",
311         @"Apple Garamond BT",
312         @"Apple LiGothic",
313         @"Apple LiSung",
314         @"Apple Symbols",
315         @"AppleGothic",
316         @"AppleMyungjo",
317         @"Arial Black",
318         @"Arial Hebrew",
319         @"Arial Narrow",
320         @"Arial Rounded MT Bold",
321         @"Arial Unicode MS",
322         @"Arial",
323         @"Avenir Next",
324         @"Ayuthaya",
325         @"Baghdad",
326         @"Baskerville",
327         @"BiauKai",
328         @"Big Caslon",
329         @"Brush Script MT",
330         @"Chalkboard",
331         @"Chalkduster",
332         @"Charcoal CY",
333         @"Cochin",
334         @"Comic Sans MS",
335         @"Copperplate",
336         @"Corsiva Hebrew",
337         @"Courier New",
338         @"Courier",
339         @"DecoType Naskh",
340         @"Devanagari MT",
341         @"Didot",
342         @"Euphemia UCAS",
343         @"Futura",
344         @"GB18030 Bitmap",
345         @"Geeza Pro",
346         @"Geneva CY",
347         @"Geneva",
348         @"Georgia",
349         @"Gill Sans",
350         @"Gujarati MT",
351         @"GungSeo",
352         @"Gurmukhi MT",
353         @"HeadLineA",
354         @"Hei",
355         @"Heiti SC",
356         @"Heiti TC",
357         @"Helvetica CY",
358         @"Helvetica Neue",
359         @"Helvetica",
360         @"Herculanum",
361         @"Hiragino Kaku Gothic Pro",
362         @"Hiragino Kaku Gothic ProN",
363         @"Hiragino Kaku Gothic Std",
364         @"Hiragino Kaku Gothic StdN",
365         @"Hiragino Maru Gothic Pro",
366         @"Hiragino Maru Gothic ProN",
367         @"Hiragino Mincho Pro",
368         @"Hiragino Mincho ProN",
369         @"Hiragino Sans GB",
370         @"Hoefler Text",
371         @"Impact",
372         @"InaiMathi",
373         @"Kai",
374         @"Kailasa",
375         @"Kokonor",
376         @"Krungthep",
377         @"KufiStandardGK",
378         @"LiHei Pro",
379         @"LiSong Pro",
380         @"Lucida Grande",
381         @"Marker Felt",
382         @"Menlo",
383         @"Microsoft Sans Serif",
384         @"Monaco",
385         @"Mshtakan",
386         @"Nadeem",
387         @"New Peninim MT",
388         @"Optima",
389         @"Osaka",
390         @"Papyrus",
391         @"PCMyungjo",
392         @"PilGi",
393         @"Plantagenet Cherokee",
394         @"Raanana",
395         @"Sathu",
396         @"Silom",
397         @"Skia",
398         @"Songti SC",
399         @"Songti TC",
400         @"STFangsong",
401         @"STHeiti",
402         @"STIXGeneral",
403         @"STIXSizeOneSym",
404         @"STKaiti",
405         @"STSong",
406         @"Symbol",
407         @"Tahoma",
408         @"Thonburi",
409         @"Times New Roman",
410         @"Times",
411         @"Trebuchet MS",
412         @"Verdana",
413         @"Webdings",
414         @"WebKit WeightWatcher",
415         @"FontWithFeaturesOTF",
416         @"FontWithFeaturesTTF",
417         @"Wingdings 2",
418         @"Wingdings 3",
419         @"Wingdings",
420         @"Zapf Dingbats",
421         @"Zapfino",
422         nil] retain];
423     
424     return fontFamilySet;
425 }
426
427 #if !ENABLE(PLATFORM_FONT_LOOKUP)
428 static IMP appKitAvailableFontFamiliesIMP;
429 static IMP appKitAvailableFontsIMP;
430
431 static NSArray *drt_NSFontManager_availableFontFamilies(id self, SEL _cmd)
432 {
433     static NSArray *availableFontFamilies;
434     if (availableFontFamilies)
435         return availableFontFamilies;
436     
437     NSArray *availableFamilies = wtfCallIMP<id>(appKitAvailableFontFamiliesIMP, self, _cmd);
438
439     NSMutableSet *prunedFamiliesSet = [NSMutableSet setWithArray:availableFamilies];
440     [prunedFamiliesSet intersectSet:allowedFontFamilySet()];
441
442     availableFontFamilies = [[prunedFamiliesSet allObjects] retain];
443     return availableFontFamilies;
444 }
445
446 static NSArray *drt_NSFontManager_availableFonts(id self, SEL _cmd)
447 {
448     static NSArray *availableFonts;
449     if (availableFonts)
450         return availableFonts;
451     
452     NSSet *allowedFamilies = allowedFontFamilySet();
453     NSMutableArray *availableFontList = [[NSMutableArray alloc] initWithCapacity:[allowedFamilies count] * 2];
454     for (NSString *fontFamily in allowedFontFamilySet()) {
455         NSArray* fontsForFamily = [[NSFontManager sharedFontManager] availableMembersOfFontFamily:fontFamily];
456         for (NSArray* fontInfo in fontsForFamily) {
457             // Font name is the first entry in the array.
458             [availableFontList addObject:[fontInfo objectAtIndex:0]];
459         }
460     }
461
462     availableFonts = availableFontList;
463     return availableFonts;
464 }
465
466 static void swizzleNSFontManagerMethods()
467 {
468     Method availableFontFamiliesMethod = class_getInstanceMethod(objc_getClass("NSFontManager"), @selector(availableFontFamilies));
469     ASSERT(availableFontFamiliesMethod);
470     if (!availableFontFamiliesMethod) {
471         NSLog(@"Failed to swizzle the \"availableFontFamilies\" method on NSFontManager");
472         return;
473     }
474     
475     appKitAvailableFontFamiliesIMP = method_setImplementation(availableFontFamiliesMethod, (IMP)drt_NSFontManager_availableFontFamilies);
476
477     Method availableFontsMethod = class_getInstanceMethod(objc_getClass("NSFontManager"), @selector(availableFonts));
478     ASSERT(availableFontsMethod);
479     if (!availableFontsMethod) {
480         NSLog(@"Failed to swizzle the \"availableFonts\" method on NSFontManager");
481         return;
482     }
483     
484     appKitAvailableFontsIMP = method_setImplementation(availableFontsMethod, (IMP)drt_NSFontManager_availableFonts);
485 }
486
487 #else
488
489 static NSArray *fontWhitelist()
490 {
491     static NSArray *availableFonts;
492     if (availableFonts)
493         return availableFonts;
494
495     NSMutableArray *availableFontList = [[NSMutableArray alloc] init];
496     for (NSString *fontFamily in allowedFontFamilySet()) {
497         NSArray* fontsForFamily = [[NSFontManager sharedFontManager] availableMembersOfFontFamily:fontFamily];
498         [availableFontList addObject:fontFamily];
499         for (NSArray* fontInfo in fontsForFamily) {
500             // Font name is the first entry in the array.
501             [availableFontList addObject:[fontInfo objectAtIndex:0]];
502         }
503     }
504
505     availableFonts = availableFontList;
506     return availableFonts;
507 }
508 #endif
509
510 // Activating system copies of these fonts overrides any others that could be preferred, such as ones
511 // in /Library/Fonts/Microsoft, and which don't always have the same metrics.
512 // FIXME: Switch to a solution from <rdar://problem/19553550> once it's available.
513 static void activateSystemCoreWebFonts()
514 {
515     NSArray *coreWebFontNames = @[
516         @"Andale Mono",
517         @"Arial",
518         @"Arial Black",
519         @"Comic Sans MS",
520         @"Courier New",
521         @"Georgia",
522         @"Impact",
523         @"Times New Roman",
524         @"Trebuchet MS",
525         @"Verdana",
526         @"Webdings"
527     ];
528
529     NSArray *fontFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL fileURLWithPath:@"/Library/Fonts" isDirectory:YES]
530         includingPropertiesForKeys:@[NSURLFileResourceTypeKey, NSURLNameKey] options:0 error:0];
531
532     for (NSURL *fontURL in fontFiles) {
533         NSString *resourceType;
534         NSString *fileName;
535         if (![fontURL getResourceValue:&resourceType forKey:NSURLFileResourceTypeKey error:0]
536             || ![fontURL getResourceValue:&fileName forKey:NSURLNameKey error:0])
537             continue;
538         if (![resourceType isEqualToString:NSURLFileResourceTypeRegular])
539             continue;
540
541         // Activate all font variations, such as Arial Bold Italic.ttf. This algorithm is not 100% precise, as it
542         // also activates e.g. Arial Unicode, which is not a variation of Arial.
543         for (NSString *coreWebFontName in coreWebFontNames) {
544             if ([fileName hasPrefix:coreWebFontName]) {
545                 CTFontManagerRegisterFontsForURL((CFURLRef)fontURL, kCTFontManagerScopeProcess, 0);
546                 break;
547             }
548         }
549     }
550 }
551
552 static void activateTestingFonts()
553 {
554     static const char* fontFileNames[] = {
555         "AHEM____.TTF",
556         "WebKitWeightWatcher100.ttf",
557         "WebKitWeightWatcher200.ttf",
558         "WebKitWeightWatcher300.ttf",
559         "WebKitWeightWatcher400.ttf",
560         "WebKitWeightWatcher500.ttf",
561         "WebKitWeightWatcher600.ttf",
562         "WebKitWeightWatcher700.ttf",
563         "WebKitWeightWatcher800.ttf",
564         "WebKitWeightWatcher900.ttf",
565         "FontWithFeatures.ttf",
566         "FontWithFeatures.otf",
567         0
568     };
569
570     NSMutableArray *fontURLs = [NSMutableArray array];
571     NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
572     for (unsigned i = 0; fontFileNames[i]; ++i) {
573         NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]]];
574         [fontURLs addObject:[fontURL absoluteURL]];
575     }
576
577     CFArrayRef errors = 0;
578     if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
579         NSLog(@"Failed to activate fonts: %@", errors);
580         CFRelease(errors);
581         exit(1);
582     }
583 }
584
585 static void adjustFonts()
586 {
587 #if !ENABLE(PLATFORM_FONT_LOOKUP)
588     swizzleNSFontManagerMethods();
589 #endif
590     activateSystemCoreWebFonts();
591     activateTestingFonts();
592 }
593 #else
594 static void activateFontIOS(const uint8_t* fontData, unsigned long length, std::string sectionName)
595 {
596     CGDataProviderRef data = CGDataProviderCreateWithData(nullptr, fontData, length, nullptr);
597     if (!data) {
598         fprintf(stderr, "Failed to create CGDataProviderRef for the %s font.\n", sectionName.c_str());
599         exit(1);
600     }
601
602     CGFontRef cgFont = CGFontCreateWithDataProvider(data);
603     CGDataProviderRelease(data);
604     if (!cgFont) {
605         fprintf(stderr, "Failed to create CGFontRef for the %s font.\n", sectionName.c_str());
606         exit(1);
607     }
608
609     CFErrorRef error = nullptr;
610     CTFontManagerRegisterGraphicsFont(cgFont, &error);
611     if (error) {
612         fprintf(stderr, "Failed to add CGFont to CoreText for the %s font: %s.\n", sectionName.c_str(), CFStringGetCStringPtr(CFErrorCopyDescription(error), kCFStringEncodingUTF8));
613         exit(1);
614     }
615     CGFontRelease(cgFont);
616 }
617
618 static void activateFontsIOS()
619 {
620     // __asm() requires a string literal, so we can't do this as either local variables or template parameters.
621 #define fontData(sectionName) \
622 { \
623     extern const uint8_t start##sectionName __asm("section$start$__DATA$" # sectionName); \
624     extern const uint8_t end##sectionName __asm("section$end$__DATA$" # sectionName); \
625     activateFontIOS(&start##sectionName, &end##sectionName - &start##sectionName, #sectionName); \
626 }
627     fontData(Ahem);
628     fontData(WeightWatcher100);
629     fontData(WeightWatcher200);
630     fontData(WeightWatcher300);
631     fontData(WeightWatcher400);
632     fontData(WeightWatcher500);
633     fontData(WeightWatcher600);
634     fontData(WeightWatcher700);
635     fontData(WeightWatcher800);
636     fontData(WeightWatcher900);
637     fontData(FWFTTF);
638     fontData(FWFOTF);
639 }
640 #endif // !PLATFORM(IOS)
641
642
643 #if PLATFORM(IOS)
644 static void adjustWebDocumentForFlexibleViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
645 {
646     // These values match MobileSafari's, see -[TabDocument _createDocumentView].
647     [webBrowserView setMinimumScale:0.25f forDocumentTypes:UIEveryDocumentMask];
648     [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
649     [webBrowserView setInitialScale:UIWebViewScalesToFitScale forDocumentTypes:UIEveryDocumentMask];
650     [webBrowserView setViewportSize:CGSizeMake(UIWebViewStandardViewportWidth, UIWebViewGrowsAndShrinksToFitHeight) forDocumentTypes:UIEveryDocumentMask];
651
652     // Adjust the viewport view and viewport to have similar behavior
653     // as the browser.
654     [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:YES];
655     [webBrowserView setDelegate:scrollViewResizerDelegate];
656
657     CGRect screenBounds = [UIScreen mainScreen].bounds;
658     CGRect viewportRect = CGRectMake(0, 0, screenBounds.size.width, screenBounds.size.height);
659
660     [scrollView setBounds:viewportRect];
661     [scrollView setFrame:viewportRect];
662
663     [webBrowserView setMinimumSize:viewportRect.size];
664     [webBrowserView setAutoresizes:YES];
665     [webBrowserView setFrame:screenBounds];
666
667     // This just affects text autosizing.
668     [mainFrame _setVisibleSize:CGSizeMake(screenBounds.size.width, screenBounds.size.height)];
669 }
670
671 static void adjustWebDocumentForStandardViewport(UIWebBrowserView *webBrowserView, UIWebScrollView *scrollView)
672 {
673     [webBrowserView setMinimumScale:1.0f forDocumentTypes:UIEveryDocumentMask];
674     [webBrowserView setMaximumScale:5.0f forDocumentTypes:UIEveryDocumentMask];
675     [webBrowserView setInitialScale:1.0f forDocumentTypes:UIEveryDocumentMask];
676
677     [(DumpRenderTreeBrowserView *)webBrowserView setScrollingUsesUIWebScrollView:NO];
678     [webBrowserView setDelegate: nil];
679
680     [scrollView setBounds:layoutTestViewportRect];
681     [scrollView setFrame:layoutTestViewportRect];
682
683     [webBrowserView setMinimumSize:layoutTestViewportRect.size];
684     [webBrowserView setAutoresizes:NO];
685     [webBrowserView setFrame:layoutTestViewportRect];
686
687     // This just affects text autosizing.
688     [mainFrame _setVisibleSize:CGSizeMake(layoutTestViewportRect.size.width, layoutTestViewportRect.size.height)];
689
690 }
691 #endif
692
693 #if !PLATFORM(IOS)
694 @interface DRTMockScroller : NSScroller
695 @end
696
697 @implementation DRTMockScroller
698
699 - (NSRect)rectForPart:(NSScrollerPart)partCode
700 {
701     if (partCode != NSScrollerKnob)
702         return [super rectForPart:partCode];
703
704     NSRect frameRect = [self frame];
705     NSRect bounds = [self bounds];
706     BOOL isHorizontal = frameRect.size.width > frameRect.size.height;
707     CGFloat trackLength = isHorizontal ? bounds.size.width : bounds.size.height;
708     CGFloat minKnobSize = isHorizontal ? bounds.size.height : bounds.size.width;
709     CGFloat knobLength = max(minKnobSize, static_cast<CGFloat>(round(trackLength * [self knobProportion])));
710     CGFloat knobPosition = static_cast<CGFloat>((round([self doubleValue] * (trackLength - knobLength))));
711     
712     if (isHorizontal)
713         return NSMakeRect(bounds.origin.x + knobPosition, bounds.origin.y, knobLength, bounds.size.height);
714
715     return NSMakeRect(bounds.origin.x, bounds.origin.y +  + knobPosition, bounds.size.width, knobLength);
716 }
717
718 - (void)drawKnob
719 {
720     if (![self isEnabled])
721         return;
722
723     NSRect knobRect = [self rectForPart:NSScrollerKnob];
724     
725     static NSColor *knobColor = [[NSColor colorWithDeviceRed:0x80 / 255.0 green:0x80 / 255.0 blue:0x80 / 255.0 alpha:1] retain];
726     [knobColor set];
727
728     NSRectFill(knobRect);
729 }
730
731 - (void)drawRect:(NSRect)dirtyRect
732 {
733     static NSColor *trackColor = [[NSColor colorWithDeviceRed:0xC0 / 255.0 green:0xC0 / 255.0 blue:0xC0 / 255.0 alpha:1] retain];
734     static NSColor *disabledTrackColor = [[NSColor colorWithDeviceRed:0xE0 / 255.0 green:0xE0 / 255.0 blue:0xE0 / 255.0 alpha:1] retain];
735
736     if ([self isEnabled])
737         [trackColor set];
738     else
739         [disabledTrackColor set];
740
741     NSRectFill(dirtyRect);
742     
743     [self drawKnob];
744 }
745
746 @end
747
748 static void registerMockScrollbars()
749 {
750     [WebDynamicScrollBarsView setCustomScrollerClass:[DRTMockScroller class]];
751 }
752 #endif
753
754 WebView *createWebViewAndOffscreenWindow()
755 {
756 #if !PLATFORM(IOS)
757     NSRect rect = NSMakeRect(0, 0, TestRunner::viewWidth, TestRunner::viewHeight);
758     WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
759 #else
760     DumpRenderTreeBrowserView *webBrowserView = [[[DumpRenderTreeBrowserView alloc] initWithFrame:layoutTestViewportRect] autorelease];
761     [webBrowserView setInputViewObeysDOMFocus:YES];
762     WebView *webView = [[webBrowserView webView] retain];
763     [webView setGroupName:@"org.webkit.DumpRenderTree"];
764 #endif
765
766     [webView setUIDelegate:uiDelegate];
767     [webView setFrameLoadDelegate:frameLoadDelegate];
768     [webView setEditingDelegate:editingDelegate];
769     [webView setResourceLoadDelegate:resourceLoadDelegate];
770     [webView _setGeolocationProvider:[MockGeolocationProvider shared]];
771     [webView _setDeviceOrientationProvider:[WebDeviceOrientationProviderMock shared]];
772     [webView _setNotificationProvider:[MockWebNotificationProvider shared]];
773
774     // Register the same schemes that Safari does
775     [WebView registerURLSchemeAsLocal:@"feed"];
776     [WebView registerURLSchemeAsLocal:@"feeds"];
777     [WebView registerURLSchemeAsLocal:@"feedsearch"];
778     
779 #if PLATFORM(MAC) && ENABLE(PLATFORM_FONT_LOOKUP)
780     [WebView _setFontWhitelist:fontWhitelist()];
781 #endif
782
783 #if !PLATFORM(IOS)
784     [webView setContinuousSpellCheckingEnabled:YES];
785     [webView setAutomaticQuoteSubstitutionEnabled:NO];
786     [webView setAutomaticLinkDetectionEnabled:NO];
787     [webView setAutomaticDashSubstitutionEnabled:NO];
788     [webView setAutomaticTextReplacementEnabled:NO];
789     [webView setAutomaticSpellingCorrectionEnabled:YES];
790     [webView setGrammarCheckingEnabled:YES];
791
792     [webView setDefersCallbacks:NO];
793     [webView setInteractiveFormValidationEnabled:YES];
794     [webView setValidationMessageTimerMagnification:-1];
795     
796     // To make things like certain NSViews, dragging, and plug-ins work, put the WebView a window, but put it off-screen so you don't see it.
797     // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
798     NSScreen *firstScreen = [[NSScreen screens] firstObject];
799     NSRect windowRect = (showWebView) ? NSOffsetRect(rect, 100, 100) : NSOffsetRect(rect, -10000, [firstScreen frame].size.height - rect.size.height + 10000);
800     DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
801
802     [window setColorSpace:[firstScreen colorSpace]];
803     [window setCollectionBehavior:NSWindowCollectionBehaviorStationary];
804     [[window contentView] addSubview:webView];
805     if (showWebView)
806         [window orderFront:nil];
807     else
808         [window orderBack:nil];
809     [window setAutodisplay:NO];
810
811     [window startListeningForAcceleratedCompositingChanges];
812 #else
813     DumpRenderTreeWindow *drtWindow = [[DumpRenderTreeWindow alloc] initWithLayer:[webBrowserView layer]];
814     [drtWindow setContentView:webView];
815     [webBrowserView setWAKWindow:drtWindow];
816
817     [[webView window] makeFirstResponder:[[[webView mainFrame] frameView] documentView]];
818
819     CGRect uiWindowRect = layoutTestViewportRect;
820     uiWindowRect.origin.y += [UIApp statusBarHeight];
821     UIWindow *uiWindow = [[[UIWindow alloc] initWithFrame:uiWindowRect] autorelease];
822
823     UIViewController *viewController = [[UIViewController alloc] init];
824     [uiWindow setRootViewController:viewController];
825     [viewController release];
826
827     // The UIWindow and UIWebBrowserView are released when the DumpRenderTreeWindow is closed.
828     drtWindow.uiWindow = uiWindow;
829     drtWindow.browserView = webBrowserView;
830
831     DumpRenderTreeWebScrollView *scrollView = [[DumpRenderTreeWebScrollView alloc] initWithFrame:layoutTestViewportRect];
832     [scrollView addSubview:webBrowserView];
833
834     [viewController.view addSubview:scrollView];
835     [scrollView release];
836
837     adjustWebDocumentForStandardViewport(webBrowserView, scrollView);
838 #endif
839     
840 #if !PLATFORM(IOS)
841     // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
842     // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
843     NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
844     [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
845 #else
846     [[webView preferences] _setTelephoneNumberParsingEnabled:NO];
847
848     // Initialize the global UIViews, and set the key UIWindow to be painted.
849     if (!gWebBrowserView) {
850         gWebBrowserView = [webBrowserView retain];
851         gWebScrollView = [scrollView retain];
852         gDrtWindow = [drtWindow retain];
853         [uiWindow makeKeyAndVisible];
854         [uiWindow retain];
855     }
856 #endif
857
858     [webView setMediaVolume:0];
859
860     return webView;
861 }
862
863 static void destroyWebViewAndOffscreenWindow(WebView *webView)
864 {
865     ASSERT(webView == [mainFrame webView]);
866 #if !PLATFORM(IOS)
867     NSWindow *window = [webView window];
868 #endif
869     [webView close];
870     mainFrame = nil;
871
872 #if !PLATFORM(IOS)
873     // Work around problem where registering drag types leaves an outstanding
874     // "perform selector" on the window, which retains the window. It's a bit
875     // inelegant and perhaps dangerous to just blow them all away, but in practice
876     // it probably won't cause any trouble (and this is just a test tool, after all).
877     [NSObject cancelPreviousPerformRequestsWithTarget:window];
878
879     [window close]; // releases when closed
880 #else
881     UIWindow *uiWindow = [gWebBrowserView window];
882     [uiWindow removeFromSuperview];
883     [uiWindow release];
884 #endif
885
886     [webView release];
887 }
888
889 static NSString *libraryPathForDumpRenderTree()
890 {
891     char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
892     if (dumpRenderTreeTemp)
893         return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
894     else
895         return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
896 }
897
898 static void enableExperimentalFeatures(WebPreferences* preferences)
899 {
900     [preferences setCSSGridLayoutEnabled:YES];
901     // FIXME: SpringTimingFunction
902     [preferences setGamepadsEnabled:YES];
903     [preferences setModernMediaControlsEnabled:YES];
904     // FIXME: InputEvents
905     [preferences setSubtleCryptoEnabled:YES];
906     [preferences setUserTimingEnabled:YES];
907     [preferences setWebAnimationsEnabled:YES];
908     [preferences setWebGL2Enabled:YES];
909 }
910
911 // Called before each test.
912 static void resetWebPreferencesToConsistentValues()
913 {
914     WebPreferences *preferences = [WebPreferences standardPreferences];
915     enableExperimentalFeatures(preferences);
916
917     [preferences setNeedsStorageAccessFromFileURLsQuirk: NO];
918     [preferences setAllowUniversalAccessFromFileURLs:YES];
919     [preferences setAllowFileAccessFromFileURLs:YES];
920     [preferences setStandardFontFamily:@"Times"];
921     [preferences setFixedFontFamily:@"Courier"];
922     [preferences setSerifFontFamily:@"Times"];
923     [preferences setSansSerifFontFamily:@"Helvetica"];
924     [preferences setCursiveFontFamily:@"Apple Chancery"];
925     [preferences setFantasyFontFamily:@"Papyrus"];
926     [preferences setPictographFontFamily:@"Apple Color Emoji"];
927     [preferences setDefaultFontSize:16];
928     [preferences setDefaultFixedFontSize:13];
929     [preferences setMinimumFontSize:0];
930     [preferences setDefaultTextEncodingName:@"ISO-8859-1"];
931     [preferences setJavaEnabled:NO];
932     [preferences setJavaScriptEnabled:YES];
933     [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
934 #if !PLATFORM(IOS)
935     [preferences setTabsToLinks:NO];
936 #endif
937     [preferences setDOMPasteAllowed:YES];
938 #if !PLATFORM(IOS)
939     [preferences setShouldPrintBackgrounds:YES];
940 #endif
941     [preferences setCacheModel:WebCacheModelDocumentBrowser];
942     [preferences setXSSAuditorEnabled:NO];
943     [preferences setExperimentalNotificationsEnabled:NO];
944     [preferences setPlugInsEnabled:YES];
945 #if !PLATFORM(IOS)
946     [preferences setTextAreasAreResizable:YES];
947 #endif
948
949     [preferences setPrivateBrowsingEnabled:NO];
950     [preferences setAuthorAndUserStylesEnabled:YES];
951     [preferences setShrinksStandaloneImagesToFit:YES];
952     [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
953     [preferences setJavaScriptCanAccessClipboard:YES];
954     [preferences setOfflineWebApplicationCacheEnabled:YES];
955     [preferences setDeveloperExtrasEnabled:NO];
956     [preferences setJavaScriptRuntimeFlags:WebKitJavaScriptRuntimeFlagsAllEnabled];
957     [preferences setLoadsImagesAutomatically:YES];
958     [preferences setLoadsSiteIconsIgnoringImageLoadingPreference:NO];
959     [preferences setFrameFlatteningEnabled:NO];
960     [preferences setSpatialNavigationEnabled:NO];
961     [preferences setMetaRefreshEnabled:YES];
962
963     if (persistentUserStyleSheetLocation) {
964         [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
965         [preferences setUserStyleSheetEnabled:YES];
966     } else
967         [preferences setUserStyleSheetEnabled:NO];
968     [preferences setMediaPlaybackAllowsInline:YES];
969     [preferences setVideoPlaybackRequiresUserGesture:NO];
970     [preferences setAudioPlaybackRequiresUserGesture:NO];
971     [preferences setMediaDataLoadsAutomatically:YES];
972     [preferences setInvisibleAutoplayNotPermitted:NO];
973
974 #if PLATFORM(IOS)
975     // Enable the tracker before creating the first WebView will
976     // cause initialization to use the correct database paths.
977     [preferences setStorageTrackerEnabled:YES];
978 #endif
979
980     [preferences _setTextAutosizingEnabled:NO];
981
982     // The back/forward cache is causing problems due to layouts during transition from one page to another.
983     // So, turn it off for now, but we might want to turn it back on some day.
984     [preferences setUsesPageCache:NO];
985     [preferences setAllowsPageCacheWithWindowOpener:NO];
986     [preferences setAcceleratedCompositingEnabled:YES];
987 #if USE(CA)
988     [preferences setCanvasUsesAcceleratedDrawing:YES];
989     [preferences setAcceleratedDrawingEnabled:useAcceleratedDrawing];
990 #endif
991     [preferences setUsePreHTML5ParserQuirks:NO];
992     [preferences setAsynchronousSpellCheckingEnabled:NO];
993 #if !PLATFORM(IOS)
994     ASSERT([preferences mockScrollbarsEnabled]);
995 #endif
996
997     [preferences setWebAudioEnabled:YES];
998     [preferences setMediaSourceEnabled:YES];
999
1000     [preferences setShadowDOMEnabled:YES];
1001     [preferences setCustomElementsEnabled:YES];
1002
1003     [preferences setWebGL2Enabled:YES];
1004
1005     [preferences setFetchAPIEnabled:YES];
1006
1007     [preferences setDownloadAttributeEnabled:YES];
1008
1009     [preferences setHiddenPageDOMTimerThrottlingEnabled:NO];
1010     [preferences setHiddenPageCSSAnimationSuspensionEnabled:NO];
1011     
1012     [preferences setMediaStreamEnabled:YES];
1013     [preferences setPeerConnectionEnabled:YES];
1014
1015     [WebPreferences _clearNetworkLoaderSession];
1016     [WebPreferences _setCurrentNetworkLoaderSessionCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
1017 }
1018
1019 static void setWebPreferencesForTestOptions(const TestOptions& options)
1020 {
1021     WebPreferences *preferences = [WebPreferences standardPreferences];
1022
1023     preferences.intersectionObserverEnabled = options.enableIntersectionObserver;
1024     preferences.modernMediaControlsEnabled = options.enableModernMediaControls;
1025 }
1026
1027 // Called once on DumpRenderTree startup.
1028 static void setDefaultsToConsistentValuesForTesting()
1029 {
1030 #if PLATFORM(IOS)
1031     WebThreadLock();
1032 #endif
1033
1034     static const int NoFontSmoothing = 0;
1035     static const int BlueTintedAppearance = 1;
1036
1037     NSString *libraryPath = libraryPathForDumpRenderTree();
1038
1039     NSDictionary *dict = @{
1040         @"AppleKeyboardUIMode": @1,
1041         @"AppleAntiAliasingThreshold": @4,
1042         @"AppleFontSmoothing": @(NoFontSmoothing),
1043         @"AppleAquaColorVariant": @(BlueTintedAppearance),
1044         @"AppleHighlightColor": @"0.709800 0.835300 1.000000",
1045         @"AppleOtherHighlightColor":@"0.500000 0.500000 0.500000",
1046         @"AppleLanguages": @[ @"en" ],
1047         WebKitEnableFullDocumentTeardownPreferenceKey: @YES,
1048         WebKitFullScreenEnabledPreferenceKey: @YES,
1049         WebKitAllowsInlineMediaPlaybackPreferenceKey: @YES,
1050         WebKitInlineMediaPlaybackRequiresPlaysInlineAttributeKey: @NO,
1051         @"UseWebKitWebInspector": @YES,
1052 #if !PLATFORM(IOS)
1053         @"NSPreferredSpellServerLanguage": @"en_US",
1054         @"NSUserDictionaryReplacementItems": @[],
1055         @"NSTestCorrectionDictionary": @{
1056             @"notationl": @"notational",
1057             @"mesage": @"message",
1058             @"wouldn": @"would",
1059             @"wellcome": @"welcome",
1060             @"hellolfworld": @"hello\nworld"
1061         },
1062 #endif
1063         @"AppleScrollBarVariant": @"DoubleMax",
1064 #if !PLATFORM(IOS)
1065         @"NSScrollAnimationEnabled": @NO,
1066 #endif
1067         @"NSOverlayScrollersEnabled": @NO,
1068         @"AppleShowScrollBars": @"Always",
1069         @"NSButtonAnimationsEnabled": @NO, // Ideally, we should find a way to test animations, but for now, make sure that the dumped snapshot matches actual state.
1070 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1071         @"AppleSystemFontOSSubversion": @(10),
1072 #endif
1073         @"NSWindowDisplayWithRunLoopObserver": @YES, // Temporary workaround, see <rdar://problem/20351297>.
1074         @"AppleEnableSwipeNavigateWithScrolls": @YES,
1075         @"com.apple.swipescrolldirection": @1,
1076     };
1077
1078     [[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:dict];
1079
1080 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1081     // Make NSFont use the new defaults.
1082     [NSFont initialize];
1083 #endif
1084
1085     NSDictionary *processInstanceDefaults = @{
1086         WebDatabaseDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"Databases"],
1087         WebStorageDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1088         WebKitLocalCacheDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalCache"],
1089         WebKitResourceLoadStatisticsDirectoryDefaultsKey: [libraryPath stringByAppendingPathComponent:@"LocalStorage"],
1090 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100 && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200
1091         // This needs to also be added to argument domain because of <rdar://problem/20210002>.
1092         @"AppleSystemFontOSSubversion": @(10),
1093 #endif
1094     };
1095
1096     [[NSUserDefaults standardUserDefaults] setVolatileDomain:processInstanceDefaults forName:NSArgumentDomain];
1097 }
1098
1099 static void runThread(void* arg)
1100 {
1101     static ThreadIdentifier previousId = 0;
1102     ThreadIdentifier currentId = currentThread();
1103     // Verify 2 successive threads do not get the same Id.
1104     ASSERT(previousId != currentId);
1105     previousId = currentId;
1106 }
1107
1108 static void* runPthread(void* arg)
1109 {
1110     runThread(arg);
1111     return 0;
1112 }
1113
1114 static void testThreadIdentifierMap()
1115 {
1116     // Imitate 'foreign' threads that are not created by WTF.
1117     pthread_t pthread;
1118     pthread_create(&pthread, 0, &runPthread, 0);
1119     pthread_join(pthread, 0);
1120
1121     pthread_create(&pthread, 0, &runPthread, 0);
1122     pthread_join(pthread, 0);
1123
1124     // Now create another thread using WTF. On OSX, it will have the same pthread handle
1125     // but should get a different ThreadIdentifier.
1126     createThread(runThread, 0, "DumpRenderTree: test");
1127 }
1128
1129 static void allocateGlobalControllers()
1130 {
1131     // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
1132     gNavigationController = [[NavigationController alloc] init];
1133     frameLoadDelegate = [[FrameLoadDelegate alloc] init];
1134     uiDelegate = [[UIDelegate alloc] init];
1135     editingDelegate = [[EditingDelegate alloc] init];
1136     resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
1137     policyDelegate = [[PolicyDelegate alloc] init];
1138     historyDelegate = [[HistoryDelegate alloc] init];
1139     defaultPolicyDelegate = [[DefaultPolicyDelegate alloc] init];
1140 #if PLATFORM(IOS)
1141     scrollViewResizerDelegate = [[ScrollViewResizerDelegate alloc] init];
1142 #endif
1143 }
1144
1145 // ObjC++ doens't seem to let me pass NSObject*& sadly.
1146 static inline void releaseAndZero(NSObject** object)
1147 {
1148     [*object release];
1149     *object = nil;
1150 }
1151
1152 static void releaseGlobalControllers()
1153 {
1154     releaseAndZero(&gNavigationController);
1155     releaseAndZero(&frameLoadDelegate);
1156     releaseAndZero(&editingDelegate);
1157     releaseAndZero(&resourceLoadDelegate);
1158     releaseAndZero(&uiDelegate);
1159     releaseAndZero(&policyDelegate);
1160 #if PLATFORM(IOS)
1161     releaseAndZero(&scrollViewResizerDelegate);
1162 #endif
1163 }
1164
1165 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
1166 {
1167     struct option options[] = {
1168         {"notree", no_argument, &dumpTree, NO},
1169         {"pixel-tests", no_argument, &dumpPixelsForAllTests, YES},
1170         {"tree", no_argument, &dumpTree, YES},
1171         {"threaded", no_argument, &threaded, YES},
1172         {"complex-text", no_argument, &forceComplexText, YES},
1173         {"accelerated-drawing", no_argument, &useAcceleratedDrawing, YES},
1174         {"gc-between-tests", no_argument, &gcBetweenTests, YES},
1175         {"no-timeout", no_argument, &useTimeoutWatchdog, NO},
1176         {"allowed-host", required_argument, nullptr, 'a'},
1177         {"show-webview", no_argument, &showWebView, YES},
1178         {"print-test-count", no_argument, &printTestCount, YES},
1179         {nullptr, 0, nullptr, 0}
1180     };
1181     
1182     int option;
1183     while ((option = getopt_long(argc, (char * const *)argv, "", options, nullptr)) != -1) {
1184         switch (option) {
1185             case '?':   // unknown or ambiguous option
1186             case ':':   // missing argument
1187                 exit(1);
1188                 break;
1189             case 'a': // "allowed-host"
1190                 allowedHosts.insert(optarg);
1191                 break;
1192         }
1193     }
1194 }
1195
1196 static void addTestPluginsToPluginSearchPath(const char* executablePath)
1197 {
1198 #if !PLATFORM(IOS)
1199     NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
1200     [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
1201     [[WebPluginDatabase sharedDatabase] refresh];
1202 #endif
1203 }
1204
1205 static bool useLongRunningServerMode(int argc, const char *argv[])
1206 {
1207     // This assumes you've already called getopt_long
1208     return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
1209 }
1210
1211 static void runTestingServerLoop()
1212 {
1213     // When DumpRenderTree run in server mode, we just wait around for file names
1214     // to be passed to us and read each in turn, passing the results back to the client
1215     char filenameBuffer[2048];
1216     unsigned testCount = 0;
1217     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1218         char *newLineCharacter = strchr(filenameBuffer, '\n');
1219         if (newLineCharacter)
1220             *newLineCharacter = '\0';
1221
1222         if (strlen(filenameBuffer) == 0)
1223             continue;
1224
1225         runTest(filenameBuffer);
1226
1227         if (printTestCount) {
1228             ++testCount;
1229             printf("\nServer mode has completed %u tests.\n\n", testCount);
1230         }
1231     }
1232 }
1233
1234 static void prepareConsistentTestingEnvironment()
1235 {
1236 #if !PLATFORM(IOS)
1237     poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
1238     poseAsClass("DumpRenderTreeEvent", "NSEvent");
1239 #else
1240     poseAsClass("DumpRenderTreeEvent", "GSEvent");
1241 #endif
1242
1243     [[WebPreferences standardPreferences] setAutosaves:NO];
1244
1245     // +[WebPreferences _switchNetworkLoaderToNewTestingSession] calls +[NSURLCache sharedURLCache], which initializes a default cache on disk.
1246     // Making the shared cache memory-only avoids touching the file system.
1247     RetainPtr<NSURLCache> sharedCache =
1248         adoptNS([[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
1249                                       diskCapacity:0
1250                                           diskPath:nil]);
1251     [NSURLCache setSharedURLCache:sharedCache.get()];
1252
1253     [WebPreferences _switchNetworkLoaderToNewTestingSession];
1254
1255 #if !PLATFORM(IOS)
1256     adjustFonts();
1257     registerMockScrollbars();
1258
1259     // The mock scrollbars setting cannot be modified after creating a view, so we have to do it now.
1260     [[WebPreferences standardPreferences] setMockScrollbarsEnabled:YES];
1261 #else
1262     activateFontsIOS();
1263 #endif
1264     
1265     allocateGlobalControllers();
1266     
1267 #if PLATFORM(MAC)
1268     NSActivityOptions options = (NSActivityUserInitiatedAllowingIdleSystemSleep | NSActivityLatencyCritical) & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled);
1269     static id assertion = [[[NSProcessInfo processInfo] beginActivityWithOptions:options reason:@"DumpRenderTree should not be subject to process suppression"] retain];
1270     ASSERT_UNUSED(assertion, assertion);
1271 #endif
1272 }
1273
1274 const char crashedMessage[] = "#CRASHED\n";
1275
1276 void writeCrashedMessageOnFatalError(int signalCode)
1277 {
1278     // Reset the default action for the signal so that we run ReportCrash(8) on pending and
1279     // subsequent instances of the signal.
1280     signal(signalCode, SIG_DFL);
1281
1282     // WRITE(2) and FSYNC(2) are considered safe to call from a signal handler by SIGACTION(2).
1283     write(STDERR_FILENO, &crashedMessage[0], sizeof(crashedMessage) - 1);
1284     fsync(STDERR_FILENO);
1285 }
1286
1287 void dumpRenderTree(int argc, const char *argv[])
1288 {
1289 #if PLATFORM(IOS)
1290     const char* identifier = getenv("IPC_IDENTIFIER");
1291     const char *stdinPath = [[NSString stringWithFormat:@"/tmp/%s_IN", identifier] UTF8String];
1292     const char *stdoutPath = [[NSString stringWithFormat:@"/tmp/%s_OUT", identifier] UTF8String];
1293     const char *stderrPath = [[NSString stringWithFormat:@"/tmp/%s_ERROR", identifier] UTF8String];
1294
1295     int infd = open(stdinPath, O_RDWR);
1296     dup2(infd, STDIN_FILENO);
1297     int outfd = open(stdoutPath, O_RDWR);
1298     dup2(outfd, STDOUT_FILENO);
1299     int errfd = open(stderrPath, O_RDWR | O_NONBLOCK);
1300     dup2(errfd, STDERR_FILENO);
1301 #endif
1302
1303     signal(SIGILL, &writeCrashedMessageOnFatalError);
1304     signal(SIGFPE, &writeCrashedMessageOnFatalError);
1305     signal(SIGBUS, &writeCrashedMessageOnFatalError);
1306     signal(SIGSEGV, &writeCrashedMessageOnFatalError);
1307
1308     initializeGlobalsFromCommandLineOptions(argc, argv);
1309     prepareConsistentTestingEnvironment();
1310     addTestPluginsToPluginSearchPath(argv[0]);
1311
1312     if (forceComplexText)
1313         [WebView _setAlwaysUsesComplexTextCodePath:YES];
1314
1315 #if USE(APPKIT)
1316     [NSSound _setAlertType:0];
1317 #endif
1318
1319     WebView *webView = createWebViewAndOffscreenWindow();
1320     mainFrame = [webView mainFrame];
1321
1322     [[NSURLCache sharedURLCache] removeAllCachedResponses];
1323     [WebCache empty];
1324
1325     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
1326     [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
1327
1328     // http://webkit.org/b/32689
1329     testThreadIdentifierMap();
1330
1331     if (threaded)
1332         startJavaScriptThreads();
1333
1334     if (useLongRunningServerMode(argc, argv)) {
1335         printSeparators = YES;
1336         runTestingServerLoop();
1337     } else {
1338         printSeparators = optind < argc - 1;
1339         for (int i = optind; i != argc; ++i)
1340             runTest(argv[i]);
1341     }
1342
1343     if (threaded)
1344         stopJavaScriptThreads();
1345
1346     destroyWebViewAndOffscreenWindow(webView);
1347     
1348     releaseGlobalControllers();
1349     
1350 #if !PLATFORM(IOS)
1351     [DumpRenderTreePasteboard releaseLocalPasteboards];
1352 #endif
1353
1354     // FIXME: This should be moved onto TestRunner and made into a HashSet
1355     if (disallowedURLs) {
1356         CFRelease(disallowedURLs);
1357         disallowedURLs = 0;
1358     }
1359
1360 #if PLATFORM(IOS)
1361     close(infd);
1362     close(outfd);
1363     close(errfd);
1364 #endif
1365 }
1366
1367 #if PLATFORM(IOS)
1368 static int _argc;
1369 static const char **_argv;
1370
1371 @implementation DumpRenderTree
1372
1373 - (void)_runDumpRenderTree
1374 {
1375     dumpRenderTree(_argc, _argv);
1376 }
1377
1378 - (void)applicationDidFinishLaunching:(NSNotification *)notification
1379 {
1380     [self performSelectorOnMainThread:@selector(_runDumpRenderTree) withObject:nil waitUntilDone:NO];
1381 }
1382
1383 - (void)applicationDidEnterBackground:(UIApplication *)application
1384 {
1385     RELEASE_ASSERT_NOT_REACHED();
1386 }
1387
1388 - (void)_webThreadEventLoopHasRun
1389 {
1390     ASSERT(!WebThreadIsCurrent());
1391     _hasFlushedWebThreadRunQueue = YES;
1392 }
1393
1394 - (void)_webThreadInvoked
1395 {
1396     ASSERT(WebThreadIsCurrent());
1397     dispatch_async(dispatch_get_main_queue(), ^{
1398         [self _webThreadEventLoopHasRun];
1399     });
1400 }
1401
1402 // The test can end in response to a delegate callback while there are still methods queued on the Web Thread.
1403 // If we do not ensure the Web Thread has been run, the callback can be done on a WebView that no longer exists.
1404 // To avoid this, _waitForWebThread dispatches a call to the WebThread event loop, actively processing the delegate
1405 // callbacks in the main thread while waiting for the call to be invoked on the Web Thread.
1406 - (void)_waitForWebThread
1407 {
1408     ASSERT(!WebThreadIsCurrent());
1409     _hasFlushedWebThreadRunQueue = NO;
1410     WebThreadRun(^{
1411         [self _webThreadInvoked];
1412     });
1413     while (!_hasFlushedWebThreadRunQueue) {
1414         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1415         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1416         [pool release];
1417     }
1418 }
1419
1420 @end
1421 #endif
1422
1423 static bool returningFromMain = false;
1424
1425 void atexitFunction()
1426 {
1427     if (returningFromMain)
1428         return;
1429
1430     NSLog(@"DumpRenderTree is exiting unexpectedly. Generating a crash log.");
1431     __builtin_trap();
1432 }
1433
1434 int DumpRenderTreeMain(int argc, const char *argv[])
1435 {
1436     atexit(atexitFunction);
1437
1438 #if PLATFORM(IOS)
1439     _UIApplicationLoadWebKit();
1440 #endif
1441     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1442
1443     setDefaultsToConsistentValuesForTesting(); // Must be called before NSApplication initialization.
1444
1445 #if !PLATFORM(IOS)
1446     [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
1447
1448     dumpRenderTree(argc, argv);
1449 #else
1450     _argc = argc;
1451     _argv = argv;
1452     UIApplicationMain(argc, (char**)argv, @"DumpRenderTree", @"DumpRenderTree");
1453 #endif
1454     [WebCoreStatistics garbageCollectJavaScriptObjects];
1455     [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
1456     JSC::finalizeStatsAtEndOfTesting();
1457     [pool release];
1458     returningFromMain = true;
1459     return 0;
1460 }
1461
1462 static NSInteger compareHistoryItems(id item1, id item2, void *context)
1463 {
1464     return [[item1 target] caseInsensitiveCompare:[item2 target]];
1465 }
1466
1467 static NSData *dumpAudio()
1468 {
1469     const vector<char>& dataVector = gTestRunner->audioResult();
1470     
1471     NSData *data = [NSData dataWithBytes:dataVector.data() length:dataVector.size()];
1472     return data;
1473 }
1474
1475 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
1476 {
1477     int start = 0;
1478     if (current) {
1479         printf("curr->");
1480         start = 6;
1481     }
1482     for (int i = start; i < indent; i++)
1483         putchar(' ');
1484     
1485     NSString *urlString = [item URLString];
1486     if ([[NSURL URLWithString:urlString] isFileURL]) {
1487         NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
1488         urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
1489     }
1490     
1491     printf("%s", [urlString UTF8String]);
1492     NSString *target = [item target];
1493     if (target && [target length] > 0)
1494         printf(" (in frame \"%s\")", [target UTF8String]);
1495     if ([item isTargetItem])
1496         printf("  **nav target**");
1497     putchar('\n');
1498     NSArray *kids = [item children];
1499     if (kids) {
1500         // must sort to eliminate arbitrary result ordering which defeats reproducible testing
1501         kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
1502         for (unsigned i = 0; i < [kids count]; i++)
1503             dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
1504     }
1505 }
1506
1507 static void dumpFrameScrollPosition(WebFrame *f)
1508 {
1509     WebScriptObject* scriptObject = [f windowObject];
1510     NSPoint scrollPosition = NSMakePoint(
1511         [[scriptObject valueForKey:@"pageXOffset"] floatValue],
1512         [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
1513     if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
1514         if ([f parentFrame] != nil)
1515             printf("frame '%s' ", [[f name] UTF8String]);
1516         printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
1517     }
1518
1519     if (gTestRunner->dumpChildFrameScrollPositions()) {
1520         NSArray *kids = [f childFrames];
1521         if (kids)
1522             for (unsigned i = 0; i < [kids count]; i++)
1523                 dumpFrameScrollPosition([kids objectAtIndex:i]);
1524     }
1525 }
1526
1527 static NSString *dumpFramesAsText(WebFrame *frame)
1528 {
1529     DOMDocument *document = [frame DOMDocument];
1530     DOMElement *documentElement = [document documentElement];
1531
1532     if (!documentElement)
1533         return @"";
1534
1535     NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
1536
1537     // Add header for all but the main frame.
1538     if ([frame parentFrame])
1539         result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
1540
1541     NSString *innerText = [documentElement innerText];
1542     // We use WKStringGetUTF8CStringNonStrict() to convert innerText to a WK String since
1543     // WKStringGetUTF8CStringNonStrict() can handle dangling surrogates and the NSString
1544     // conversion methods cannot. After the conversion to a buffer, we turn that buffer into
1545     // a CFString via fromUTF8WithLatin1Fallback().createCFString() which can be appended to
1546     // the result without any conversion.
1547     WKRetainPtr<WKStringRef> stringRef(AdoptWK, WKStringCreateWithCFString((CFStringRef)innerText));
1548     size_t bufferSize = WKStringGetMaximumUTF8CStringSize(stringRef.get());
1549     auto buffer = std::make_unique<char[]>(bufferSize);
1550     size_t stringLength = WKStringGetUTF8CStringNonStrict(stringRef.get(), buffer.get(), bufferSize);
1551     [result appendFormat:@"%@\n", String::fromUTF8WithLatin1Fallback(buffer.get(), stringLength - 1).createCFString().get()];
1552
1553     if (gTestRunner->dumpChildFramesAsText()) {
1554         NSArray *kids = [frame childFrames];
1555         if (kids) {
1556             for (unsigned i = 0; i < [kids count]; i++)
1557                 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
1558         }
1559     }
1560
1561     return result;
1562 }
1563
1564 static NSData *dumpFrameAsPDF(WebFrame *frame)
1565 {
1566 #if !PLATFORM(IOS)
1567     if (!frame)
1568         return nil;
1569
1570     // Sadly we have to dump to a file and then read from that file again
1571     // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
1572     // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
1573     // The goal of this function is to test "real" printing across multiple pages.
1574     // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
1575     NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
1576
1577     NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
1578     [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
1579     [printInfoDict setObject:path forKey:NSPrintSavePath];
1580
1581     NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
1582     [printInfo setHorizontalPagination:NSAutoPagination];
1583     [printInfo setVerticalPagination:NSAutoPagination];
1584     [printInfo setVerticallyCentered:NO];
1585
1586     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
1587     [printOperation setShowPanels:NO];
1588     [printOperation runOperation];
1589
1590     [printInfo release];
1591
1592     NSData *pdfData = [NSData dataWithContentsOfFile:path];
1593     [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
1594
1595     return pdfData;
1596 #else
1597     return nil;
1598 #endif
1599 }
1600
1601 static void dumpBackForwardListForWebView(WebView *view)
1602 {
1603     printf("\n============== Back Forward List ==============\n");
1604     WebBackForwardList *bfList = [view backForwardList];
1605
1606     // Print out all items in the list after prevTestBFItem, which was from the previous test
1607     // Gather items from the end of the list, the print them out from oldest to newest
1608     NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
1609     for (int i = [bfList forwardListCount]; i > 0; i--) {
1610         WebHistoryItem *item = [bfList itemAtIndex:i];
1611         // something is wrong if the item from the last test is in the forward part of the b/f list
1612         assert(item != prevTestBFItem);
1613         [itemsToPrint addObject:item];
1614     }
1615             
1616     assert([bfList currentItem] != prevTestBFItem);
1617     [itemsToPrint addObject:[bfList currentItem]];
1618     int currentItemIndex = [itemsToPrint count] - 1;
1619
1620     for (int i = -1; i >= -[bfList backListCount]; i--) {
1621         WebHistoryItem *item = [bfList itemAtIndex:i];
1622         if (item == prevTestBFItem)
1623             break;
1624         [itemsToPrint addObject:item];
1625     }
1626
1627     for (int i = [itemsToPrint count]-1; i >= 0; i--)
1628         dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
1629
1630     [itemsToPrint release];
1631     printf("===============================================\n");
1632 }
1633
1634 #if !PLATFORM(IOS)
1635 static void changeWindowScaleIfNeeded(const char* testPathOrUR)
1636 {
1637     WTF::String localPathOrUrl = String(testPathOrUR);
1638     float currentScaleFactor = [[[mainFrame webView] window] backingScaleFactor];
1639     float requiredScaleFactor = 1;
1640     if (localPathOrUrl.findIgnoringCase("/hidpi-3x-") != notFound)
1641         requiredScaleFactor = 3;
1642     else if (localPathOrUrl.findIgnoringCase("/hidpi-") != notFound)
1643         requiredScaleFactor = 2;
1644     if (currentScaleFactor == requiredScaleFactor)
1645         return;
1646     // When the new scale factor is set on the window first, WebView doesn't see it as a new scale and stops propagating the behavior change to WebCore::Page.
1647     gTestRunner->setBackingScaleFactor(requiredScaleFactor);
1648     [[[mainFrame webView] window] _setWindowResolution:requiredScaleFactor displayIfChanged:YES];
1649 }
1650 #endif
1651
1652 static void sizeWebViewForCurrentTest()
1653 {
1654     [uiDelegate resetWindowOrigin];
1655
1656     // W3C SVG tests expect to be 480x360
1657     bool isSVGW3CTest = (gTestRunner->testURL().find("svg/W3C-SVG-1.1") != string::npos);
1658     if (isSVGW3CTest)
1659         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::w3cSVGViewWidth, TestRunner::w3cSVGViewHeight)];
1660     else
1661         [[mainFrame webView] setFrameSize:NSMakeSize(TestRunner::viewWidth, TestRunner::viewHeight)];
1662 }
1663
1664 static const char *methodNameStringForFailedTest()
1665 {
1666     const char *errorMessage;
1667     if (gTestRunner->dumpAsText())
1668         errorMessage = "[documentElement innerText]";
1669     else if (gTestRunner->dumpDOMAsWebArchive())
1670         errorMessage = "[[mainFrame DOMDocument] webArchive]";
1671     else if (gTestRunner->dumpSourceAsWebArchive())
1672         errorMessage = "[[mainFrame dataSource] webArchive]";
1673     else
1674         errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
1675
1676     return errorMessage;
1677 }
1678
1679 static void dumpBackForwardListForAllWindows()
1680 {
1681     CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
1682     unsigned count = CFArrayGetCount(openWindows);
1683     for (unsigned i = 0; i < count; i++) {
1684         NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
1685 #if !PLATFORM(IOS)
1686         WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1687 #else
1688         ASSERT([[window contentView] isKindOfClass:[WebView class]]);
1689         WebView *webView = (WebView *)[window contentView];
1690 #endif
1691         dumpBackForwardListForWebView(webView);
1692     }
1693 }
1694
1695 static void invalidateAnyPreviousWaitToDumpWatchdog()
1696 {
1697     if (waitToDumpWatchdog) {
1698         CFRunLoopTimerInvalidate(waitToDumpWatchdog);
1699         CFRelease(waitToDumpWatchdog);
1700         waitToDumpWatchdog = 0;
1701     }
1702 }
1703
1704 void setWaitToDumpWatchdog(CFRunLoopTimerRef timer)
1705 {
1706     ASSERT(timer);
1707     ASSERT(shouldSetWaitToDumpWatchdog());
1708     waitToDumpWatchdog = timer;
1709     CFRunLoopAddTimer(CFRunLoopGetCurrent(), waitToDumpWatchdog, kCFRunLoopCommonModes);
1710 }
1711
1712 bool shouldSetWaitToDumpWatchdog()
1713 {
1714     return !waitToDumpWatchdog && useTimeoutWatchdog;
1715 }
1716
1717 static void updateDisplay()
1718 {
1719     WebView *webView = [mainFrame webView];
1720 #if PLATFORM(IOS)
1721     [gWebBrowserView layoutIfNeeded]; // Re-enables tile painting, which was disabled when committing the frame load.
1722     [gDrtWindow layoutTilesNow];
1723     [webView _flushCompositingChanges];
1724 #else
1725     if ([webView _isUsingAcceleratedCompositing])
1726         [webView display];
1727     else
1728         [webView displayIfNeeded];
1729 #endif
1730 }
1731
1732 void dump()
1733 {
1734 #if PLATFORM(IOS)
1735     WebThreadLock();
1736 #endif
1737
1738     updateDisplay();
1739
1740     invalidateAnyPreviousWaitToDumpWatchdog();
1741     ASSERT(!gTestRunner->hasPendingWebNotificationClick());
1742
1743     if (dumpTree) {
1744         NSString *resultString = nil;
1745         NSData *resultData = nil;
1746         NSString *resultMimeType = @"text/plain";
1747
1748         if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
1749             gTestRunner->setDumpAsText(true);
1750             gTestRunner->setGeneratePixelResults(false);
1751         }
1752         if (gTestRunner->dumpAsAudio()) {
1753             resultData = dumpAudio();
1754             resultMimeType = @"audio/wav";
1755         } else if (gTestRunner->dumpAsText()) {
1756             resultString = dumpFramesAsText(mainFrame);
1757         } else if (gTestRunner->dumpAsPDF()) {
1758             resultData = dumpFrameAsPDF(mainFrame);
1759             resultMimeType = @"application/pdf";
1760         } else if (gTestRunner->dumpDOMAsWebArchive()) {
1761             WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
1762             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1763             resultMimeType = @"application/x-webarchive";
1764         } else if (gTestRunner->dumpSourceAsWebArchive()) {
1765             WebArchive *webArchive = [[mainFrame dataSource] webArchive];
1766             resultString = CFBridgingRelease(WebCoreTestSupport::createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
1767             resultMimeType = @"application/x-webarchive";
1768         } else
1769             resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gTestRunner->isPrinting()];
1770
1771         if (resultString && !resultData)
1772             resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
1773
1774         printf("Content-Type: %s\n", [resultMimeType UTF8String]);
1775
1776         WTF::FastMallocStatistics mallocStats = WTF::fastMallocStatistics();
1777         printf("DumpMalloc: %li\n", mallocStats.committedVMBytes);
1778
1779         if (gTestRunner->dumpAsAudio())
1780             printf("Content-Length: %lu\n", static_cast<unsigned long>([resultData length]));
1781
1782         if (resultData) {
1783             fwrite([resultData bytes], 1, [resultData length], stdout);
1784
1785             if (!gTestRunner->dumpAsText() && !gTestRunner->dumpDOMAsWebArchive() && !gTestRunner->dumpSourceAsWebArchive() && !gTestRunner->dumpAsAudio())
1786                 dumpFrameScrollPosition(mainFrame);
1787
1788             if (gTestRunner->dumpBackForwardList())
1789                 dumpBackForwardListForAllWindows();
1790         } else
1791             printf("ERROR: nil result from %s", methodNameStringForFailedTest());
1792
1793         // Stop the watchdog thread before we leave this test to make sure it doesn't
1794         // fire in between tests causing the next test to fail.
1795         // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
1796         invalidateAnyPreviousWaitToDumpWatchdog();
1797
1798         if (printSeparators)
1799             puts("#EOF");       // terminate the content block
1800     }
1801
1802     if (dumpPixelsForCurrentTest && gTestRunner->generatePixelResults())
1803         // FIXME: when isPrinting is set, dump the image with page separators.
1804         dumpWebViewAsPixelsAndCompareWithExpected(gTestRunner->expectedPixelHash());
1805
1806     puts("#EOF");   // terminate the (possibly empty) pixels block
1807     fflush(stdout);
1808
1809     done = YES;
1810     CFRunLoopStop(CFRunLoopGetMain());
1811 }
1812
1813 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
1814 {
1815     return strstr(pathOrURL, "loading/");
1816 }
1817
1818 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1819 {
1820     return strstr(pathOrURL, "globalhistory/");
1821 }
1822
1823 static bool shouldDumpAsText(const char* pathOrURL)
1824 {
1825     return strstr(pathOrURL, "dumpAsText/");
1826 }
1827
1828 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1829 {
1830     return true;
1831 }
1832
1833 #if PLATFORM(IOS)
1834 static bool shouldMakeViewportFlexible(const char* pathOrURL)
1835 {
1836     return strstr(pathOrURL, "viewport/") && !strstr(pathOrURL, "visual-viewport/");
1837 }
1838 #endif
1839
1840 static void resetWebViewToConsistentStateBeforeTesting(const TestOptions& options)
1841 {
1842     WebView *webView = [mainFrame webView];
1843 #if PLATFORM(IOS)
1844     adjustWebDocumentForStandardViewport(gWebBrowserView, gWebScrollView);
1845     [webView _setAllowsMessaging:YES];
1846 #endif
1847     [webView setEditable:NO];
1848     [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1849     [webView makeTextStandardSize:nil];
1850     [webView resetPageZoom:nil];
1851     [webView _scaleWebView:1.0 atOrigin:NSZeroPoint];
1852 #if !PLATFORM(IOS)
1853     [webView _setCustomBackingScaleFactor:0];
1854 #endif
1855     [webView setTabKeyCyclesThroughElements:YES];
1856     [webView setPolicyDelegate:defaultPolicyDelegate];
1857     [policyDelegate setPermissive:NO];
1858     [policyDelegate setControllerToNotifyDone:0];
1859     [frameLoadDelegate resetToConsistentState];
1860 #if !PLATFORM(IOS)
1861     [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1862 #endif
1863     [webView _clearMainFrameName];
1864     [[webView undoManager] removeAllActions];
1865     [WebView _removeAllUserContentFromGroup:[webView groupName]];
1866 #if !PLATFORM(IOS)
1867     [[webView window] setAutodisplay:NO];
1868 #endif
1869     [webView setTracksRepaints:NO];
1870
1871     [WebCache clearCachedCredentials];
1872     
1873     resetWebPreferencesToConsistentValues();
1874     setWebPreferencesForTestOptions(options);
1875
1876     TestRunner::setSerializeHTTPLoads(false);
1877     TestRunner::setAllowsAnySSLCertificate(false);
1878
1879     setlocale(LC_ALL, "");
1880
1881     if (gTestRunner) {
1882         WebCoreTestSupport::resetInternalsObject([mainFrame globalContext]);
1883         // in the case that a test using the chrome input field failed, be sure to clean up for the next test
1884         gTestRunner->removeChromeInputField();
1885     }
1886
1887 #if !PLATFORM(IOS)
1888     if (WebCore::Frame* frame = [webView _mainCoreFrame])
1889         WebCoreTestSupport::clearWheelEventTestTrigger(*frame);
1890 #endif
1891
1892 #if !PLATFORM(IOS)
1893     [webView setContinuousSpellCheckingEnabled:YES];
1894     [webView setAutomaticQuoteSubstitutionEnabled:NO];
1895     [webView setAutomaticLinkDetectionEnabled:NO];
1896     [webView setAutomaticDashSubstitutionEnabled:NO];
1897     [webView setAutomaticTextReplacementEnabled:NO];
1898     [webView setAutomaticSpellingCorrectionEnabled:YES];
1899     [webView setGrammarCheckingEnabled:YES];
1900
1901     [WebView _setUsesTestModeFocusRingColor:YES];
1902 #endif
1903     [WebView _resetOriginAccessWhitelists];
1904
1905     [[MockGeolocationProvider shared] stopTimer];
1906     [[MockWebNotificationProvider shared] reset];
1907     
1908 #if !PLATFORM(IOS)
1909     // Clear the contents of the general pasteboard
1910     [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1911 #endif
1912
1913     [mainFrame _clearOpener];
1914
1915     setSpellCheckerLoggingEnabled(false);
1916
1917     resetAccumulatedLogs();
1918     WebCoreTestSupport::initializeLogChannelsIfNecessary();
1919 }
1920
1921 #if PLATFORM(IOS)
1922 // Work around <rdar://problem/9909073> WebKit's method of calling delegates on
1923 // the main thread is not thread safe. If the web thread is attempting to call
1924 // out to a delegate method on the main thread, we want to spin the main thread
1925 // run loop until the delegate method completes before taking the web thread
1926 // lock to prevent potentially re-entering WebCore.
1927 static void WebThreadLockAfterDelegateCallbacksHaveCompleted()
1928 {
1929     dispatch_semaphore_t delegateSemaphore = dispatch_semaphore_create(0);
1930     WebThreadRun(^{
1931         dispatch_semaphore_signal(delegateSemaphore);
1932     });
1933
1934     while (dispatch_semaphore_wait(delegateSemaphore, DISPATCH_TIME_NOW)) {
1935         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1936         [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1937         [pool release];
1938     }
1939
1940     WebThreadLock();
1941     
1942     dispatch_release(delegateSemaphore);
1943 }
1944 #endif
1945
1946 static NSURL *computeTestURL(NSString *pathOrURLString, NSString **relativeTestPath)
1947 {
1948     *relativeTestPath = nil;
1949
1950     if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"] || [pathOrURLString hasPrefix:@"file://"])
1951         return [NSURL URLWithString:pathOrURLString];
1952
1953     NSString *absolutePath = [[[NSURL fileURLWithPath:pathOrURLString] absoluteURL] path];
1954
1955     NSRange layoutTestsRange = [absolutePath rangeOfString:@"/LayoutTests/"];
1956     if (layoutTestsRange.location == NSNotFound)
1957         return [NSURL fileURLWithPath:absolutePath];
1958
1959     *relativeTestPath = [absolutePath substringFromIndex:NSMaxRange(layoutTestsRange)];
1960
1961     // Convert file URLs in LayoutTests/http/tests to HTTP URLs, except for file URLs in LayoutTests/http/tests/local.
1962
1963     NSRange httpTestsRange = [absolutePath rangeOfString:@"/LayoutTests/http/tests/"];
1964     if (httpTestsRange.location == NSNotFound || [absolutePath rangeOfString:@"/LayoutTests/http/tests/local/"].location != NSNotFound)
1965         return [NSURL fileURLWithPath:absolutePath];
1966
1967     auto components = adoptNS([[NSURLComponents alloc] init]);
1968     [components setPath:[absolutePath substringFromIndex:NSMaxRange(httpTestsRange) - 1]];
1969     [components setHost:@"127.0.0.1"];
1970
1971     // Paths under /ssl/ should be loaded using HTTPS.
1972     BOOL isSecure = [[components path] hasPrefix:@"/ssl/"];
1973     if (isSecure) {
1974         [components setScheme:@"https"];
1975         [components setPort:@(8443)];
1976     } else {
1977         [components setScheme:@"http"];
1978         [components setPort:@(8000)];
1979     }
1980
1981     return [components URL];
1982 }
1983
1984 static void runTest(const string& inputLine)
1985 {
1986     ASSERT(!inputLine.empty());
1987
1988     TestCommand command = parseInputLine(inputLine);
1989     const string& pathOrURL = command.pathOrURL;
1990     dumpPixelsForCurrentTest = command.shouldDumpPixels || dumpPixelsForAllTests;
1991
1992     NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1993     if (!pathOrURLString) {
1994         fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1995         return;
1996     }
1997
1998     NSString *testPath;
1999     NSURL *url = computeTestURL(pathOrURLString, &testPath);
2000     if (!url) {
2001         fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
2002         return;
2003     }
2004     if (!testPath)
2005         testPath = [url absoluteString];
2006
2007     NSString *informationString = [@"CRASHING TEST: " stringByAppendingString:testPath];
2008     WKSetCrashReportApplicationSpecificInformation((CFStringRef)informationString);
2009
2010     TestOptions options(url, command);
2011     resetWebViewToConsistentStateBeforeTesting(options);
2012
2013     const char* testURL([[url absoluteString] UTF8String]);
2014
2015 #if !PLATFORM(IOS)
2016     changeWindowScaleIfNeeded(testURL);
2017 #endif
2018
2019     gTestRunner = TestRunner::create(testURL, command.expectedPixelHash);
2020     gTestRunner->setAllowedHosts(allowedHosts);
2021     gTestRunner->setCustomTimeout(command.timeout);
2022     gTestRunner->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr);
2023     topLoadingFrame = nil;
2024 #if !PLATFORM(IOS)
2025     ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
2026     releaseAndZero(&draggingInfo);
2027 #endif
2028     done = NO;
2029
2030     sizeWebViewForCurrentTest();
2031     gTestRunner->setIconDatabaseEnabled(false);
2032     gTestRunner->clearAllApplicationCaches();
2033
2034     if (disallowedURLs)
2035         CFSetRemoveAllValues(disallowedURLs);
2036     if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
2037         gTestRunner->setDumpFrameLoadCallbacks(true);
2038
2039     if (shouldLogHistoryDelegates(pathOrURL.c_str()))
2040         [[mainFrame webView] setHistoryDelegate:historyDelegate];
2041     else
2042         [[mainFrame webView] setHistoryDelegate:nil];
2043
2044     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2045         gTestRunner->setDeveloperExtrasEnabled(true);
2046         if (shouldDumpAsText(pathOrURL.c_str())) {
2047             gTestRunner->setDumpAsText(true);
2048             gTestRunner->setGeneratePixelResults(false);
2049         }
2050     }
2051
2052 #if PLATFORM(IOS)
2053     if (shouldMakeViewportFlexible(pathOrURL.c_str()))
2054         adjustWebDocumentForFlexibleViewport(gWebBrowserView, gWebScrollView);
2055 #endif
2056
2057     if ([WebHistory optionalSharedHistory])
2058         [WebHistory setOptionalSharedHistory:nil];
2059
2060     lastMousePosition = NSZeroPoint;
2061     lastClickPosition = NSZeroPoint;
2062
2063     [prevTestBFItem release];
2064     prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
2065
2066     auto& workQueue = WorkQueue::singleton();
2067     workQueue.clear();
2068     workQueue.setFrozen(false);
2069
2070     bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
2071     if (ignoreWebCoreNodeLeaks)
2072         [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
2073
2074     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2075     [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
2076     [pool release];
2077
2078     while (!done) {
2079         pool = [[NSAutoreleasePool alloc] init];
2080         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
2081         [pool release];
2082     }
2083
2084 #if PLATFORM(IOS)
2085     [(DumpRenderTree *)UIApp _waitForWebThread];
2086     WebThreadLockAfterDelegateCallbacksHaveCompleted();
2087 #endif
2088     pool = [[NSAutoreleasePool alloc] init];
2089     [EventSendingController clearSavedEvents];
2090     [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
2091
2092     workQueue.clear();
2093
2094     // If the test page could have possibly opened the Web Inspector frontend,
2095     // then try to close it in case it was accidentally left open.
2096     if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
2097         gTestRunner->closeWebInspector();
2098         gTestRunner->setDeveloperExtrasEnabled(false);
2099     }
2100
2101     if (gTestRunner->closeRemainingWindowsWhenComplete()) {
2102         NSArray* array = [DumpRenderTreeWindow openWindows];
2103
2104         unsigned count = [array count];
2105         for (unsigned i = 0; i < count; i++) {
2106             NSWindow *window = [array objectAtIndex:i];
2107
2108             // Don't try to close the main window
2109             if (window == [[mainFrame webView] window])
2110                 continue;
2111             
2112 #if !PLATFORM(IOS)
2113             WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
2114 #else
2115             ASSERT([[window contentView] isKindOfClass:[WebView class]]);
2116             WebView *webView = (WebView *)[window contentView];
2117 #endif
2118
2119             [webView close];
2120             [window close];
2121         }
2122     }
2123
2124     resetWebViewToConsistentStateBeforeTesting(options);
2125
2126     // Loading an empty request synchronously replaces the document with a blank one, which is necessary
2127     // to stop timers, WebSockets and other activity that could otherwise spill output into next test's results.
2128     [mainFrame loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
2129
2130     [pool release];
2131
2132     // We should only have our main window left open when we're done
2133     ASSERT(CFArrayGetCount(openWindowsRef) == 1);
2134     ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
2135
2136     gTestRunner->cleanup();
2137     gTestRunner = nullptr;
2138
2139     if (ignoreWebCoreNodeLeaks)
2140         [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
2141
2142     if (gcBetweenTests)
2143         [WebCoreStatistics garbageCollectJavaScriptObjects];
2144
2145     fputs("#EOF\n", stderr);
2146     fflush(stderr);
2147 }
2148
2149 void displayWebView()
2150 {
2151 #if !PLATFORM(IOS)
2152     WebView *webView = [mainFrame webView];
2153     [webView display];
2154
2155     // FIXME: Tracking repaints is not specific to Mac. We should enable such support on iOS.
2156     [webView setTracksRepaints:YES];
2157     [webView resetTrackedRepaints];
2158 #else
2159     [gDrtWindow layoutTilesNow];
2160     [gDrtWindow setNeedsDisplayInRect:[gDrtWindow frame]];
2161     [CATransaction flush];
2162 #endif
2163 }
2164
2165 #if !PLATFORM(IOS)
2166 @implementation DumpRenderTreeEvent
2167
2168 + (NSPoint)mouseLocation
2169 {
2170     return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
2171 }
2172
2173 @end
2174
2175 @implementation DumpRenderTreeApplication
2176
2177 - (BOOL)isRunning
2178 {
2179     // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running
2180     return YES;
2181 }
2182
2183 @end
2184 #endif