[Mac] Crashes in CFURLGetBytes under WebProcess::updateActivePages()
[WebKit-https.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 "CustomProtocolManager.h"
30 #import "SandboxExtension.h"
31 #import "SandboxInitializationParameters.h"
32 #import "WKFullKeyboardAccessWatcher.h"
33 #import "WebFrame.h"
34 #import "WebInspector.h"
35 #import "WebPage.h"
36 #import "WebProcessCreationParameters.h"
37 #import "WebProcessProxyMessages.h"
38 #import <WebCore/FileSystem.h>
39 #import <WebCore/Font.h>
40 #import <WebCore/LocalizedStrings.h>
41 #import <WebCore/MemoryCache.h>
42 #import <WebCore/PageCache.h>
43 #import <WebCore/WebCoreNSURLExtras.h>
44 #import <WebKitSystemInterface.h>
45 #import <algorithm>
46 #import <dispatch/dispatch.h>
47 #import <mach/host_info.h>
48 #import <mach/mach.h>
49 #import <mach/mach_error.h>
50 #import <objc/runtime.h>
51 #import <stdio.h>
52
53 #if USE(SECURITY_FRAMEWORK)
54 #import "SecItemShim.h"
55 #endif
56
57 using namespace WebCore;
58
59 const CFStringRef kLSActivePageUserVisibleOriginsKey = CFSTR("LSActivePageUserVisibleOriginsKey");
60
61 namespace WebKit {
62
63 static uint64_t memorySize()
64 {
65     static host_basic_info_data_t hostInfo;
66
67     static dispatch_once_t once;
68     dispatch_once(&once, ^() {
69         mach_port_t host = mach_host_self();
70         mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
71         kern_return_t r = host_info(host, HOST_BASIC_INFO, (host_info_t)&hostInfo, &count);
72         mach_port_deallocate(mach_task_self(), host);
73
74         if (r != KERN_SUCCESS)
75             LOG_ERROR("%s : host_info(%d) : %s.\n", __FUNCTION__, r, mach_error_string(r));
76     });
77
78     return hostInfo.max_mem;
79 }
80
81 static uint64_t volumeFreeSize(NSString *path)
82 {
83     NSDictionary *fileSystemAttributesDictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:NULL];
84     return [[fileSystemAttributesDictionary objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
85 }
86
87 void WebProcess::platformSetCacheModel(CacheModel cacheModel)
88 {
89     RetainPtr<NSString> nsurlCacheDirectory = adoptNS((NSString *)WKCopyFoundationCacheDirectory());
90     if (!nsurlCacheDirectory)
91         nsurlCacheDirectory = NSHomeDirectory();
92
93     // As a fudge factor, use 1000 instead of 1024, in case the reported byte 
94     // count doesn't align exactly to a megabyte boundary.
95     uint64_t memSize = memorySize() / 1024 / 1000;
96     uint64_t diskFreeSize = volumeFreeSize(nsurlCacheDirectory.get()) / 1024 / 1000;
97
98     unsigned cacheTotalCapacity = 0;
99     unsigned cacheMinDeadCapacity = 0;
100     unsigned cacheMaxDeadCapacity = 0;
101     double deadDecodedDataDeletionInterval = 0;
102     unsigned pageCacheCapacity = 0;
103     unsigned long urlCacheMemoryCapacity = 0;
104     unsigned long urlCacheDiskCapacity = 0;
105
106     calculateCacheSizes(cacheModel, memSize, diskFreeSize,
107         cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
108         pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);
109
110
111     memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
112     memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
113     pageCache()->setCapacity(pageCacheCapacity);
114
115     NSURLCache *nsurlCache = [NSURLCache sharedURLCache];
116
117 #if ENABLE(NETWORK_PROCESS)
118     // FIXME: Once there is no loading being done in the WebProcess, we should remove this,
119     // as calling [NSURLCache sharedURLCache] initializes the cache, which we would rather not do.
120     if (m_usesNetworkProcess) {
121         [nsurlCache setMemoryCapacity:0];
122         [nsurlCache setDiskCapacity:0];
123         return;
124     }
125 #endif
126
127     [nsurlCache setMemoryCapacity:urlCacheMemoryCapacity];
128     [nsurlCache setDiskCapacity:max<unsigned long>(urlCacheDiskCapacity, [nsurlCache diskCapacity])]; // Don't shrink a big disk cache, since that would cause churn.
129 }
130
131 void WebProcess::platformClearResourceCaches(ResourceCachesToClear cachesToClear)
132 {
133     if (cachesToClear == InMemoryResourceCachesOnly)
134         return;
135
136     // If we're using the network process then it is the only one that needs to clear the disk cache.
137     if (usesNetworkProcess())
138         return;
139
140     if (!m_clearResourceCachesDispatchGroup)
141         m_clearResourceCachesDispatchGroup = dispatch_group_create();
142
143     dispatch_group_async(m_clearResourceCachesDispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
144         [[NSURLCache sharedURLCache] removeAllCachedResponses];
145     });
146 }
147
148 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
149 {
150     WebPage* page = WebProcess::shared().focusedWebPage();
151     if (!page || !page->accessibilityRemoteObject())
152         return 0;
153
154     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
155 }
156
157 void WebProcess::platformInitializeWebProcess(const WebProcessCreationParameters& parameters, CoreIPC::MessageDecoder&)
158 {
159     SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
160     SandboxExtension::consumePermanently(parameters.localStorageDirectoryExtensionHandle);
161     SandboxExtension::consumePermanently(parameters.databaseDirectoryExtensionHandle);
162     SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
163     SandboxExtension::consumePermanently(parameters.diskCacheDirectoryExtensionHandle);
164
165     // When the network process is enabled, each web process wants a stand-alone
166     // NSURLCache, which it can disable to save memory.
167 #if ENABLE(NETWORK_PROCESS)
168     if (!m_usesNetworkProcess) {
169 #endif
170         if (!parameters.diskCacheDirectory.isNull()) {
171             [NSURLCache setSharedURLCache:adoptNS([[NSURLCache alloc]
172                 initWithMemoryCapacity:parameters.nsURLCacheMemoryCapacity
173                 diskCapacity:parameters.nsURLCacheDiskCapacity
174                 diskPath:parameters.diskCacheDirectory]).get()];
175         }
176 #if ENABLE(NETWORK_PROCESS)
177     }
178 #endif
179
180     m_shouldForceScreenFontSubstitution = parameters.shouldForceScreenFontSubstitution;
181     Font::setDefaultTypesettingFeatures(parameters.shouldEnableKerningAndLigaturesByDefault ? Kerning | Ligatures : 0);
182
183     m_compositingRenderServerPort = parameters.acceleratedCompositingPort.port();
184
185     m_presenterApplicationPid = parameters.presenterApplicationPid;
186
187     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
188     // no window in WK2, NSApplication needs to use the focused page's focused element.
189     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
190     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
191 }
192
193 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
194 {
195     NSString *applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
196     WKSetVisibleApplicationName((CFStringRef)applicationName);
197 }
198
199 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
200 {
201     WKAXRegisterRemoteApp();
202
203 #if USE(SECURITY_FRAMEWORK)
204     SecItemShim::shared().initialize(this);
205 #endif
206 }
207
208 void WebProcess::platformTerminate()
209 {
210     if (m_clearResourceCachesDispatchGroup) {
211         dispatch_group_wait(m_clearResourceCachesDispatchGroup, DISPATCH_TIME_FOREVER);
212         dispatch_release(m_clearResourceCachesDispatchGroup);
213         m_clearResourceCachesDispatchGroup = 0;
214     }
215 }
216
217 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
218 {
219     // Need to overide the default, because service has a different bundle ID.
220     NSBundle *webkit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
221     sandboxParameters.setOverrideSandboxProfilePath([webkit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
222
223     ChildProcess::initializeSandbox(parameters, sandboxParameters);
224 }
225
226 void WebProcess::updateActivePages()
227 {
228 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
229     RetainPtr<CFMutableArrayRef> activePageURLs = adoptCF(CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
230     for (const auto& iter: m_pageMap) {
231         WebPage* page = iter.value.get();
232         WebFrame* mainFrame = page->mainWebFrame();
233         if (!mainFrame)
234             continue;
235         String mainFrameOriginString;
236         RefPtr<SecurityOrigin> mainFrameOrigin = SecurityOrigin::createFromString(mainFrame->url());
237         if (!mainFrameOrigin->isUnique())
238             mainFrameOriginString = mainFrameOrigin->toRawString();
239         else
240             mainFrameOriginString = KURL(KURL(), mainFrame->url()).protocol() + ':'; // toRawString() is not supposed to work with unique origins, and would just return "://".
241
242         NSURL *originAsNSURL = [NSURL URLWithString:mainFrameOriginString];
243         // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear how we can possibly have a malformed URL here,
244         // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
245         ASSERT(originAsNSURL);
246         NSString *userVisibleOriginString = originAsNSURL ? userVisibleString(originAsNSURL) : @"(null)";
247
248         CFArrayAppendValue(activePageURLs.get(), userVisibleOriginString);
249     }
250     WKSetApplicationInformationItem(kLSActivePageUserVisibleOriginsKey, activePageURLs.get());
251 #endif
252 }
253
254 } // namespace WebKit