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