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