2011-01-24 Maciej Stachowiak <mjs@apple.com>
[WebKit.git] / Source / WebKit2 / WebProcess / mac / WebProcessMac.mm
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 "WebProcess.h"
27
28 #import "SandboxExtension.h"
29 #import "WebProcessCreationParameters.h"
30 #import <WebCore/MemoryCache.h>
31 #import <WebCore/PageCache.h>
32 #import <WebKitSystemInterface.h>
33 #import <algorithm>
34 #import <dispatch/dispatch.h>
35 #import <mach/host_info.h>
36 #import <mach/mach.h>
37 #import <mach/mach_error.h>
38
39 #if ENABLE(WEB_PROCESS_SANDBOX)
40 #import <sandbox.h>
41 #import <stdlib.h>
42 #import <sysexits.h>
43 #endif
44
45 using namespace WebCore;
46 using namespace std;
47
48 namespace WebKit {
49
50 static uint64_t memorySize()
51 {
52     static host_basic_info_data_t hostInfo;
53
54     static dispatch_once_t once;
55     dispatch_once(&once, ^() {
56         mach_port_t host = mach_host_self();
57         mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
58         kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
59         mach_port_deallocate(mach_task_self(), host);
60
61         if (r != KERN_SUCCESS)
62             LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
63     });
64
65     return hostInfo.max_mem;
66 }
67
68 static uint64_t volumeFreeSize(NSString *path)
69 {
70     NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
71     return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
72 }
73
74 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
75 {
76     RetainPtr<NSString> nsurlCacheDirectory(AdoptNS, (NSString *)WKCopyFoundationCacheDirectory());
77     if (!nsurlCacheDirectory)
78         nsurlCacheDirectory.adoptNS(NSHomeDirectory());
79
80     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
81     // count doesn't align exactly to a megabyte boundary.
82     uint64_t memSize = memorySize() / 1024 / 1000;
83     uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
84
85     unsigned cacheTotalCapacity = 0;
86     unsigned cacheMinDeadCapacity = 0;
87     unsigned cacheMaxDeadCapacity = 0;
88     double deadDecodedDataDeletionInterval = 0;
89     unsigned pageCacheCapacity = 0;
90     unsigned long urlCacheMemoryCapacity = 0;
91     unsigned long urlCacheDiskCapacity = 0;
92
93     calculateCacheSizes(cacheModel, memSize, diskFreeSize,
94         cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
95         pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);
96
97
98     memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
99     memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
100     pageCache()->setCapacity(pageCacheCapacity);
101
102     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
103     [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
104     [nsurlCache setDiskCapacity:max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
105 }
106
107 void WebProcess::platformClearResourceCaches()
108 {
109     [[NSURLCache sharedURLCache] removeAllCachedResponses];
110 }
111
112 static void initializeSandbox(const WebProcessCreationParameters& parameters)
113 {
114 #if ENABLE(WEB_PROCESS_SANDBOX)
115     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DisableSandbox"]) {
116         fprintf(stderr, "Bypassing sandbox due to DisableSandbox user default.\n");
117         return;
118     }
119
120     char* errorBuf;
121     char tmpPath[PATH_MAX];
122     char tmpRealPath[PATH_MAX];
123     char cachePath[PATH_MAX];
124     char cacheRealPath[PATH_MAX];
125     const char* frameworkPath = [[[[NSBundle bundleForClass:NSClassFromString(@"WKView")] bundlePath] stringByDeletingLastPathComponent] UTF8String];
126     const char* profilePath = [[[NSBundle mainBundle] pathForResource:@"com.apple.WebProcess" ofType:@"sb"] UTF8String];
127
128     if (confstr(_CS_DARWIN_USER_TEMP_DIR, tmpPath, PATH_MAX) <= 0 || !realpath(tmpPath, tmpRealPath))
129         tmpRealPath[0] = '\0';
130
131     if (confstr(_CS_DARWIN_USER_CACHE_DIR, cachePath, PATH_MAX) <= 0 || !realpath(cachePath, cacheRealPath))
132         cacheRealPath[0] = '\0';
133
134     const char* const sandboxParam[] = {
135         "WEBKIT2_FRAMEWORK_DIR", frameworkPath,
136         "DARWIN_USER_TEMP_DIR", (const char*)tmpRealPath,
137         "DARWIN_USER_CACHE_DIR", (const char*)cacheRealPath,
138         "WEBKIT_DATABASE_DIR", (const char*)parameters.databaseDirectory.data(),
139         "NSURL_CACHE_DIR", (const char*)parameters.nsURLCachePath.data(),
140         "UI_PROCESS_BUNDLE_RESOURCE_DIR", (const char*)parameters.uiProcessBundleResourcePath.data(),
141         NULL
142     };
143
144     if (sandbox_init_with_parameters(profilePath, SANDBOX_NAMED_EXTERNAL, sandboxParam, &errorBuf)) {
145         fprintf(stderr, "WebProcess: couldn't initialize sandbox profile [%s] with framework path [%s], tmp path [%s], cache path [%s]: %s\n", profilePath, frameworkPath, tmpRealPath, cacheRealPath, errorBuf);
146         exit(EX_NOPERM);
147     }
148 #endif
149 }
150
151 void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::ArgumentDecoder*)
152 {
153     initializeSandbox(parameters);
154
155     if (!parameters.parentProcessName.isNull()) {
156         // FIXME (WebKit2) <rdar://problem/8728860> WebKit2 needs to be localized
157         NSString *applicationName = [NSString stringWithFormat:@"%@ Web Content", (NSString *)parameters.parentProcessName];
158         WKSetVisibleApplicationName((CFStringRef)applicationName);
159     }
160
161     if (!parameters.nsURLCachePath.isNull()) {
162         NSUInteger cacheMemoryCapacity = parameters.nsURLCacheMemoryCapacity;
163         NSUInteger cacheDiskCapacity = parameters.nsURLCacheDiskCapacity;
164
165         NSString *nsCachePath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:parameters.nsURLCachePath.data() length:parameters.nsURLCachePath.length()];
166         RetainPtr<NSURLCache> parentProcessURLCache(AdoptNS, [[NSURLCache alloc] initWithMemoryCapacity:cacheMemoryCapacity diskCapacity:cacheDiskCapacity diskPath:nsCachePath]);
167         [NSURLCache setSharedURLCache:parentProcessURLCache.get()];
168     }
169
170     m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port();
171 }
172
173 void WebProcess::platformShutdown()
174 {
175 }
176
177 } // namespace WebKit