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