2 * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
3 * (C) 2007 Graham Dennis (graham.dennis@gmail.com)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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 Computer, 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.
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.
31 #import "DumpRenderTree.h"
33 #import "AccessibilityController.h"
34 #import "CheckedMalloc.h"
35 #import "DumpRenderTreeDraggingInfo.h"
36 #import "DumpRenderTreePasteboard.h"
37 #import "DumpRenderTreeWindow.h"
38 #import "EditingDelegate.h"
39 #import "EventSendingController.h"
40 #import "FrameLoadDelegate.h"
41 #import "HistoryDelegate.h"
42 #import "JavaScriptThreading.h"
43 #import "LayoutTestController.h"
44 #import "MockGeolocationProvider.h"
45 #import "NavigationController.h"
46 #import "ObjCPlugin.h"
47 #import "ObjCPluginFunction.h"
48 #import "PixelDumpSupport.h"
49 #import "PolicyDelegate.h"
50 #import "ResourceLoadDelegate.h"
51 #import "StorageTrackerDelegate.h"
52 #import "UIDelegate.h"
53 #import "WebArchiveDumpSupport.h"
55 #import "WorkQueueItem.h"
56 #import <Carbon/Carbon.h>
57 #import <CoreFoundation/CoreFoundation.h>
58 #import <WebCore/FoundationExtras.h>
59 #import <WebKit/DOMElement.h>
60 #import <WebKit/DOMExtensions.h>
61 #import <WebKit/DOMRange.h>
62 #import <WebKit/WebArchive.h>
63 #import <WebKit/WebBackForwardList.h>
64 #import <WebKit/WebCache.h>
65 #import <WebKit/WebCoreStatistics.h>
66 #import <WebKit/WebDataSourcePrivate.h>
67 #import <WebKit/WebDatabaseManagerPrivate.h>
68 #import <WebKit/WebDocumentPrivate.h>
69 #import <WebKit/WebDeviceOrientationProviderMock.h>
70 #import <WebKit/WebEditingDelegate.h>
71 #import <WebKit/WebFrameView.h>
72 #import <WebKit/WebHistory.h>
73 #import <WebKit/WebHistoryItemPrivate.h>
74 #import <WebKit/WebInspector.h>
75 #import <WebKit/WebKitNSStringExtras.h>
76 #import <WebKit/WebPluginDatabase.h>
77 #import <WebKit/WebPreferences.h>
78 #import <WebKit/WebPreferencesPrivate.h>
79 #import <WebKit/WebPreferenceKeysPrivate.h>
80 #import <WebKit/WebResourceLoadDelegate.h>
81 #import <WebKit/WebStorageManagerPrivate.h>
82 #import <WebKit/WebTypesInternal.h>
83 #import <WebKit/WebViewPrivate.h>
85 #import <objc/objc-runtime.h>
86 #import <wtf/Assertions.h>
87 #import <wtf/RetainPtr.h>
88 #import <wtf/Threading.h>
89 #import <wtf/OwnPtr.h>
92 #import <mach-o/getsect.h>
97 @interface DumpRenderTreeApplication : NSApplication
100 @interface DumpRenderTreeEvent : NSEvent
103 @interface NSURLRequest (PrivateThingsWeShouldntReallyUse)
104 +(void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host;
107 static void runTest(const string& testPathOrURL);
109 // Deciding when it's OK to dump out the state is a bit tricky. All these must be true:
110 // - There is no load in progress
111 // - There is no work queued up (see workQueue var, below)
112 // - waitToDump==NO. This means either waitUntilDone was never called, or it was called
113 // and notifyDone was called subsequently.
114 // Note that the call to notifyDone and the end of the load can happen in either order.
118 NavigationController* gNavigationController = 0;
119 RefPtr<LayoutTestController> gLayoutTestController;
121 WebFrame *mainFrame = 0;
122 // This is the topmost frame that is loading, during a given load, or nil when no load is
123 // in progress. Usually this is the same as the main frame, but not always. In the case
124 // where a frameset is loaded, and then new content is loaded into one of the child frames,
125 // that child frame is the "topmost frame that is loading".
126 WebFrame *topLoadingFrame = nil; // !nil iff a load is in progress
129 CFMutableSetRef disallowedURLs = 0;
130 CFRunLoopTimerRef waitToDumpWatchdog = 0;
133 static FrameLoadDelegate *frameLoadDelegate;
134 static UIDelegate *uiDelegate;
135 static EditingDelegate *editingDelegate;
136 static ResourceLoadDelegate *resourceLoadDelegate;
137 static HistoryDelegate *historyDelegate;
138 PolicyDelegate *policyDelegate;
139 StorageTrackerDelegate *storageDelegate;
141 static int dumpPixels;
143 static int dumpTree = YES;
144 static int forceComplexText;
145 static BOOL printSeparators;
146 static RetainPtr<CFStringRef> persistentUserStyleSheetLocation;
148 static WebHistoryItem *prevTestBFItem = nil; // current b/f item at the end of the previous test
151 static void swizzleAllMethods(Class imposter, Class original)
153 unsigned int imposterMethodCount;
154 Method* imposterMethods = class_copyMethodList(imposter, &imposterMethodCount);
156 unsigned int originalMethodCount;
157 Method* originalMethods = class_copyMethodList(original, &originalMethodCount);
159 for (unsigned int i = 0; i < imposterMethodCount; i++) {
160 SEL imposterMethodName = method_getName(imposterMethods[i]);
162 // Attempt to add the method to the original class. If it fails, the method already exists and we should
163 // instead exchange the implementations.
164 if (class_addMethod(original, imposterMethodName, method_getImplementation(imposterMethods[i]), method_getTypeEncoding(imposterMethods[i])))
168 for (; j < originalMethodCount; j++) {
169 SEL originalMethodName = method_getName(originalMethods[j]);
170 if (sel_isEqual(imposterMethodName, originalMethodName))
174 // If class_addMethod failed above then the method must exist on the original class.
175 ASSERT(j < originalMethodCount);
176 method_exchangeImplementations(imposterMethods[i], originalMethods[j]);
179 free(imposterMethods);
180 free(originalMethods);
184 static void poseAsClass(const char* imposter, const char* original)
186 Class imposterClass = objc_getClass(imposter);
187 Class originalClass = objc_getClass(original);
190 class_poseAs(imposterClass, originalClass);
193 // Swizzle instance methods
194 swizzleAllMethods(imposterClass, originalClass);
195 // and then class methods
196 swizzleAllMethods(object_getClass(imposterClass), object_getClass(originalClass));
200 void setPersistentUserStyleSheetLocation(CFStringRef url)
202 persistentUserStyleSheetLocation = url;
205 static bool shouldIgnoreWebCoreNodeLeaks(const string& URLString)
207 static char* const ignoreSet[] = {
208 // Keeping this infrastructure around in case we ever need it again.
210 static const int ignoreSetCount = sizeof(ignoreSet) / sizeof(char*);
212 for (int i = 0; i < ignoreSetCount; i++) {
213 // FIXME: ignore case
214 string curIgnore(ignoreSet[i]);
215 // Match at the end of the URLString
216 if (!URLString.compare(URLString.length() - curIgnore.length(), curIgnore.length(), curIgnore))
222 static void activateFonts()
224 #if defined(BUILDING_ON_LEOPARD) || defined(BUILDING_ON_TIGER)
225 static const char* fontSectionNames[] = {
239 for (unsigned i = 0; fontSectionNames[i]; ++i) {
240 unsigned long fontDataLength;
241 char* fontData = getsectdata("__DATA", fontSectionNames[i], &fontDataLength);
243 fprintf(stderr, "Failed to locate the %s font.\n", fontSectionNames[i]);
247 ATSFontContainerRef fontContainer;
248 OSStatus status = ATSFontActivateFromMemory(fontData, fontDataLength, kATSFontContextLocal, kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &fontContainer);
250 if (status != noErr) {
251 fprintf(stderr, "Failed to activate the %s font.\n", fontSectionNames[i]);
257 // Work around <rdar://problem/6698023> by activating fonts from disk
258 // FIXME: This code can be removed once <rdar://problem/6698023> is addressed.
260 static const char* fontFileNames[] = {
263 "WebKitWeightWatcher100.ttf",
264 "WebKitWeightWatcher200.ttf",
265 "WebKitWeightWatcher300.ttf",
266 "WebKitWeightWatcher400.ttf",
267 "WebKitWeightWatcher500.ttf",
268 "WebKitWeightWatcher600.ttf",
269 "WebKitWeightWatcher700.ttf",
270 "WebKitWeightWatcher800.ttf",
271 "WebKitWeightWatcher900.ttf",
275 NSMutableArray *fontURLs = [NSMutableArray array];
276 NSURL *resourcesDirectory = [NSURL URLWithString:@"DumpRenderTree.resources" relativeToURL:[[NSBundle mainBundle] executableURL]];
277 for (unsigned i = 0; fontFileNames[i]; ++i) {
278 NSURL *fontURL = [resourcesDirectory URLByAppendingPathComponent:[NSString stringWithUTF8String:fontFileNames[i]]];
279 [fontURLs addObject:[fontURL absoluteURL]];
282 CFArrayRef errors = 0;
283 if (!CTFontManagerRegisterFontsForURLs((CFArrayRef)fontURLs, kCTFontManagerScopeProcess, &errors)) {
284 NSLog(@"Failed to activate fonts: %@", errors);
291 WebView *createWebViewAndOffscreenWindow()
293 NSRect rect = NSMakeRect(0, 0, LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight);
294 WebView *webView = [[WebView alloc] initWithFrame:rect frameName:nil groupName:@"org.webkit.DumpRenderTree"];
296 [webView setUIDelegate:uiDelegate];
297 [webView setFrameLoadDelegate:frameLoadDelegate];
298 [webView setEditingDelegate:editingDelegate];
299 [webView setResourceLoadDelegate:resourceLoadDelegate];
300 [webView _setGeolocationProvider:[MockGeolocationProvider shared]];
301 [webView _setDeviceOrientationProvider:[WebDeviceOrientationProviderMock shared]];
303 // Register the same schemes that Safari does
304 [WebView registerURLSchemeAsLocal:@"feed"];
305 [WebView registerURLSchemeAsLocal:@"feeds"];
306 [WebView registerURLSchemeAsLocal:@"feedsearch"];
308 [webView setContinuousSpellCheckingEnabled:YES];
309 [webView setGrammarCheckingEnabled:YES];
310 [webView setInteractiveFormValidationEnabled:YES];
311 [webView setValidationMessageTimerMagnification:-1];
313 // 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.
314 // Put it at -10000, -10000 in "flipped coordinates", since WebCore and the DOM use flipped coordinates.
315 NSRect windowRect = NSOffsetRect(rect, -10000, [[[NSScreen screens] objectAtIndex:0] frame].size.height - rect.size.height + 10000);
316 DumpRenderTreeWindow *window = [[DumpRenderTreeWindow alloc] initWithContentRect:windowRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
318 #if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
319 [window setColorSpace:[[NSScreen mainScreen] colorSpace]];
322 [[window contentView] addSubview:webView];
323 [window orderBack:nil];
324 [window setAutodisplay:NO];
326 [window startListeningForAcceleratedCompositingChanges];
328 // For reasons that are not entirely clear, the following pair of calls makes WebView handle its
329 // dynamic scrollbars properly. Without it, every frame will always have scrollbars.
330 NSBitmapImageRep *imageRep = [webView bitmapImageRepForCachingDisplayInRect:[webView bounds]];
331 [webView cacheDisplayInRect:[webView bounds] toBitmapImageRep:imageRep];
336 void testStringByEvaluatingJavaScriptFromString()
338 // maps expected result <= JavaScript expression
339 NSDictionary *expressions = [NSDictionary dictionaryWithObjectsAndKeys:
344 @"", @"new String()",
345 @"", @"new String('0')",
351 @"", @"(function() { throw 'error'; })()",
359 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
360 WebView *webView = [[WebView alloc] initWithFrame:NSZeroRect frameName:@"" groupName:@""];
362 NSEnumerator *enumerator = [expressions keyEnumerator];
364 while ((expression = [enumerator nextObject])) {
365 NSString *expectedResult = [expressions objectForKey:expression];
366 NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
367 assert([result isEqualToString:expectedResult]);
375 static NSString *libraryPathForDumpRenderTree()
377 //FIXME: This may not be sufficient to prevent interactions/crashes
378 //when running more than one copy of DumpRenderTree.
379 //See https://bugs.webkit.org/show_bug.cgi?id=10906
380 char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
381 if (dumpRenderTreeTemp)
382 return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:dumpRenderTreeTemp length:strlen(dumpRenderTreeTemp)];
384 return [@"~/Library/Application Support/DumpRenderTree" stringByExpandingTildeInPath];
387 // Called before each test.
388 static void resetDefaultsToConsistentValues()
390 // Give some clear to undocumented defaults values
391 static const int NoFontSmoothing = 0;
392 static const int BlueTintedAppearance = 1;
394 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
395 [defaults setInteger:4 forKey:@"AppleAntiAliasingThreshold"]; // smallest font size to CG should perform antialiasing on
396 [defaults setInteger:NoFontSmoothing forKey:@"AppleFontSmoothing"];
397 [defaults setInteger:BlueTintedAppearance forKey:@"AppleAquaColorVariant"];
398 [defaults setObject:@"0.709800 0.835300 1.000000" forKey:@"AppleHighlightColor"];
399 [defaults setObject:@"0.500000 0.500000 0.500000" forKey:@"AppleOtherHighlightColor"];
400 [defaults setObject:[NSArray arrayWithObject:@"en"] forKey:@"AppleLanguages"];
401 [defaults setBool:YES forKey:WebKitEnableFullDocumentTeardownPreferenceKey];
402 [defaults setBool:YES forKey:WebKitFullScreenEnabledPreferenceKey];
404 // Scrollbars are drawn either using AppKit (which uses NSUserDefaults) or using HIToolbox (which uses CFPreferences / kCFPreferencesAnyApplication / kCFPreferencesCurrentUser / kCFPreferencesAnyHost)
405 [defaults setObject:@"DoubleMax" forKey:@"AppleScrollBarVariant"];
406 RetainPtr<CFTypeRef> initialValue = CFPreferencesCopyValue(CFSTR("AppleScrollBarVariant"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
407 CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), CFSTR("DoubleMax"), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
409 // See <rdar://problem/6347388>.
410 ThemeScrollBarArrowStyle style;
411 GetThemeScrollBarArrowStyle(&style); // Force HIToolbox to read from CFPreferences
414 [defaults setBool:NO forKey:@"AppleScrollAnimationEnabled"];
415 [defaults setBool:NO forKey:@"NSOverlayScrollersEnabled"];
416 [defaults setObject:@"Always" forKey:@"AppleShowScrollBars"];
419 CFPreferencesSetValue(CFSTR("AppleScrollBarVariant"), initialValue.get(), kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
421 NSString *path = libraryPathForDumpRenderTree();
422 [defaults setObject:[path stringByAppendingPathComponent:@"Databases"] forKey:WebDatabaseDirectoryDefaultsKey];
423 [defaults setObject:[path stringByAppendingPathComponent:@"LocalStorage"] forKey:WebStorageDirectoryDefaultsKey];
424 [defaults setObject:[path stringByAppendingPathComponent:@"LocalCache"] forKey:WebKitLocalCacheDefaultsKey];
426 WebPreferences *preferences = [WebPreferences standardPreferences];
428 [preferences setAllowUniversalAccessFromFileURLs:YES];
429 [preferences setAllowFileAccessFromFileURLs:YES];
430 [preferences setStandardFontFamily:@"Times"];
431 [preferences setFixedFontFamily:@"Courier"];
432 [preferences setSerifFontFamily:@"Times"];
433 [preferences setSansSerifFontFamily:@"Helvetica"];
434 [preferences setCursiveFontFamily:@"Apple Chancery"];
435 [preferences setFantasyFontFamily:@"Papyrus"];
436 [preferences setDefaultFontSize:16];
437 [preferences setDefaultFixedFontSize:13];
438 [preferences setMinimumFontSize:0];
439 [preferences setJavaEnabled:NO];
440 [preferences setJavaScriptEnabled:YES];
441 [preferences setEditableLinkBehavior:WebKitEditableLinkOnlyLiveWithShiftKey];
442 [preferences setTabsToLinks:NO];
443 [preferences setDOMPasteAllowed:YES];
444 [preferences setShouldPrintBackgrounds:YES];
445 [preferences setCacheModel:WebCacheModelDocumentBrowser];
446 [preferences setXSSAuditorEnabled:NO];
447 [preferences setExperimentalNotificationsEnabled:NO];
448 [preferences setPluginAllowedRunTime:1];
449 [preferences setPlugInsEnabled:YES];
451 [preferences setPrivateBrowsingEnabled:NO];
452 [preferences setAuthorAndUserStylesEnabled:YES];
453 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
454 [preferences setJavaScriptCanAccessClipboard:YES];
455 [preferences setOfflineWebApplicationCacheEnabled:YES];
456 [preferences setDeveloperExtrasEnabled:NO];
457 [preferences setLoadsImagesAutomatically:YES];
458 [preferences setFrameFlatteningEnabled:NO];
459 [preferences setSpatialNavigationEnabled:NO];
460 [preferences setEditingBehavior:WebKitEditingMacBehavior];
461 if (persistentUserStyleSheetLocation) {
462 [preferences setUserStyleSheetLocation:[NSURL URLWithString:(NSString *)(persistentUserStyleSheetLocation.get())]];
463 [preferences setUserStyleSheetEnabled:YES];
465 [preferences setUserStyleSheetEnabled:NO];
467 // The back/forward cache is causing problems due to layouts during transition from one page to another.
468 // So, turn it off for now, but we might want to turn it back on some day.
469 [preferences setUsesPageCache:NO];
470 [preferences setAcceleratedCompositingEnabled:YES];
471 [preferences setWebGLEnabled:NO];
472 [preferences setUsePreHTML5ParserQuirks:NO];
473 [preferences setAsynchronousSpellCheckingEnabled:NO];
475 [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain];
477 LayoutTestController::setSerializeHTTPLoads(false);
479 setlocale(LC_ALL, "");
482 // Called once on DumpRenderTree startup.
483 static void setDefaultsToConsistentValuesForTesting()
485 resetDefaultsToConsistentValues();
487 NSString *path = libraryPathForDumpRenderTree();
488 NSURLCache *sharedCache =
489 [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
491 diskPath:[path stringByAppendingPathComponent:@"URLCache"]];
492 [NSURLCache setSharedURLCache:sharedCache];
493 [sharedCache release];
497 static void* runThread(void* arg)
499 static ThreadIdentifier previousId = 0;
500 ThreadIdentifier currentId = currentThread();
501 // Verify 2 successive threads do not get the same Id.
502 ASSERT(previousId != currentId);
503 previousId = currentId;
507 static void testThreadIdentifierMap()
509 // Imitate 'foreign' threads that are not created by WTF.
511 pthread_create(&pthread, 0, &runThread, 0);
512 pthread_join(pthread, 0);
514 pthread_create(&pthread, 0, &runThread, 0);
515 pthread_join(pthread, 0);
517 // Now create another thread using WTF. On OSX, it will have the same pthread handle
518 // but should get a different ThreadIdentifier.
519 createThread(runThread, 0, "DumpRenderTree: test");
522 static void crashHandler(int sig)
524 char *signalName = strsignal(sig);
525 write(STDERR_FILENO, signalName, strlen(signalName));
526 write(STDERR_FILENO, "\n", 1);
527 restoreMainDisplayColorProfile(0);
531 static void installSignalHandlers()
533 signal(SIGILL, crashHandler); /* 4: illegal instruction (not reset when caught) */
534 signal(SIGTRAP, crashHandler); /* 5: trace trap (not reset when caught) */
535 signal(SIGEMT, crashHandler); /* 7: EMT instruction */
536 signal(SIGFPE, crashHandler); /* 8: floating point exception */
537 signal(SIGBUS, crashHandler); /* 10: bus error */
538 signal(SIGSEGV, crashHandler); /* 11: segmentation violation */
539 signal(SIGSYS, crashHandler); /* 12: bad argument to system call */
540 signal(SIGPIPE, crashHandler); /* 13: write on a pipe with no reader */
541 signal(SIGXCPU, crashHandler); /* 24: exceeded CPU time limit */
542 signal(SIGXFSZ, crashHandler); /* 25: exceeded file size limit */
545 static void allocateGlobalControllers()
547 // FIXME: We should remove these and move to the ObjC standard [Foo sharedInstance] model
548 gNavigationController = [[NavigationController alloc] init];
549 frameLoadDelegate = [[FrameLoadDelegate alloc] init];
550 uiDelegate = [[UIDelegate alloc] init];
551 editingDelegate = [[EditingDelegate alloc] init];
552 resourceLoadDelegate = [[ResourceLoadDelegate alloc] init];
553 policyDelegate = [[PolicyDelegate alloc] init];
554 historyDelegate = [[HistoryDelegate alloc] init];
555 storageDelegate = [[StorageTrackerDelegate alloc] init];
558 // ObjC++ doens't seem to let me pass NSObject*& sadly.
559 static inline void releaseAndZero(NSObject** object)
565 static void releaseGlobalControllers()
567 releaseAndZero(&gNavigationController);
568 releaseAndZero(&frameLoadDelegate);
569 releaseAndZero(&editingDelegate);
570 releaseAndZero(&resourceLoadDelegate);
571 releaseAndZero(&uiDelegate);
572 releaseAndZero(&policyDelegate);
573 releaseAndZero(&storageDelegate);
576 static void initializeGlobalsFromCommandLineOptions(int argc, const char *argv[])
578 struct option options[] = {
579 {"notree", no_argument, &dumpTree, NO},
580 {"pixel-tests", no_argument, &dumpPixels, YES},
581 {"tree", no_argument, &dumpTree, YES},
582 {"threaded", no_argument, &threaded, YES},
583 {"complex-text", no_argument, &forceComplexText, YES},
588 while ((option = getopt_long(argc, (char * const *)argv, "", options, NULL)) != -1) {
590 case '?': // unknown or ambiguous option
591 case ':': // missing argument
598 static void addTestPluginsToPluginSearchPath(const char* executablePath)
600 NSString *pwd = [[NSString stringWithUTF8String:executablePath] stringByDeletingLastPathComponent];
601 [WebPluginDatabase setAdditionalWebPlugInPaths:[NSArray arrayWithObject:pwd]];
602 [[WebPluginDatabase sharedDatabase] refresh];
605 static bool useLongRunningServerMode(int argc, const char *argv[])
607 // This assumes you've already called getopt_long
608 return (argc == optind+1 && strcmp(argv[optind], "-") == 0);
611 static void runTestingServerLoop()
613 // When DumpRenderTree run in server mode, we just wait around for file names
614 // to be passed to us and read each in turn, passing the results back to the client
615 char filenameBuffer[2048];
616 while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
617 char *newLineCharacter = strchr(filenameBuffer, '\n');
618 if (newLineCharacter)
619 *newLineCharacter = '\0';
621 if (strlen(filenameBuffer) == 0)
624 runTest(filenameBuffer);
628 static void prepareConsistentTestingEnvironment()
630 poseAsClass("DumpRenderTreePasteboard", "NSPasteboard");
631 poseAsClass("DumpRenderTreeEvent", "NSEvent");
633 setDefaultsToConsistentValuesForTesting();
637 setupMainDisplayColorProfile();
638 allocateGlobalControllers();
640 makeLargeMallocFailSilently();
643 void dumpRenderTree(int argc, const char *argv[])
645 initializeGlobalsFromCommandLineOptions(argc, argv);
646 prepareConsistentTestingEnvironment();
647 addTestPluginsToPluginSearchPath(argv[0]);
649 installSignalHandlers();
651 if (forceComplexText)
652 [WebView _setAlwaysUsesComplexTextCodePath:YES];
654 WebView *webView = createWebViewAndOffscreenWindow();
655 mainFrame = [webView mainFrame];
657 [[NSURLCache sharedURLCache] removeAllCachedResponses];
660 // <http://webkit.org/b/31200> In order to prevent extra frame load delegate logging being generated if the first test to use SSL
661 // is set to log frame load delegate calls we ignore SSL certificate errors on localhost and 127.0.0.1.
662 #if BUILDING_ON_TIGER
663 // Initialize internal NSURLRequest data for setAllowsAnyHTTPSCertificate:forHost: to work properly.
664 [[[[NSURLRequest alloc] init] autorelease] HTTPMethod];
666 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"localhost"];
667 [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"127.0.0.1"];
669 // <rdar://problem/5222911>
670 testStringByEvaluatingJavaScriptFromString();
672 // http://webkit.org/b/32689
673 testThreadIdentifierMap();
676 startJavaScriptThreads();
678 if (useLongRunningServerMode(argc, argv)) {
679 printSeparators = YES;
680 runTestingServerLoop();
682 printSeparators = (optind < argc-1 || (dumpPixels && dumpTree));
683 for (int i = optind; i != argc; ++i)
688 stopJavaScriptThreads();
690 NSWindow *window = [webView window];
694 // Work around problem where registering drag types leaves an outstanding
695 // "perform selector" on the window, which retains the window. It's a bit
696 // inelegant and perhaps dangerous to just blow them all away, but in practice
697 // it probably won't cause any trouble (and this is just a test tool, after all).
698 [NSObject cancelPreviousPerformRequestsWithTarget:window];
700 [window close]; // releases when closed
703 releaseGlobalControllers();
705 [DumpRenderTreePasteboard releaseLocalPasteboards];
707 // FIXME: This should be moved onto LayoutTestController and made into a HashSet
708 if (disallowedURLs) {
709 CFRelease(disallowedURLs);
714 restoreMainDisplayColorProfile(0);
717 int main(int argc, const char *argv[])
719 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
720 [DumpRenderTreeApplication sharedApplication]; // Force AppKit to init itself
721 dumpRenderTree(argc, argv);
722 [WebCoreStatistics garbageCollectJavaScriptObjects];
723 [WebCoreStatistics emptyCache]; // Otherwise SVGImages trigger false positives for Frame/Node counts
728 static NSInteger compareHistoryItems(id item1, id item2, void *context)
730 return [[item1 target] caseInsensitiveCompare:[item2 target]];
733 static void dumpHistoryItem(WebHistoryItem *item, int indent, BOOL current)
740 for (int i = start; i < indent; i++)
743 NSString *urlString = [item URLString];
744 if ([[NSURL URLWithString:urlString] isFileURL]) {
745 NSRange range = [urlString rangeOfString:@"/LayoutTests/"];
746 urlString = [@"(file test):" stringByAppendingString:[urlString substringFromIndex:(range.length + range.location)]];
749 printf("%s", [urlString UTF8String]);
750 NSString *target = [item target];
751 if (target && [target length] > 0)
752 printf(" (in frame \"%s\")", [target UTF8String]);
753 if ([item isTargetItem])
754 printf(" **nav target**");
756 NSArray *kids = [item children];
758 // must sort to eliminate arbitrary result ordering which defeats reproducible testing
759 kids = [kids sortedArrayUsingFunction:&compareHistoryItems context:nil];
760 for (unsigned i = 0; i < [kids count]; i++)
761 dumpHistoryItem([kids objectAtIndex:i], indent+4, NO);
765 static void dumpFrameScrollPosition(WebFrame *f)
767 WebScriptObject* scriptObject = [f windowObject];
768 NSPoint scrollPosition = NSMakePoint(
769 [[scriptObject valueForKey:@"pageXOffset"] floatValue],
770 [[scriptObject valueForKey:@"pageYOffset"] floatValue]);
771 if (ABS(scrollPosition.x) > 0.00000001 || ABS(scrollPosition.y) > 0.00000001) {
772 if ([f parentFrame] != nil)
773 printf("frame '%s' ", [[f name] UTF8String]);
774 printf("scrolled to %.f,%.f\n", scrollPosition.x, scrollPosition.y);
777 if (gLayoutTestController->dumpChildFrameScrollPositions()) {
778 NSArray *kids = [f childFrames];
780 for (unsigned i = 0; i < [kids count]; i++)
781 dumpFrameScrollPosition([kids objectAtIndex:i]);
785 static NSString *dumpFramesAsText(WebFrame *frame)
787 DOMDocument *document = [frame DOMDocument];
788 DOMElement *documentElement = [document documentElement];
790 if (!documentElement)
793 NSMutableString *result = [[[NSMutableString alloc] init] autorelease];
795 // Add header for all but the main frame.
796 if ([frame parentFrame])
797 result = [NSMutableString stringWithFormat:@"\n--------\nFrame: '%@'\n--------\n", [frame name]];
799 [result appendFormat:@"%@\n", [documentElement innerText]];
801 if (gLayoutTestController->dumpChildFramesAsText()) {
802 NSArray *kids = [frame childFrames];
804 for (unsigned i = 0; i < [kids count]; i++)
805 [result appendString:dumpFramesAsText([kids objectAtIndex:i])];
812 static NSData *dumpFrameAsPDF(WebFrame *frame)
817 // Sadly we have to dump to a file and then read from that file again
818 // +[NSPrintOperation PDFOperationWithView:insideRect:] requires a rect and prints to a single page
819 // likewise +[NSView dataWithPDFInsideRect:] also prints to a single continuous page
820 // The goal of this function is to test "real" printing across multiple pages.
821 // FIXME: It's possible there might be printing SPI to let us print a multi-page PDF to an NSData object
822 NSString *path = [libraryPathForDumpRenderTree() stringByAppendingPathComponent:@"test.pdf"];
824 NSMutableDictionary *printInfoDict = [NSMutableDictionary dictionaryWithDictionary:[[NSPrintInfo sharedPrintInfo] dictionary]];
825 [printInfoDict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
826 [printInfoDict setObject:path forKey:NSPrintSavePath];
828 NSPrintInfo *printInfo = [[NSPrintInfo alloc] initWithDictionary:printInfoDict];
829 [printInfo setHorizontalPagination:NSAutoPagination];
830 [printInfo setVerticalPagination:NSAutoPagination];
831 [printInfo setVerticallyCentered:NO];
833 NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[frame frameView] printInfo:printInfo];
834 [printOperation setShowPanels:NO];
835 [printOperation runOperation];
839 NSData *pdfData = [NSData dataWithContentsOfFile:path];
840 [[NSFileManager defaultManager] removeFileAtPath:path handler:nil];
845 static void dumpBackForwardListForWebView(WebView *view)
847 printf("\n============== Back Forward List ==============\n");
848 WebBackForwardList *bfList = [view backForwardList];
850 // Print out all items in the list after prevTestBFItem, which was from the previous test
851 // Gather items from the end of the list, the print them out from oldest to newest
852 NSMutableArray *itemsToPrint = [[NSMutableArray alloc] init];
853 for (int i = [bfList forwardListCount]; i > 0; i--) {
854 WebHistoryItem *item = [bfList itemAtIndex:i];
855 // something is wrong if the item from the last test is in the forward part of the b/f list
856 assert(item != prevTestBFItem);
857 [itemsToPrint addObject:item];
860 assert([bfList currentItem] != prevTestBFItem);
861 [itemsToPrint addObject:[bfList currentItem]];
862 int currentItemIndex = [itemsToPrint count] - 1;
864 for (int i = -1; i >= -[bfList backListCount]; i--) {
865 WebHistoryItem *item = [bfList itemAtIndex:i];
866 if (item == prevTestBFItem)
868 [itemsToPrint addObject:item];
871 for (int i = [itemsToPrint count]-1; i >= 0; i--)
872 dumpHistoryItem([itemsToPrint objectAtIndex:i], 8, i == currentItemIndex);
874 [itemsToPrint release];
875 printf("===============================================\n");
878 static void sizeWebViewForCurrentTest()
880 // W3C SVG tests expect to be 480x360
881 bool isSVGW3CTest = (gLayoutTestController->testPathOrURL().find("svg/W3C-SVG-1.1") != string::npos);
883 [[mainFrame webView] setFrameSize:NSMakeSize(480, 360)];
885 [[mainFrame webView] setFrameSize:NSMakeSize(LayoutTestController::maxViewWidth, LayoutTestController::maxViewHeight)];
888 static const char *methodNameStringForFailedTest()
890 const char *errorMessage;
891 if (gLayoutTestController->dumpAsText())
892 errorMessage = "[documentElement innerText]";
893 else if (gLayoutTestController->dumpDOMAsWebArchive())
894 errorMessage = "[[mainFrame DOMDocument] webArchive]";
895 else if (gLayoutTestController->dumpSourceAsWebArchive())
896 errorMessage = "[[mainFrame dataSource] webArchive]";
898 errorMessage = "[mainFrame renderTreeAsExternalRepresentation]";
903 static void dumpBackForwardListForAllWindows()
905 CFArrayRef openWindows = (CFArrayRef)[DumpRenderTreeWindow openWindows];
906 unsigned count = CFArrayGetCount(openWindows);
907 for (unsigned i = 0; i < count; i++) {
908 NSWindow *window = (NSWindow *)CFArrayGetValueAtIndex(openWindows, i);
909 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
910 dumpBackForwardListForWebView(webView);
914 static void invalidateAnyPreviousWaitToDumpWatchdog()
916 if (waitToDumpWatchdog) {
917 CFRunLoopTimerInvalidate(waitToDumpWatchdog);
918 CFRelease(waitToDumpWatchdog);
919 waitToDumpWatchdog = 0;
925 invalidateAnyPreviousWaitToDumpWatchdog();
928 NSString *resultString = nil;
929 NSData *resultData = nil;
930 NSString *resultMimeType = @"text/plain";
932 if ([[[mainFrame dataSource] _responseMIMEType] isEqualToString:@"text/plain"]) {
933 gLayoutTestController->setDumpAsText(true);
934 gLayoutTestController->setGeneratePixelResults(false);
936 if (gLayoutTestController->dumpAsText()) {
937 resultString = dumpFramesAsText(mainFrame);
938 } else if (gLayoutTestController->dumpAsPDF()) {
939 resultData = dumpFrameAsPDF(mainFrame);
940 resultMimeType = @"application/pdf";
941 } else if (gLayoutTestController->dumpDOMAsWebArchive()) {
942 WebArchive *webArchive = [[mainFrame DOMDocument] webArchive];
943 resultString = HardAutorelease(createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
944 resultMimeType = @"application/x-webarchive";
945 } else if (gLayoutTestController->dumpSourceAsWebArchive()) {
946 WebArchive *webArchive = [[mainFrame dataSource] webArchive];
947 resultString = HardAutorelease(createXMLStringFromWebArchiveData((CFDataRef)[webArchive data]));
948 resultMimeType = @"application/x-webarchive";
950 sizeWebViewForCurrentTest();
951 resultString = [mainFrame renderTreeAsExternalRepresentationForPrinting:gLayoutTestController->isPrinting()];
954 if (resultString && !resultData)
955 resultData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
957 printf("Content-Type: %s\n", [resultMimeType UTF8String]);
960 fwrite([resultData bytes], 1, [resultData length], stdout);
962 if (!gLayoutTestController->dumpAsText() && !gLayoutTestController->dumpDOMAsWebArchive() && !gLayoutTestController->dumpSourceAsWebArchive())
963 dumpFrameScrollPosition(mainFrame);
965 if (gLayoutTestController->dumpBackForwardList())
966 dumpBackForwardListForAllWindows();
968 printf("ERROR: nil result from %s", methodNameStringForFailedTest());
970 // Stop the watchdog thread before we leave this test to make sure it doesn't
971 // fire in between tests causing the next test to fail.
972 // This is a speculative fix for: https://bugs.webkit.org/show_bug.cgi?id=32339
973 invalidateAnyPreviousWaitToDumpWatchdog();
975 if (printSeparators) {
976 puts("#EOF"); // terminate the content block
977 fputs("#EOF\n", stderr);
981 if (dumpPixels && gLayoutTestController->generatePixelResults())
982 // FIXME: when isPrinting is set, dump the image with page separators.
983 dumpWebViewAsPixelsAndCompareWithExpected(gLayoutTestController->expectedPixelHash());
985 puts("#EOF"); // terminate the (possibly empty) pixels block
993 static bool shouldLogFrameLoadDelegates(const char* pathOrURL)
995 return strstr(pathOrURL, "loading/");
998 static bool shouldLogHistoryDelegates(const char* pathOrURL)
1000 return strstr(pathOrURL, "globalhistory/");
1003 static bool shouldOpenWebInspector(const char* pathOrURL)
1005 return strstr(pathOrURL, "inspector/");
1008 static bool shouldDumpAsText(const char* pathOrURL)
1010 return strstr(pathOrURL, "dumpAsText/");
1013 static bool shouldEnableDeveloperExtras(const char* pathOrURL)
1018 static void resetWebViewToConsistentStateBeforeTesting()
1020 WebView *webView = [mainFrame webView];
1021 [webView setEditable:NO];
1022 [(EditingDelegate *)[webView editingDelegate] setAcceptsEditing:YES];
1023 [webView makeTextStandardSize:nil];
1024 [webView resetPageZoom:nil];
1025 [webView setTabKeyCyclesThroughElements:YES];
1026 [webView setPolicyDelegate:nil];
1027 [policyDelegate setPermissive:NO];
1028 [policyDelegate setControllerToNotifyDone:0];
1029 [frameLoadDelegate resetToConsistentState];
1030 [webView _setDashboardBehavior:WebDashboardBehaviorUseBackwardCompatibilityMode to:NO];
1031 [webView _clearMainFrameName];
1032 [[webView undoManager] removeAllActions];
1033 [WebView _removeAllUserContentFromGroup:[webView groupName]];
1034 [[webView window] setAutodisplay:NO];
1035 [webView _setMinimumTimerInterval:[WebView _defaultMinimumTimerInterval]];
1037 resetDefaultsToConsistentValues();
1039 [[mainFrame webView] setSmartInsertDeleteEnabled:YES];
1040 [[[mainFrame webView] inspector] setJavaScriptProfilingEnabled:NO];
1042 [WebView _setUsesTestModeFocusRingColor:YES];
1043 [WebView _resetOriginAccessWhitelists];
1045 [[MockGeolocationProvider shared] stopTimer];
1047 // Clear the contents of the general pasteboard
1048 [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
1050 [mainFrame _clearOpener];
1053 static void runTest(const string& testPathOrURL)
1055 ASSERT(!testPathOrURL.empty());
1057 // Look for "'" as a separator between the path or URL, and the pixel dump hash that follows.
1058 string pathOrURL(testPathOrURL);
1059 string expectedPixelHash;
1061 size_t separatorPos = pathOrURL.find("'");
1062 if (separatorPos != string::npos) {
1063 pathOrURL = string(testPathOrURL, 0, separatorPos);
1064 expectedPixelHash = string(testPathOrURL, separatorPos + 1);
1067 NSString *pathOrURLString = [NSString stringWithUTF8String:pathOrURL.c_str()];
1068 if (!pathOrURLString) {
1069 fprintf(stderr, "Failed to parse \"%s\" as UTF-8\n", pathOrURL.c_str());
1074 if ([pathOrURLString hasPrefix:@"http://"] || [pathOrURLString hasPrefix:@"https://"])
1075 url = [NSURL URLWithString:pathOrURLString];
1077 url = [NSURL fileURLWithPath:pathOrURLString];
1079 fprintf(stderr, "Failed to parse \"%s\" as a URL\n", pathOrURL.c_str());
1083 const string testURL([[url absoluteString] UTF8String]);
1085 resetWebViewToConsistentStateBeforeTesting();
1087 gLayoutTestController = LayoutTestController::create(testURL, expectedPixelHash);
1088 topLoadingFrame = nil;
1089 ASSERT(!draggingInfo); // the previous test should have called eventSender.mouseUp to drop!
1090 releaseAndZero(&draggingInfo);
1093 gLayoutTestController->setIconDatabaseEnabled(false);
1096 CFSetRemoveAllValues(disallowedURLs);
1097 if (shouldLogFrameLoadDelegates(pathOrURL.c_str()))
1098 gLayoutTestController->setDumpFrameLoadCallbacks(true);
1100 if (shouldLogHistoryDelegates(pathOrURL.c_str()))
1101 [[mainFrame webView] setHistoryDelegate:historyDelegate];
1103 [[mainFrame webView] setHistoryDelegate:nil];
1105 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1106 gLayoutTestController->setDeveloperExtrasEnabled(true);
1107 if (shouldOpenWebInspector(pathOrURL.c_str()))
1108 gLayoutTestController->showWebInspector();
1109 if (shouldDumpAsText(pathOrURL.c_str())) {
1110 gLayoutTestController->setDumpAsText(true);
1111 gLayoutTestController->setGeneratePixelResults(false);
1115 if ([WebHistory optionalSharedHistory])
1116 [WebHistory setOptionalSharedHistory:nil];
1117 lastMousePosition = NSZeroPoint;
1118 lastClickPosition = NSZeroPoint;
1120 [prevTestBFItem release];
1121 prevTestBFItem = [[[[mainFrame webView] backForwardList] currentItem] retain];
1123 WorkQueue::shared()->clear();
1124 WorkQueue::shared()->setFrozen(false);
1126 bool ignoreWebCoreNodeLeaks = shouldIgnoreWebCoreNodeLeaks(testURL);
1127 if (ignoreWebCoreNodeLeaks)
1128 [WebCoreStatistics startIgnoringWebCoreNodeLeaks];
1130 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1131 [mainFrame loadRequest:[NSURLRequest requestWithURL:url]];
1135 pool = [[NSAutoreleasePool alloc] init];
1136 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
1140 pool = [[NSAutoreleasePool alloc] init];
1141 [EventSendingController clearSavedEvents];
1142 [[mainFrame webView] setSelectedDOMRange:nil affinity:NSSelectionAffinityDownstream];
1144 WorkQueue::shared()->clear();
1146 if (gLayoutTestController->closeRemainingWindowsWhenComplete()) {
1147 NSArray* array = [DumpRenderTreeWindow openWindows];
1149 unsigned count = [array count];
1150 for (unsigned i = 0; i < count; i++) {
1151 NSWindow *window = [array objectAtIndex:i];
1153 // Don't try to close the main window
1154 if (window == [[mainFrame webView] window])
1157 WebView *webView = [[[window contentView] subviews] objectAtIndex:0];
1164 // If developer extras enabled Web Inspector may have been open by the test.
1165 if (shouldEnableDeveloperExtras(pathOrURL.c_str())) {
1166 gLayoutTestController->closeWebInspector();
1167 gLayoutTestController->setDeveloperExtrasEnabled(false);
1170 resetWebViewToConsistentStateBeforeTesting();
1172 [mainFrame loadHTMLString:@"<html></html>" baseURL:[NSURL URLWithString:@"about:blank"]];
1173 [mainFrame stopLoading];
1177 // We should only have our main window left open when we're done
1178 ASSERT(CFArrayGetCount(openWindowsRef) == 1);
1179 ASSERT(CFArrayGetValueAtIndex(openWindowsRef, 0) == [[mainFrame webView] window]);
1181 gLayoutTestController.clear();
1183 if (ignoreWebCoreNodeLeaks)
1184 [WebCoreStatistics stopIgnoringWebCoreNodeLeaks];
1187 void displayWebView()
1189 NSView *webView = [mainFrame webView];
1191 [webView lockFocus];
1192 [[[NSColor blackColor] colorWithAlphaComponent:0.66] set];
1193 NSRectFillUsingOperation([webView frame], NSCompositeSourceOver);
1194 [webView unlockFocus];
1197 @implementation DumpRenderTreeEvent
1199 + (NSPoint)mouseLocation
1201 return [[[mainFrame webView] window] convertBaseToScreen:lastMousePosition];
1206 @implementation DumpRenderTreeApplication
1210 // <rdar://problem/7686123> Java plug-in freezes unless NSApplication is running