[PSON] Introduce a WebContent Process cache
[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::CachedWebContent:
244         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content (Cached)", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
245         break;
246     case ProcessType::WebContent:
247         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)m_uiProcessName];
248         break;
249     }
250
251     dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
252         // Note that it is important for _RegisterApplication() to have been called before setting the display name.
253         auto error = _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
254         ASSERT(!error);
255         if (error) {
256             RELEASE_LOG_ERROR(Process, "Failed to set the display name of the WebContent process, error code: %ld", static_cast<long>(error));
257             return;
258         }
259 #if !ASSERT_DISABLED
260         // 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.
261         String actualApplicationName = adoptCF((CFStringRef)_LSCopyApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey)).get();
262         ASSERT(!actualApplicationName.isEmpty());
263 #endif
264     });
265 }
266 #endif // PLATFORM(MAC)
267
268 static void registerWithAccessibility()
269 {
270 #if USE(APPKIT)
271     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
272 #endif
273 #if PLATFORM(IOS_FAMILY)
274     NSString *accessibilityBundlePath = [(NSString *)GSSystemRootDirectory() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
275     NSError *error = nil;
276     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
277         LOG_ERROR("Failed to load accessibility bundle at %@: %@", accessibilityBundlePath, error);
278 #endif
279 }
280
281 #if USE(OS_STATE)
282 void WebProcess::registerWithStateDumper()
283 {
284     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
285
286         @autoreleasepool {
287             os_state_data_t os_state = nil;
288
289             // Only gather state on faults and sysdiagnose. It's overkill for
290             // general error messages.
291             if (hints->osh_api == OS_STATE_API_ERROR)
292                 return os_state;
293
294             // Create a dictionary to contain the collected state. This
295             // dictionary will be serialized and passed back to os_state.
296             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
297
298             {
299                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
300                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
301                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
302                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
303                 }
304                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
305             }
306
307             {
308                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
309                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
310                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
311                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
312                 }
313                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
314             }
315
316             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
317             for (auto& page : m_pageMap.values()) {
318                 if (page->usesEphemeralSession())
319                     continue;
320
321                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
322                 [pageLoadTimes addObject:date];
323             }
324
325             // Adding an empty array to the process state may provide an
326             // indication of the existance of private sessions, which we'd like
327             // to hide, so don't add empty arrays.
328             if ([pageLoadTimes count])
329                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
330
331             // --- Possibly add other state here as other entries in the dictionary. ---
332
333             // Submitting an empty process state object may provide an
334             // indication of the existance of private sessions, which we'd like
335             // to hide, so don't return empty dictionaries.
336             if (![stateDict count])
337                 return os_state;
338
339             // Serialize the accumulated process state so that we can put the
340             // result in an os_state_data_t structure.
341             NSError* error = nil;
342             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
343
344             if (!data) {
345                 ASSERT(data);
346                 return os_state;
347             }
348
349             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
350             os_state = (os_state_data_t)malloc(neededSize);
351             if (os_state) {
352                 memset(os_state, 0, neededSize);
353                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
354                 os_state->osd_data_size = data.length;
355                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
356                 memcpy(os_state->osd_data, data.bytes, data.length);
357             }
358
359             return os_state;
360         }
361     });
362 }
363 #endif
364
365 void WebProcess::platformInitializeProcess(const AuxiliaryProcessInitializationParameters& parameters)
366 {
367 #if PLATFORM(MAC)
368 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
369     // Deny the WebContent process access to the WindowServer.
370     // This call will not succeed if there are open WindowServer connections at this point.
371     auto retval = CGSSetDenyWindowServerConnections(true);
372     RELEASE_ASSERT(retval == kCGErrorSuccess);
373     // Make sure that we close any WindowServer connections after checking in with Launch Services.
374     CGSShutdownServerConnections();
375
376     SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
377 #else
378
379     if (![NSApp isRunning]) {
380         // This call is needed when the WebProcess is not running the NSApplication event loop.
381         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
382         launchServicesCheckIn();
383     }
384 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
385
386     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
387         m_processType = ProcessType::Inspector;
388 #if ENABLE(SERVICE_WORKER)
389     else if (parameters.extraInitializationData.get("service-worker-process"_s) == "1") {
390         m_processType = ProcessType::ServiceWorker;
391         m_securityOrigin = parameters.extraInitializationData.get("security-origin"_s);
392     }
393 #endif
394     else if (parameters.extraInitializationData.get("is-prewarmed"_s) == "1")
395         m_processType = ProcessType::PrewarmedWebContent;
396     else
397         m_processType = ProcessType::WebContent;
398
399     m_uiProcessName = parameters.uiProcessName;
400 #else
401     UNUSED_PARAM(parameters);
402 #endif // PLATFORM(MAC)
403
404     registerWithAccessibility();
405
406 #if USE(OS_STATE)
407     registerWithStateDumper();
408 #endif
409 }
410
411 #if USE(APPKIT)
412 void WebProcess::stopRunLoop()
413 {
414 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
415     AuxiliaryProcess::stopNSRunLoop();
416 #else
417     AuxiliaryProcess::stopNSAppRunLoop();
418 #endif
419 }
420 #endif
421
422 void WebProcess::platformTerminate()
423 {
424     AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
425 }
426
427 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
428 {
429 #if USE(SOURCE_APPLICATION_AUDIT_DATA)
430     ASSERT(parentProcessConnection());
431     if (!parentProcessConnection())
432         return nullptr;
433     Optional<audit_token_t> auditToken = parentProcessConnection()->getAuditToken();
434     if (!auditToken)
435         return nullptr;
436     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&*auditToken, sizeof(*auditToken)));
437 #else
438     return nullptr;
439 #endif
440 }
441
442 void WebProcess::initializeSandbox(const AuxiliaryProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
443 {
444 #if ENABLE(WEB_PROCESS_SANDBOX)
445 #if ENABLE(MANUAL_SANDBOXING)
446     // Need to override the default, because service has a different bundle ID.
447 #if WK_API_ENABLED
448     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
449 #else
450     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
451 #endif
452 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOSMAC)
453     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
454 #else
455     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
456 #endif
457     AuxiliaryProcess::initializeSandbox(parameters, sandboxParameters);
458 #endif
459 #else
460     UNUSED_PARAM(parameters);
461     UNUSED_PARAM(sandboxParameters);
462 #endif
463 }
464
465 #if PLATFORM(MAC)
466
467 static NSURL *origin(WebPage& page)
468 {
469     WebFrame* mainFrame = page.mainWebFrame();
470     if (!mainFrame)
471         return nil;
472
473     URL mainFrameURL = { URL(), mainFrame->url() };
474     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
475     String mainFrameOriginString;
476     if (!mainFrameOrigin->isUnique())
477         mainFrameOriginString = mainFrameOrigin->toRawString();
478     else
479         mainFrameOriginString = makeString(mainFrameURL.protocol(), ':'); // toRawString() is not supposed to work with unique origins, and would just return "://".
480
481     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
482     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
483     ASSERT([NSURL URLWithString:mainFrameOriginString]);
484
485     return [NSURL URLWithString:mainFrameOriginString];
486 }
487
488 #endif
489
490 #if PLATFORM(MAC)
491 static RetainPtr<NSArray<NSString *>> activePagesOrigins(const HashMap<uint64_t, RefPtr<WebPage>>& pageMap)
492 {
493     RetainPtr<NSMutableArray<NSString *>> activeOrigins = adoptNS([[NSMutableArray alloc] init]);
494
495     for (auto& page : pageMap.values()) {
496         if (page->usesEphemeralSession())
497             continue;
498
499         if (NSURL *originAsURL = origin(*page))
500             [activeOrigins addObject:WTF::userVisibleString(originAsURL)];
501     }
502
503     return activeOrigins;
504 }
505 #endif
506
507 void WebProcess::updateActivePages()
508 {
509 #if PLATFORM(MAC)
510     auto activeOrigins = activePagesOrigins(m_pageMap);
511
512     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activeOrigins = WTFMove(activeOrigins)] {
513         _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activeOrigins.get(), nullptr);
514     });
515 #endif
516 }
517
518 void WebProcess::getActivePagesOriginsForTesting(CompletionHandler<void(Vector<String>&&)>&& completionHandler)
519 {
520 #if PLATFORM(MAC)
521     auto activeOriginsAsNSStrings = activePagesOrigins(m_pageMap);
522     Vector<String> activeOrigins;
523     activeOrigins.reserveInitialCapacity([activeOriginsAsNSStrings count]);
524     for (NSString* activeOrigin in activeOriginsAsNSStrings.get())
525         activeOrigins.uncheckedAppend(activeOrigin);
526     completionHandler(WTFMove(activeOrigins));
527 #else
528     completionHandler({ });
529 #endif
530 }
531
532 void WebProcess::updateCPULimit()
533 {
534 #if PLATFORM(MAC)
535     Optional<double> cpuLimit;
536
537     // Use the largest limit among all pages in this process.
538     for (auto& page : m_pageMap.values()) {
539         auto pageCPULimit = page->cpuLimit();
540         if (!pageCPULimit) {
541             cpuLimit = WTF::nullopt;
542             break;
543         }
544         if (!cpuLimit || pageCPULimit > cpuLimit.value())
545             cpuLimit = pageCPULimit;
546     }
547
548     if (m_cpuLimit == cpuLimit)
549         return;
550
551     m_cpuLimit = cpuLimit;
552     updateCPUMonitorState(CPUMonitorUpdateReason::LimitHasChanged);
553 #endif
554 }
555
556 void WebProcess::updateCPUMonitorState(CPUMonitorUpdateReason reason)
557 {
558 #if PLATFORM(MAC)
559     if (!m_cpuLimit) {
560         if (m_cpuMonitor)
561             m_cpuMonitor->setCPULimit(WTF::nullopt);
562         return;
563     }
564
565     if (!m_cpuMonitor) {
566         m_cpuMonitor = std::make_unique<CPUMonitor>(cpuMonitoringInterval, [this](double cpuUsage) {
567             RELEASE_LOG(PerformanceLogging, "%p - WebProcess exceeded CPU limit of %.1f%% (was using %.1f%%) hasVisiblePages? %d", this, m_cpuLimit.value() * 100, cpuUsage * 100, hasVisibleWebPage());
568             parentProcessConnection()->send(Messages::WebProcessProxy::DidExceedCPULimit(), 0);
569         });
570     } else if (reason == CPUMonitorUpdateReason::VisibilityHasChanged) {
571         // 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
572         // 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.
573         m_cpuMonitor->setCPULimit(WTF::nullopt);
574     }
575     m_cpuMonitor->setCPULimit(m_cpuLimit);
576 #else
577     UNUSED_PARAM(reason);
578 #endif
579 }
580
581 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
582 {
583     struct Transformer final : ObjCObjectGraph::Transformer {
584         Transformer(WebProcess& webProcess)
585             : m_webProcess(webProcess)
586         {
587         }
588
589         bool shouldTransformObject(id object) const override
590         {
591 #if WK_API_ENABLED
592             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
593                 return true;
594
595             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
596             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
597                 return true;
598             ALLOW_DEPRECATED_DECLARATIONS_END
599 #endif
600             return false;
601         }
602
603         RetainPtr<id> transformObject(id object) const override
604         {
605 #if WK_API_ENABLED
606             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
607                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
608                     return wrapper(*webPage);
609
610                 return [NSNull null];
611             }
612
613             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
614             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
615                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
616             ALLOW_DEPRECATED_DECLARATIONS_END
617 #endif
618             return object;
619         }
620
621         WebProcess& m_webProcess;
622     };
623
624     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
625 }
626
627 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
628 {
629     struct Transformer final : ObjCObjectGraph::Transformer {
630         bool shouldTransformObject(id object) const override
631         {
632 #if WK_API_ENABLED
633             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
634                 return true;
635
636             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
637             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
638                 return true;
639             ALLOW_DEPRECATED_DECLARATIONS_END
640 #endif
641
642             return false;
643         }
644
645         RetainPtr<id> transformObject(id object) const override
646         {
647 #if WK_API_ENABLED
648             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
649                 return controller.handle;
650
651             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
652             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
653                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
654             ALLOW_DEPRECATED_DECLARATIONS_END
655 #endif
656             return object;
657         }
658     };
659
660     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
661 }
662
663 void WebProcess::destroyRenderingResources()
664 {
665 #if !RELEASE_LOG_DISABLED
666     MonotonicTime startTime = MonotonicTime::now();
667 #endif
668     CABackingStoreCollectBlocking();
669 #if !RELEASE_LOG_DISABLED
670     MonotonicTime endTime = MonotonicTime::now();
671 #endif
672     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::destroyRenderingResources() took %.2fms", this, (endTime - startTime).milliseconds());
673 }
674
675 // FIXME: This should live somewhere else, and it should have the implementation in line instead of calling out to WKSI.
676 void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
677 {
678     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
679 }
680
681 #if PLATFORM(IOS_FAMILY)
682 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
683 {
684     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
685 }
686 #endif
687
688 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
689 void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
690 {
691     ScrollerStyle::setUseOverlayScrollbars(useOverlayScrollbars);
692
693     ScrollbarTheme& theme = ScrollbarTheme::theme();
694     if (theme.isMockTheme())
695         return;
696
697     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
698     
699     NSScrollerStyle style = useOverlayScrollbars ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
700     [NSScrollerImpPair _updateAllScrollerImpPairsForNewRecommendedScrollerStyle:style];
701 }
702
703 void WebProcess::displayConfigurationChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags)
704 {
705     GraphicsContext3DManager::displayWasReconfigured(displayID, flags, nullptr);
706 }
707     
708 void WebProcess::displayWasRefreshed(CGDirectDisplayID displayID)
709 {
710     DisplayRefreshMonitorManager::sharedManager().displayWasUpdated(displayID);
711 }
712 #endif
713
714 void WebProcess::setMediaMIMETypes(const Vector<String> types)
715 {
716     AVFoundationMIMETypeCache::singleton().setSupportedTypes(types);
717 }
718
719 } // namespace WebKit