[iOS] Deny mach lookup access to content filter service in the WebContent sandbox
[WebKit.git] / Source / WebKit / WebProcess / cocoa / WebProcessCocoa.mm
1 /*
2  * Copyright (C) 2010-2018 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 #import "WebProcessCocoa.h"
29
30 #import "LegacyCustomProtocolManager.h"
31 #import "LogInitialization.h"
32 #import "Logging.h"
33 #import "ObjCObjectGraph.h"
34 #import "ProcessAssertion.h"
35 #import "SandboxExtension.h"
36 #import "SandboxInitializationParameters.h"
37 #import "WKAPICast.h"
38 #import "WKBrowsingContextHandleInternal.h"
39 #import "WKCrashReporter.h"
40 #import "WKFullKeyboardAccessWatcher.h"
41 #import "WKTypeRefWrapper.h"
42 #import "WKWebProcessPlugInBrowserContextControllerInternal.h"
43 #import "WebFrame.h"
44 #import "WebInspector.h"
45 #import "WebPage.h"
46 #import "WebProcessCreationParameters.h"
47 #import "WebProcessDataStoreParameters.h"
48 #import "WebProcessProxyMessages.h"
49 #import "WebsiteDataStoreParameters.h"
50 #import <JavaScriptCore/ConfigFile.h>
51 #import <JavaScriptCore/Options.h>
52 #import <WebCore/AVAssetMIMETypeCache.h>
53 #import <WebCore/AXObjectCache.h>
54 #import <WebCore/CPUMonitor.h>
55 #import <WebCore/DisplayRefreshMonitorManager.h>
56 #import <WebCore/FontCache.h>
57 #import <WebCore/FontCascade.h>
58 #import <WebCore/HistoryController.h>
59 #import <WebCore/HistoryItem.h>
60 #import <WebCore/LocalizedStrings.h>
61 #import <WebCore/LogInitialization.h>
62 #import <WebCore/MemoryRelease.h>
63 #import <WebCore/NSScrollerImpDetails.h>
64 #import <WebCore/PerformanceLogging.h>
65 #import <WebCore/RuntimeApplicationChecks.h>
66 #import <WebCore/SWContextManager.h>
67 #import <algorithm>
68 #import <dispatch/dispatch.h>
69 #import <objc/runtime.h>
70 #import <pal/spi/cf/CFNetworkSPI.h>
71 #import <pal/spi/cf/CFUtilitiesSPI.h>
72 #import <pal/spi/cg/CoreGraphicsSPI.h>
73 #import <pal/spi/cocoa/LaunchServicesSPI.h>
74 #import <pal/spi/cocoa/NSAccessibilitySPI.h>
75 #import <pal/spi/cocoa/QuartzCoreSPI.h>
76 #import <pal/spi/cocoa/pthreadSPI.h>
77 #import <pal/spi/mac/NSApplicationSPI.h>
78 #import <stdio.h>
79 #import <wtf/FileSystem.h>
80 #import <wtf/cocoa/NSURLExtras.h>
81
82 #if PLATFORM(IOS)
83 #import "UIKitSPI.h"
84 #import <WebCore/ParentalControlsContentFilter.h>
85 #endif
86
87 #if PLATFORM(IOS_FAMILY)
88 #include <bmalloc/MemoryStatusSPI.h>
89 #endif
90
91 #if PLATFORM(IOS_FAMILY)
92 #import "AccessibilitySupportSPI.h"
93 #import "AssertionServicesSPI.h"
94 #import "WKAccessibilityWebPageObjectIOS.h"
95 #import <UIKit/UIAccessibility.h>
96 #import <pal/spi/ios/GraphicsServicesSPI.h>
97 #endif
98
99 #if PLATFORM(IOS_FAMILY) && USE(APPLE_INTERNAL_SDK)
100 #import <AXRuntime/AXDefines.h>
101 #import <AXRuntime/AXNotificationConstants.h>
102 #endif
103
104 #if PLATFORM(IOS_FAMILY) && !USE(APPLE_INTERNAL_SDK)
105 #define kAXPidStatusChangedNotification 0
106 #endif
107
108 #if PLATFORM(MAC)
109 #import "WKAccessibilityWebPageObjectMac.h"
110 #import "WebSwitchingGPUClient.h"
111 #import <WebCore/GraphicsContext3DManager.h>
112 #import <WebCore/ScrollbarThemeMac.h>
113 #import <pal/spi/mac/NSScrollerImpSPI.h>
114 #endif
115
116 #if USE(OS_STATE)
117 #import <os/state_private.h>
118 #endif
119
120 #if PLATFORM(COCOA)
121 #import <WebCore/NetworkExtensionContentFilter.h>
122 #endif
123
124 #if HAVE(CSCHECKFIXDISABLE)
125 extern "C" void _CSCheckFixDisable();
126 #endif
127
128 namespace WebKit {
129 using namespace WebCore;
130
131 #if PLATFORM(MAC)
132 static const Seconds cpuMonitoringInterval { 8_min };
133 static const double serviceWorkerCPULimit { 0.5 }; // 50% average CPU usage over 8 minutes.
134 #endif
135
136 void WebProcess::platformSetCacheModel(CacheModel)
137 {
138 }
139
140 #if USE(APPKIT)
141 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
142 {
143     WebPage* page = WebProcess::singleton().focusedWebPage();
144     if (!page || !page->accessibilityRemoteObject())
145         return 0;
146
147     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
148 }
149 #endif
150
151 void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters& parameters)
152 {
153 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
154     WebCore::initializeLogChannelsIfNecessary(parameters.webCoreLoggingChannels);
155     WebKit::initializeLogChannelsIfNecessary(parameters.webKitLoggingChannels);
156 #endif
157
158     WebCore::setApplicationBundleIdentifier(parameters.uiProcessBundleIdentifier);
159     WebCore::setApplicationSDKVersion(parameters.uiProcessSDKVersion);
160
161     m_uiProcessBundleIdentifier = parameters.uiProcessBundleIdentifier;
162
163 #if ENABLE(SANDBOX_EXTENSIONS)
164     SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
165 #if ENABLE(MEDIA_STREAM)
166     SandboxExtension::consumePermanently(parameters.audioCaptureExtensionHandle);
167 #endif
168 #if PLATFORM(IOS_FAMILY)
169     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
170     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
171     SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle);
172 #endif
173 #endif
174
175     // Disable NSURLCache.
176     auto urlCache = adoptNS([[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]);
177     [NSURLCache setSharedURLCache:urlCache.get()];
178
179 #if PLATFORM(MAC)
180     WebCore::FontCache::setFontWhitelist(parameters.fontWhitelist);
181 #endif
182
183     m_compositingRenderServerPort = WTFMove(parameters.acceleratedCompositingPort);
184
185     WebCore::registerMemoryReleaseNotifyCallbacks();
186     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
187
188     setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled);
189
190 #if USE(APPKIT)
191     [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions" : @YES }];
192
193     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
194     // no window in WK2, NSApplication needs to use the focused page's focused element.
195     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
196     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
197 #endif
198     
199 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
200     // Need to initialize accessibility for VoiceOver to work when the WebContent process is using NSRunLoop.
201     // Currently, it is also needed to allocate and initialize an NSApplication object.
202     [NSApplication _accessibilityInitialize];
203 #endif
204
205 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
206     // App nap must be manually enabled when not running the NSApplication run loop.
207     __CFRunLoopSetOptionsReason(__CFRunLoopOptionsEnableAppNap, CFSTR("Finished checkin as application - enable app nap"));
208 #endif
209
210 #if TARGET_OS_IPHONE
211     // Priority decay on iOS 9 is impacting page load time so we fix the priority of the WebProcess' main thread (rdar://problem/22003112).
212     pthread_set_fixedpriority_self();
213 #endif
214
215     if (!parameters.mediaMIMETypes.isEmpty())
216         setMediaMIMETypes(parameters.mediaMIMETypes);
217     else {
218         AVAssetMIMETypeCache::singleton().setCacheMIMETypesCallback([this](const Vector<String>& types) {
219             parentProcessConnection()->send(Messages::WebProcessProxy::CacheMediaMIMETypes(types), 0);
220         });
221     }
222
223 #if PLATFORM(MAC)
224     WebCore::setScreenProperties(parameters.screenProperties);
225 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
226     scrollerStylePreferenceChanged(parameters.useOverlayScrollbars);
227 #endif
228 #endif
229     
230 #if PLATFORM(IOS)
231     if (parameters.compilerServiceExtensionHandle)
232         SandboxExtension::consumePermanently(*parameters.compilerServiceExtensionHandle);
233
234     if (parameters.contentFilterExtensionHandle)
235         SandboxExtension::consumePermanently(*parameters.contentFilterExtensionHandle);
236     ParentalControlsContentFilter::setHasConsumedSandboxExtension(parameters.contentFilterExtensionHandle.hasValue());
237 #endif
238     
239 #if PLATFORM(COCOA)
240     if (parameters.neHelperExtensionHandle)
241         SandboxExtension::consumePermanently(*parameters.neHelperExtensionHandle);
242     if (parameters.neSessionManagerExtensionHandle)
243         SandboxExtension::consumePermanently(*parameters.neSessionManagerExtensionHandle);
244     NetworkExtensionContentFilter::setHasConsumedSandboxExtensions(parameters.neHelperExtensionHandle.hasValue() && parameters.neSessionManagerExtensionHandle.hasValue());
245 #endif
246 }
247
248 void WebProcess::platformSetWebsiteDataStoreParameters(WebProcessDataStoreParameters&& parameters)
249 {
250 #if ENABLE(SANDBOX_EXTENSIONS)
251     SandboxExtension::consumePermanently(parameters.webSQLDatabaseDirectoryExtensionHandle);
252     SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
253     SandboxExtension::consumePermanently(parameters.mediaCacheDirectoryExtensionHandle);
254     SandboxExtension::consumePermanently(parameters.mediaKeyStorageDirectoryExtensionHandle);
255     SandboxExtension::consumePermanently(parameters.javaScriptConfigurationDirectoryExtensionHandle);
256 #endif
257
258     if (!parameters.javaScriptConfigurationDirectory.isEmpty()) {
259         String javaScriptConfigFile = parameters.javaScriptConfigurationDirectory + "/JSC.config";
260         JSC::processConfigFile(javaScriptConfigFile.latin1().data(), "com.apple.WebKit.WebContent", m_uiProcessBundleIdentifier.latin1().data());
261     }
262 }
263
264 void WebProcess::initializeProcessName(const AuxiliaryProcessInitializationParameters&)
265 {
266 #if PLATFORM(MAC)
267 #if HAVE(CSCHECKFIXDISABLE)
268     // _CSCheckFixDisable() needs to be called before checking in with Launch Services.
269     _CSCheckFixDisable();
270 #endif
271     // This is necessary so that we are able to set the process' display name.
272     _RegisterApplication(nullptr, nullptr);
273
274     updateProcessName();
275 #endif
276 }
277
278 void WebProcess::updateProcessName()
279 {
280 #if PLATFORM(MAC)
281     NSString *applicationName;
282     switch (m_processType) {
283     case ProcessType::Inspector:
284         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Inspector", "Visible name of Web Inspector's web process. The argument is the application name."), (NSString *)m_uiProcessName];
285         break;
286     case ProcessType::ServiceWorker:
287         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Service Worker (%@)", "Visible name of Service Worker process. The argument is the application name."), (NSString *)m_uiProcessName, (NSString *)m_registrableDomain.string()];
288         break;
289     case ProcessType::PrewarmedWebContent:
290         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content (Prewarmed)", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
291         break;
292     case ProcessType::CachedWebContent:
293         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content (Cached)", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
294         break;
295     case ProcessType::WebContent:
296         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
297         break;
298     }
299
300     dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
301         // Note that it is important for _RegisterApplication() to have been called before setting the display name.
302         auto error = _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
303         ASSERT(!error);
304         if (error) {
305             RELEASE_LOG_ERROR(Process, "Failed to set the display name of the WebContent process, error code: %ld", static_cast<long>(error));
306             return;
307         }
308 #if !ASSERT_DISABLED
309         // It is possible for _LSSetApplicationInformationItem() to return 0 and yet fail to set the display name so we make sure the display name has actually been set.
310         String actualApplicationName = adoptCF((CFStringRef)_LSCopyApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey)).get();
311         ASSERT(!actualApplicationName.isEmpty());
312 #endif
313     });
314 #endif // PLATFORM(MAC)
315 }
316
317 #if PLATFORM(IOS_FAMILY)
318 void WebProcess::processTaskStateDidChange(ProcessTaskStateObserver::TaskState taskState)
319 {
320     // NOTE: This will be called from a background thread.
321     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::processTaskStateDidChange() - taskState(%d)", this, taskState);
322     if (taskState != ProcessTaskStateObserver::Running)
323         return;
324
325     LockHolder holder(m_processWasResumedAssertionsLock);
326     if (m_processWasResumedUIAssertion && m_processWasResumedOwnAssertion)
327         return;
328
329     // We were awakened from suspension unexpectedly. Notify the WebProcessProxy, but take a process assertion on our parent PID
330     // to ensure that it too is awakened.
331     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::processTaskStateChanged() Taking 'WebProcess was resumed' assertion on behalf on UIProcess", this);
332     m_processWasResumedUIAssertion = adoptNS([[BKSProcessAssertion alloc] initWithPID:parentProcessConnection()->remoteProcessID() flags:BKSProcessAssertionPreventTaskSuspend reason:BKSProcessAssertionReasonFinishTask name:@"WebProcess was resumed" withHandler:^(BOOL acquired) {
333         if (!acquired)
334             RELEASE_LOG_ERROR(ProcessSuspension, "%p - WebProcess::processTaskStateDidChange() failed to take 'WebProcess was resumed' assertion for parent process", this);
335     }]);
336     m_processWasResumedUIAssertion.get().invalidationHandler = [this] {
337         RELEASE_LOG_ERROR(ProcessSuspension, "%p - WebProcess::processTaskStateChanged() Releasing 'WebProcess was resumed' assertion on behalf on UIProcess due to invalidation", this);
338         releaseProcessWasResumedAssertions();
339     };
340     m_processWasResumedOwnAssertion = adoptNS([[BKSProcessAssertion alloc] initWithPID:getpid() flags:BKSProcessAssertionPreventTaskSuspend reason:BKSProcessAssertionReasonFinishTask name:@"WebProcess was resumed" withHandler:^(BOOL acquired) {
341         if (!acquired)
342             RELEASE_LOG_ERROR(ProcessSuspension, "%p - WebProcess::processTaskStateDidChange() failed to take 'WebProcess was resumed' assertion for WebContent process", this);
343     }]);
344     m_processWasResumedOwnAssertion.get().invalidationHandler = [this] {
345         RELEASE_LOG_ERROR(ProcessSuspension, "%p - WebProcess::processTaskStateChanged() Releasing 'WebProcess was resumed' assertion on behalf on WebContent process due to invalidation", this);
346         releaseProcessWasResumedAssertions();
347     };
348
349     parentProcessConnection()->sendWithAsyncReply(Messages::WebProcessProxy::ProcessWasResumed(), [this] {
350         RELEASE_LOG(ProcessSuspension, "%p - WebProcess::processTaskStateDidChange() Parent process handled ProcessWasResumed IPC, releasing our assertions", this);
351         releaseProcessWasResumedAssertions();
352     });
353 }
354
355 void WebProcess::releaseProcessWasResumedAssertions()
356 {
357     LockHolder holder(m_processWasResumedAssertionsLock);
358     if (m_processWasResumedUIAssertion) {
359         RELEASE_LOG(ProcessSuspension, "%p - WebProcess::releaseProcessWasResumedAssertions() Releasing parent process 'WebProcess was resumed' assertion", this);
360         [m_processWasResumedUIAssertion invalidate];
361         m_processWasResumedUIAssertion = nullptr;
362     }
363     if (m_processWasResumedOwnAssertion) {
364         RELEASE_LOG(ProcessSuspension, "%p - WebProcess::releaseProcessWasResumedAssertions() Releasing WebContent process 'WebProcess was resumed' assertion", this);
365         [m_processWasResumedOwnAssertion invalidate];
366         m_processWasResumedOwnAssertion = nullptr;
367     }
368 }
369
370 #endif
371
372 #if PLATFORM(IOS_FAMILY)
373 static NSString *webProcessLoaderAccessibilityBundlePath()
374 {
375     NSString *accessibilityBundlesPath = nil;
376 #if HAVE(ACCESSIBILITY_BUNDLES_PATH)
377     accessibilityBundlesPath = (__bridge NSString *)_AXSAccessibilityBundlesPath();
378 #else
379     accessibilityBundlesPath = (__bridge NSString *)GSSystemRootDirectory();
380 #if PLATFORM(MACCATALYST)
381     accessibilityBundlesPath = [accessibilityBundlesPath stringByAppendingPathComponent:@"System/iOSSupport"];
382 #endif
383     accessibilityBundlesPath = [accessibilityBundlesPath stringByAppendingPathComponent:@"System/Library/AccessibilityBundles"];
384 #endif // HAVE(ACCESSIBILITY_BUNDLES_PATH)
385     return [accessibilityBundlesPath stringByAppendingPathComponent:@"WebProcessLoader.axbundle"];
386 }
387 #endif
388
389 static void registerWithAccessibility()
390 {
391 #if USE(APPKIT)
392     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
393 #endif
394
395 #if PLATFORM(IOS_FAMILY)
396     NSString *bundlePath = webProcessLoaderAccessibilityBundlePath();
397     NSError *error = nil;
398     if (![[NSBundle bundleWithPath:bundlePath] loadAndReturnError:&error])
399         LOG_ERROR("Failed to load accessibility bundle at %@: %@", bundlePath, error);
400 #endif
401 }
402
403 #if USE(OS_STATE)
404 void WebProcess::registerWithStateDumper()
405 {
406     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
407
408         @autoreleasepool {
409             os_state_data_t os_state = nil;
410
411             // Only gather state on faults and sysdiagnose. It's overkill for
412             // general error messages.
413             if (hints->osh_api == OS_STATE_API_ERROR)
414                 return os_state;
415
416             // Create a dictionary to contain the collected state. This
417             // dictionary will be serialized and passed back to os_state.
418             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
419
420             {
421                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
422                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
423                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
424                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
425                 }
426                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
427             }
428
429             {
430                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
431                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
432                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
433                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
434                 }
435                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
436             }
437
438             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
439             for (auto& page : m_pageMap.values()) {
440                 if (page->usesEphemeralSession())
441                     continue;
442
443                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
444                 [pageLoadTimes addObject:date];
445             }
446
447             // Adding an empty array to the process state may provide an
448             // indication of the existance of private sessions, which we'd like
449             // to hide, so don't add empty arrays.
450             if ([pageLoadTimes count])
451                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
452
453             // --- Possibly add other state here as other entries in the dictionary. ---
454
455             // Submitting an empty process state object may provide an
456             // indication of the existance of private sessions, which we'd like
457             // to hide, so don't return empty dictionaries.
458             if (![stateDict count])
459                 return os_state;
460
461             // Serialize the accumulated process state so that we can put the
462             // result in an os_state_data_t structure.
463             NSError* error = nil;
464             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
465
466             if (!data) {
467                 ASSERT(data);
468                 return os_state;
469             }
470
471             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
472             os_state = (os_state_data_t)malloc(neededSize);
473             if (os_state) {
474                 memset(os_state, 0, neededSize);
475                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
476                 os_state->osd_data_size = data.length;
477                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
478                 memcpy(os_state->osd_data, data.bytes, data.length);
479             }
480
481             return os_state;
482         }
483     });
484 }
485 #endif
486
487 void WebProcess::platformInitializeProcess(const AuxiliaryProcessInitializationParameters& parameters)
488 {
489 #if PLATFORM(MAC)
490 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
491     // Deny the WebContent process access to the WindowServer.
492     // This call will not succeed if there are open WindowServer connections at this point.
493     auto retval = CGSSetDenyWindowServerConnections(true);
494     RELEASE_ASSERT(retval == kCGErrorSuccess);
495     // Make sure that we close any WindowServer connections after checking in with Launch Services.
496     CGSShutdownServerConnections();
497
498     SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
499 #else
500
501     if (![NSApp isRunning]) {
502         // This call is needed when the WebProcess is not running the NSApplication event loop.
503         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
504         launchServicesCheckIn();
505     }
506 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
507
508     m_uiProcessName = parameters.uiProcessName;
509 #endif // PLATFORM(MAC)
510
511     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
512         m_processType = ProcessType::Inspector;
513 #if ENABLE(SERVICE_WORKER)
514     else if (parameters.extraInitializationData.get("service-worker-process"_s) == "1") {
515         m_processType = ProcessType::ServiceWorker;
516 #if PLATFORM(MAC)
517         m_registrableDomain = RegistrableDomain::uncheckedCreateFromRegistrableDomainString(parameters.extraInitializationData.get("registrable-domain"_s));
518 #endif
519     }
520 #endif
521     else if (parameters.extraInitializationData.get("is-prewarmed"_s) == "1")
522         m_processType = ProcessType::PrewarmedWebContent;
523     else
524         m_processType = ProcessType::WebContent;
525
526     registerWithAccessibility();
527
528 #if USE(OS_STATE)
529     registerWithStateDumper();
530 #endif
531
532 #if HAVE(APP_SSO)
533     [NSURLSession _disableAppSSO];
534 #endif
535 }
536
537 #if USE(APPKIT)
538 void WebProcess::stopRunLoop()
539 {
540 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
541     AuxiliaryProcess::stopNSRunLoop();
542 #else
543     AuxiliaryProcess::stopNSAppRunLoop();
544 #endif
545 }
546 #endif
547
548 void WebProcess::platformTerminate()
549 {
550     AVAssetMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
551 }
552
553 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
554 {
555 #if USE(SOURCE_APPLICATION_AUDIT_DATA)
556     ASSERT(parentProcessConnection());
557     if (!parentProcessConnection())
558         return nullptr;
559     Optional<audit_token_t> auditToken = parentProcessConnection()->getAuditToken();
560     if (!auditToken)
561         return nullptr;
562     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&*auditToken, sizeof(*auditToken)));
563 #else
564     return nullptr;
565 #endif
566 }
567
568 void WebProcess::initializeSandbox(const AuxiliaryProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
569 {
570 #if PLATFORM(MAC) || PLATFORM(MACCATALYST)
571     // Need to override the default, because service has a different bundle ID.
572     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
573
574     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
575
576     AuxiliaryProcess::initializeSandbox(parameters, sandboxParameters);
577 #endif
578 }
579
580 #if PLATFORM(MAC)
581
582 static NSURL *origin(WebPage& page)
583 {
584     WebFrame* mainFrame = page.mainWebFrame();
585     if (!mainFrame)
586         return nil;
587
588     URL mainFrameURL = { URL(), mainFrame->url() };
589     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
590     String mainFrameOriginString;
591     if (!mainFrameOrigin->isUnique())
592         mainFrameOriginString = mainFrameOrigin->toRawString();
593     else
594         mainFrameOriginString = makeString(mainFrameURL.protocol(), ':'); // toRawString() is not supposed to work with unique origins, and would just return "://".
595
596     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
597     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
598     ASSERT([NSURL URLWithString:mainFrameOriginString]);
599
600     return [NSURL URLWithString:mainFrameOriginString];
601 }
602
603 #endif
604
605 #if PLATFORM(MAC)
606 static RetainPtr<NSArray<NSString *>> activePagesOrigins(const HashMap<PageIdentifier, RefPtr<WebPage>>& pageMap)
607 {
608     RetainPtr<NSMutableArray<NSString *>> activeOrigins = adoptNS([[NSMutableArray alloc] init]);
609
610     for (auto& page : pageMap.values()) {
611         if (page->usesEphemeralSession())
612             continue;
613
614         if (NSURL *originAsURL = origin(*page))
615             [activeOrigins addObject:WTF::userVisibleString(originAsURL)];
616     }
617
618     return activeOrigins;
619 }
620 #endif
621
622 void WebProcess::updateActivePages()
623 {
624 #if PLATFORM(MAC)
625     auto activeOrigins = activePagesOrigins(m_pageMap);
626
627     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activeOrigins = WTFMove(activeOrigins)] {
628         _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activeOrigins.get(), nullptr);
629     });
630 #endif
631 }
632
633 void WebProcess::getActivePagesOriginsForTesting(CompletionHandler<void(Vector<String>&&)>&& completionHandler)
634 {
635 #if PLATFORM(MAC)
636     auto activeOriginsAsNSStrings = activePagesOrigins(m_pageMap);
637     Vector<String> activeOrigins;
638     activeOrigins.reserveInitialCapacity([activeOriginsAsNSStrings count]);
639     for (NSString* activeOrigin in activeOriginsAsNSStrings.get())
640         activeOrigins.uncheckedAppend(activeOrigin);
641     completionHandler(WTFMove(activeOrigins));
642 #else
643     completionHandler({ });
644 #endif
645 }
646
647 void WebProcess::updateCPULimit()
648 {
649 #if PLATFORM(MAC)
650     Optional<double> cpuLimit;
651     if (m_processType == ProcessType::ServiceWorker)
652         cpuLimit = serviceWorkerCPULimit;
653     else {
654         // Use the largest limit among all pages in this process.
655         for (auto& page : m_pageMap.values()) {
656             auto pageCPULimit = page->cpuLimit();
657             if (!pageCPULimit) {
658                 cpuLimit = WTF::nullopt;
659                 break;
660             }
661             if (!cpuLimit || pageCPULimit > cpuLimit.value())
662                 cpuLimit = pageCPULimit;
663         }
664     }
665
666     if (m_cpuLimit == cpuLimit)
667         return;
668
669     m_cpuLimit = cpuLimit;
670     updateCPUMonitorState(CPUMonitorUpdateReason::LimitHasChanged);
671 #endif
672 }
673
674 void WebProcess::updateCPUMonitorState(CPUMonitorUpdateReason reason)
675 {
676 #if PLATFORM(MAC)
677     if (!m_cpuLimit) {
678         if (m_cpuMonitor)
679             m_cpuMonitor->setCPULimit(WTF::nullopt);
680         return;
681     }
682
683     if (!m_cpuMonitor) {
684         m_cpuMonitor = makeUnique<CPUMonitor>(cpuMonitoringInterval, [this](double cpuUsage) {
685             if (m_processType == ProcessType::ServiceWorker)
686                 RELEASE_LOG_ERROR(PerformanceLogging, "%p - Service worker process exceeded CPU limit of %.1f%% (was using %.1f%%)", this, m_cpuLimit.value() * 100, cpuUsage * 100);
687             else
688                 RELEASE_LOG_ERROR(PerformanceLogging, "%p - WebProcess exceeded CPU limit of %.1f%% (was using %.1f%%) hasVisiblePages? %d", this, m_cpuLimit.value() * 100, cpuUsage * 100, hasVisibleWebPage());
689             parentProcessConnection()->send(Messages::WebProcessProxy::DidExceedCPULimit(), 0);
690         });
691     } else if (reason == CPUMonitorUpdateReason::VisibilityHasChanged) {
692         // If the visibility has changed, stop the CPU monitor before setting its limit. This is needed because the CPU usage can vary wildly based on visibility and we would
693         // not want to report that a process has exceeded its background CPU limit even though most of the CPU time was used while the process was visible.
694         m_cpuMonitor->setCPULimit(WTF::nullopt);
695     }
696     m_cpuMonitor->setCPULimit(m_cpuLimit);
697 #else
698     UNUSED_PARAM(reason);
699 #endif
700 }
701
702 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
703 {
704     struct Transformer final : ObjCObjectGraph::Transformer {
705         Transformer(WebProcess& webProcess)
706             : m_webProcess(webProcess)
707         {
708         }
709
710         bool shouldTransformObject(id object) const override
711         {
712             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
713                 return true;
714
715             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
716             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
717                 return true;
718             ALLOW_DEPRECATED_DECLARATIONS_END
719             return false;
720         }
721
722         RetainPtr<id> transformObject(id object) const override
723         {
724             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
725                 if (auto* webPage = m_webProcess.webPage(handle._webPageID))
726                     return wrapper(*webPage);
727
728                 return [NSNull null];
729             }
730
731             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
732             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
733                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
734             ALLOW_DEPRECATED_DECLARATIONS_END
735             return object;
736         }
737
738         WebProcess& m_webProcess;
739     };
740
741     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
742 }
743
744 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
745 {
746     struct Transformer final : ObjCObjectGraph::Transformer {
747         bool shouldTransformObject(id object) const override
748         {
749             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
750                 return true;
751
752             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
753             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
754                 return true;
755             ALLOW_DEPRECATED_DECLARATIONS_END
756             return false;
757         }
758
759         RetainPtr<id> transformObject(id object) const override
760         {
761             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
762                 return controller.handle;
763
764             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
765             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
766                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
767             ALLOW_DEPRECATED_DECLARATIONS_END
768             return object;
769         }
770     };
771
772     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
773 }
774
775 void WebProcess::destroyRenderingResources()
776 {
777 #if !RELEASE_LOG_DISABLED
778     MonotonicTime startTime = MonotonicTime::now();
779 #endif
780     CABackingStoreCollectBlocking();
781 #if !RELEASE_LOG_DISABLED
782     MonotonicTime endTime = MonotonicTime::now();
783 #endif
784     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::destroyRenderingResources() took %.2fms", this, (endTime - startTime).milliseconds());
785 }
786
787 // FIXME: This should live somewhere else, and it should have the implementation in line instead of calling out to WKSI.
788 void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
789 {
790     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
791 }
792
793 #if PLATFORM(IOS_FAMILY)
794 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
795 {
796     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
797 }
798
799 bool WebProcess::shouldFreezeOnSuspension() const
800 {
801     switch (m_processType) {
802     case ProcessType::Inspector:
803     case ProcessType::ServiceWorker:
804     case ProcessType::PrewarmedWebContent:
805     case ProcessType::CachedWebContent:
806         return false;
807     case ProcessType::WebContent:
808         break;
809     }
810
811     for (auto& page : m_pageMap.values()) {
812         if (!page->isSuspended())
813             return true;
814     }
815
816     // Since all of the pages in this process were suspended, we should not bother freezing it.
817     return false;
818 }
819
820 void WebProcess::updateFreezerStatus()
821 {
822     bool isFreezable = shouldFreezeOnSuspension();
823     auto result = memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE, getpid(), isFreezable ? 1 : 0, nullptr, 0);
824     if (result)
825         RELEASE_LOG_ERROR(ProcessSuspension, "%p - WebProcess::updateFreezerStatus() isFreezable: %d, error: %d", this, isFreezable, result);
826     else
827         RELEASE_LOG(ProcessSuspension, "%p - WebProcess::updateFreezerStatus() isFreezable: %d, success", this, isFreezable);
828 }
829 #endif
830
831 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
832 void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
833 {
834     ScrollerStyle::setUseOverlayScrollbars(useOverlayScrollbars);
835
836     ScrollbarTheme& theme = ScrollbarTheme::theme();
837     if (theme.isMockTheme())
838         return;
839
840     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
841     
842     NSScrollerStyle style = useOverlayScrollbars ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
843     [NSScrollerImpPair _updateAllScrollerImpPairsForNewRecommendedScrollerStyle:style];
844 }
845
846 void WebProcess::displayConfigurationChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags)
847 {
848     GraphicsContext3DManager::displayWasReconfigured(displayID, flags, nullptr);
849 }
850     
851 void WebProcess::displayWasRefreshed(CGDirectDisplayID displayID)
852 {
853     DisplayRefreshMonitorManager::sharedManager().displayWasUpdated(displayID);
854 }
855 #endif
856
857 #if PLATFORM(IOS)
858 static float currentBacklightLevel()
859 {
860     return WebProcess::singleton().backlightLevel();
861 }
862
863 void WebProcess::backlightLevelDidChange(float backlightLevel)
864 {
865     m_backlightLevel = backlightLevel;
866
867     static std::once_flag onceFlag;
868     std::call_once(
869         onceFlag,
870         [] {
871             Method methodToPatch = class_getInstanceMethod([UIDevice class], @selector(_backlightLevel));
872             method_setImplementation(methodToPatch, reinterpret_cast<IMP>(currentBacklightLevel));
873         });
874 }
875 #endif
876
877 void WebProcess::setMediaMIMETypes(const Vector<String> types)
878 {
879     AVAssetMIMETypeCache::singleton().setSupportedTypes(types);
880 }
881
882 } // namespace WebKit