3d5dfb4e78a66604eabe2fddd369d94244c95c88
[WebKit.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() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
325     NSError *error = nil;
326     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
327         LOG_ERROR("Failed to load accessibility bundle at %@: %@", accessibilityBundlePath, error);
328 #endif
329 }
330
331 #if USE(OS_STATE)
332 void WebProcess::registerWithStateDumper()
333 {
334     os_state_add_handler(dispatch_get_main_queue(), ^(os_state_hints_t hints) {
335
336         @autoreleasepool {
337             os_state_data_t os_state = nil;
338
339             // Only gather state on faults and sysdiagnose. It's overkill for
340             // general error messages.
341             if (hints->osh_api == OS_STATE_API_ERROR)
342                 return os_state;
343
344             // Create a dictionary to contain the collected state. This
345             // dictionary will be serialized and passed back to os_state.
346             auto stateDict = adoptNS([[NSMutableDictionary alloc] init]);
347
348             {
349                 auto memoryUsageStats = adoptNS([[NSMutableDictionary alloc] init]);
350                 for (auto& it : PerformanceLogging::memoryUsageStatistics(ShouldIncludeExpensiveComputations::Yes)) {
351                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
352                     [memoryUsageStats setObject:@(it.value) forKey:keyString.get()];
353                 }
354                 [stateDict setObject:memoryUsageStats.get() forKey:@"Memory Usage Stats"];
355             }
356
357             {
358                 auto jsObjectCounts = adoptNS([[NSMutableDictionary alloc] init]);
359                 for (auto& it : PerformanceLogging::javaScriptObjectCounts()) {
360                     auto keyString = adoptNS([[NSString alloc] initWithUTF8String:it.key]);
361                     [jsObjectCounts setObject:@(it.value) forKey:keyString.get()];
362                 }
363                 [stateDict setObject:jsObjectCounts.get() forKey:@"JavaScript Object Counts"];
364             }
365
366             auto pageLoadTimes = adoptNS([[NSMutableArray alloc] init]);
367             for (auto& page : m_pageMap.values()) {
368                 if (page->usesEphemeralSession())
369                     continue;
370
371                 NSDate* date = [NSDate dateWithTimeIntervalSince1970:page->loadCommitTime().secondsSinceEpoch().seconds()];
372                 [pageLoadTimes addObject:date];
373             }
374
375             // Adding an empty array to the process state may provide an
376             // indication of the existance of private sessions, which we'd like
377             // to hide, so don't add empty arrays.
378             if ([pageLoadTimes count])
379                 [stateDict setObject:pageLoadTimes.get() forKey:@"Page Load Times"];
380
381             // --- Possibly add other state here as other entries in the dictionary. ---
382
383             // Submitting an empty process state object may provide an
384             // indication of the existance of private sessions, which we'd like
385             // to hide, so don't return empty dictionaries.
386             if (![stateDict count])
387                 return os_state;
388
389             // Serialize the accumulated process state so that we can put the
390             // result in an os_state_data_t structure.
391             NSError* error = nil;
392             NSData* data = [NSPropertyListSerialization dataWithPropertyList:stateDict.get() format:NSPropertyListBinaryFormat_v1_0 options:0 error:&error];
393
394             if (!data) {
395                 ASSERT(data);
396                 return os_state;
397             }
398
399             size_t neededSize = OS_STATE_DATA_SIZE_NEEDED(data.length);
400             os_state = (os_state_data_t)malloc(neededSize);
401             if (os_state) {
402                 memset(os_state, 0, neededSize);
403                 os_state->osd_type = OS_STATE_DATA_SERIALIZED_NSCF_OBJECT;
404                 os_state->osd_data_size = data.length;
405                 strlcpy(os_state->osd_title, "WebContent state", sizeof(os_state->osd_title));
406                 memcpy(os_state->osd_data, data.bytes, data.length);
407             }
408
409             return os_state;
410         }
411     });
412 }
413 #endif
414
415 void WebProcess::platformInitializeProcess(const AuxiliaryProcessInitializationParameters& parameters)
416 {
417 #if PLATFORM(MAC)
418 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
419     // Deny the WebContent process access to the WindowServer.
420     // This call will not succeed if there are open WindowServer connections at this point.
421     auto retval = CGSSetDenyWindowServerConnections(true);
422     RELEASE_ASSERT(retval == kCGErrorSuccess);
423     // Make sure that we close any WindowServer connections after checking in with Launch Services.
424     CGSShutdownServerConnections();
425
426     SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
427 #else
428
429     if (![NSApp isRunning]) {
430         // This call is needed when the WebProcess is not running the NSApplication event loop.
431         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
432         launchServicesCheckIn();
433     }
434 #endif // ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
435
436     m_uiProcessName = parameters.uiProcessName;
437 #endif // PLATFORM(MAC)
438
439     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
440         m_processType = ProcessType::Inspector;
441 #if ENABLE(SERVICE_WORKER)
442     else if (parameters.extraInitializationData.get("service-worker-process"_s) == "1") {
443         m_processType = ProcessType::ServiceWorker;
444 #if PLATFORM(MAC)
445         m_registrableDomain = RegistrableDomain::uncheckedCreateFromRegistrableDomainString(parameters.extraInitializationData.get("registrable-domain"_s));
446 #endif
447     }
448 #endif
449     else if (parameters.extraInitializationData.get("is-prewarmed"_s) == "1")
450         m_processType = ProcessType::PrewarmedWebContent;
451     else
452         m_processType = ProcessType::WebContent;
453
454     registerWithAccessibility();
455
456 #if USE(OS_STATE)
457     registerWithStateDumper();
458 #endif
459
460 #if HAVE(APP_SSO)
461     [NSURLSession _disableAppSSO];
462 #endif
463 }
464
465 #if USE(APPKIT)
466 void WebProcess::stopRunLoop()
467 {
468 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_NSRUNLOOP)
469     AuxiliaryProcess::stopNSRunLoop();
470 #else
471     AuxiliaryProcess::stopNSAppRunLoop();
472 #endif
473 }
474 #endif
475
476 void WebProcess::platformTerminate()
477 {
478     AVAssetMIMETypeCache::singleton().setCacheMIMETypesCallback(nullptr);
479 }
480
481 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
482 {
483 #if USE(SOURCE_APPLICATION_AUDIT_DATA)
484     ASSERT(parentProcessConnection());
485     if (!parentProcessConnection())
486         return nullptr;
487     Optional<audit_token_t> auditToken = parentProcessConnection()->getAuditToken();
488     if (!auditToken)
489         return nullptr;
490     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&*auditToken, sizeof(*auditToken)));
491 #else
492     return nullptr;
493 #endif
494 }
495
496 void WebProcess::initializeSandbox(const AuxiliaryProcessInitializationParameters& parameters, SandboxInitializationParameters& sandboxParameters)
497 {
498 #if ENABLE(WEB_PROCESS_SANDBOX)
499 #if ENABLE(MANUAL_SANDBOXING)
500     // Need to override the default, because service has a different bundle ID.
501     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKWebView")];
502 #if PLATFORM(IOS_FAMILY) && !PLATFORM(MACCATALYST)
503     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
504 #else
505     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
506 #endif
507     AuxiliaryProcess::initializeSandbox(parameters, sandboxParameters);
508 #endif
509 #else
510     UNUSED_PARAM(parameters);
511     UNUSED_PARAM(sandboxParameters);
512 #endif
513 }
514
515 #if PLATFORM(MAC)
516
517 static NSURL *origin(WebPage& page)
518 {
519     WebFrame* mainFrame = page.mainWebFrame();
520     if (!mainFrame)
521         return nil;
522
523     URL mainFrameURL = { URL(), mainFrame->url() };
524     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
525     String mainFrameOriginString;
526     if (!mainFrameOrigin->isUnique())
527         mainFrameOriginString = mainFrameOrigin->toRawString();
528     else
529         mainFrameOriginString = makeString(mainFrameURL.protocol(), ':'); // toRawString() is not supposed to work with unique origins, and would just return "://".
530
531     // +[NSURL URLWithString:] returns nil when its argument is malformed. It's unclear when we would have a malformed URL here,
532     // but it happens in practice according to <rdar://problem/14173389>. Leaving an assertion in to catch a reproducible case.
533     ASSERT([NSURL URLWithString:mainFrameOriginString]);
534
535     return [NSURL URLWithString:mainFrameOriginString];
536 }
537
538 #endif
539
540 #if PLATFORM(MAC)
541 static RetainPtr<NSArray<NSString *>> activePagesOrigins(const HashMap<PageIdentifier, RefPtr<WebPage>>& pageMap)
542 {
543     RetainPtr<NSMutableArray<NSString *>> activeOrigins = adoptNS([[NSMutableArray alloc] init]);
544
545     for (auto& page : pageMap.values()) {
546         if (page->usesEphemeralSession())
547             continue;
548
549         if (NSURL *originAsURL = origin(*page))
550             [activeOrigins addObject:WTF::userVisibleString(originAsURL)];
551     }
552
553     return activeOrigins;
554 }
555 #endif
556
557 void WebProcess::updateActivePages()
558 {
559 #if PLATFORM(MAC)
560     auto activeOrigins = activePagesOrigins(m_pageMap);
561
562     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activeOrigins = WTFMove(activeOrigins)] {
563         _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activeOrigins.get(), nullptr);
564     });
565 #endif
566 }
567
568 void WebProcess::getActivePagesOriginsForTesting(CompletionHandler<void(Vector<String>&&)>&& completionHandler)
569 {
570 #if PLATFORM(MAC)
571     auto activeOriginsAsNSStrings = activePagesOrigins(m_pageMap);
572     Vector<String> activeOrigins;
573     activeOrigins.reserveInitialCapacity([activeOriginsAsNSStrings count]);
574     for (NSString* activeOrigin in activeOriginsAsNSStrings.get())
575         activeOrigins.uncheckedAppend(activeOrigin);
576     completionHandler(WTFMove(activeOrigins));
577 #else
578     completionHandler({ });
579 #endif
580 }
581
582 void WebProcess::updateCPULimit()
583 {
584 #if PLATFORM(MAC)
585     Optional<double> cpuLimit;
586     if (m_processType == ProcessType::ServiceWorker)
587         cpuLimit = serviceWorkerCPULimit;
588     else {
589         // Use the largest limit among all pages in this process.
590         for (auto& page : m_pageMap.values()) {
591             auto pageCPULimit = page->cpuLimit();
592             if (!pageCPULimit) {
593                 cpuLimit = WTF::nullopt;
594                 break;
595             }
596             if (!cpuLimit || pageCPULimit > cpuLimit.value())
597                 cpuLimit = pageCPULimit;
598         }
599     }
600
601     if (m_cpuLimit == cpuLimit)
602         return;
603
604     m_cpuLimit = cpuLimit;
605     updateCPUMonitorState(CPUMonitorUpdateReason::LimitHasChanged);
606 #endif
607 }
608
609 void WebProcess::updateCPUMonitorState(CPUMonitorUpdateReason reason)
610 {
611 #if PLATFORM(MAC)
612     if (!m_cpuLimit) {
613         if (m_cpuMonitor)
614             m_cpuMonitor->setCPULimit(WTF::nullopt);
615         return;
616     }
617
618     if (!m_cpuMonitor) {
619         m_cpuMonitor = std::make_unique<CPUMonitor>(cpuMonitoringInterval, [this](double cpuUsage) {
620             if (m_processType == ProcessType::ServiceWorker)
621                 RELEASE_LOG_ERROR(PerformanceLogging, "%p - Service worker process exceeded CPU limit of %.1f%% (was using %.1f%%)", this, m_cpuLimit.value() * 100, cpuUsage * 100);
622             else
623                 RELEASE_LOG_ERROR(PerformanceLogging, "%p - WebProcess exceeded CPU limit of %.1f%% (was using %.1f%%) hasVisiblePages? %d", this, m_cpuLimit.value() * 100, cpuUsage * 100, hasVisibleWebPage());
624             parentProcessConnection()->send(Messages::WebProcessProxy::DidExceedCPULimit(), 0);
625         });
626     } else if (reason == CPUMonitorUpdateReason::VisibilityHasChanged) {
627         // 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
628         // 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.
629         m_cpuMonitor->setCPULimit(WTF::nullopt);
630     }
631     m_cpuMonitor->setCPULimit(m_cpuLimit);
632 #else
633     UNUSED_PARAM(reason);
634 #endif
635 }
636
637 RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& objectGraph)
638 {
639     struct Transformer final : ObjCObjectGraph::Transformer {
640         Transformer(WebProcess& webProcess)
641             : m_webProcess(webProcess)
642         {
643         }
644
645         bool shouldTransformObject(id object) const override
646         {
647             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
648                 return true;
649
650             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
651             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
652                 return true;
653             ALLOW_DEPRECATED_DECLARATIONS_END
654             return false;
655         }
656
657         RetainPtr<id> transformObject(id object) const override
658         {
659             if (auto* handle = dynamic_objc_cast<WKBrowsingContextHandle>(object)) {
660                 if (auto* webPage = m_webProcess.webPage(handle._pageID))
661                     return wrapper(*webPage);
662
663                 return [NSNull null];
664             }
665
666             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
667             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
668                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
669             ALLOW_DEPRECATED_DECLARATIONS_END
670             return object;
671         }
672
673         WebProcess& m_webProcess;
674     };
675
676     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer(*this)).get());
677 }
678
679 RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& objectGraph)
680 {
681     struct Transformer final : ObjCObjectGraph::Transformer {
682         bool shouldTransformObject(id object) const override
683         {
684             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
685                 return true;
686
687             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
688             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
689                 return true;
690             ALLOW_DEPRECATED_DECLARATIONS_END
691             return false;
692         }
693
694         RetainPtr<id> transformObject(id object) const override
695         {
696             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
697                 return controller.handle;
698
699             ALLOW_DEPRECATED_DECLARATIONS_BEGIN
700             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
701                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
702             ALLOW_DEPRECATED_DECLARATIONS_END
703             return object;
704         }
705     };
706
707     return ObjCObjectGraph::create(ObjCObjectGraph::transform(objectGraph.rootObject(), Transformer()).get());
708 }
709
710 void WebProcess::destroyRenderingResources()
711 {
712 #if !RELEASE_LOG_DISABLED
713     MonotonicTime startTime = MonotonicTime::now();
714 #endif
715     CABackingStoreCollectBlocking();
716 #if !RELEASE_LOG_DISABLED
717     MonotonicTime endTime = MonotonicTime::now();
718 #endif
719     RELEASE_LOG(ProcessSuspension, "%p - WebProcess::destroyRenderingResources() took %.2fms", this, (endTime - startTime).milliseconds());
720 }
721
722 // FIXME: This should live somewhere else, and it should have the implementation in line instead of calling out to WKSI.
723 void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
724 {
725     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
726 }
727
728 #if PLATFORM(IOS_FAMILY)
729 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
730 {
731     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
732 }
733
734 bool WebProcess::shouldFreezeOnSuspension() const
735 {
736     switch (m_processType) {
737     case ProcessType::Inspector:
738     case ProcessType::ServiceWorker:
739     case ProcessType::PrewarmedWebContent:
740     case ProcessType::CachedWebContent:
741         return false;
742     case ProcessType::WebContent:
743         break;
744     }
745
746     for (auto& page : m_pageMap.values()) {
747         if (!page->isSuspended())
748             return true;
749     }
750
751     // Since all of the pages in this process were suspended, we should not bother freezing it.
752     return false;
753 }
754
755 void WebProcess::updateFreezerStatus()
756 {
757     bool isFreezable = shouldFreezeOnSuspension();
758     auto result = memorystatus_control(MEMORYSTATUS_CMD_SET_PROCESS_IS_FREEZABLE, getpid(), isFreezable ? 1 : 0, nullptr, 0);
759     if (result)
760         RELEASE_LOG_ERROR(ProcessSuspension, "%p - WebProcess::updateFreezerStatus() isFreezable: %d, error: %d", this, isFreezable, result);
761     else
762         RELEASE_LOG(ProcessSuspension, "%p - WebProcess::updateFreezerStatus() isFreezable: %d, success", this, isFreezable);
763 }
764 #endif
765
766 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
767 void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
768 {
769     ScrollerStyle::setUseOverlayScrollbars(useOverlayScrollbars);
770
771     ScrollbarTheme& theme = ScrollbarTheme::theme();
772     if (theme.isMockTheme())
773         return;
774
775     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
776     
777     NSScrollerStyle style = useOverlayScrollbars ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
778     [NSScrollerImpPair _updateAllScrollerImpPairsForNewRecommendedScrollerStyle:style];
779 }
780
781 void WebProcess::displayConfigurationChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags)
782 {
783     GraphicsContext3DManager::displayWasReconfigured(displayID, flags, nullptr);
784 }
785     
786 void WebProcess::displayWasRefreshed(CGDirectDisplayID displayID)
787 {
788     DisplayRefreshMonitorManager::sharedManager().displayWasUpdated(displayID);
789 }
790 #endif
791
792 #if PLATFORM(IOS)
793 static float currentBacklightLevel()
794 {
795     return WebProcess::singleton().backlightLevel();
796 }
797
798 void WebProcess::backlightLevelDidChange(float backlightLevel)
799 {
800     m_backlightLevel = backlightLevel;
801
802     static std::once_flag onceFlag;
803     std::call_once(
804         onceFlag,
805         [] {
806             Method methodToPatch = class_getInstanceMethod([UIDevice class], @selector(_backlightLevel));
807             method_setImplementation(methodToPatch, reinterpret_cast<IMP>(currentBacklightLevel));
808         });
809 }
810 #endif
811
812 void WebProcess::setMediaMIMETypes(const Vector<String> types)
813 {
814     AVAssetMIMETypeCache::singleton().setSupportedTypes(types);
815 }
816
817 } // namespace WebKit