Move URL from WebCore to WTF
[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 <algorithm>
67 #import <dispatch/dispatch.h>
68 #import <objc/runtime.h>
69 #import <pal/spi/cg/CoreGraphicsSPI.h>
70 #import <pal/spi/cocoa/LaunchServicesSPI.h>
71 #import <pal/spi/cocoa/QuartzCoreSPI.h>
72 #import <pal/spi/cocoa/pthreadSPI.h>
73 #import <pal/spi/mac/NSAccessibilitySPI.h>
74 #import <pal/spi/mac/NSApplicationSPI.h>
75 #import <stdio.h>
76 #import <wtf/cocoa/NSURLExtras.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     [NSApplication _accessibilityInitialize];
189 #endif
190
191 #if TARGET_OS_IPHONE
192     // Priority decay on iOS 9 is impacting page load time so we fix the priority of the WebProcess' main thread (rdar://problem/22003112).
193     pthread_set_fixedpriority_self();
194 #endif
195
196     if (!parameters.mediaMIMETypes.isEmpty())
197         setMediaMIMETypes(parameters.mediaMIMETypes);
198     else {
199         AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback([this](const Vector<String>& types) {
200             parentProcessConnection()->send(Messages::WebProcessProxy::CacheMediaMIMETypes(types), 0);
201         });
202     }
203
204 #if PLATFORM(MAC)
205     WebCore::setScreenProperties(parameters.screenProperties);
206 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
207     scrollerStylePreferenceChanged(parameters.useOverlayScrollbars);
208 #endif
209 #endif
210 }
211
212 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters&)
213 {
214 #if PLATFORM(MAC)
215     updateProcessName();
216 #endif
217 }
218
219 #if PLATFORM(MAC)
220 void WebProcess::updateProcessName()
221 {
222     NSString *applicationName;
223     switch (m_processType) {
224     case ProcessType::Inspector:
225         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];
226         break;
227     case ProcessType::ServiceWorker:
228         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];
229         break;
230     case ProcessType::PrewarmedWebContent:
231         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content (Prewarmed)", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
232         break;
233     case ProcessType::WebContent:
234         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
235         break;
236     }
237
238     dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
239         // Note that it is important for _RegisterApplication() to have been called before setting the display name.
240         auto error = _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
241         ASSERT(!error);
242         if (error) {
243             RELEASE_LOG_ERROR(Process, "Failed to set the display name of the WebContent process, error code: %ld", static_cast<long>(error));
244             return;
245         }
246 #if !ASSERT_DISABLED
247         // 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.
248         String actualApplicationName = adoptCF((CFStringRef)_LSCopyApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey)).get();
249         ASSERT(!actualApplicationName.isEmpty());
250 #endif
251     });
252 }
253 #endif // PLATFORM(MAC)
254
255 static void registerWithAccessibility()
256 {
257 #if USE(APPKIT)
258     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
259 #endif
260 #if PLATFORM(IOS_FAMILY)
261     NSString *accessibilityBundlePath = [(NSString *)GSSystemRootDirectory() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
262     NSError *error = nil;
263     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
264         LOG_ERROR("Failed to load accessibility bundle at %@: %@", accessibilityBundlePath, error);
265 #endif
266 }
267
268 #if USE(OS_STATE)
269 void WebProcess::registerWithStateDumper()
270 {
271     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
272
273         @autoreleasepool {
274             os_state_data_t os_state = nil;
275
276             // Only gather state on faults and sysdiagnose. It's overkill for
277             // general error messages.
278             if (hints->osh_api == OS_STATE_API_ERROR)
279                 return os_state;
280
281             // Create a dictionary to contain the collected state. This
282             // dictionary will be serialized and passed back to os_state.
283             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
284
285             {
286                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
287                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
288                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
289                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
290                 }
291                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
292             }
293
294             {
295                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
296                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
297                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
298                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
299                 }
300                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
301             }
302
303             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
304             for (auto& page : m_pageMap.values()) {
305                 if (page->usesEphemeralSession())
306                     continue;
307
308                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
309                 [pageLoadTimes addObject:date];
310             }
311
312             // Adding an empty array to the process state may provide an
313             // indication of the existance of private sessions, which we'd like
314             // to hide, so don't add empty arrays.
315             if ([pageLoadTimes count])
316                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
317
318             // --- Possibly add other state here as other entries in the dictionary. ---
319
320             // Submitting an empty process state object may provide an
321             // indication of the existance of private sessions, which we'd like
322             // to hide, so don't return empty dictionaries.
323             if (![stateDict count])
324                 return os_state;
325
326             // Serialize the accumulated process state so that we can put the
327             // result in an os_state_data_t structure.
328             NSError* error = nil;
329             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
330
331             if (!data) {
332                 ASSERT(data);
333                 return os_state;
334             }
335
336             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
337             os_state = (os_state_data_t)malloc(neededSize);
338             if (os_state) {
339                 memset(os_state, 0, neededSize);
340                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
341                 os_state->osd_data_size = data.length;
342                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
343                 memcpy(os_state->osd_data, data.bytes, data.length);
344             }
345
346             return os_state;
347         }
348     });
349 }
350 #endif
351
352 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters& parameters)
353 {
354 #if PLATFORM(MAC)
355 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
356     // Deny the WebContent process access to the WindowServer.
357     // This call will not succeed if there are open WindowServer connections at this point.
358     auto retval = CGSSetDenyWindowServerConnections(true);
359     RELEASE_ASSERT(retval == kCGErrorSuccess);
360     // Make sure that we close any WindowServer connections after checking in with Launch Services.
361     CGSShutdownServerConnections();
362
363     SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
364
365     // This is necessary so that we are able to set the process' display name.
366     _RegisterApplication(nullptr, nullptr);
367
368 #else
369
370     if (![NSApp isRunning]) {
371         // This call is needed when the WebProcess is not running the NSApplication event loop.
372         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
373         launchServicesCheckIn();
374     }
375 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
376
377     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
378         m_processType = ProcessType::Inspector;
379 #if ENABLE(SERVICE_WORKER)
380     else if (parameters.extraInitializationData.get("service-worker-process"_s) == "1") {
381         m_processType = ProcessType::ServiceWorker;
382         m_securityOrigin = parameters.extraInitializationData.get("security-origin"_s);
383     }
384 #endif
385     else if (parameters.extraInitializationData.get("is-prewarmed"_s) == "1")
386         m_processType = ProcessType::PrewarmedWebContent;
387     else
388         m_processType = ProcessType::WebContent;
389
390     m_uiProcessName = parameters.uiProcessName;
391 #else
392     UNUSED_PARAM(parameters);
393 #endif // PLATFORM(MAC)
394
395     registerWithAccessibility();
396
397 #if USE(OS_STATE)
398     registerWithStateDumper();
399 #endif
400 }
401
402 #if USE(APPKIT)
403 void WebProcess::stopRunLoop()
404 {
405 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
406     ChildProcess::stopNSRunLoop();
407 #else
408     ChildProcess::stopNSAppRunLoop();
409 #endif
410 }
411 #endif
412
413 void WebProcess::platformTerminate()
414 {
415     AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
416 }
417
418 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
419 {
420 #if PLATFORM(IOS_FAMILY)
421     audit_token_t auditToken;
422     ASSERT(parentProcessConnection());
423     if (!parentProcessConnection() || !parentProcessConnection()->getAuditToken(auditToken))
424         return nullptr;
425     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
426 #else
427     return nullptr;
428 #endif
429 }
430
431 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
432 {
433 #if ENABLE(WEB_PROCESS_SANDBOX)
434 #if ENABLE(MANUAL_SANDBOXING)
435     // Need to override the default, because service has a different bundle ID.
436 #if WK_API_ENABLED
437     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
438 #else
439     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
440 #endif
441 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOSMAC)
442     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
443 #else
444     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
445 #endif
446     ChildProcess::initializeSandbox(parameters, sandboxParameters);
447 #endif
448 #else
449     UNUSED_PARAM(parameters);
450     UNUSED_PARAM(sandboxParameters);
451 #endif
452 }
453
454 #if PLATFORM(MAC)
455
456 static NSURL *origin(WebPage& page)
457 {
458     WebFrame* mainFrame = page.mainWebFrame();
459     if (!mainFrame)
460         return nil;
461
462     URL mainFrameURL = { URL(), mainFrame->url() };
463     if (page.isSuspended()) {
464         // Suspended page are navigated to about:blank upon suspension so we really want to report the previous URL.
465         if (auto* coreFrame = mainFrame->coreFrame()) {
466             if (auto* backHistoryItem = coreFrame->loader().history().previousItem())
467                 mainFrameURL = { URL(), backHistoryItem->urlString() };
468         }
469     }
470
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     std::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 = std::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(std::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(std::nullopt);
571     }
572     m_cpuMonitor->setCPULimit(m_cpuLimit.value());
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