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