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