There should only be one way to get the system memory size.
[WebKit-https.git] / Source / WebKit2 / WebProcess / cocoa / WebProcessCocoa.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 "CustomProtocolManager.h"
30 #import "ObjCObjectGraph.h"
31 #import "SandboxExtension.h"
32 #import "SandboxInitializationParameters.h"
33 #import "SecItemShim.h"
34 #import "WKBrowsingContextHandleInternal.h"
35 #import "WKFullKeyboardAccessWatcher.h"
36 #import "WKTypeRefWrapper.h"
37 #import "WKWebProcessPlugInBrowserContextControllerInternal.h"
38 #import "WebFrame.h"
39 #import "WebInspector.h"
40 #import "WebPage.h"
41 #import "WebProcessCreationParameters.h"
42 #import "WebProcessProxyMessages.h"
43 #import <JavaScriptCore/Options.h>
44 #import <WebCore/AXObjectCache.h>
45 #import <WebCore/CFNetworkSPI.h>
46 #import <WebCore/FileSystem.h>
47 #import <WebCore/FontCascade.h>
48 #import <WebCore/LocalizedStrings.h>
49 #import <WebCore/MemoryCache.h>
50 #import <WebCore/MemoryPressureHandler.h>
51 #import <WebCore/PageCache.h>
52 #import <WebCore/WebCoreNSURLExtras.h>
53 #import <WebKitSystemInterface.h>
54 #import <algorithm>
55 #import <dispatch/dispatch.h>
56 #import <objc/runtime.h>
57 #import <stdio.h>
58 #import <wtf/RamSize.h>
59
60 #define ENABLE_MANUAL_WEBPROCESS_SANDBOXING !PLATFORM(IOS)
61
62 using namespace WebCore;
63
64 namespace WebKit {
65
66 static uint64_t volumeFreeSize(NSString *path)
67 {
68     NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
69     return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
70 }
71
72 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
73 {
74     RetainPtr<NSString> nsurlCacheDirectory = adoptNS((NSString *)WKCopyFoundationCacheDirectory());
75     if (!nsurlCacheDirectory)
76         nsurlCacheDirectory = NSHomeDirectory();
77
78     uint64_t memSize = ramSize() / 1024 / 1024;
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 diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
83
84     unsigned cacheTotalCapacity = 0;
85     unsigned cacheMinDeadCapacity = 0;
86     unsigned cacheMaxDeadCapacity = 0;
87     auto deadDecodedDataDeletionInterval = std::chrono::seconds { 0 };
88     unsigned pageCacheSize = 0;
89     unsigned long urlCacheMemoryCapacity = 0;
90     unsigned long urlCacheDiskCapacity = 0;
91
92     calculateCacheSizes(cacheModel, memSize, diskFreeSize,
93         cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
94         pageCacheSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
95
96     auto& memoryCache = MemoryCache::singleton();
97     memoryCache.setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
98     memoryCache.setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
99     PageCache::singleton().setMaxSize(pageCacheSize);
100
101     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
102
103     [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
104     if (!m_diskCacheIsDisabledForTesting)
105         [nsurlCache setDiskCapacity:std::max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
106 }
107
108 void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear)
109 {
110     if (cachesToClear == InMemoryResourceCachesOnly)
111         return;
112
113     // If we're using the network process then it is the only one that needs to clear the disk cache.
114     if (usesNetworkProcess())
115         return;
116
117     if (!m_clearResourceCachesDispatchGroup)
118         m_clearResourceCachesDispatchGroup = dispatch_group_create();
119
120     dispatch_group_async(m_clearResourceCachesDispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
121         [[NSURLCache sharedURLCache] removeAllCachedResponses];
122     });
123 }
124
125 #if USE(APPKIT)
126 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
127 {
128     WebPage* page = WebProcess::singleton().focusedWebPage();
129     if (!page || !page->accessibilityRemoteObject())
130         return 0;
131
132     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
133 }
134 #endif
135
136 void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& parameters)
137 {
138 #if ENABLE(SANDBOX_EXTENSIONS)
139     SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
140     SandboxExtension::consumePermanently(parameters.webSQLDatabaseDirectoryExtensionHandle);
141     SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
142     SandboxExtension::consumePermanently(parameters.diskCacheDirectoryExtensionHandle);
143     SandboxExtension::consumePermanently(parameters.mediaKeyStorageDirectoryExtensionHandle);
144 #if PLATFORM(IOS)
145     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
146     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
147     SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle);
148 #endif
149 #endif
150
151     // FIXME: Most of what this function does for cache size gets immediately overridden by setCacheModel().
152     // - memory cache size passed from UI process is always ignored;
153     // - disk cache size passed from UI process is effectively a minimum size.
154     // One non-obvious constraint is that we need to use -setSharedURLCache: even in testing mode, to prevent creating a default one on disk later, when some other code touches the cache.
155
156     ASSERT(!m_diskCacheIsDisabledForTesting || !parameters.nsURLCacheDiskCapacity);
157
158 #if PLATFORM(IOS)
159     if (!parameters.uiProcessBundleIdentifier.isNull()) {
160         [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc]
161             _initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity
162             diskCapacity:parameters.nsURLCacheDiskCapacity
163             relativePath:parameters.uiProcessBundleIdentifier]).get()];
164     }
165 #else
166     if (!parameters.diskCacheDirectory.isNull()) {
167         [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc]
168             initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity
169             diskCapacity:parameters.nsURLCacheDiskCapacity
170             diskPath:parameters.diskCacheDirectory]).get()];
171     }
172 #endif
173
174     m_compositingRenderServerPort = WTF::move(parameters.acceleratedCompositingPort);
175     m_presenterApplicationPid = parameters.presenterApplicationPid;
176     FontCascade::setDefaultTypesettingFeatures(parameters.shouldEnableKerningAndLigaturesByDefault ? Kerning | Ligatures : 0);
177
178     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
179
180     setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled);
181
182 #if USE(APPKIT)
183     [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions" : @YES }];
184
185     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
186     // no window in WK2, NSApplication needs to use the focused page's focused element.
187     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
188     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
189 #endif
190 #if (TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
191     _CFNetworkSetATSContext(parameters.networkATSContext.get());
192 #endif
193 }
194
195 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
196 {
197 #if !PLATFORM(IOS)
198     NSString *applicationName;
199     if (parameters.extraInitializationData.get(ASCIILiteral("inspector-process")) == "1")
200         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Inspector", "Visible name of Web Inspector's web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
201     else
202         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
203     WKSetVisibleApplicationName((CFStringRef)applicationName);
204 #endif
205 }
206
207 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
208 {
209     WKAXRegisterRemoteApp();
210
211 #if ENABLE(SEC_ITEM_SHIM)
212     SecItemShim::singleton().initialize(this);
213 #endif
214 }
215
216 #if USE(APPKIT)
217 void WebProcess::stopRunLoop()
218 {
219     ChildProcess::stopNSAppRunLoop();
220 }
221 #endif
222
223 void WebProcess::platformTerminate()
224 {
225     if (m_clearResourceCachesDispatchGroup) {
226         dispatch_group_wait(m_clearResourceCachesDispatchGroup, DISPATCH_TIME_FOREVER);
227         dispatch_release(m_clearResourceCachesDispatchGroup);
228         m_clearResourceCachesDispatchGroup = 0;
229     }
230 }
231
232 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
233 {
234 #if ENABLE(WEB_PROCESS_SANDBOX)
235 #if ENABLE_MANUAL_WEBPROCESS_SANDBOXING
236     // Need to override the default, because service has a different bundle ID.
237     NSBundle *webkit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
238 #if PLATFORM(IOS)
239     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
240 #else
241     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
242 #endif
243     ChildProcess::initializeSandbox(parameters, sandboxParameters);
244 #endif
245 #else
246     UNUSED_PARAM(parameters);
247     UNUSED_PARAM(sandboxParameters);
248 #endif
249 }
250
251 #if PLATFORM(MAC)
252
253 static NSURL *origin(WebPage& page)
254 {
255     WebFrame* mainFrame = page.mainWebFrame();
256     if (!mainFrame)
257         return nil;
258
259     URL mainFrameURL(URL(), mainFrame->url());
260     RefPtr<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
261     String mainFrameOriginString;
262     if (!mainFrameOrigin->isUnique())
263         mainFrameOriginString = mainFrameOrigin->toRawString();
264     else
265         mainFrameOriginString = mainFrameURL.protocol() + ':'; // toRawString() is not supposed to work with unique origins, and would just return "://".
266
267     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
268     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
269     ASSERT([NSURL URLWithString:mainFrameOriginString]);
270
271     return [NSURL URLWithString:mainFrameOriginString];
272 }
273
274 #endif
275
276 void WebProcess::updateActivePages()
277 {
278 #if PLATFORM(MAC)
279     RetainPtr<CFMutableArrayRef> activePageURLs = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
280     for (auto& page : m_pageMap.values()) {
281         if (NSURL *originAsURL = origin(*page))
282             CFArrayAppendValue(activePageURLs.get(), userVisibleString(originAsURL));
283     }
284     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activePageURLs] {
285         WKSetApplicationInformationItem(CFSTR("LSActivePageUserVisibleOriginsKey"), activePageURLs.get());
286     });
287 #endif
288 }
289
290 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
291 {
292     struct Transformer final : ObjCObjectGraph::Transformer {
293         Transformer(WebProcess& webProcess)
294             : m_webProcess(webProcess)
295         {
296         }
297
298         virtual bool shouldTransformObject(id object) const override
299         {
300 #if WK_API_ENABLED
301             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
302                 return true;
303
304             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
305                 return true;
306 #endif
307             return false;
308         }
309
310         virtual RetainPtr<id> transformObject(id object) const override
311         {
312 #if WK_API_ENABLED
313             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
314                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
315                     return wrapper(*webPage);
316
317                 return [NSNull null];
318             }
319
320             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
321                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
322 #endif
323             return object;
324         }
325
326         WebProcess& m_webProcess;
327     };
328
329     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
330 }
331
332 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
333 {
334     struct Transformer final : ObjCObjectGraph::Transformer {
335         virtual bool shouldTransformObject(id object) const override
336         {
337 #if WK_API_ENABLED
338             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
339                 return true;
340
341             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
342                 return true;
343 #endif
344
345             return false;
346         }
347
348         virtual RetainPtr<id> transformObject(id object) const override
349         {
350 #if WK_API_ENABLED
351             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
352                 return controller.handle;
353
354             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
355                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
356 #endif
357             return object;
358         }
359     };
360
361     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
362 }
363
364 } // namespace WebKit