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