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