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