1/* 2 * Copyright (C) 2010 Apple Inc. All rights reserved. 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 1. Redistributions of source code must retain the above copyright 8 * notice, this list of conditions and the following disclaimer. 9 * 2. Redistributions in binary form must reproduce the above copyright 10 * notice, this list of conditions and the following disclaimer in the 11 * documentation and/or other materials provided with the distribution. 12 * 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' 14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS 17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 23 * THE POSSIBILITY OF SUCH DAMAGE. 24 */ 25 26#import "config.h" 27#import "WebProcess.h" 28 29#import "CustomProtocolManager.h" 30#import "SandboxExtension.h" 31#import "SandboxInitializationParameters.h" 32#import "SecItemShim.h" 33#import "WKFullKeyboardAccessWatcher.h" 34#import "WebFrame.h" 35#import "WebInspector.h" 36#import "WebPage.h" 37#import "WebProcessCreationParameters.h" 38#import "WebProcessProxyMessages.h" 39#import <JavaScriptCore/Options.h> 40#import <WebCore/AXObjectCache.h> 41#import <WebCore/FileSystem.h> 42#import <WebCore/Font.h> 43#import <WebCore/LocalizedStrings.h> 44#import <WebCore/MemoryCache.h> 45#import <WebCore/MemoryPressureHandler.h> 46#import <WebCore/PageCache.h> 47#import <WebCore/WebCoreNSURLExtras.h> 48#import <WebKitSystemInterface.h> 49#import <algorithm> 50#import <dispatch/dispatch.h> 51#import <mach/host_info.h> 52#import <mach/mach.h> 53#import <mach/mach_error.h> 54#import <objc/runtime.h> 55#import <stdio.h> 56 57#define ENABLE_MANUAL_WEBPROCESS_SANDBOXING !PLATFORM(IOS) 58 59#if PLATFORM(IOS) 60@interface NSURLCache (WKDetails) 61-(id)_initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity relativePath:(NSString *)path; 62@end 63#endif 64 65using namespace WebCore; 66 67namespace WebKit { 68 69static uint64_t memorySize() 70{ 71 static host_basic_info_data_t hostInfo; 72 73 static dispatch_once_t once; 74 dispatch_once(&once, ^() { 75 mach_port_t host = mach_host_self(); 76 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT; 77 kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count); 78 mach_port_deallocate(mach_task_self(), host); 79 80 if (r != KERN_SUCCESS) 81 LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r)); 82 }); 83 84 return hostInfo.max_mem; 85} 86 87static uint64_t volumeFreeSize(NSString *path) 88{ 89 NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL]; 90 return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue]; 91} 92 93void WebProcess::platformSetCacheModel(CacheModel cacheModel) 94{ 95 RetainPtr<NSString> nsurlCacheDirectory = adoptNS((NSString *)WKCopyFoundationCacheDirectory()); 96 if (!nsurlCacheDirectory) 97 nsurlCacheDirectory = NSHomeDirectory(); 98 99 // As a fudge factor, use 1000 instead of 1024, in case the reported byte 100 // count doesn't align exactly to a megabyte boundary. 101 uint64_t memSize = memorySize() / 1024 / 1000; 102 uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000; 103 104 unsigned cacheTotalCapacity = 0; 105 unsigned cacheMinDeadCapacity = 0; 106 unsigned cacheMaxDeadCapacity = 0; 107 auto deadDecodedDataDeletionInterval = std::chrono::seconds { 0 }; 108 unsigned pageCacheCapacity = 0; 109 unsigned long urlCacheMemoryCapacity = 0; 110 unsigned long urlCacheDiskCapacity = 0; 111 112 calculateCacheSizes(cacheModel, memSize, diskFreeSize, 113 cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval, 114 pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity); 115 116 117 memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity); 118 memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval); 119 pageCache()->setCapacity(pageCacheCapacity); 120 121 NSURLCache *nsurlCache = [NSURLCache sharedURLCache]; 122 123 // FIXME: Once there is no loading being done in the WebProcess, we should remove this, 124 // as calling [NSURLCache sharedURLCache] initializes the cache, which we would rather not do. 125 if (usesNetworkProcess()) { 126 [nsurlCache setMemoryCapacity:0]; 127 [nsurlCache setDiskCapacity:0]; 128 return; 129 } 130 131 [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity]; 132 [nsurlCache setDiskCapacity:std::max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn. 133} 134 135void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear) 136{ 137 if (cachesToClear == InMemoryResourceCachesOnly) 138 return; 139 140 // If we're using the network process then it is the only one that needs to clear the disk cache. 141 if (usesNetworkProcess()) 142 return; 143 144 if (!m_clearResourceCachesDispatchGroup) 145 m_clearResourceCachesDispatchGroup = dispatch_group_create(); 146 147 dispatch_group_async(m_clearResourceCachesDispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 148 [[NSURLCache sharedURLCache] removeAllCachedResponses]; 149 }); 150} 151 152#if USE(APPKIT) 153static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL) 154{ 155 WebPage* page = WebProcess::shared().focusedWebPage(); 156 if (!page || !page->accessibilityRemoteObject()) 157 return 0; 158 159 return [page->accessibilityRemoteObject() accessibilityFocusedUIElement]; 160} 161#endif 162 163void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, IPC::MessageDecoder&) 164{ 165#if ENABLE(SANDBOX_EXTENSIONS) 166 SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle); 167 SandboxExtension::consumePermanently(parameters.webSQLDatabaseDirectoryExtensionHandle); 168 SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle); 169 SandboxExtension::consumePermanently(parameters.diskCacheDirectoryExtensionHandle); 170#if PLATFORM(IOS) 171 SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle); 172 SandboxExtension::consumePermanently(parameters.openGLCacheDirectoryExtensionHandle); 173 SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle); 174 SandboxExtension::consumePermanently(parameters.hstsDatabasePathExtensionHandle); 175#endif 176#endif 177 178 // When the network process is enabled, each web process wants a stand-alone 179 // NSURLCache, which it can disable to save memory. 180#if PLATFORM(IOS) 181 if (!parameters.uiProcessBundleIdentifier.isNull()) { 182 [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc] 183 _initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity 184 diskCapacity:parameters.nsURLCacheDiskCapacity 185 relativePath:parameters.uiProcessBundleIdentifier]).get()]; 186 } 187#else 188 if (!parameters.diskCacheDirectory.isNull()) { 189 [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc] 190 initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity 191 diskCapacity:parameters.nsURLCacheDiskCapacity 192 diskPath:parameters.diskCacheDirectory]).get()]; 193 } 194#endif 195 196 m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port(); 197 m_presenterApplicationPid = parameters.presenterApplicationPid; 198 m_shouldForceScreenFontSubstitution = parameters.shouldForceScreenFontSubstitution; 199 Font::setDefaultTypesettingFeatures(parameters.shouldEnableKerningAndLigaturesByDefault ? Kerning | Ligatures : 0); 200 201 MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging); 202 203 setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled); 204 205#if USE(APPKIT) 206 [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions" : @YES }]; 207 208 // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's 209 // no window in WK2, NSApplication needs to use the focused page's focused element. 210 Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement)); 211 method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement); 212#endif 213} 214 215void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters) 216{ 217#if !PLATFORM(IOS) 218 NSString *applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName]; 219 WKSetVisibleApplicationName((CFStringRef)applicationName); 220#endif 221} 222 223void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&) 224{ 225 WKAXRegisterRemoteApp(); 226 227#if ENABLE(SEC_ITEM_SHIM) 228 SecItemShim::shared().initialize(this); 229#endif 230} 231 232#if USE(APPKIT) 233void WebProcess::stopRunLoop() 234{ 235 ChildProcess::stopNSAppRunLoop(); 236} 237#endif 238 239void WebProcess::platformTerminate() 240{ 241 if (m_clearResourceCachesDispatchGroup) { 242 dispatch_group_wait(m_clearResourceCachesDispatchGroup, DISPATCH_TIME_FOREVER); 243 dispatch_release(m_clearResourceCachesDispatchGroup); 244 m_clearResourceCachesDispatchGroup = 0; 245 } 246} 247 248void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters) 249{ 250#if ENABLE(WEB_PROCESS_SANDBOX) 251#if ENABLE_MANUAL_WEBPROCESS_SANDBOXING 252 // Need to override the default, because service has a different bundle ID. 253 NSBundle *webkit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")]; 254#if PLATFORM(IOS) 255 sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]); 256#else 257 sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]); 258#endif 259 ChildProcess::initializeSandbox(parameters, sandboxParameters); 260#endif 261#else 262 UNUSED_PARAM(parameters); 263 UNUSED_PARAM(sandboxParameters); 264#endif 265} 266 267void WebProcess::updateActivePages() 268{ 269#if USE(APPKIT) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 270 RetainPtr<CFMutableArrayRef> activePageURLs = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks)); 271 for (const auto& iter: m_pageMap) { 272 WebPage* page = iter.value.get(); 273 WebFrame* mainFrame = page->mainWebFrame(); 274 if (!mainFrame) 275 continue; 276 String mainFrameOriginString; 277 RefPtr<SecurityOrigin> mainFrameOrigin = SecurityOrigin::createFromString(mainFrame->url()); 278 if (!mainFrameOrigin->isUnique()) 279 mainFrameOriginString = mainFrameOrigin->toRawString(); 280 else 281 mainFrameOriginString = URL(URL(), mainFrame->url()).protocol() + ':'; // toRawString() is not supposed to work with unique origins, and would just return "://". 282 283 NSURL *originAsNSURL = [NSURL URLWithString:mainFrameOriginString]; 284 // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear how we can possibly have a malformed URL here, 285 // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case. 286 ASSERT(originAsNSURL); 287 NSString *userVisibleOriginString = originAsNSURL ? userVisibleString(originAsNSURL) : @"(null)"; 288 289 CFArrayAppendValue(activePageURLs.get(), userVisibleOriginString); 290 } 291 WKSetApplicationInformationItem(CFSTR("LSActivePageUserVisibleOriginsKey"), activePageURLs.get()); 292#endif 293} 294 295} // namespace WebKit 296