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