Add missing builtin files to the JavaScriptCore Xcode project
[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
174 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
175 {
176 #if !PLATFORM(IOS)
177     NSString *applicationName;
178     if (parameters.extraInitializationData.get(ASCIILiteral("inspector-process")) == "1")
179         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];
180     else
181         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
182     WKSetVisibleApplicationName((CFStringRef)applicationName);
183 #endif
184 }
185
186 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
187 {
188     WKAXRegisterRemoteApp();
189
190 #if ENABLE(SEC_ITEM_SHIM)
191     SecItemShim::singleton().initialize(this);
192 #endif
193 }
194
195 #if USE(APPKIT)
196 void WebProcess::stopRunLoop()
197 {
198     ChildProcess::stopNSAppRunLoop();
199 }
200 #endif
201
202 void WebProcess::platformTerminate()
203 {
204 }
205
206 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
207 {
208 #if ENABLE(WEB_PROCESS_SANDBOX)
209 #if ENABLE(MANUAL_SANDBOXING)
210     // Need to override the default, because service has a different bundle ID.
211     NSBundle *webkit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
212 #if PLATFORM(IOS)
213     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
214 #else
215     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
216 #endif
217     ChildProcess::initializeSandbox(parameters, sandboxParameters);
218 #endif
219 #else
220     UNUSED_PARAM(parameters);
221     UNUSED_PARAM(sandboxParameters);
222 #endif
223 }
224
225 #if PLATFORM(MAC)
226
227 static NSURL *origin(WebPage& page)
228 {
229     WebFrame* mainFrame = page.mainWebFrame();
230     if (!mainFrame)
231         return nil;
232
233     URL mainFrameURL(URL(), mainFrame->url());
234     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
235     String mainFrameOriginString;
236     if (!mainFrameOrigin->isUnique())
237         mainFrameOriginString = mainFrameOrigin->toRawString();
238     else
239         mainFrameOriginString = mainFrameURL.protocol() + ':'; // toRawString() is not supposed to work with unique origins, and would just return "://".
240
241     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
242     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
243     ASSERT([NSURL URLWithString:mainFrameOriginString]);
244
245     return [NSURL URLWithString:mainFrameOriginString];
246 }
247
248 #endif
249
250 void WebProcess::updateActivePages()
251 {
252 #if PLATFORM(MAC)
253     RetainPtr<CFMutableArrayRef> activePageURLs = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
254     for (auto& page : m_pageMap.values()) {
255         if (NSURL *originAsURL = origin(*page))
256             CFArrayAppendValue(activePageURLs.get(), userVisibleString(originAsURL));
257     }
258     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activePageURLs] {
259         WKSetApplicationInformationItem(CFSTR("LSActivePageUserVisibleOriginsKey"), activePageURLs.get());
260     });
261 #endif
262 }
263
264 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
265 {
266     struct Transformer final : ObjCObjectGraph::Transformer {
267         Transformer(WebProcess& webProcess)
268             : m_webProcess(webProcess)
269         {
270         }
271
272         virtual bool shouldTransformObject(id object) const override
273         {
274 #if WK_API_ENABLED
275             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
276                 return true;
277
278             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
279                 return true;
280 #endif
281             return false;
282         }
283
284         virtual RetainPtr<id> transformObject(id object) const override
285         {
286 #if WK_API_ENABLED
287             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
288                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
289                     return wrapper(*webPage);
290
291                 return [NSNull null];
292             }
293
294             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
295                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
296 #endif
297             return object;
298         }
299
300         WebProcess& m_webProcess;
301     };
302
303     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
304 }
305
306 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
307 {
308     struct Transformer final : ObjCObjectGraph::Transformer {
309         virtual bool shouldTransformObject(id object) const override
310         {
311 #if WK_API_ENABLED
312             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
313                 return true;
314
315             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
316                 return true;
317 #endif
318
319             return false;
320         }
321
322         virtual RetainPtr<id> transformObject(id object) const override
323         {
324 #if WK_API_ENABLED
325             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
326                 return controller.handle;
327
328             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
329                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
330 #endif
331             return object;
332         }
333     };
334
335     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
336 }
337
338 void WebProcess::destroyRenderingResources()
339 {
340     WKDestroyRenderingResources();
341 }
342
343 } // namespace WebKit