2 * Copyright (C) 2010 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #import "WebProcess.h"
29 #import "FullKeyboardAccessWatcher.h"
30 #import "SandboxExtension.h"
32 #import "WebProcessCreationParameters.h"
33 #import "WebProcessProxyMessages.h"
34 #import <WebCore/FileSystem.h>
35 #import <WebCore/LocalizedStrings.h>
36 #import <WebCore/MemoryCache.h>
37 #import <WebCore/PageCache.h>
38 #import <WebKitSystemInterface.h>
40 #import <dispatch/dispatch.h>
41 #import <mach/host_info.h>
43 #import <mach/mach_error.h>
44 #import <objc/runtime.h>
47 #if defined(BUILDING_ON_SNOW_LEOPARD)
48 #import "KeychainItemShimMethods.h"
50 #import "SecItemShimMethods.h"
53 #if ENABLE(WEB_PROCESS_SANDBOX)
57 // We have to #undef __APPLE_API_PRIVATE to prevent sandbox.h from looking for a header file that does not exist (<rdar://problem/9679211>).
58 #undef __APPLE_API_PRIVATE
61 #define SANDBOX_NAMED_EXTERNAL 0x0003
62 extern "C" int sandbox_init_with_parameters(const char *profile, uint64_t flags, const char *const parameters[], char **errorbuf);
66 using namespace WebCore;
71 static uint64_t memorySize()
73 static host_basic_info_data_t hostInfo;
75 static dispatch_once_t once;
76 dispatch_once(&once, ^() {
77 mach_port_t host = mach_host_self();
78 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
79 kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
80 mach_port_deallocate(mach_task_self(), host);
82 if (r != KERN_SUCCESS)
83 LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
86 return hostInfo.max_mem;
89 static uint64_t volumeFreeSize(NSString *path)
91 NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
92 return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
95 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
97 RetainPtr<NSString> nsurlCacheDirectory(AdoptNS, (NSString *)WKCopyFoundationCacheDirectory());
98 if (!nsurlCacheDirectory)
99 nsurlCacheDirectory = NSHomeDirectory();
101 // As a fudge factor, use 1000 instead of 1024, in case the reported byte
102 // count doesn't align exactly to a megabyte boundary.
103 uint64_t memSize = memorySize() / 1024 / 1000;
104 uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
106 unsigned cacheTotalCapacity = 0;
107 unsigned cacheMinDeadCapacity = 0;
108 unsigned cacheMaxDeadCapacity = 0;
109 double deadDecodedDataDeletionInterval = 0;
110 unsigned pageCacheCapacity = 0;
111 unsigned long urlCacheMemoryCapacity = 0;
112 unsigned long urlCacheDiskCapacity = 0;
114 calculateCacheSizes(cacheModel, memSize, diskFreeSize,
115 cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
116 pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);
119 memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
120 memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
121 pageCache()->setCapacity(pageCacheCapacity);
123 NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
124 [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
125 [nsurlCache setDiskCapacity:max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
128 void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear)
130 if (cachesToClear == InMemoryResourceCachesOnly)
132 [[NSURLCache sharedURLCache] removeAllCachedResponses];
135 bool WebProcess::fullKeyboardAccessEnabled()
137 return [FullKeyboardAccessWatcher fullKeyboardAccessEnabled];
140 #if ENABLE(WEB_PROCESS_SANDBOX)
141 static void appendSandboxParameterPathInternal(Vector<const char*>& vector, const char* name, const char* path)
143 char normalizedPath[PATH_MAX];
144 if (!realpath(path, normalizedPath))
145 normalizedPath[0] = '\0';
148 vector.append(fastStrDup(normalizedPath));
151 static void appendReadwriteConfDirectory(Vector<const char*>& vector, const char* name, int confID)
154 if (confstr(confID, path, PATH_MAX) <= 0)
157 appendSandboxParameterPathInternal(vector, name, path);
160 static void appendReadonlySandboxDirectory(Vector<const char*>& vector, const char* name, NSString *path)
162 appendSandboxParameterPathInternal(vector, name, [(NSString *)path fileSystemRepresentation]);
165 static void appendReadwriteSandboxDirectory(Vector<const char*>& vector, const char* name, NSString *path)
167 NSError *error = nil;
169 // This is very unlikely to fail, but in case it actually happens, we'd like some sort of output in the console.
170 if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error])
171 NSLog(@"could not create \"%@\", error %@", path, error);
173 appendSandboxParameterPathInternal(vector, name, [(NSString *)path fileSystemRepresentation]);
178 static void initializeSandbox(const WebProcessCreationParameters& parameters)
180 #if ENABLE(WEB_PROCESS_SANDBOX)
181 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DisableSandbox"]) {
182 fprintf(stderr, "Bypassing sandbox due to DisableSandbox user default.\n");
186 Vector<const char*> sandboxParameters;
188 // These are read-only.
189 appendReadonlySandboxDirectory(sandboxParameters, "WEBKIT2_FRAMEWORK_DIR", [[[NSBundle bundleForClass:NSClassFromString(@"WKView")] bundlePath] stringByDeletingLastPathComponent]);
190 appendReadonlySandboxDirectory(sandboxParameters, "UI_PROCESS_BUNDLE_RESOURCE_DIR", parameters.uiProcessBundleResourcePath);
192 // These are read-write getconf paths.
193 appendReadwriteConfDirectory(sandboxParameters, "DARWIN_USER_TEMP_DIR", _CS_DARWIN_USER_TEMP_DIR);
194 appendReadwriteConfDirectory(sandboxParameters, "DARWIN_USER_CACHE_DIR", _CS_DARWIN_USER_CACHE_DIR);
196 // These are read-write paths.
197 appendReadwriteSandboxDirectory(sandboxParameters, "HOME_DIR", NSHomeDirectory());
198 appendReadwriteSandboxDirectory(sandboxParameters, "WEBKIT_DATABASE_DIR", parameters.databaseDirectory);
199 appendReadwriteSandboxDirectory(sandboxParameters, "WEBKIT_LOCALSTORAGE_DIR", parameters.localStorageDirectory);
200 appendReadwriteSandboxDirectory(sandboxParameters, "WEBKIT_APPLICATION_CACHE_DIR", parameters.applicationCacheDirectory);
201 appendReadwriteSandboxDirectory(sandboxParameters, "NSURL_CACHE_DIR", parameters.nsURLCachePath);
203 sandboxParameters.append(static_cast<const char*>(0));
205 const char* profilePath = [[[NSBundle mainBundle] pathForResource:@"com.apple.WebProcess" ofType:@"sb"] fileSystemRepresentation];
208 if (sandbox_init_with_parameters(profilePath, SANDBOX_NAMED_EXTERNAL, sandboxParameters.data(), &errorBuf)) {
209 fprintf(stderr, "WebProcess: couldn't initialize sandbox profile [%s]\n", profilePath);
210 for (size_t i = 0; sandboxParameters[i]; i += 2)
211 fprintf(stderr, "%s=%s\n", sandboxParameters[i], sandboxParameters[i + 1]);
215 for (size_t i = 0; sandboxParameters[i]; i += 2)
216 fastFree(const_cast<char*>(sandboxParameters[i + 1]));
220 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
222 WebPage* page = WebProcess::shared().focusedWebPage();
223 if (!page || !page->accessibilityRemoteObject())
226 return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
229 void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::ArgumentDecoder*)
231 [[NSFileManager defaultManager] changeCurrentDirectoryPath:[[NSBundle mainBundle] bundlePath]];
233 initializeSandbox(parameters);
235 if (!parameters.parentProcessName.isNull()) {
236 NSString *applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.parentProcessName];
237 WKSetVisibleApplicationName((CFStringRef)applicationName);
240 if (!parameters.nsURLCachePath.isNull()) {
241 NSUInteger cacheMemoryCapacity = parameters.nsURLCacheMemoryCapacity;
242 NSUInteger cacheDiskCapacity = parameters.nsURLCacheDiskCapacity;
244 RetainPtr<NSURLCache> parentProcessURLCache(AdoptNS, [[NSURLCache alloc] initWithMemoryCapacity:cacheMemoryCapacity diskCapacity:cacheDiskCapacity diskPath:parameters.nsURLCachePath]);
245 [NSURLCache setSharedURLCache:parentProcessURLCache.get()];
248 m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port();
250 // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
251 // no window in WK2, NSApplication needs to use the focused page's focused element.
252 Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
253 method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
256 void WebProcess::initializeShim()
258 #if defined(BUILDING_ON_SNOW_LEOPARD)
259 initializeKeychainItemShim();
261 initializeSecItemShim();
265 void WebProcess::platformTerminate()
269 } // namespace WebKit