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