Drop support for NSURLCache in WebKit2
[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
196 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
197 {
198 #if !PLATFORM(IOS)
199     NSString *applicationName;
200     if (parameters.extraInitializationData.get(ASCIILiteral("inspector-process")) == "1")
201         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];
202 #if ENABLE(SERVICE_WORKER)
203     else if (parameters.extraInitializationData.get(ASCIILiteral("service-worker-process")) == "1")
204         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"))];
205 #endif
206     else
207         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
208     _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
209 #endif
210 }
211
212 static void registerWithAccessibility()
213 {
214 #if USE(APPKIT)
215     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
216 #endif
217 #if PLATFORM(IOS)
218     NSString *accessibilityBundlePath = [(NSString *)GSSystemRootDirectory() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
219     NSError *error = nil;
220     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
221         LOG_ERROR("Failed to load accessibility bundle at %@: %@", accessibilityBundlePath, error);
222 #endif
223 }
224
225 #if USE(OS_STATE)
226 void WebProcess::registerWithStateDumper()
227 {
228     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
229
230         @autoreleasepool {
231             os_state_data_t os_state = nil;
232
233             // Only gather state on faults and sysdiagnose. It's overkill for
234             // general error messages.
235             if (hints->osh_api == OS_STATE_API_ERROR)
236                 return os_state;
237
238             // Create a dictionary to contain the collected state. This
239             // dictionary will be serialized and passed back to os_state.
240             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
241
242             {
243                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
244                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
245                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
246                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
247                 }
248                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
249             }
250
251             {
252                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
253                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
254                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
255                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
256                 }
257                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
258             }
259
260             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
261             for (auto& page : m_pageMap.values()) {
262                 if (page->usesEphemeralSession())
263                     continue;
264
265                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
266                 [pageLoadTimes addObject:date];
267             }
268
269             // Adding an empty array to the process state may provide an
270             // indication of the existance of private sessions, which we'd like
271             // to hide, so don't add empty arrays.
272             if ([pageLoadTimes count])
273                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
274
275             // --- Possibly add other state here as other entries in the dictionary. ---
276
277             // Submitting an empty process state object may provide an
278             // indication of the existance of private sessions, which we'd like
279             // to hide, so don't return empty dictionaries.
280             if (![stateDict count])
281                 return os_state;
282
283             // Serialize the accumulated process state so that we can put the
284             // result in an os_state_data_t structure.
285             NSError* error = nil;
286             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
287
288             if (!data) {
289                 ASSERT(data);
290                 return os_state;
291             }
292
293             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
294             os_state = (os_state_data_t)malloc(neededSize);
295             if (os_state) {
296                 memset(os_state, 0, neededSize);
297                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
298                 os_state->osd_data_size = data.length;
299                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
300                 memcpy(os_state->osd_data, data.bytes, data.length);
301             }
302
303             return os_state;
304         }
305     });
306 }
307 #endif
308
309 void WebProcess::platformInitializeProcess(const ChildProcessInitializationParameters&)
310 {
311 #if PLATFORM(MAC)
312 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
313     // Deny the WebContent process access to the WindowServer.
314     // This call will not succeed if there are open WindowServer connections at this point.
315     setApplicationIsDaemon();
316     // Make sure that we close any WindowServer connections after checking in with Launch Services.
317     CGSShutdownServerConnections();
318 #else
319     if (![NSApp isRunning]) {
320         // This call is needed when the WebProcess is not running the NSApplication event loop.
321         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
322         launchServicesCheckIn();
323     }
324 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
325 #endif // PLATFORM(MAC)
326
327     registerWithAccessibility();
328
329 #if USE(OS_STATE)
330     registerWithStateDumper();
331 #endif
332 }
333
334 #if USE(APPKIT)
335 void WebProcess::stopRunLoop()
336 {
337 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
338     ChildProcess::stopNSRunLoop();
339 #else
340     ChildProcess::stopNSAppRunLoop();
341 #endif
342 }
343 #endif
344
345 void WebProcess::platformTerminate()
346 {
347     AVFoundationMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
348 }
349
350 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
351 {
352 #if PLATFORM(IOS)
353     audit_token_t auditToken;
354     ASSERT(parentProcessConnection());
355     if (!parentProcessConnection() || !parentProcessConnection()->getAuditToken(auditToken))
356         return nullptr;
357     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
358 #else
359     return nullptr;
360 #endif
361 }
362
363 void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
364 {
365 #if ENABLE(WEB_PROCESS_SANDBOX)
366 #if ENABLE(MANUAL_SANDBOXING)
367     // Need to override the default, because service has a different bundle ID.
368 #if WK_API_ENABLED
369     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
370 #else
371     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
372 #endif
373 #if PLATFORM(IOS) && !ENABLE(MINIMAL_SIMULATOR)
374     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
375 #else
376     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
377 #endif
378     ChildProcess::initializeSandbox(parameters, sandboxParameters);
379 #endif
380 #else
381     UNUSED_PARAM(parameters);
382     UNUSED_PARAM(sandboxParameters);
383 #endif
384 }
385
386 #if PLATFORM(MAC)
387
388 static NSURL *origin(WebPage& page)
389 {
390     WebFrame* mainFrame = page.mainWebFrame();
391     if (!mainFrame)
392         return nil;
393
394     URL mainFrameURL(URL(), mainFrame->url());
395     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
396     String mainFrameOriginString;
397     if (!mainFrameOrigin->isUnique())
398         mainFrameOriginString = mainFrameOrigin->toRawString();
399     else
400         mainFrameOriginString = makeString(mainFrameURL.protocol(), ':'); // toRawString() is not supposed to work with unique origins, and would just return "://".
401
402     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
403     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
404     ASSERT([NSURL URLWithString:mainFrameOriginString]);
405
406     return [NSURL URLWithString:mainFrameOriginString];
407 }
408
409 #endif
410
411 void WebProcess::updateActivePages()
412 {
413 #if PLATFORM(MAC)
414     auto activePageURLs = adoptNS([[NSMutableArray alloc] init]);
415
416     for (auto& page : m_pageMap.values()) {
417         if (page->usesEphemeralSession() || page->isSuspended())
418             continue;
419
420         if (NSURL *originAsURL = origin(*page))
421             [activePageURLs addObject:userVisibleString(originAsURL)];
422     }
423
424     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activePageURLs] {
425         _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activePageURLs.get(), nullptr);
426     });
427 #endif
428 }
429
430 void WebProcess::updateCPULimit()
431 {
432 #if PLATFORM(MAC)
433     std::optional<double> cpuLimit;
434
435     // Use the largest limit among all pages in this process.
436     for (auto& page : m_pageMap.values()) {
437         auto pageCPULimit = page->cpuLimit();
438         if (!pageCPULimit) {
439             cpuLimit = std::nullopt;
440             break;
441         }
442         if (!cpuLimit || pageCPULimit > cpuLimit.value())
443             cpuLimit = pageCPULimit;
444     }
445
446     if (m_cpuLimit == cpuLimit)
447         return;
448
449     m_cpuLimit = cpuLimit;
450     updateCPUMonitorState(CPUMonitorUpdateReason::LimitHasChanged);
451 #endif
452 }
453
454 void WebProcess::updateCPUMonitorState(CPUMonitorUpdateReason reason)
455 {
456 #if PLATFORM(MAC)
457     if (!m_cpuLimit) {
458         if (m_cpuMonitor)
459             m_cpuMonitor->setCPULimit(std::nullopt);
460         return;
461     }
462
463     if (!m_cpuMonitor) {
464         m_cpuMonitor = std::make_unique<CPUMonitor>(cpuMonitoringInterval, [this](double cpuUsage) {
465             RELEASE_LOG(PerformanceLogging, "%p - WebProcess exceeded CPU limit of %.1f%% (was using %.1f%%) hasVisiblePages? %d", this, m_cpuLimit.value() * 100, cpuUsage * 100, hasVisibleWebPage());
466             parentProcessConnection()->send(Messages::WebProcessProxy::DidExceedCPULimit(), 0);
467         });
468     } else if (reason == CPUMonitorUpdateReason::VisibilityHasChanged) {
469         // 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
470         // 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.
471         m_cpuMonitor->setCPULimit(std::nullopt);
472     }
473     m_cpuMonitor->setCPULimit(m_cpuLimit.value());
474 #else
475     UNUSED_PARAM(reason);
476 #endif
477 }
478
479 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
480 {
481     struct Transformer final : ObjCObjectGraph::Transformer {
482         Transformer(WebProcess& webProcess)
483             : m_webProcess(webProcess)
484         {
485         }
486
487         bool shouldTransformObject(id object) const override
488         {
489 #if WK_API_ENABLED
490             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
491                 return true;
492
493             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
494                 return true;
495 #endif
496             return false;
497         }
498
499         RetainPtr<id> transformObject(id object) const override
500         {
501 #if WK_API_ENABLED
502             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
503                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
504                     return wrapper(*webPage);
505
506                 return [NSNull null];
507             }
508
509             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
510                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
511 #endif
512             return object;
513         }
514
515         WebProcess& m_webProcess;
516     };
517
518     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
519 }
520
521 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
522 {
523     struct Transformer final : ObjCObjectGraph::Transformer {
524         bool shouldTransformObject(id object) const override
525         {
526 #if WK_API_ENABLED
527             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
528                 return true;
529
530             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
531                 return true;
532 #endif
533
534             return false;
535         }
536
537         RetainPtr<id> transformObject(id object) const override
538         {
539 #if WK_API_ENABLED
540             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
541                 return controller.handle;
542
543             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
544                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
545 #endif
546             return object;
547         }
548     };
549
550     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
551 }
552
553 void WebProcess::destroyRenderingResources()
554 {
555 #if !RELEASE_LOG_DISABLED
556     MonotonicTime startTime = MonotonicTime::now();
557 #endif
558     CABackingStoreCollectBlocking();
559 #if !RELEASE_LOG_DISABLED
560     MonotonicTime endTime = MonotonicTime::now();
561 #endif
562     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::destroyRenderingResources() took %.2fms", this, (endTime - startTime).milliseconds());
563 }
564
565 // FIXME: This should live somewhere else, and it should have the implementation in line instead of calling out to WKSI.
566 void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
567 {
568     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
569 }
570
571 #if PLATFORM(IOS)
572 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
573 {
574     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
575 }
576 #endif
577
578 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
579 void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
580 {
581     ScrollerStyle::setUseOverlayScrollbars(useOverlayScrollbars);
582
583     ScrollbarTheme& theme = ScrollbarTheme::theme();
584     if (theme.isMockTheme())
585         return;
586
587     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
588 }
589 #endif    
590
591 void WebProcess::setMediaMIMETypes(const Vector<String> types)
592 {
593     AVFoundationMIMETypeCache::singleton().setSupportedTypes(types);
594 }
595
596 } // namespace WebKit