[Mac] Regression: WebContent process's display name is no longer set
[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 "SandboxExtension.h"
35 #import "SandboxInitializationParameters.h"
36 #import "SessionTracker.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 "WebProcessProxyMessages.h"
48 #import "WebsiteDataStoreParameters.h"
49 #import <JavaScriptCore/ConfigFile.h>
50 #import <JavaScriptCore/Options.h>
51 #import <WebCore/AVFoundationMIMETypeCache.h>
52 #import <WebCore/AXObjectCache.h>
53 #import <WebCore/CPUMonitor.h>
54 #import <WebCore/DisplayRefreshMonitorManager.h>
55 #import <WebCore/FileSystem.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/WebCoreNSURLExtras.h>
67 #import <algorithm>
68 #import <dispatch/dispatch.h>
69 #import <objc/runtime.h>
70 #import <pal/spi/cg/CoreGraphicsSPI.h>
71 #import <pal/spi/cocoa/LaunchServicesSPI.h>
72 #import <pal/spi/cocoa/QuartzCoreSPI.h>
73 #import <pal/spi/cocoa/pthreadSPI.h>
74 #import <pal/spi/mac/NSAccessibilitySPI.h>
75 #import <pal/spi/mac/NSApplicationSPI.h>
76 #import <stdio.h>
77
78 #if PLATFORM(IOS_FAMILY)
79 #import "WKAccessibilityWebPageObjectIOS.h"
80 #import <UIKit/UIAccessibility.h>
81 #import <pal/spi/ios/GraphicsServicesSPI.h>
82 #endif
83
84 #if PLATFORM(IOS_FAMILY) && USE(APPLE_INTERNAL_SDK)
85 #import <AXRuntime/AXDefines.h>
86 #import <AXRuntime/AXNotificationConstants.h>
87 #endif
88
89 #if PLATFORM(IOS_FAMILY) && !USE(APPLE_INTERNAL_SDK)
90 #define kAXPidStatusChangedNotification 0
91 #endif
92
93 #if PLATFORM(MAC)
94 #import "WKAccessibilityWebPageObjectMac.h"
95 #import "WebSwitchingGPUClient.h"
96 #import <WebCore/GraphicsContext3DManager.h>
97 #import <WebCore/ScrollbarThemeMac.h>
98 #import <pal/spi/mac/NSScrollerImpSPI.h>
99 #endif
100
101 #if USE(OS_STATE)
102 #import <os/state_private.h>
103 #endif
104
105 namespace WebKit {
106 using namespace WebCore;
107
108 #if PLATFORM(MAC)
109 static const Seconds cpuMonitoringInterval { 8_min };
110 #endif
111
112 void WebProcess::platformSetCacheModel(CacheModel)
113 {
114 }
115
116 #if USE(APPKIT)
117 static id NSApplicationAccessibilityFocusedUIElement(NSApplication*, SEL)
118 {
119     WebPage* page = WebProcess::singleton().focusedWebPage();
120     if (!page || !page->accessibilityRemoteObject())
121         return 0;
122
123     return [page->accessibilityRemoteObject() accessibilityFocusedUIElement];
124 }
125 #endif
126
127 void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& parameters)
128 {
129 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
130     WebCore::initializeLogChannelsIfNecessary(parameters.webCoreLoggingChannels);
131     WebKit::initializeLogChannelsIfNecessary(parameters.webKitLoggingChannels);
132 #endif
133
134     WebCore::setApplicationBundleIdentifier(parameters.uiProcessBundleIdentifier);
135     WebCore::setApplicationSDKVersion(parameters.uiProcessSDKVersion);
136
137     SessionTracker::setIdentifierBase(parameters.uiProcessBundleIdentifier);
138
139 #if ENABLE(SANDBOX_EXTENSIONS)
140     SandboxExtension::consumePermanently(parameters.uiProcessBundleResourcePathExtensionHandle);
141     SandboxExtension::consumePermanently(parameters.webSQLDatabaseDirectoryExtensionHandle);
142     SandboxExtension::consumePermanently(parameters.applicationCacheDirectoryExtensionHandle);
143     SandboxExtension::consumePermanently(parameters.mediaCacheDirectoryExtensionHandle);
144     SandboxExtension::consumePermanently(parameters.mediaKeyStorageDirectoryExtensionHandle);
145     SandboxExtension::consumePermanently(parameters.javaScriptConfigurationDirectoryExtensionHandle);
146 #if ENABLE(MEDIA_STREAM)
147     SandboxExtension::consumePermanently(parameters.audioCaptureExtensionHandle);
148 #endif
149 #if PLATFORM(IOS_FAMILY)
150     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
151     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
152     SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle);
153 #endif
154 #endif
155
156     if (!parameters.javaScriptConfigurationDirectory.isEmpty()) {
157         String javaScriptConfigFile = parameters.javaScriptConfigurationDirectory + "/JSC.config";
158         JSC::processConfigFile(javaScriptConfigFile.latin1().data(), "com.apple.WebKit.WebContent", parameters.uiProcessBundleIdentifier.latin1().data());
159     }
160
161     // Disable NSURLCache.
162     auto urlCache = adoptNS([[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]);
163     [NSURLCache setSharedURLCache:urlCache.get()];
164
165 #if PLATFORM(MAC)
166     WebCore::FontCache::setFontWhitelist(parameters.fontWhitelist);
167 #endif
168
169     m_compositingRenderServerPort = WTFMove(parameters.acceleratedCompositingPort);
170
171     WebCore::registerMemoryReleaseNotifyCallbacks();
172     MemoryPressureHandler::ReliefLogger::setLoggingEnabled(parameters.shouldEnableMemoryPressureReliefLogging);
173
174     setEnhancedAccessibility(parameters.accessibilityEnhancedUserInterfaceEnabled);
175
176 #if USE(APPKIT)
177     [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions" : @YES }];
178
179     // rdar://9118639 accessibilityFocusedUIElement in NSApplication defaults to use the keyWindow. Since there's
180     // no window in WK2, NSApplication needs to use the focused page's focused element.
181     Method methodToPatch = class_getInstanceMethod([NSApplication class], @selector(accessibilityFocusedUIElement));
182     method_setImplementation(methodToPatch, (IMP)NSApplicationAccessibilityFocusedUIElement);
183 #endif
184     
185 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
186     // Need to initialize accessibility for VoiceOver to work when the WebContent process is using NSRunLoop.
187     // Currently, it is also needed to allocate and initialize an NSApplication object.
188     // FIXME: Remove the following line when rdar://problem/36323569 is fixed.
189     [NSApplication sharedApplication];
190     [NSApplication _accessibilityInitialize];
191 #endif
192
193 #if TARGET_OS_IPHONE
194     // Priority decay on iOS 9 is impacting page load time so we fix the priority of the WebProcess' main thread (rdar://problem/22003112).
195     pthread_set_fixedpriority_self();
196 #endif
197
198     if (!parameters.mediaMIMETypes.isEmpty())
199         setMediaMIMETypes(parameters.mediaMIMETypes);
200     else {
201         AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback([this](const Vector<String>& types) {
202             parentProcessConnection()->send(Messages::WebProcessProxy::CacheMediaMIMETypes(types), 0);
203         });
204     }
205
206 #if PLATFORM(MAC)
207     WebCore::setScreenProperties(parameters.screenProperties);
208 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
209     scrollerStylePreferenceChanged(parameters.useOverlayScrollbars);
210 #endif
211 #endif
212 }
213
214 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
215 {
216 #if !PLATFORM(IOS_FAMILY)
217     NSString *applicationName;
218     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
219         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Inspector", "Visible name of Web Inspector's web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
220 #if ENABLE(SERVICE_WORKER)
221     else if (parameters.extraInitializationData.get("service-worker-process"_s) == "1")
222         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Service Worker (%@)", "Visible name of Service Worker process. The argument is the application name."), (NSString *)parameters.uiProcessName, (NSString *)parameters.extraInitializationData.get("security-origin"_s)];
223 #endif
224     else
225         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
226
227     dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
228         // Note that it is important for _RegisterApplication() to have been called before setting the display name.
229         auto error = _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
230         ASSERT(!error);
231         if (error) {
232             RELEASE_LOG_ERROR(Process, "Failed to set the display name of the WebContent process, error code: %ld", static_cast<long>(error));
233             return;
234         }
235 #if !ASSERT_DISABLED
236         // 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.
237         String actualApplicationName = adoptCF((CFStringRef)_LSCopyApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey)).get();
238         ASSERT(!actualApplicationName.isEmpty());
239 #endif
240     });
241 #endif
242 }
243
244 static void registerWithAccessibility()
245 {
246 #if USE(APPKIT)
247     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
248 #endif
249 #if PLATFORM(IOS_FAMILY)
250     NSString *accessibilityBundlePath = [(NSString *)GSSystemRootDirectory() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
251     NSError *error = nil;
252     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
253         LOG_ERROR("Failed to load accessibility bundle at %@: %@", accessibilityBundlePath, error);
254 #endif
255 }
256
257 #if USE(OS_STATE)
258 void WebProcess::registerWithStateDumper()
259 {
260     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
261
262         @autoreleasepool {
263             os_state_data_t os_state = nil;
264
265             // Only gather state on faults and sysdiagnose. It's overkill for
266             // general error messages.
267             if (hints->osh_api == OS_STATE_API_ERROR)
268                 return os_state;
269
270             // Create a dictionary to contain the collected state. This
271             // dictionary will be serialized and passed back to os_state.
272             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
273
274             {
275                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
276                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
277                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
278                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
279                 }
280                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
281             }
282
283             {
284                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
285                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
286                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
287                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
288                 }
289                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
290             }
291
292             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
293             for (auto& page : m_pageMap.values()) {
294                 if (page->usesEphemeralSession())
295                     continue;
296
297                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
298                 [pageLoadTimes addObject:date];
299             }
300
301             // Adding an empty array to the process state may provide an
302             // indication of the existance of private sessions, which we'd like
303             // to hide, so don't add empty arrays.
304             if ([pageLoadTimes count])
305                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
306
307             // --- Possibly add other state here as other entries in the dictionary. ---
308
309             // Submitting an empty process state object may provide an
310             // indication of the existance of private sessions, which we'd like
311             // to hide, so don't return empty dictionaries.
312             if (![stateDict count])
313                 return os_state;
314
315             // Serialize the accumulated process state so that we can put the
316             // result in an os_state_data_t structure.
317             NSError* error = nil;
318             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
319
320             if (!data) {
321                 ASSERT(data);
322                 return os_state;
323             }
324
325             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
326             os_state = (os_state_data_t)malloc(neededSize);
327             if (os_state) {
328                 memset(os_state, 0, neededSize);
329                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
330                 os_state->osd_data_size = data.length;
331                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
332                 memcpy(os_state->osd_data, data.bytes, data.length);
333             }
334
335             return os_state;
336         }
337     });
338 }
339 #endif
340
341 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
342 {
343 #if PLATFORM(MAC)
344 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
345     // Deny the WebContent process access to the WindowServer.
346     // This call will not succeed if there are open WindowServer connections at this point.
347     auto retval = CGSSetDenyWindowServerConnections(true);
348     RELEASE_ASSERT(retval == kCGErrorSuccess);
349     // Make sure that we close any WindowServer connections after checking in with Launch Services.
350     CGSShutdownServerConnections();
351
352     SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
353
354     // This is necessary so that we are able to set the process' display name.
355     _RegisterApplication(nullptr, nullptr);
356
357 #else
358
359     if (![NSApp isRunning]) {
360         // This call is needed when the WebProcess is not running the NSApplication event loop.
361         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
362         launchServicesCheckIn();
363     }
364 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
365 #endif // PLATFORM(MAC)
366
367     registerWithAccessibility();
368
369 #if USE(OS_STATE)
370     registerWithStateDumper();
371 #endif
372 }
373
374 #if USE(APPKIT)
375 void WebProcess::stopRunLoop()
376 {
377 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
378     ChildProcess::stopNSRunLoop();
379 #else
380     ChildProcess::stopNSAppRunLoop();
381 #endif
382 }
383 #endif
384
385 void WebProcess::platformTerminate()
386 {
387     AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
388 }
389
390 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
391 {
392 #if PLATFORM(IOS_FAMILY)
393     audit_token_t auditToken;
394     ASSERT(parentProcessConnection());
395     if (!parentProcessConnection() || !parentProcessConnection()->getAuditToken(auditToken))
396         return nullptr;
397     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
398 #else
399     return nullptr;
400 #endif
401 }
402
403 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
404 {
405 #if ENABLE(WEB_PROCESS_SANDBOX)
406 #if ENABLE(MANUAL_SANDBOXING)
407     // Need to override the default, because service has a different bundle ID.
408 #if WK_API_ENABLED
409     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
410 #else
411     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
412 #endif
413 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOSMAC)
414     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
415 #else
416     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
417 #endif
418     ChildProcess::initializeSandbox(parameters, sandboxParameters);
419 #endif
420 #else
421     UNUSED_PARAM(parameters);
422     UNUSED_PARAM(sandboxParameters);
423 #endif
424 }
425
426 #if PLATFORM(MAC)
427
428 static NSURL *origin(WebPage& page)
429 {
430     WebFrame* mainFrame = page.mainWebFrame();
431     if (!mainFrame)
432         return nil;
433
434     URL mainFrameURL = { URL(), mainFrame->url() };
435     if (page.isSuspended()) {
436         // Suspended page are navigated to about:blank upon suspension so we really want to report the previous URL.
437         if (auto* coreFrame = mainFrame->coreFrame()) {
438             if (auto* backHistoryItem = coreFrame->loader().history().previousItem())
439                 mainFrameURL = { URL(), backHistoryItem->urlString() };
440         }
441     }
442
443     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
444     String mainFrameOriginString;
445     if (!mainFrameOrigin->isUnique())
446         mainFrameOriginString = mainFrameOrigin->toRawString();
447     else
448         mainFrameOriginString = makeString(mainFrameURL.protocol(), ':'); // toRawString() is not supposed to work with unique origins, and would just return "://".
449
450     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
451     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
452     ASSERT([NSURL URLWithString:mainFrameOriginString]);
453
454     return [NSURL URLWithString:mainFrameOriginString];
455 }
456
457 #endif
458
459 #if PLATFORM(MAC)
460 static RetainPtr<NSArray<NSString *>> activePagesOrigins(const HashMap<uint64_t, RefPtr<WebPage>>& pageMap)
461 {
462     RetainPtr<NSMutableArray<NSString *>> activeOrigins = adoptNS([[NSMutableArray alloc] init]);
463
464     for (auto& page : pageMap.values()) {
465         if (page->usesEphemeralSession())
466             continue;
467
468         if (NSURL *originAsURL = origin(*page))
469             [activeOrigins addObject:userVisibleString(originAsURL)];
470     }
471
472     return activeOrigins;
473 }
474 #endif
475
476 void WebProcess::updateActivePages()
477 {
478 #if PLATFORM(MAC)
479     auto activeOrigins = activePagesOrigins(m_pageMap);
480
481     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activeOrigins = WTFMove(activeOrigins)] {
482         _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activeOrigins.get(), nullptr);
483     });
484 #endif
485 }
486
487 void WebProcess::getActivePagesOriginsForTesting(Vector<String>& activeOrigins)
488 {
489 #if PLATFORM(MAC)
490     auto activeOriginsAsNSStrings = activePagesOrigins(m_pageMap);
491     activeOrigins.reserveCapacity([activeOriginsAsNSStrings count]);
492     for (NSString* activeOrigin in activeOriginsAsNSStrings.get())
493         activeOrigins.uncheckedAppend(activeOrigin);
494 #else
495     UNUSED_PARAM(activeOrigins);
496 #endif
497 }
498
499 void WebProcess::updateCPULimit()
500 {
501 #if PLATFORM(MAC)
502     std::optional<double> cpuLimit;
503
504     // Use the largest limit among all pages in this process.
505     for (auto& page : m_pageMap.values()) {
506         auto pageCPULimit = page->cpuLimit();
507         if (!pageCPULimit) {
508             cpuLimit = std::nullopt;
509             break;
510         }
511         if (!cpuLimit || pageCPULimit > cpuLimit.value())
512             cpuLimit = pageCPULimit;
513     }
514
515     if (m_cpuLimit == cpuLimit)
516         return;
517
518     m_cpuLimit = cpuLimit;
519     updateCPUMonitorState(CPUMonitorUpdateReason::LimitHasChanged);
520 #endif
521 }
522
523 void WebProcess::updateCPUMonitorState(CPUMonitorUpdateReason reason)
524 {
525 #if PLATFORM(MAC)
526     if (!m_cpuLimit) {
527         if (m_cpuMonitor)
528             m_cpuMonitor->setCPULimit(std::nullopt);
529         return;
530     }
531
532     if (!m_cpuMonitor) {
533         m_cpuMonitor = std::make_unique<CPUMonitor>(cpuMonitoringInterval, [this](double cpuUsage) {
534             RELEASE_LOG(PerformanceLogging, "%p - WebProcess exceeded CPU limit of %.1f%% (was using %.1f%%) hasVisiblePages? %d", this, m_cpuLimit.value() * 100, cpuUsage * 100, hasVisibleWebPage());
535             parentProcessConnection()->send(Messages::WebProcessProxy::DidExceedCPULimit(), 0);
536         });
537     } else if (reason == CPUMonitorUpdateReason::VisibilityHasChanged) {
538         // 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
539         // 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.
540         m_cpuMonitor->setCPULimit(std::nullopt);
541     }
542     m_cpuMonitor->setCPULimit(m_cpuLimit.value());
543 #else
544     UNUSED_PARAM(reason);
545 #endif
546 }
547
548 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
549 {
550     struct Transformer final : ObjCObjectGraph::Transformer {
551         Transformer(WebProcess& webProcess)
552             : m_webProcess(webProcess)
553         {
554         }
555
556         bool shouldTransformObject(id object) const override
557         {
558 #if WK_API_ENABLED
559             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
560                 return true;
561
562             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
563             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
564                 return true;
565             ALLOW_DEPRECATED_DECLARATIONS_END
566 #endif
567             return false;
568         }
569
570         RetainPtr<id> transformObject(id object) const override
571         {
572 #if WK_API_ENABLED
573             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
574                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
575                     return wrapper(*webPage);
576
577                 return [NSNull null];
578             }
579
580             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
581             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
582                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
583             ALLOW_DEPRECATED_DECLARATIONS_END
584 #endif
585             return object;
586         }
587
588         WebProcess& m_webProcess;
589     };
590
591     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
592 }
593
594 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
595 {
596     struct Transformer final : ObjCObjectGraph::Transformer {
597         bool shouldTransformObject(id object) const override
598         {
599 #if WK_API_ENABLED
600             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
601                 return true;
602
603             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
604             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
605                 return true;
606             ALLOW_DEPRECATED_DECLARATIONS_END
607 #endif
608
609             return false;
610         }
611
612         RetainPtr<id> transformObject(id object) const override
613         {
614 #if WK_API_ENABLED
615             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
616                 return controller.handle;
617
618             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
619             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
620                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
621             ALLOW_DEPRECATED_DECLARATIONS_END
622 #endif
623             return object;
624         }
625     };
626
627     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
628 }
629
630 void WebProcess::destroyRenderingResources()
631 {
632 #if !RELEASE_LOG_DISABLED
633     MonotonicTime startTime = MonotonicTime::now();
634 #endif
635     CABackingStoreCollectBlocking();
636 #if !RELEASE_LOG_DISABLED
637     MonotonicTime endTime = MonotonicTime::now();
638 #endif
639     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::destroyRenderingResources() took %.2fms", this, (endTime - startTime).milliseconds());
640 }
641
642 // FIXME: This should live somewhere else, and it should have the implementation in line instead of calling out to WKSI.
643 void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
644 {
645     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
646 }
647
648 #if PLATFORM(IOS_FAMILY)
649 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
650 {
651     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
652 }
653 #endif
654
655 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
656 void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
657 {
658     ScrollerStyle::setUseOverlayScrollbars(useOverlayScrollbars);
659
660     ScrollbarTheme& theme = ScrollbarTheme::theme();
661     if (theme.isMockTheme())
662         return;
663
664     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
665     
666     NSScrollerStyle style = useOverlayScrollbars ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
667     [NSScrollerImpPair _updateAllScrollerImpPairsForNewRecommendedScrollerStyle:style];
668 }
669
670 void WebProcess::displayConfigurationChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags)
671 {
672     GraphicsContext3DManager::displayWasReconfigured(displayID, flags, nullptr);
673 }
674     
675 void WebProcess::displayWasRefreshed(CGDirectDisplayID displayID)
676 {
677     DisplayRefreshMonitorManager::sharedManager().displayWasUpdated(displayID);
678 }
679 #endif
680
681 void WebProcess::setMediaMIMETypes(const Vector<String> types)
682 {
683     AVFoundationMIMETypeCache::singleton().setSupportedTypes(types);
684 }
685
686 } // namespace WebKit