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