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