Cleanup RuntimeEnabledFeatures includes
[WebKit.git] / Source / WebKit / UIProcess / WebProcessPool.cpp
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 #include "config.h"
27 #include "WebProcessPool.h"
28
29 #include "APIArray.h"
30 #include "APIAutomationClient.h"
31 #include "APICustomProtocolManagerClient.h"
32 #include "APIDownloadClient.h"
33 #include "APIHTTPCookieStore.h"
34 #include "APIInjectedBundleClient.h"
35 #include "APILegacyContextHistoryClient.h"
36 #include "APINavigation.h"
37 #include "APIPageConfiguration.h"
38 #include "APIProcessPoolConfiguration.h"
39 #include "AuxiliaryProcessMessages.h"
40 #include "DownloadProxy.h"
41 #include "DownloadProxyMessages.h"
42 #include "GamepadData.h"
43 #include "HighPerformanceGraphicsUsageSampler.h"
44 #include "LegacyGlobalSettings.h"
45 #include "LogInitialization.h"
46 #include "Logging.h"
47 #include "NetworkProcessCreationParameters.h"
48 #include "NetworkProcessMessages.h"
49 #include "NetworkProcessProxy.h"
50 #include "PerActivityStateCPUUsageSampler.h"
51 #include "PluginProcessManager.h"
52 #include "SandboxExtension.h"
53 #include "StatisticsData.h"
54 #include "TextChecker.h"
55 #include "UIGamepad.h"
56 #include "UIGamepadProvider.h"
57 #include "WKContextPrivate.h"
58 #include "WebAutomationSession.h"
59 #include "WebBackForwardCache.h"
60 #include "WebBackForwardList.h"
61 #include "WebBackForwardListItem.h"
62 #include "WebCertificateInfo.h"
63 #include "WebContextSupplement.h"
64 #include "WebCookieManagerProxy.h"
65 #include "WebCoreArgumentCoders.h"
66 #include "WebGeolocationManagerProxy.h"
67 #include "WebInspectorUtilities.h"
68 #include "WebKit2Initialize.h"
69 #include "WebMemorySampler.h"
70 #include "WebNotificationManagerProxy.h"
71 #include "WebPageGroup.h"
72 #include "WebPreferences.h"
73 #include "WebPreferencesKeys.h"
74 #include "WebProcessCache.h"
75 #include "WebProcessCreationParameters.h"
76 #include "WebProcessDataStoreParameters.h"
77 #include "WebProcessMessages.h"
78 #include "WebProcessPoolMessages.h"
79 #include "WebProcessProxy.h"
80 #include "WebsiteDataStore.h"
81 #include "WebsiteDataStoreParameters.h"
82 #include <JavaScriptCore/JSCInlines.h>
83 #include <WebCore/ApplicationCacheStorage.h>
84 #include <WebCore/LogInitialization.h>
85 #include <WebCore/MockRealtimeMediaSourceCenter.h>
86 #include <WebCore/NetworkStorageSession.h>
87 #include <WebCore/PlatformScreen.h>
88 #include <WebCore/ProcessIdentifier.h>
89 #include <WebCore/ProcessWarming.h>
90 #include <WebCore/RegistrationDatabase.h>
91 #include <WebCore/ResourceRequest.h>
92 #include <WebCore/RuntimeApplicationChecks.h>
93 #include <pal/SessionID.h>
94 #include <wtf/Language.h>
95 #include <wtf/MainThread.h>
96 #include <wtf/NeverDestroyed.h>
97 #include <wtf/ProcessPrivilege.h>
98 #include <wtf/RunLoop.h>
99 #include <wtf/Scope.h>
100 #include <wtf/URLParser.h>
101 #include <wtf/WallTime.h>
102 #include <wtf/text/StringBuilder.h>
103 #include <wtf/text/StringConcatenateNumbers.h>
104
105 #if ENABLE(SERVICE_CONTROLS)
106 #include "ServicesController.h"
107 #endif
108
109 #if ENABLE(REMOTE_INSPECTOR)
110 #include <JavaScriptCore/RemoteInspector.h>
111 #endif
112
113 #if OS(LINUX)
114 #include "MemoryPressureMonitor.h"
115 #endif
116
117 #if PLATFORM(COCOA)
118 #include "VersionChecks.h"
119 #endif
120
121 #if PLATFORM(MAC)
122 #include <pal/spi/cg/CoreGraphicsSPI.h>
123 #endif
124
125 #ifndef NDEBUG
126 #include <wtf/RefCountedLeakCounter.h>
127 #endif
128
129 namespace WebKit {
130 using namespace WebCore;
131
132 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, processPoolCounter, ("WebProcessPool"));
133
134 const Seconds serviceWorkerTerminationDelay { 5_s };
135
136 static uint64_t generateListenerIdentifier()
137 {
138     static uint64_t nextIdentifier = 1;
139     return nextIdentifier++;
140 }
141
142 static HashMap<uint64_t, Function<void(WebProcessPool&)>>& processPoolCreationListenerFunctionMap()
143 {
144     static NeverDestroyed<HashMap<uint64_t, Function<void(WebProcessPool&)>>> map;
145     return map;
146 }
147
148 uint64_t WebProcessPool::registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&& function)
149 {
150     ASSERT(function);
151
152     auto identifier = generateListenerIdentifier();
153     processPoolCreationListenerFunctionMap().set(identifier, WTFMove(function));
154     return identifier;
155 }
156
157 void WebProcessPool::unregisterProcessPoolCreationListener(uint64_t identifier)
158 {
159     processPoolCreationListenerFunctionMap().remove(identifier);
160 }
161
162 Ref<WebProcessPool> WebProcessPool::create(API::ProcessPoolConfiguration& configuration)
163 {
164     InitializeWebKit2();
165     return adoptRef(*new WebProcessPool(configuration));
166 }
167
168 void WebProcessPool::notifyThisWebProcessPoolWasCreated()
169 {
170     auto& listenerMap = processPoolCreationListenerFunctionMap();
171
172     Vector<uint64_t> identifiers;
173     identifiers.reserveInitialCapacity(listenerMap.size());
174     for (auto identifier : listenerMap.keys())
175         identifiers.uncheckedAppend(identifier);
176
177     for (auto identifier : identifiers) {
178         auto iterator = listenerMap.find(identifier);
179         if (iterator == listenerMap.end())
180             continue;
181
182         // To make sure the Function object stays alive until after the function call has been made,
183         // we temporarily move it out of the map.
184         // This protects it from the Function calling unregisterProcessPoolCreationListener thereby
185         // removing itself from the map of listeners.
186         // If the identifier still exists in the map later, we move it back in.
187         Function<void(WebProcessPool&)> function = WTFMove(iterator->value);
188         function(*this);
189
190         iterator = listenerMap.find(identifier);
191         if (iterator != listenerMap.end()) {
192             ASSERT(!iterator->value);
193             iterator->value = WTFMove(function);
194         }
195     }
196 }
197
198 static Vector<WebProcessPool*>& processPools()
199 {
200     static NeverDestroyed<Vector<WebProcessPool*>> processPools;
201     return processPools;
202 }
203
204 const Vector<WebProcessPool*>& WebProcessPool::allProcessPools()
205 {
206     return processPools();
207 }
208
209 static HashSet<String, ASCIICaseInsensitiveHash>& globalURLSchemesWithCustomProtocolHandlers()
210 {
211     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> set;
212     return set;
213 }
214
215 WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
216     : m_configuration(configuration.copy())
217     , m_defaultPageGroup(WebPageGroup::create())
218     , m_injectedBundleClient(makeUnique<API::InjectedBundleClient>())
219     , m_automationClient(makeUnique<API::AutomationClient>())
220     , m_downloadClient(makeUniqueRef<API::DownloadClient>())
221     , m_historyClient(makeUnique<API::LegacyContextHistoryClient>())
222     , m_customProtocolManagerClient(makeUnique<API::CustomProtocolManagerClient>())
223     , m_visitedLinkStore(VisitedLinkStore::create())
224 #if PLATFORM(MAC)
225     , m_highPerformanceGraphicsUsageSampler(makeUnique<HighPerformanceGraphicsUsageSampler>(*this))
226     , m_perActivityStateCPUUsageSampler(makeUnique<PerActivityStateCPUUsageSampler>(*this))
227 #endif
228     , m_alwaysRunsAtBackgroundPriority(m_configuration->alwaysRunsAtBackgroundPriority())
229     , m_shouldTakeUIBackgroundAssertion(m_configuration->shouldTakeUIBackgroundAssertion())
230     , m_userObservablePageCounter([this](RefCounterEvent) { updateProcessSuppressionState(); })
231     , m_processSuppressionDisabledForPageCounter([this](RefCounterEvent) { updateProcessSuppressionState(); })
232     , m_hiddenPageThrottlingAutoIncreasesCounter([this](RefCounterEvent) { m_hiddenPageThrottlingTimer.startOneShot(0_s); })
233     , m_hiddenPageThrottlingTimer(RunLoop::main(), this, &WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit)
234     , m_serviceWorkerProcessesTerminationTimer(RunLoop::main(), this, &WebProcessPool::terminateServiceWorkerProcesses)
235 #if PLATFORM(IOS_FAMILY)
236     , m_foregroundWebProcessCounter([this](RefCounterEvent) { updateProcessAssertions(); })
237     , m_backgroundWebProcessCounter([this](RefCounterEvent) { updateProcessAssertions(); })
238 #endif
239     , m_backForwardCache(makeUniqueRef<WebBackForwardCache>())
240     , m_webProcessCache(makeUniqueRef<WebProcessCache>(*this))
241 {
242     static std::once_flag onceFlag;
243     std::call_once(onceFlag, [] {
244         WTF::setProcessPrivileges(allPrivileges());
245         WebCore::NetworkStorageSession::permitProcessToUseCookieAPI(true);
246         Process::setIdentifier(WebCore::ProcessIdentifier::generate());
247     });
248
249     if (!m_websiteDataStore && WebKit::WebsiteDataStore::defaultDataStoreExists())
250         m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore();
251
252     for (auto& scheme : m_configuration->alwaysRevalidatedURLSchemes())
253         m_schemesToRegisterAsAlwaysRevalidated.add(scheme);
254
255     for (const auto& urlScheme : m_configuration->cachePartitionedURLSchemes())
256         m_schemesToRegisterAsCachePartitioned.add(urlScheme);
257
258     platformInitialize();
259
260 #if OS(LINUX)
261     MemoryPressureMonitor::singleton().start();
262 #endif
263
264     addMessageReceiver(Messages::WebProcessPool::messageReceiverName(), *this);
265
266     // NOTE: These sub-objects must be initialized after m_messageReceiverMap..
267     addSupplement<WebCookieManagerProxy>();
268     addSupplement<WebGeolocationManagerProxy>();
269     addSupplement<WebNotificationManagerProxy>();
270 #if ENABLE(MEDIA_SESSION)
271     addSupplement<WebMediaSessionFocusManager>();
272 #endif
273
274     processPools().append(this);
275
276     addLanguageChangeObserver(this, languageChanged);
277
278     resolvePathsForSandboxExtensions();
279
280 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
281     WebCore::initializeLogChannelsIfNecessary();
282     WebKit::initializeLogChannelsIfNecessary();
283 #endif // !LOG_DISABLED || !RELEASE_LOG_DISABLED
284
285 #ifndef NDEBUG
286     processPoolCounter.increment();
287 #endif
288
289     notifyThisWebProcessPoolWasCreated();
290
291     updateBackForwardCacheCapacity();
292 }
293
294 WebProcessPool::~WebProcessPool()
295 {
296     m_webProcessCache->clear();
297
298     bool removed = processPools().removeFirst(this);
299     ASSERT_UNUSED(removed, removed);
300
301     removeLanguageChangeObserver(this);
302
303     m_messageReceiverMap.invalidate();
304
305     for (auto& supplement : m_supplements.values()) {
306         supplement->processPoolDestroyed();
307         supplement->clearProcessPool();
308     }
309
310     invalidateCallbackMap(m_dictionaryCallbacks, CallbackBase::Error::OwnerWasInvalidated);
311
312     platformInvalidateContext();
313
314 #ifndef NDEBUG
315     processPoolCounter.decrement();
316 #endif
317
318     if (m_networkProcess)
319         m_networkProcess->shutDownProcess();
320
321 #if ENABLE(GAMEPAD)
322     if (!m_processesUsingGamepads.isEmpty())
323         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
324 #endif
325
326     // Only remaining processes should be pre-warmed ones as other keep the process pool alive.
327     while (!m_processes.isEmpty()) {
328         auto& process = m_processes.first();
329
330         ASSERT(process->isPrewarmed());
331         // We need to be the only one holding a reference to the pre-warmed process so that it gets destroyed.
332         // WebProcessProxies currently always expect to have a WebProcessPool.
333         ASSERT(process->hasOneRef());
334
335         process->shutDown();
336     }
337 }
338
339 void WebProcessPool::initializeClient(const WKContextClientBase* client)
340 {
341     m_client.initialize(client);
342 }
343
344 void WebProcessPool::setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&& client)
345 {
346     if (!client)
347         m_injectedBundleClient = makeUnique<API::InjectedBundleClient>();
348     else
349         m_injectedBundleClient = WTFMove(client);
350 }
351
352 void WebProcessPool::initializeConnectionClient(const WKContextConnectionClientBase* client)
353 {
354     m_connectionClient.initialize(client);
355 }
356
357 void WebProcessPool::setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&& historyClient)
358 {
359     if (!historyClient)
360         m_historyClient = makeUnique<API::LegacyContextHistoryClient>();
361     else
362         m_historyClient = WTFMove(historyClient);
363 }
364
365 void WebProcessPool::setDownloadClient(UniqueRef<API::DownloadClient>&& downloadClient)
366 {
367     m_downloadClient = WTFMove(downloadClient);
368 }
369
370 void WebProcessPool::setAutomationClient(std::unique_ptr<API::AutomationClient>&& automationClient)
371 {
372     if (!automationClient)
373         m_automationClient = makeUnique<API::AutomationClient>();
374     else
375         m_automationClient = WTFMove(automationClient);
376 }
377
378 void WebProcessPool::setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&& customProtocolManagerClient)
379 {
380 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
381     if (!customProtocolManagerClient)
382         m_customProtocolManagerClient = makeUnique<API::CustomProtocolManagerClient>();
383     else
384         m_customProtocolManagerClient = WTFMove(customProtocolManagerClient);
385 #endif
386 }
387
388 void WebProcessPool::setStorageAccessAPIEnabled(bool enabled)
389 {
390     m_storageAccessAPIEnabled = enabled;
391 #if PLATFORM(COCOA)
392     sendToNetworkingProcess(Messages::NetworkProcess::SetStorageAccessAPIEnabled(enabled));
393 #endif
394 }
395
396 void WebProcessPool::setCustomWebContentServiceBundleIdentifier(const String& customWebContentServiceBundleIdentifier)
397 {
398     // Guard against API misuse.
399     if (!customWebContentServiceBundleIdentifier.isAllASCII())
400         CRASH();
401
402     m_configuration->setCustomWebContentServiceBundleIdentifier(customWebContentServiceBundleIdentifier);
403 }
404
405 IPC::Connection* WebProcessPool::networkingProcessConnection()
406 {
407     return m_networkProcess->connection();
408 }
409
410 void WebProcessPool::languageChanged(void* context)
411 {
412     static_cast<WebProcessPool*>(context)->languageChanged();
413 }
414
415 void WebProcessPool::languageChanged()
416 {
417     sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged(userPreferredLanguages()));
418 #if USE(SOUP)
419     if (m_networkProcess)
420         m_networkProcess->send(Messages::NetworkProcess::UserPreferredLanguagesChanged(userPreferredLanguages()), 0);
421 #endif
422 }
423
424 void WebProcessPool::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled)
425 {
426     sendToAllProcesses(Messages::WebProcess::FullKeyboardAccessModeChanged(fullKeyboardAccessEnabled));
427 }
428
429 #if OS(LINUX)
430 void WebProcessPool::sendMemoryPressureEvent(bool isCritical)
431 {
432     sendToAllProcesses(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
433     sendToNetworkingProcess(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
434 #if ENABLE(NETSCAPE_PLUGIN_API)
435     PluginProcessManager::singleton().sendMemoryPressureEvent(isCritical);
436 #endif
437 }
438 #endif
439
440 void WebProcessPool::textCheckerStateChanged()
441 {
442     sendToAllProcesses(Messages::WebProcess::SetTextCheckerState(TextChecker::state()));
443 }
444
445 void WebProcessPool::setApplicationIsActive(bool isActive)
446 {
447     m_webProcessCache->setApplicationIsActive(isActive);
448 }
449
450 void WebProcessPool::screenPropertiesStateChanged()
451 {
452 #if PLATFORM(MAC)
453     auto screenProperties = WebCore::collectScreenProperties();
454     sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
455 #endif
456 }
457
458 NetworkProcessProxy& WebProcessPool::ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore)
459 {
460     ASSERT(RunLoop::isMain());
461     
462     // FIXME: This is a temporary workaround for apps using WebKit API on non-main threads.
463     // We should remove this once we enforce threading violation check on our APIs.
464     // https://bugs.webkit.org/show_bug.cgi?id=200246.
465     if (!RunLoop::isMain()) {
466         callOnMainRunLoopAndWait([this, protectedThis = makeRef(*this)] {
467             ensureNetworkProcess();
468         });
469         return *m_networkProcess;
470     }
471
472     if (m_networkProcess) {
473         if (withWebsiteDataStore) {
474             m_networkProcess->addSession(makeRef(*withWebsiteDataStore));
475             withWebsiteDataStore->clearPendingCookies();
476         }
477         return *m_networkProcess;
478     }
479
480     auto networkProcess = makeUnique<NetworkProcessProxy>(*this);
481
482     NetworkProcessCreationParameters parameters;
483
484     if (m_websiteDataStore) {
485         parameters.defaultDataStoreParameters.pendingCookies = copyToVector(m_websiteDataStore->pendingCookies());
486         m_websiteDataStore->clearPendingCookies();
487 #if PLATFORM(COCOA)
488         parameters.defaultDataStoreParameters.networkSessionParameters.sourceApplicationBundleIdentifier = m_websiteDataStore->sourceApplicationBundleIdentifier();
489         parameters.defaultDataStoreParameters.networkSessionParameters.sourceApplicationSecondaryIdentifier = m_websiteDataStore->sourceApplicationSecondaryIdentifier();
490 #endif
491         m_websiteDataStore->networkingHasBegun();
492     }
493
494     parameters.cacheModel = LegacyGlobalSettings::singleton().cacheModel();
495
496     for (auto& scheme : globalURLSchemesWithCustomProtocolHandlers())
497         parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
498
499 #if PLATFORM(IOS_FAMILY)
500     String cookieStorageDirectory = WebProcessPool::cookieStorageDirectory();
501     if (!cookieStorageDirectory.isEmpty())
502         SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle);
503
504     String containerCachesDirectory = WebProcessPool::networkingCachesDirectory();
505     if (!containerCachesDirectory.isEmpty())
506         SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle);
507
508     String parentBundleDirectory = WebProcessPool::parentBundleDirectory();
509     if (!parentBundleDirectory.isEmpty())
510         SandboxExtension::createHandle(parentBundleDirectory, SandboxExtension::Type::ReadOnly, parameters.parentBundleDirectoryExtensionHandle);
511
512 #if ENABLE(INDEXED_DATABASE)
513     SandboxExtension::createHandleForTemporaryFile(emptyString(), SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.indexedDatabaseTempBlobDirectoryExtensionHandle);
514 #endif
515 #endif
516
517     parameters.hstsStorageDirectory = LegacyGlobalSettings::singleton().hstsStorageDirectory();
518     if (!parameters.hstsStorageDirectory.isNull())
519         SandboxExtension::createHandleForReadWriteDirectory(parameters.hstsStorageDirectory, parameters.hstsStorageDirectoryExtensionHandle);
520
521     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
522     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
523     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
524     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
525     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
526     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
527
528 #if ENABLE(INDEXED_DATABASE)
529     // *********
530     // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>)
531     // *********
532     if (WebKit::WebsiteDataStore::defaultDataStoreExists())
533         parameters.defaultDataStoreParameters.indexedDatabaseDirectory = WebKit::WebsiteDataStore::defaultDataStore()->parameters().indexedDatabaseDirectory;
534     
535     if (!parameters.defaultDataStoreParameters.indexedDatabaseDirectory.isEmpty()) {
536         SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.indexedDatabaseDirectory, parameters.defaultDataStoreParameters.indexedDatabaseDirectoryExtensionHandle);
537         networkProcess->createSymLinkForFileUpgrade(parameters.defaultDataStoreParameters.indexedDatabaseDirectory);
538     }
539 #endif
540
541 #if ENABLE(SERVICE_WORKER)
542     if (m_websiteDataStore)
543         parameters.serviceWorkerRegistrationDirectory = m_websiteDataStore->resolvedServiceWorkerRegistrationDirectory();
544     if (!parameters.serviceWorkerRegistrationDirectory)
545         parameters.serviceWorkerRegistrationDirectory =  WebKit::WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
546     SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
547 #endif
548
549     auto localStorageDirectory = m_websiteDataStore ? m_websiteDataStore->resolvedLocalStorageDirectory() : nullString();
550     if (!localStorageDirectory)
551         localStorageDirectory = WebKit::WebsiteDataStore::defaultLocalStorageDirectory();
552     parameters.defaultDataStoreParameters.localStorageDirectory = localStorageDirectory;
553     SandboxExtension::createHandleForReadWriteDirectory(localStorageDirectory, parameters.defaultDataStoreParameters.localStorageDirectoryExtensionHandle);
554
555     if (m_websiteDataStore)
556         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = m_websiteDataStore->resolvedResourceLoadStatisticsDirectory();
557     if (parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory.isEmpty())
558         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = WebKit::WebsiteDataStore::defaultResourceLoadStatisticsDirectory();
559
560     SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory, parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectoryExtensionHandle);
561
562     bool enableResourceLoadStatistics = false;
563     bool enableResourceLoadStatisticsLogTestingEvent = false;
564     bool shouldIncludeLocalhost = true;
565     bool enableResourceLoadStatisticsDebugMode = false;
566     WebCore::RegistrableDomain manualPrevalentResource { };
567     if (withWebsiteDataStore) {
568         enableResourceLoadStatistics = withWebsiteDataStore->resourceLoadStatisticsEnabled();
569 #if ENABLE(RESOURCE_LOAD_STATISTICS)
570         enableResourceLoadStatisticsLogTestingEvent = withWebsiteDataStore->hasStatisticsTestingCallback();
571 #endif
572         if (enableResourceLoadStatistics) {
573             auto networkSessionParameters = withWebsiteDataStore->parameters().networkSessionParameters;
574             shouldIncludeLocalhost = networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics;
575             enableResourceLoadStatisticsDebugMode = networkSessionParameters.enableResourceLoadStatisticsDebugMode;
576             manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsManualPrevalentResource;
577         }
578
579         parameters.defaultDataStoreParameters.perOriginStorageQuota = withWebsiteDataStore->perOriginStorageQuota();
580         parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = withWebsiteDataStore->perThirdPartyOriginStorageQuota();
581         
582         const auto& networkCacheDirectory = withWebsiteDataStore->resolvedNetworkCacheDirectory();
583         if (!networkCacheDirectory.isNull()) {
584             parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
585             SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
586         }
587     } else if (m_websiteDataStore) {
588         enableResourceLoadStatistics = m_websiteDataStore->resourceLoadStatisticsEnabled();
589 #if ENABLE(RESOURCE_LOAD_STATISTICS)
590         enableResourceLoadStatisticsLogTestingEvent = m_websiteDataStore->hasStatisticsTestingCallback();
591 #endif
592         if (enableResourceLoadStatistics) {
593             auto networkSessionParameters = m_websiteDataStore->parameters().networkSessionParameters;
594             shouldIncludeLocalhost = networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics;
595             enableResourceLoadStatisticsDebugMode = networkSessionParameters.enableResourceLoadStatisticsDebugMode;
596             manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsManualPrevalentResource;
597         }
598
599         parameters.defaultDataStoreParameters.perOriginStorageQuota = m_websiteDataStore->perOriginStorageQuota();
600         parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = m_websiteDataStore->perThirdPartyOriginStorageQuota();
601
602         const auto& networkCacheDirectory = m_websiteDataStore->resolvedNetworkCacheDirectory();
603         if (!networkCacheDirectory.isNull()) {
604             parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
605             SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
606         }
607     } else {
608         if (WebsiteDataStore::defaultDataStoreExists())
609             enableResourceLoadStatistics = WebsiteDataStore::defaultDataStore()->resourceLoadStatisticsEnabled();
610         auto networkCacheDirectory = WebsiteDataStore::defaultNetworkCacheDirectory();
611         parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
612         SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
613     }
614
615     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatistics = enableResourceLoadStatistics;
616     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatisticsLogTestingEvent = enableResourceLoadStatisticsLogTestingEvent;
617     parameters.defaultDataStoreParameters.networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics = shouldIncludeLocalhost;
618     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatisticsDebugMode = enableResourceLoadStatisticsDebugMode;
619     parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsManualPrevalentResource = manualPrevalentResource;
620
621     // Add any platform specific parameters
622     platformInitializeNetworkProcess(parameters);
623
624     // Initialize the network process.
625     networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0);
626
627 #if PLATFORM(COCOA)
628     networkProcess->send(Messages::NetworkProcess::SetQOS(networkProcessLatencyQOS(), networkProcessThroughputQOS()), 0);
629 #endif
630
631     if (m_didNetworkProcessCrash) {
632         m_didNetworkProcessCrash = false;
633         reinstateNetworkProcessAssertionState(*networkProcess);
634     }
635
636     if (withWebsiteDataStore) {
637         networkProcess->addSession(makeRef(*withWebsiteDataStore));
638         withWebsiteDataStore->clearPendingCookies();
639     }
640
641     // Make sure the network process knows about all the sessions that have been registered before it started.
642     for (auto& sessionID : m_sessionToPageIDsMap.keys()) {
643         if (auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID))
644             networkProcess->addSession(*websiteDataStore);
645     }
646
647     m_networkProcess = WTFMove(networkProcess);
648     return *m_networkProcess;
649 }
650
651 void WebProcessPool::networkProcessCrashed(NetworkProcessProxy& networkProcessProxy, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&& pendingReplies)
652 {
653     ASSERT(m_networkProcess);
654     ASSERT(&networkProcessProxy == m_networkProcess.get());
655     m_didNetworkProcessCrash = true;
656
657     for (auto& supplement : m_supplements.values())
658         supplement->processDidClose(&networkProcessProxy);
659
660     m_client.networkProcessDidCrash(this);
661
662     if (m_automationSession)
663         m_automationSession->terminate();
664
665     // Leave the process proxy around during client call, so that the client could query the process identifier.
666     m_networkProcess = nullptr;
667
668     // Attempt to re-launch.
669     if (pendingReplies.isEmpty())
670         return;
671     auto& newNetworkProcess = ensureNetworkProcess();
672     for (auto& reply : pendingReplies)
673         newNetworkProcess.getNetworkProcessConnection(*reply.first, WTFMove(reply.second));
674 }
675
676 void WebProcessPool::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
677 {
678     ensureNetworkProcess();
679     ASSERT(m_networkProcess);
680
681     m_networkProcess->getNetworkProcessConnection(webProcessProxy, WTFMove(reply));
682 }
683
684 #if ENABLE(SERVICE_WORKER)
685 void WebProcessPool::establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy& proxy, RegistrableDomain&& registrableDomain, PAL::SessionID sessionID)
686 {
687     ASSERT_UNUSED(proxy, &proxy == m_networkProcess.get());
688
689     m_mayHaveRegisteredServiceWorkers.clear();
690
691     auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID);
692
693     if (!websiteDataStore) {
694         if (!m_websiteDataStore)
695             m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore().ptr();
696         websiteDataStore = m_websiteDataStore.get();
697     }
698
699     RegistrableDomainWithSessionID registrableDomainWithSessionID { RegistrableDomain { registrableDomain }, sessionID };
700     if (m_serviceWorkerProcesses.contains(registrableDomainWithSessionID))
701         return;
702
703     if (m_serviceWorkerProcesses.isEmpty())
704         sendToAllProcesses(Messages::WebProcess::RegisterServiceWorkerClients { });
705
706     auto serviceWorkerProcessProxy = WebProcessProxy::createForServiceWorkers(*this, WTFMove(registrableDomain), *websiteDataStore);
707     m_serviceWorkerProcesses.add(WTFMove(registrableDomainWithSessionID), serviceWorkerProcessProxy.ptr());
708
709     updateProcessAssertions();
710     initializeNewWebProcess(serviceWorkerProcessProxy, websiteDataStore);
711
712     auto* serviceWorkerProcessProxyPtr = serviceWorkerProcessProxy.ptr();
713     m_processes.append(WTFMove(serviceWorkerProcessProxy));
714
715     serviceWorkerProcessProxyPtr->establishServiceWorkerContext(m_serviceWorkerPreferences ? m_serviceWorkerPreferences.value() : m_defaultPageGroup->preferences().store());
716     if (!m_serviceWorkerUserAgent.isNull())
717         serviceWorkerProcessProxyPtr->setServiceWorkerUserAgent(m_serviceWorkerUserAgent);
718 }
719 #endif
720
721 void WebProcessPool::windowServerConnectionStateChanged()
722 {
723     size_t processCount = m_processes.size();
724     for (size_t i = 0; i < processCount; ++i)
725         m_processes[i]->windowServerConnectionStateChanged();
726 }
727
728 void (*s_invalidMessageCallback)(WKStringRef messageName);
729
730 void WebProcessPool::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName))
731 {
732     s_invalidMessageCallback = invalidMessageCallback;
733 }
734
735 void WebProcessPool::didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName)
736 {
737     if (!s_invalidMessageCallback)
738         return;
739
740     StringBuilder messageNameStringBuilder;
741     messageNameStringBuilder.appendCharacters(messageReceiverName.data(), messageReceiverName.size());
742     messageNameStringBuilder.append('.');
743     messageNameStringBuilder.appendCharacters(messageName.data(), messageName.size());
744
745     s_invalidMessageCallback(toAPI(API::String::create(messageNameStringBuilder.toString()).ptr()));
746 }
747
748 void WebProcessPool::processDidCachePage(WebProcessProxy* process)
749 {
750     if (m_processWithPageCache && m_processWithPageCache != process)
751         m_processWithPageCache->releasePageCache();
752     m_processWithPageCache = process;
753 }
754
755 void WebProcessPool::resolvePathsForSandboxExtensions()
756 {
757     m_resolvedPaths.injectedBundlePath = resolvePathForSandboxExtension(injectedBundlePath());
758
759     m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.reserveCapacity(m_configuration->additionalReadAccessAllowedPaths().size());
760     for (const auto& path : m_configuration->additionalReadAccessAllowedPaths())
761         m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.uncheckedAppend(resolvePathForSandboxExtension(path.data()));
762
763     platformResolvePathsForSandboxExtensions();
764 }
765
766 WebProcessProxy& WebProcessPool::createNewWebProcess(WebsiteDataStore* websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
767 {
768     auto processProxy = WebProcessProxy::create(*this, websiteDataStore, isPrewarmed);
769     auto& process = processProxy.get();
770     initializeNewWebProcess(process, websiteDataStore, isPrewarmed);
771     m_processes.append(WTFMove(processProxy));
772
773     if (m_serviceWorkerProcessesTerminationTimer.isActive())
774         m_serviceWorkerProcessesTerminationTimer.stop();
775
776     return process;
777 }
778
779 RefPtr<WebProcessProxy> WebProcessPool::tryTakePrewarmedProcess(WebsiteDataStore& websiteDataStore)
780 {
781     if (!m_prewarmedProcess)
782         return nullptr;
783     
784     // There is sometimes a delay until we get notified that a prewarmed process has been terminated (e.g. after resuming
785     // from suspension) so make sure the process is still running here before deciding to use it.
786     if (m_prewarmedProcess->wasTerminated()) {
787         RELEASE_LOG_ERROR(Process, "Not using prewarmed process %d because it has been terminated", m_prewarmedProcess->processIdentifier());
788         m_prewarmedProcess = nullptr;
789         return nullptr;
790     }
791
792 #if PLATFORM(GTK) || PLATFORM(WPE)
793     // In platforms using Bubblewrap for sandboxing, prewarmed process is launched using the WebProcessPool primary WebsiteDataStore,
794     // so we don't use it in case of using a different WebsiteDataStore.
795     if (m_sandboxEnabled && m_websiteDataStore && m_websiteDataStore.get() != &websiteDataStore)
796         return nullptr;
797 #endif
798
799     ASSERT(m_prewarmedProcess->isPrewarmed());
800     m_prewarmedProcess->markIsNoLongerInPrewarmedPool();
801     m_prewarmedProcess->setWebsiteDataStore(websiteDataStore);
802
803     return std::exchange(m_prewarmedProcess, nullptr);
804 }
805
806 #if PLATFORM(MAC)
807 static void displayReconfigurationCallBack(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *userInfo)
808 {
809     auto screenProperties = WebCore::collectScreenProperties();
810     for (auto& processPool : WebProcessPool::allProcessPools()) {
811         processPool->sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
812 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
813         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, flags));
814 #endif
815     }
816 }
817
818 static void registerDisplayConfigurationCallback()
819 {
820     static std::once_flag onceFlag;
821     std::call_once(
822         onceFlag,
823         [] {
824             CGDisplayRegisterReconfigurationCallback(displayReconfigurationCallBack, nullptr);
825         });
826 }
827 #endif
828
829 WebProcessDataStoreParameters WebProcessPool::webProcessDataStoreParameters(WebProcessProxy& process, WebsiteDataStore& websiteDataStore)
830 {
831     websiteDataStore.resolveDirectoriesIfNecessary();
832
833     String applicationCacheDirectory = websiteDataStore.resolvedApplicationCacheDirectory();
834     SandboxExtension::Handle applicationCacheDirectoryExtensionHandle;
835     if (!applicationCacheDirectory.isEmpty())
836         SandboxExtension::createHandleWithoutResolvingPath(applicationCacheDirectory, SandboxExtension::Type::ReadWrite, applicationCacheDirectoryExtensionHandle);
837
838     String applicationCacheFlatFileSubdirectoryName = websiteDataStore.applicationCacheFlatFileSubdirectoryName();
839
840     String webSQLDatabaseDirectory = websiteDataStore.resolvedDatabaseDirectory();
841     SandboxExtension::Handle webSQLDatabaseDirectoryExtensionHandle;
842     if (!webSQLDatabaseDirectory.isEmpty())
843         SandboxExtension::createHandleWithoutResolvingPath(webSQLDatabaseDirectory, SandboxExtension::Type::ReadWrite, webSQLDatabaseDirectoryExtensionHandle);
844
845     String mediaCacheDirectory = websiteDataStore.resolvedMediaCacheDirectory();
846     SandboxExtension::Handle mediaCacheDirectoryExtensionHandle;
847     if (!mediaCacheDirectory.isEmpty())
848         SandboxExtension::createHandleWithoutResolvingPath(mediaCacheDirectory, SandboxExtension::Type::ReadWrite, mediaCacheDirectoryExtensionHandle);
849
850     String mediaKeyStorageDirectory = websiteDataStore.resolvedMediaKeysDirectory();
851     SandboxExtension::Handle mediaKeyStorageDirectoryExtensionHandle;
852     if (!mediaKeyStorageDirectory.isEmpty())
853         SandboxExtension::createHandleWithoutResolvingPath(mediaKeyStorageDirectory, SandboxExtension::Type::ReadWrite, mediaKeyStorageDirectoryExtensionHandle);
854
855     String javaScriptConfigurationDirectory;
856     if (!m_javaScriptConfigurationDirectory.isEmpty())
857         javaScriptConfigurationDirectory = m_javaScriptConfigurationDirectory;
858     else if (javaScriptConfigurationFileEnabled())
859         javaScriptConfigurationDirectory = websiteDataStore.resolvedJavaScriptConfigurationDirectory();
860
861     SandboxExtension::Handle javaScriptConfigurationDirectoryExtensionHandle;
862     if (!javaScriptConfigurationDirectory.isEmpty())
863         SandboxExtension::createHandleWithoutResolvingPath(javaScriptConfigurationDirectory, SandboxExtension::Type::ReadWrite, javaScriptConfigurationDirectoryExtensionHandle);
864         
865     auto plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy(websiteDataStore.sessionID());
866
867     return WebProcessDataStoreParameters {
868         websiteDataStore.sessionID(),
869         WTFMove(applicationCacheDirectory),
870         WTFMove(applicationCacheDirectoryExtensionHandle),
871         WTFMove(applicationCacheFlatFileSubdirectoryName),
872         WTFMove(webSQLDatabaseDirectory),
873         WTFMove(webSQLDatabaseDirectoryExtensionHandle),
874         WTFMove(mediaCacheDirectory),
875         WTFMove(mediaCacheDirectoryExtensionHandle),
876         WTFMove(mediaKeyStorageDirectory),
877         WTFMove(mediaKeyStorageDirectoryExtensionHandle),
878         WTFMove(javaScriptConfigurationDirectory),
879         WTFMove(javaScriptConfigurationDirectoryExtensionHandle),
880         WTFMove(plugInAutoStartOriginHashes),
881         websiteDataStore.resourceLoadStatisticsEnabled()
882     };
883 }
884
885 void WebProcessPool::initializeNewWebProcess(WebProcessProxy& process, WebsiteDataStore* websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
886 {
887     auto initializationActivityToken = process.throttler().backgroundActivityToken();
888     auto scopeExit = makeScopeExit([&process, initializationActivityToken] {
889         // Round-trip to the Web Content process before releasing the
890         // initialization activity token, so that we're sure that all
891         // messages sent from this function have been handled.
892         process.isResponsive([initializationActivityToken] (bool) { });
893     });
894
895     ensureNetworkProcess();
896
897     WebProcessCreationParameters parameters;
898
899     parameters.injectedBundlePath = m_resolvedPaths.injectedBundlePath;
900     if (!parameters.injectedBundlePath.isEmpty())
901         SandboxExtension::createHandleWithoutResolvingPath(parameters.injectedBundlePath, SandboxExtension::Type::ReadOnly, parameters.injectedBundlePathExtensionHandle);
902
903     parameters.additionalSandboxExtensionHandles.allocate(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size());
904     for (size_t i = 0, size = m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size(); i < size; ++i)
905         SandboxExtension::createHandleWithoutResolvingPath(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths[i], SandboxExtension::Type::ReadOnly, parameters.additionalSandboxExtensionHandles[i]);
906
907 #if PLATFORM(IOS_FAMILY)
908     setJavaScriptConfigurationFileEnabledFromDefaults();
909 #endif
910
911     parameters.cacheModel = LegacyGlobalSettings::singleton().cacheModel();
912     parameters.languages = configuration().overrideLanguages().isEmpty() ? userPreferredLanguages() : configuration().overrideLanguages();
913
914     parameters.urlSchemesRegisteredAsEmptyDocument = copyToVector(m_schemesToRegisterAsEmptyDocument);
915     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
916     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
917     parameters.urlSchemesForWhichDomainRelaxationIsForbidden = copyToVector(m_schemesToSetDomainRelaxationForbiddenFor);
918     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
919     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
920     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
921     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
922     parameters.urlSchemesRegisteredAsAlwaysRevalidated = copyToVector(m_schemesToRegisterAsAlwaysRevalidated);
923     parameters.urlSchemesRegisteredAsCachePartitioned = copyToVector(m_schemesToRegisterAsCachePartitioned);
924     if (websiteDataStore)
925         parameters.urlSchemesServiceWorkersCanHandle = copyToVector(websiteDataStore->configuration().serviceWorkerRegisteredSchemes());
926     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
927
928     parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath;
929     parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing;
930
931     parameters.terminationTimeout = 0_s;
932
933     parameters.textCheckerState = TextChecker::state();
934
935     parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled();
936
937     parameters.defaultRequestTimeoutInterval = API::URLRequest::defaultTimeoutInterval();
938
939 #if ENABLE(NOTIFICATIONS)
940     // FIXME: There should be a generic way for supplements to add to the intialization parameters.
941     parameters.notificationPermissions = supplement<WebNotificationManagerProxy>()->notificationPermissions();
942 #endif
943
944     parameters.plugInAutoStartOrigins = copyToVector(m_plugInAutoStartProvider.autoStartOrigins());
945
946     parameters.memoryCacheDisabled = m_memoryCacheDisabled;
947     parameters.attrStyleEnabled = m_configuration->attrStyleEnabled();
948
949 #if ENABLE(SERVICE_CONTROLS)
950     auto& serviceController = ServicesController::singleton();
951     parameters.hasImageServices = serviceController.hasImageServices();
952     parameters.hasSelectionServices = serviceController.hasSelectionServices();
953     parameters.hasRichContentServices = serviceController.hasRichContentServices();
954     serviceController.refreshExistingServices();
955 #endif
956
957 #if ENABLE(NETSCAPE_PLUGIN_API)
958     parameters.pluginLoadClientPolicies = m_pluginLoadClientPolicies;
959 #endif
960
961 #if OS(LINUX)
962     parameters.shouldEnableMemoryPressureReliefLogging = true;
963 #endif
964
965 #if ENABLE(MEDIA_STREAM)
966     parameters.shouldCaptureAudioInUIProcess = m_configuration->shouldCaptureAudioInUIProcess();
967     parameters.shouldCaptureVideoInUIProcess = m_configuration->shouldCaptureVideoInUIProcess();
968     parameters.shouldCaptureDisplayInUIProcess = m_configuration->shouldCaptureDisplayInUIProcess();
969 #endif
970
971     parameters.presentingApplicationPID = m_configuration->presentingApplicationPID();
972
973     // Add any platform specific parameters
974     platformInitializeWebProcess(process, parameters);
975
976     RefPtr<API::Object> injectedBundleInitializationUserData = m_injectedBundleClient->getInjectedBundleInitializationUserData(*this);
977     if (!injectedBundleInitializationUserData)
978         injectedBundleInitializationUserData = m_injectedBundleInitializationUserData;
979     parameters.initializationUserData = UserData(process.transformObjectsToHandles(injectedBundleInitializationUserData.get()));
980     
981     if (websiteDataStore)
982         parameters.websiteDataStoreParameters = webProcessDataStoreParameters(process, *websiteDataStore);
983
984     process.send(Messages::WebProcess::InitializeWebProcess(parameters), 0);
985
986 #if PLATFORM(COCOA)
987     process.send(Messages::WebProcess::SetQOS(webProcessLatencyQOS(), webProcessThroughputQOS()), 0);
988 #endif
989
990     if (m_automationSession)
991         process.send(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()), 0);
992
993     ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty());
994
995     if (isPrewarmed == WebProcessProxy::IsPrewarmed::Yes) {
996         ASSERT(!m_prewarmedProcess);
997         m_prewarmedProcess = &process;
998         process.send(Messages::WebProcess::PrewarmGlobally(), 0);
999     }
1000
1001 #if PLATFORM(IOS)
1002     process.send(Messages::WebProcess::BacklightLevelDidChange(displayBrightness()), 0);
1003 #endif
1004
1005 #if ENABLE(REMOTE_INSPECTOR)
1006     // Initialize remote inspector connection now that we have a sub-process that is hosting one of our web views.
1007     Inspector::RemoteInspector::singleton(); 
1008 #endif
1009
1010 #if PLATFORM(MAC)
1011     registerDisplayConfigurationCallback();
1012 #endif
1013 }
1014
1015 void WebProcessPool::prewarmProcess()
1016 {
1017     if (m_prewarmedProcess)
1018         return;
1019
1020     RELEASE_LOG(PerformanceLogging, "Prewarming a WebProcess for performance");
1021     createNewWebProcess(nullptr, WebProcessProxy::IsPrewarmed::Yes);
1022 }
1023
1024 void WebProcessPool::enableProcessTermination()
1025 {
1026     m_processTerminationEnabled = true;
1027     Vector<RefPtr<WebProcessProxy>> processes = m_processes;
1028     for (size_t i = 0; i < processes.size(); ++i) {
1029         if (shouldTerminate(processes[i].get()))
1030             processes[i]->terminate();
1031     }
1032 }
1033
1034 bool WebProcessPool::shouldTerminate(WebProcessProxy* process)
1035 {
1036     ASSERT(m_processes.contains(process));
1037
1038     if (!m_processTerminationEnabled || m_configuration->alwaysKeepAndReuseSwappedProcesses())
1039         return false;
1040
1041     return true;
1042 }
1043
1044 void WebProcessPool::processDidFinishLaunching(WebProcessProxy* process)
1045 {
1046     ASSERT(m_processes.contains(process));
1047
1048     if (!m_visitedLinksPopulated) {
1049         populateVisitedLinks();
1050         m_visitedLinksPopulated = true;
1051     }
1052
1053     // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching
1054     // so check if it needs to be started here
1055     if (m_memorySamplerEnabled) {
1056         SandboxExtension::Handle sampleLogSandboxHandle;        
1057         WallTime now = WallTime::now();
1058         String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()), "pid", process->processIdentifier());
1059         sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1060         
1061         process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0);
1062     }
1063
1064     if (m_configuration->fullySynchronousModeIsAllowedForTesting())
1065         process->connection()->allowFullySynchronousModeForTesting();
1066
1067     if (m_configuration->ignoreSynchronousMessagingTimeoutsForTesting())
1068         process->connection()->ignoreTimeoutsForTesting();
1069
1070     m_connectionClient.didCreateConnection(this, process->webConnection());
1071
1072     if (m_websiteDataStore)
1073         m_websiteDataStore->didCreateNetworkProcess();
1074 }
1075
1076 void WebProcessPool::disconnectProcess(WebProcessProxy* process)
1077 {
1078     ASSERT(m_processes.contains(process));
1079     ASSERT(!m_processesPlayingAudibleMedia.contains(process->coreProcessIdentifier()));
1080
1081     if (m_prewarmedProcess == process) {
1082         ASSERT(m_prewarmedProcess->isPrewarmed());
1083         m_prewarmedProcess = nullptr;
1084     }
1085
1086     if (m_dummyProcessProxy == process)
1087         m_dummyProcessProxy = nullptr;
1088
1089     // FIXME (Multi-WebProcess): <rdar://problem/12239765> Some of the invalidation calls of the other supplements are still necessary in multi-process mode, but they should only affect data structures pertaining to the process being disconnected.
1090     // Clearing everything causes assertion failures, so it's less trouble to skip that for now.
1091     RefPtr<WebProcessProxy> protect(process);
1092     if (m_processWithPageCache == process)
1093         m_processWithPageCache = nullptr;
1094
1095     m_backForwardCache->removeEntriesForProcess(*process);
1096
1097 #if ENABLE(SERVICE_WORKER)
1098     if (process->isRunningServiceWorkers()) {
1099         auto* removedProcess = m_serviceWorkerProcesses.take(RegistrableDomainWithSessionID { process->registrableDomain(), process->websiteDataStore().sessionID() });
1100         ASSERT_UNUSED(removedProcess, removedProcess == process);
1101         updateProcessAssertions();
1102     }
1103 #endif
1104
1105     static_cast<WebContextSupplement*>(supplement<WebGeolocationManagerProxy>())->processDidClose(process);
1106
1107     m_processes.removeFirst(process);
1108
1109 #if ENABLE(GAMEPAD)
1110     if (m_processesUsingGamepads.contains(process))
1111         processStoppedUsingGamepads(*process);
1112 #endif
1113
1114     removeProcessFromOriginCacheSet(*process);
1115
1116 #if ENABLE(SERVICE_WORKER)
1117     // FIXME: We should do better than this. For now, we just destroy the ServiceWorker process
1118     // whenever there is no regular WebContent process remaining.
1119     if (m_processes.size() == m_serviceWorkerProcesses.size()) {
1120         if (!m_serviceWorkerProcessesTerminationTimer.isActive())
1121             m_serviceWorkerProcessesTerminationTimer.startOneShot(serviceWorkerTerminationDelay);
1122     }
1123 #endif
1124 }
1125
1126 WebProcessProxy& WebProcessPool::processForRegistrableDomain(WebsiteDataStore& websiteDataStore, WebPageProxy* page, const RegistrableDomain& registrableDomain)
1127 {
1128     if (!registrableDomain.isEmpty()) {
1129         if (auto process = webProcessCache().takeProcess(registrableDomain, websiteDataStore))
1130             return *process;
1131
1132         // Check if we have a suspended page for the given registrable domain and use its process if we do, for performance reasons.
1133         if (auto process = SuspendedPageProxy::findReusableSuspendedPageProcess(*this, registrableDomain, websiteDataStore)) {
1134             RELEASE_LOG(ProcessSwapping, "Using WebProcess %i from a SuspendedPage", process->processIdentifier());
1135             return *process;
1136         }
1137     }
1138
1139     if (auto process = tryTakePrewarmedProcess(websiteDataStore)) {
1140         RELEASE_LOG(ProcessSwapping, "Using prewarmed process %i", process->processIdentifier());
1141         if (!registrableDomain.isEmpty())
1142             tryPrewarmWithDomainInformation(*process, registrableDomain);
1143         return *process;
1144     }
1145
1146     if (!usesSingleWebProcess())
1147         return createNewWebProcess(&websiteDataStore);
1148
1149 #if PLATFORM(COCOA)
1150     bool mustMatchDataStore = WebKit::WebsiteDataStore::defaultDataStoreExists() && &websiteDataStore != WebKit::WebsiteDataStore::defaultDataStore().ptr();
1151 #else
1152     bool mustMatchDataStore = false;
1153 #endif
1154
1155     for (auto& process : m_processes) {
1156         if (process == m_prewarmedProcess || process == m_dummyProcessProxy)
1157             continue;
1158 #if ENABLE(SERVICE_WORKER)
1159         if (process->isRunningServiceWorkers())
1160             continue;
1161 #endif
1162         if (mustMatchDataStore && &process->websiteDataStore() != &websiteDataStore)
1163             continue;
1164         return *process;
1165     }
1166     return createNewWebProcess(&websiteDataStore);
1167 }
1168
1169 Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API::PageConfiguration>&& pageConfiguration)
1170 {
1171     if (!pageConfiguration->pageGroup())
1172         pageConfiguration->setPageGroup(m_defaultPageGroup.ptr());
1173     if (!pageConfiguration->preferences())
1174         pageConfiguration->setPreferences(&pageConfiguration->pageGroup()->preferences());
1175     if (!pageConfiguration->userContentController())
1176         pageConfiguration->setUserContentController(&pageConfiguration->pageGroup()->userContentController());
1177     if (!pageConfiguration->visitedLinkStore())
1178         pageConfiguration->setVisitedLinkStore(m_visitedLinkStore.ptr());
1179
1180     if (!pageConfiguration->websiteDataStore()) {
1181         // We try to avoid creating the default data store as long as possible.
1182         // But if there is an attempt to create a web page without any specified data store, then we have to create it.
1183         if (!m_websiteDataStore)
1184             m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore().ptr();
1185
1186         pageConfiguration->setWebsiteDataStore(m_websiteDataStore.get());
1187     }
1188
1189     RefPtr<WebProcessProxy> process;
1190     auto* relatedPage = pageConfiguration->relatedPage();
1191     if (relatedPage && !relatedPage->isClosed()) {
1192         // Sharing processes, e.g. when creating the page via window.open().
1193         process = &pageConfiguration->relatedPage()->ensureRunningProcess();
1194         // We do not support several WebsiteDataStores sharing a single process.
1195         ASSERT(process.get() == m_dummyProcessProxy || pageConfiguration->websiteDataStore() == &process->websiteDataStore());
1196         ASSERT(&pageConfiguration->relatedPage()->websiteDataStore() == pageConfiguration->websiteDataStore());
1197     } else if (!m_isDelayedWebProcessLaunchDisabled) {
1198         // In the common case, we delay process launch until something is actually loaded in the page.
1199         if (!m_dummyProcessProxy) {
1200             auto dummyProcessProxy = WebProcessProxy::create(*this, nullptr, WebProcessProxy::IsPrewarmed::No, WebProcessProxy::ShouldLaunchProcess::No);
1201             m_dummyProcessProxy = dummyProcessProxy.ptr();
1202             m_processes.append(WTFMove(dummyProcessProxy));
1203         }
1204         process = m_dummyProcessProxy;
1205     } else
1206         process = &processForRegistrableDomain(*pageConfiguration->websiteDataStore(), nullptr, { });
1207
1208     ASSERT(process);
1209
1210     auto page = process->createWebPage(pageClient, WTFMove(pageConfiguration));
1211
1212 #if ENABLE(SERVICE_WORKER)
1213     ASSERT(!process->isRunningServiceWorkers());
1214
1215     if (!m_serviceWorkerPreferences) {
1216         m_serviceWorkerPreferences = page->preferencesStore();
1217         for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1218             serviceWorkerProcess->updateServiceWorkerPreferencesStore(*m_serviceWorkerPreferences);
1219     }
1220 #endif
1221
1222     bool enableProcessSwapOnCrossSiteNavigation = page->preferences().processSwapOnCrossSiteNavigationEnabled();
1223 #if PLATFORM(IOS_FAMILY)
1224     if (WebCore::IOSApplication::isFirefox() && !linkedOnOrAfter(WebKit::SDKVersion::FirstWithProcessSwapOnCrossSiteNavigation))
1225         enableProcessSwapOnCrossSiteNavigation = false;
1226 #endif
1227
1228     bool wasProcessSwappingOnNavigationEnabled = m_configuration->processSwapsOnNavigation();
1229     m_configuration->setProcessSwapsOnNavigationFromExperimentalFeatures(enableProcessSwapOnCrossSiteNavigation);
1230     if (wasProcessSwappingOnNavigationEnabled != m_configuration->processSwapsOnNavigation())
1231         m_webProcessCache->updateCapacity(*this);
1232
1233     m_configuration->setShouldCaptureAudioInUIProcess(page->preferences().captureAudioInUIProcessEnabled());
1234     m_configuration->setShouldCaptureVideoInUIProcess(page->preferences().captureVideoInUIProcessEnabled());
1235
1236     return page;
1237 }
1238
1239 #if ENABLE(SERVICE_WORKER)
1240 void WebProcessPool::updateServiceWorkerUserAgent(const String& userAgent)
1241 {
1242     if (m_serviceWorkerUserAgent == userAgent)
1243         return;
1244     m_serviceWorkerUserAgent = userAgent;
1245     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1246         serviceWorkerProcess->setServiceWorkerUserAgent(m_serviceWorkerUserAgent);
1247 }
1248
1249 bool WebProcessPool::mayHaveRegisteredServiceWorkers(const WebsiteDataStore& store)
1250 {
1251     if (!m_serviceWorkerProcesses.isEmpty())
1252         return true;
1253
1254     String serviceWorkerRegistrationDirectory = store.resolvedServiceWorkerRegistrationDirectory();
1255     if (serviceWorkerRegistrationDirectory.isEmpty())
1256         serviceWorkerRegistrationDirectory = WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
1257
1258     return m_mayHaveRegisteredServiceWorkers.ensure(serviceWorkerRegistrationDirectory, [&] {
1259         // FIXME: Make this computation on a background thread.
1260         return FileSystem::fileExists(WebCore::serviceWorkerRegistrationDatabaseFilename(serviceWorkerRegistrationDirectory));
1261     }).iterator->value;
1262 }
1263 #endif
1264
1265 void WebProcessPool::pageBeginUsingWebsiteDataStore(WebPageProxyIdentifier pageID, WebsiteDataStore& dataStore)
1266 {
1267     auto result = m_sessionToPageIDsMap.add(dataStore.sessionID(), HashSet<WebPageProxyIdentifier>()).iterator->value.add(pageID);
1268     ASSERT_UNUSED(result, result.isNewEntry);
1269
1270     auto sessionID = dataStore.sessionID();
1271     if (sessionID != PAL::SessionID::defaultSessionID()) {
1272         ASSERT(!sessionID.isEphemeral() || dataStore.parameters().networkSessionParameters.sessionID == sessionID);
1273         if (m_networkProcess) {
1274             m_networkProcess->addSession(makeRef(dataStore));
1275             dataStore.clearPendingCookies();
1276         }
1277     }
1278 }
1279
1280 void WebProcessPool::pageEndUsingWebsiteDataStore(WebPageProxyIdentifier pageID, WebsiteDataStore& dataStore)
1281 {
1282     auto sessionID = dataStore.sessionID();
1283     auto iterator = m_sessionToPageIDsMap.find(sessionID);
1284     ASSERT(iterator != m_sessionToPageIDsMap.end());
1285
1286     auto takenPageID = iterator->value.take(pageID);
1287     ASSERT_UNUSED(takenPageID, takenPageID == pageID);
1288
1289     if (iterator->value.isEmpty()) {
1290         m_sessionToPageIDsMap.remove(iterator);
1291
1292         if (sessionID.isEphemeral())
1293             m_webProcessCache->clearAllProcessesForSession(sessionID);
1294     }
1295 }
1296
1297 bool WebProcessPool::hasPagesUsingWebsiteDataStore(WebsiteDataStore& dataStore) const
1298 {
1299     return m_sessionToPageIDsMap.contains(dataStore.sessionID());
1300 }
1301
1302 DownloadProxy& WebProcessPool::download(WebsiteDataStore& dataStore, WebPageProxy* initiatingPage, const ResourceRequest& request, const String& suggestedFilename)
1303 {
1304     auto& downloadProxy = createDownloadProxy(dataStore, request, initiatingPage);
1305     PAL::SessionID sessionID = dataStore.sessionID();
1306
1307     if (initiatingPage)
1308         initiatingPage->handleDownloadRequest(downloadProxy);
1309
1310     if (networkProcess()) {
1311         ResourceRequest updatedRequest(request);
1312         // Request's firstPartyForCookies will be used as Original URL of the download request.
1313         // We set the value to top level document's URL.
1314         if (initiatingPage) {
1315             URL initiatingPageURL = URL { URL { }, initiatingPage->pageLoadState().url() };
1316             updatedRequest.setFirstPartyForCookies(initiatingPageURL);
1317             updatedRequest.setIsSameSite(areRegistrableDomainsEqual(initiatingPageURL, request.url()));
1318             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1319                 updatedRequest.setHTTPUserAgent(initiatingPage->userAgent());
1320         } else {
1321             updatedRequest.setFirstPartyForCookies(URL());
1322             updatedRequest.setIsSameSite(false);
1323             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1324                 updatedRequest.setHTTPUserAgent(WebPageProxy::standardUserAgent());
1325         }
1326         updatedRequest.setIsTopSite(false);
1327         networkProcess()->send(Messages::NetworkProcess::DownloadRequest(sessionID, downloadProxy.downloadID(), updatedRequest, suggestedFilename), 0);
1328         return downloadProxy;
1329     }
1330
1331     return downloadProxy;
1332 }
1333
1334 DownloadProxy& WebProcessPool::resumeDownload(WebsiteDataStore& dataStore, WebPageProxy* initiatingPage, const API::Data& resumeData, const String& path)
1335 {
1336     auto& downloadProxy = createDownloadProxy(dataStore, ResourceRequest(), initiatingPage);
1337     PAL::SessionID sessionID = dataStore.sessionID();
1338
1339     SandboxExtension::Handle sandboxExtensionHandle;
1340     if (!path.isEmpty())
1341         SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, sandboxExtensionHandle);
1342
1343     if (networkProcess()) {
1344         networkProcess()->send(Messages::NetworkProcess::ResumeDownload(sessionID, downloadProxy.downloadID(), resumeData.dataReference(), path, sandboxExtensionHandle), 0);
1345         return downloadProxy;
1346     }
1347
1348     return downloadProxy;
1349 }
1350
1351 void WebProcessPool::postMessageToInjectedBundle(const String& messageName, API::Object* messageBody)
1352 {
1353     for (auto& process : m_processes) {
1354         // FIXME: Return early if the message body contains any references to WKPageRefs/WKFrameRefs etc. since they're local to a process.
1355         process->send(Messages::WebProcess::HandleInjectedBundleMessage(messageName, UserData(process->transformObjectsToHandles(messageBody).get())), 0);
1356     }
1357 }
1358
1359 void WebProcessPool::didReachGoodTimeToPrewarm()
1360 {
1361     if (!configuration().isAutomaticProcessWarmingEnabled() || !configuration().processSwapsOnNavigation() || usesSingleWebProcess())
1362         return;
1363
1364     if (MemoryPressureHandler::singleton().isUnderMemoryPressure()) {
1365         if (!m_prewarmedProcess)
1366             RELEASE_LOG(PerformanceLogging, "Not automatically prewarming a WebProcess due to memory pressure");
1367         return;
1368     }
1369
1370     prewarmProcess();
1371 }
1372
1373 void WebProcessPool::populateVisitedLinks()
1374 {
1375     m_historyClient->populateVisitedLinks(*this);
1376 }
1377
1378 WebProcessPool::Statistics& WebProcessPool::statistics()
1379 {
1380     static Statistics statistics = Statistics();
1381
1382     return statistics;
1383 }
1384
1385 void WebProcessPool::handleMemoryPressureWarning(Critical)
1386 {
1387     RELEASE_LOG(PerformanceLogging, "%p - WebProcessPool::handleMemoryPressureWarning", this);
1388
1389
1390     m_backForwardCache->clear(AllowProcessCaching::No);
1391     m_webProcessCache->clear();
1392
1393     if (m_prewarmedProcess)
1394         m_prewarmedProcess->shutDown();
1395     ASSERT(!m_prewarmedProcess);
1396 }
1397
1398 #if ENABLE(NETSCAPE_PLUGIN_API)
1399 void WebProcessPool::setAdditionalPluginsDirectory(const String& directory)
1400 {
1401     Vector<String> directories;
1402     directories.append(directory);
1403
1404     m_pluginInfoStore.setAdditionalPluginsDirectories(directories);
1405 }
1406
1407 void WebProcessPool::refreshPlugins()
1408 {
1409     m_pluginInfoStore.refresh();
1410     sendToAllProcesses(Messages::WebProcess::RefreshPlugins());
1411 }
1412
1413 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1414
1415 ProcessID WebProcessPool::networkProcessIdentifier()
1416 {
1417     return m_networkProcess ? m_networkProcess->processIdentifier() : 0;
1418 }
1419
1420 ProcessID WebProcessPool::prewarmedProcessIdentifier()
1421 {
1422     return m_prewarmedProcess ? m_prewarmedProcess->processIdentifier() : 0;
1423 }
1424
1425 void WebProcessPool::activePagesOriginsInWebProcessForTesting(ProcessID pid, CompletionHandler<void(Vector<String>&&)>&& completionHandler)
1426 {
1427     for (auto& process : m_processes) {
1428         if (process->processIdentifier() == pid)
1429             return process->activePagesDomainsForTesting(WTFMove(completionHandler));
1430     }
1431     completionHandler({ });
1432 }
1433
1434 void WebProcessPool::setServiceWorkerTimeoutForTesting(Seconds seconds)
1435 {
1436     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting(seconds), Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting::Reply());
1437 }
1438
1439 void WebProcessPool::resetServiceWorkerTimeoutForTesting()
1440 {
1441     sendSyncToNetworkingProcess(Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting(), Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting::Reply());
1442 }
1443
1444 void WebProcessPool::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText)
1445 {
1446     m_alwaysUsesComplexTextCodePath = alwaysUseComplexText;
1447     sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText));
1448 }
1449
1450 void WebProcessPool::setShouldUseFontSmoothing(bool useFontSmoothing)
1451 {
1452     m_shouldUseFontSmoothing = useFontSmoothing;
1453     sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing));
1454 }
1455
1456 void WebProcessPool::clearResourceLoadStatistics()
1457 {
1458     sendToAllProcesses(Messages::WebProcess::ClearResourceLoadStatistics());
1459 }
1460
1461 void WebProcessPool::registerURLSchemeAsEmptyDocument(const String& urlScheme)
1462 {
1463     m_schemesToRegisterAsEmptyDocument.add(urlScheme);
1464     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme));
1465 }
1466
1467 void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme)
1468 {
1469     m_schemesToRegisterAsSecure.add(urlScheme);
1470     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
1471     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme));
1472 }
1473
1474 void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme)
1475 {
1476     m_schemesToRegisterAsBypassingContentSecurityPolicy.add(urlScheme);
1477     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1478     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1479 }
1480
1481 void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
1482 {
1483     m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme);
1484     sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme));
1485 }
1486
1487 void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme)
1488 {
1489     m_schemesToRegisterAsLocal.add(urlScheme);
1490     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme));
1491     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme));
1492 }
1493
1494 void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme)
1495 {
1496     m_schemesToRegisterAsNoAccess.add(urlScheme);
1497     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1498     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1499 }
1500
1501 void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme)
1502 {
1503     m_schemesToRegisterAsDisplayIsolated.add(urlScheme);
1504     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1505 }
1506
1507 void WebProcessPool::registerURLSchemeAsCORSEnabled(const String& urlScheme)
1508 {
1509     m_schemesToRegisterAsCORSEnabled.add(urlScheme);
1510     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1511     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1512 }
1513
1514 void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1515 {
1516     if (!urlScheme)
1517         return;
1518
1519     globalURLSchemesWithCustomProtocolHandlers().add(urlScheme);
1520     for (auto* processPool : allProcessPools()) {
1521         if (auto* networkProcess = processPool->networkProcess())
1522             networkProcess->registerSchemeForLegacyCustomProtocol(urlScheme);
1523     }
1524 }
1525
1526 void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1527 {
1528     if (!urlScheme)
1529         return;
1530
1531     globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme);
1532     for (auto* processPool : allProcessPools()) {
1533         if (auto* networkProcess = processPool->networkProcess())
1534             networkProcess->unregisterSchemeForLegacyCustomProtocol(urlScheme);
1535     }
1536 }
1537
1538 void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme)
1539 {
1540     m_schemesToRegisterAsCachePartitioned.add(urlScheme);
1541     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCachePartitioned(urlScheme));
1542 }
1543
1544 void WebProcessPool::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& urlScheme)
1545 {
1546     m_schemesToRegisterAsCanDisplayOnlyIfCanRequest.add(urlScheme);
1547     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1548     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1549 }
1550
1551 void WebProcessPool::updateBackForwardCacheCapacity()
1552 {
1553     if (!m_configuration->usesPageCache())
1554         return;
1555
1556     unsigned dummy = 0;
1557     Seconds dummyInterval;
1558     unsigned backForwardCacheCapacity = 0;
1559     calculateMemoryCacheSizes(LegacyGlobalSettings::singleton().cacheModel(), dummy, dummy, dummy, dummyInterval, backForwardCacheCapacity);
1560
1561     m_backForwardCache->setCapacity(backForwardCacheCapacity);
1562 }
1563
1564 void WebProcessPool::setCacheModel(CacheModel cacheModel)
1565 {
1566     updateBackForwardCacheCapacity();
1567
1568     sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel));
1569
1570     if (m_networkProcess)
1571         m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel, { }), 0);
1572 }
1573
1574 void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
1575 {
1576     sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval));
1577 }
1578
1579 DownloadProxy& WebProcessPool::createDownloadProxy(WebsiteDataStore& dataStore, const ResourceRequest& request, WebPageProxy* originatingPage)
1580 {
1581     auto& downloadProxy = ensureNetworkProcess().createDownloadProxy(dataStore, request);
1582     downloadProxy.setOriginatingPage(originatingPage);
1583     return downloadProxy;
1584 }
1585
1586 void WebProcessPool::synthesizeAppIsBackground(bool background)
1587 {
1588     ensureNetworkProcess().synthesizeAppIsBackground(background);
1589 }
1590
1591 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver)
1592 {
1593     m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
1594 }
1595
1596 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
1597 {
1598     m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
1599 }
1600
1601 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName)
1602 {
1603     m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
1604 }
1605
1606 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID)
1607 {
1608     m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
1609 }
1610
1611 bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
1612 {
1613     return m_messageReceiverMap.dispatchMessage(connection, decoder);
1614 }
1615
1616 bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
1617 {
1618     return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
1619 }
1620
1621 void WebProcessPool::setEnhancedAccessibility(bool flag)
1622 {
1623     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
1624 }
1625     
1626 void WebProcessPool::startMemorySampler(const double interval)
1627 {    
1628     // For new WebProcesses we will also want to start the Memory Sampler
1629     m_memorySamplerEnabled = true;
1630     m_memorySamplerInterval = interval;
1631     
1632     // For UIProcess
1633 #if ENABLE(MEMORY_SAMPLER)
1634     WebMemorySampler::singleton()->start(interval);
1635 #endif
1636     
1637     // For WebProcess
1638     SandboxExtension::Handle sampleLogSandboxHandle;    
1639     WallTime now = WallTime::now();
1640     String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()));
1641     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1642     
1643     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
1644 }
1645
1646 void WebProcessPool::stopMemorySampler()
1647 {    
1648     // For WebProcess
1649     m_memorySamplerEnabled = false;
1650     
1651     // For UIProcess
1652 #if ENABLE(MEMORY_SAMPLER)
1653     WebMemorySampler::singleton()->stop();
1654 #endif
1655
1656     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
1657 }
1658
1659 void WebProcessPool::useTestingNetworkSession()
1660 {
1661     ASSERT(m_processes.isEmpty());
1662     ASSERT(!m_networkProcess);
1663
1664     if (m_networkProcess)
1665         return;
1666
1667     if (!m_processes.isEmpty())
1668         return;
1669
1670     m_shouldUseTestingNetworkSession = true;
1671 }
1672
1673 template<typename T, typename U>
1674 void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
1675 {
1676     if (m_networkProcess && m_networkProcess->canSendMessage())
1677         m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
1678 }
1679
1680 void WebProcessPool::setAllowsAnySSLCertificateForWebSocket(bool allows)
1681 {
1682     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply());
1683 }
1684
1685 void WebProcessPool::clearCachedCredentials()
1686 {
1687     if (m_networkProcess)
1688         m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0);
1689 }
1690
1691 void WebProcessPool::terminateNetworkProcess()
1692 {
1693     if (!m_networkProcess)
1694         return;
1695     
1696     m_networkProcess->terminate();
1697     m_networkProcess = nullptr;
1698     m_didNetworkProcessCrash = true;
1699 }
1700
1701 void WebProcessPool::sendNetworkProcessWillSuspendImminentlyForTesting()
1702 {
1703     if (m_networkProcess)
1704         m_networkProcess->sendProcessWillSuspendImminentlyForTesting();
1705 }
1706
1707 void WebProcessPool::sendNetworkProcessDidResume()
1708 {
1709     if (m_networkProcess)
1710         m_networkProcess->sendProcessDidResume();
1711 }
1712
1713 void WebProcessPool::terminateServiceWorkerProcesses()
1714 {
1715 #if ENABLE(SERVICE_WORKER)
1716     auto protectedThis = makeRef(*this);
1717     while (!m_serviceWorkerProcesses.isEmpty())
1718         m_serviceWorkerProcesses.begin()->value->requestTermination(ProcessTerminationReason::RequestedByClient);
1719 #endif
1720 }
1721
1722 void WebProcessPool::syncNetworkProcessCookies()
1723 {
1724     ensureNetworkProcess().syncAllCookies();
1725 }
1726
1727 void WebProcessPool::syncLocalStorage(CompletionHandler<void()>&& completionHandler)
1728 {
1729     sendSyncToNetworkingProcess(Messages::NetworkProcess::SyncLocalStorage(), Messages::NetworkProcess::SyncLocalStorage::Reply());
1730     completionHandler();
1731 }
1732
1733 void WebProcessPool::clearLegacyPrivateBrowsingLocalStorage(CompletionHandler<void()>&& completionHandler)
1734 {
1735     if (m_networkProcess)
1736         m_networkProcess->send(Messages::NetworkProcess::ClearLegacyPrivateBrowsingLocalStorage(), 0);
1737     completionHandler();
1738 }
1739
1740 void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
1741 {
1742     ensureNetworkProcess();
1743     m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
1744 }
1745
1746 void WebProcessPool::updateAutomationCapabilities() const
1747 {
1748 #if ENABLE(REMOTE_INSPECTOR)
1749     Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange();
1750 #endif
1751 }
1752
1753 void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession)
1754 {
1755     if (m_automationSession)
1756         m_automationSession->setProcessPool(nullptr);
1757     
1758     m_automationSession = WTFMove(automationSession);
1759
1760 #if ENABLE(REMOTE_INSPECTOR)
1761     if (m_automationSession) {
1762         m_automationSession->init();
1763         m_automationSession->setProcessPool(this);
1764
1765         sendToAllProcesses(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()));
1766     } else
1767         sendToAllProcesses(Messages::WebProcess::DestroyAutomationSessionProxy());
1768 #endif
1769 }
1770
1771 void WebProcessPool::setHTTPPipeliningEnabled(bool enabled)
1772 {
1773 #if PLATFORM(COCOA)
1774     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1775 #else
1776     UNUSED_PARAM(enabled);
1777 #endif
1778 }
1779
1780 bool WebProcessPool::httpPipeliningEnabled() const
1781 {
1782 #if PLATFORM(COCOA)
1783     return ResourceRequest::httpPipeliningEnabled();
1784 #else
1785     return false;
1786 #endif
1787 }
1788
1789 void WebProcessPool::getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&& callbackFunction)
1790 {
1791     if (!statisticsMask) {
1792         callbackFunction(nullptr, CallbackBase::Error::Unknown);
1793         return;
1794     }
1795
1796     auto request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction)));
1797
1798     if (statisticsMask & StatisticsRequestTypeWebContent)
1799         requestWebContentStatistics(request.get());
1800 }
1801
1802 void WebProcessPool::requestWebContentStatistics(StatisticsRequest& request)
1803 {
1804     // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work.
1805 }
1806
1807 static WebProcessProxy* webProcessProxyFromConnection(IPC::Connection& connection, const Vector<RefPtr<WebProcessProxy>>& processes)
1808 {
1809     for (auto& process : processes) {
1810         if (process->hasConnection(connection))
1811             return process.get();
1812     }
1813
1814     ASSERT_NOT_REACHED();
1815     return nullptr;
1816 }
1817
1818 void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
1819 {
1820     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1821     if (!webProcessProxy)
1822         return;
1823     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get());
1824 }
1825
1826 void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&& completionHandler)
1827 {
1828     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1829     if (!webProcessProxy)
1830         return completionHandler({ });
1831
1832     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), [webProcessProxy = makeRef(*webProcessProxy), completionHandler = WTFMove(completionHandler)] (RefPtr<API::Object>&& returnData) mutable {
1833         completionHandler(UserData(webProcessProxy->transformObjectsToHandles(returnData.get())));
1834     });
1835 }
1836
1837 void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID)
1838 {
1839     RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID);
1840     if (!request) {
1841         LOG_ERROR("Cannot report networking statistics.");
1842         return;
1843     }
1844
1845     request->completedRequest(requestID, statisticsData);
1846 }
1847
1848 #if ENABLE(GAMEPAD)
1849
1850 void WebProcessPool::startedUsingGamepads(IPC::Connection& connection)
1851 {
1852     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1853     if (!proxy)
1854         return;
1855
1856     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1857
1858     ASSERT(!m_processesUsingGamepads.contains(proxy));
1859     m_processesUsingGamepads.add(proxy);
1860
1861     if (!wereAnyProcessesUsingGamepads)
1862         UIGamepadProvider::singleton().processPoolStartedUsingGamepads(*this);
1863
1864     proxy->send(Messages::WebProcess::SetInitialGamepads(UIGamepadProvider::singleton().snapshotGamepads()), 0);
1865 }
1866
1867 void WebProcessPool::stoppedUsingGamepads(IPC::Connection& connection)
1868 {
1869     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1870     if (!proxy)
1871         return;
1872
1873     ASSERT(m_processesUsingGamepads.contains(proxy));
1874     processStoppedUsingGamepads(*proxy);
1875 }
1876
1877 void WebProcessPool::processStoppedUsingGamepads(WebProcessProxy& process)
1878 {
1879     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1880
1881     ASSERT(m_processesUsingGamepads.contains(&process));
1882     m_processesUsingGamepads.remove(&process);
1883
1884     if (wereAnyProcessesUsingGamepads && m_processesUsingGamepads.isEmpty())
1885         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
1886 }
1887
1888 void WebProcessPool::gamepadConnected(const UIGamepad& gamepad)
1889 {
1890     for (auto& process : m_processesUsingGamepads)
1891         process->send(Messages::WebProcess::GamepadConnected(gamepad.fullGamepadData()), 0);
1892 }
1893
1894 void WebProcessPool::gamepadDisconnected(const UIGamepad& gamepad)
1895 {
1896     for (auto& process : m_processesUsingGamepads)
1897         process->send(Messages::WebProcess::GamepadDisconnected(gamepad.index()), 0);
1898 }
1899
1900 void WebProcessPool::setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>& gamepads)
1901 {
1902     Vector<GamepadData> gamepadDatas;
1903     gamepadDatas.grow(gamepads.size());
1904     for (size_t i = 0; i < gamepads.size(); ++i) {
1905         if (!gamepads[i])
1906             continue;
1907         gamepadDatas[i] = gamepads[i]->fullGamepadData();
1908     }
1909
1910     for (auto& process : m_processesUsingGamepads)
1911         process->send(Messages::WebProcess::SetInitialGamepads(gamepadDatas), 0);
1912 }
1913
1914 #endif // ENABLE(GAMEPAD)
1915
1916 void WebProcessPool::setJavaScriptConfigurationFileEnabled(bool flag)
1917 {
1918     m_javaScriptConfigurationFileEnabled = flag;
1919 }
1920
1921 void WebProcessPool::garbageCollectJavaScriptObjects()
1922 {
1923     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1924 }
1925
1926 void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1927 {
1928     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1929 }
1930
1931 Ref<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const
1932 {
1933     return m_plugInAutoStartProvider.autoStartOriginsTableCopy();
1934 }
1935
1936 void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary)
1937 {
1938     m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary);
1939 }
1940
1941 void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array)
1942 {
1943     m_plugInAutoStartProvider.setAutoStartOriginsArray(array);
1944 }
1945
1946 void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, WallTime time)
1947 {
1948     m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time);
1949 }
1950
1951 #if ENABLE(NETSCAPE_PLUGIN_API)
1952 void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString)
1953 {
1954     auto& policiesForHost = m_pluginLoadClientPolicies.ensure(host, [] { return HashMap<String, HashMap<String, uint8_t>>(); }).iterator->value;
1955     auto& versionsToPolicies = policiesForHost.ensure(bundleIdentifier, [] { return HashMap<String, uint8_t>(); }).iterator->value;
1956     versionsToPolicies.set(versionString, policy);
1957
1958     sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString));
1959 }
1960
1961 void WebProcessPool::resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&& pluginLoadClientPolicies)
1962 {
1963     m_pluginLoadClientPolicies = WTFMove(pluginLoadClientPolicies);
1964     sendToAllProcesses(Messages::WebProcess::ResetPluginLoadClientPolicies(m_pluginLoadClientPolicies));
1965 }
1966
1967 void WebProcessPool::clearPluginClientPolicies()
1968 {
1969     m_pluginLoadClientPolicies.clear();
1970     sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies());
1971 }
1972 #endif
1973
1974 void WebProcessPool::addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions)
1975 {
1976 #if ENABLE(NETSCAPE_PLUGIN_API)
1977     m_pluginInfoStore.addSupportedPlugin(WTFMove(matchingDomain), WTFMove(name), WTFMove(mimeTypes), WTFMove(extensions));
1978 #else
1979     UNUSED_PARAM(matchingDomain);
1980     UNUSED_PARAM(name);
1981     UNUSED_PARAM(mimeTypes);
1982     UNUSED_PARAM(extensions);
1983 #endif
1984 }
1985
1986 void WebProcessPool::clearSupportedPlugins()
1987 {
1988 #if ENABLE(NETSCAPE_PLUGIN_API)
1989     m_pluginInfoStore.clearSupportedPlugins();
1990 #endif
1991 }
1992
1993 void WebProcessPool::setMemoryCacheDisabled(bool disabled)
1994 {
1995     m_memoryCacheDisabled = disabled;
1996     sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled));
1997 }
1998
1999 void WebProcessPool::setFontWhitelist(API::Array* array)
2000 {
2001     m_fontWhitelist.clear();
2002     if (array) {
2003         for (size_t i = 0; i < array->size(); ++i) {
2004             if (API::String* font = array->at<API::String>(i))
2005                 m_fontWhitelist.append(font->string());
2006         }
2007     }
2008 }
2009
2010 void WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit()
2011 {
2012     // We're estimating an upper bound for a set of background timer fires for a page to be 200ms
2013     // (including all timer fires, all paging-in, and any resulting GC). To ensure this does not
2014     // result in more than 1% CPU load allow for one timer fire per 100x this duration.
2015     static int maximumTimerThrottlePerPageInMS = 200 * 100;
2016
2017     int limitInMilliseconds = maximumTimerThrottlePerPageInMS * m_hiddenPageThrottlingAutoIncreasesCounter.value();
2018     sendToAllProcesses(Messages::WebProcess::SetHiddenPageDOMTimerThrottlingIncreaseLimit(limitInMilliseconds));
2019 }
2020
2021 void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState)
2022 {
2023 #if PLATFORM(MAC)
2024     if (m_perActivityStateCPUUsageSampler)
2025         m_perActivityStateCPUUsageSampler->reportWebContentCPUTime(cpuTime, static_cast<WebCore::ActivityStateForCPUSampling>(activityState));
2026 #else
2027     UNUSED_PARAM(cpuTime);
2028     UNUSED_PARAM(activityState);
2029 #endif
2030 }
2031
2032 void WebProcessPool::updateProcessAssertions()
2033 {
2034 #if PLATFORM(IOS_FAMILY)
2035 #if ENABLE(SERVICE_WORKER)
2036     auto updateServiceWorkerProcessAssertion = [&] {
2037         if (!m_serviceWorkerProcesses.isEmpty() && m_foregroundWebProcessCounter.value()) {
2038             // FIXME: We can do better than this once we have process per origin.
2039             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2040                 auto registrableDomain = serviceWorkerProcess->registrableDomain();
2041                 if (!m_foregroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2042                     m_foregroundTokensForServiceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcess->throttler().foregroundActivityToken());
2043             }
2044             m_backgroundTokensForServiceWorkerProcesses.clear();
2045             return;
2046         }
2047         if (!m_serviceWorkerProcesses.isEmpty() && m_backgroundWebProcessCounter.value()) {
2048             // FIXME: We can do better than this once we have process per origin.
2049             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2050                 auto registrableDomain = serviceWorkerProcess->registrableDomain();
2051                 if (!m_backgroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2052                     m_backgroundTokensForServiceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcess->throttler().backgroundActivityToken());
2053             }
2054             m_foregroundTokensForServiceWorkerProcesses.clear();
2055             return;
2056         }
2057         m_foregroundTokensForServiceWorkerProcesses.clear();
2058         m_backgroundTokensForServiceWorkerProcesses.clear();
2059     };
2060     updateServiceWorkerProcessAssertion();
2061 #endif
2062
2063     auto updateNetworkProcessAssertion = [&] {
2064         auto& networkProcess = ensureNetworkProcess();
2065
2066         if (m_foregroundWebProcessCounter.value()) {
2067             if (!m_foregroundTokenForNetworkProcess) {
2068                 m_foregroundTokenForNetworkProcess = networkProcess.throttler().foregroundActivityToken();
2069                 networkProcess.sendProcessDidTransitionToForeground();
2070             }
2071             m_backgroundTokenForNetworkProcess = nullptr;
2072             return;
2073         }
2074         if (m_backgroundWebProcessCounter.value()) {
2075             if (!m_backgroundTokenForNetworkProcess) {
2076                 m_backgroundTokenForNetworkProcess = networkProcess.throttler().backgroundActivityToken();
2077                 networkProcess.sendProcessDidTransitionToBackground();
2078             }
2079             m_foregroundTokenForNetworkProcess = nullptr;
2080             return;
2081         }
2082         m_foregroundTokenForNetworkProcess = nullptr;
2083         m_backgroundTokenForNetworkProcess = nullptr;
2084     };
2085     updateNetworkProcessAssertion();
2086 #endif
2087 }
2088
2089 void WebProcessPool::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy)
2090 {
2091 #if PLATFORM(IOS_FAMILY)
2092     // The network process crashed; take new tokens for the new network process.
2093     if (m_backgroundTokenForNetworkProcess)
2094         m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken();
2095     else if (m_foregroundTokenForNetworkProcess)
2096         m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken();
2097 #else
2098     UNUSED_PARAM(newNetworkProcessProxy);
2099 #endif
2100 }
2101
2102 bool WebProcessPool::isServiceWorkerPageID(WebPageProxyIdentifier pageID) const
2103 {
2104 #if ENABLE(SERVICE_WORKER)
2105     // FIXME: This is inefficient.
2106     return WTF::anyOf(m_serviceWorkerProcesses.values(), [pageID](auto* process) {
2107         return process->hasServiceWorkerPageProxy(pageID);
2108     });
2109 #endif
2110     return false;
2111 }
2112
2113 void WebProcessPool::addProcessToOriginCacheSet(WebProcessProxy& process, const URL& url)
2114 {
2115     auto registrableDomain = WebCore::RegistrableDomain { url };
2116     auto result = m_swappedProcessesPerRegistrableDomain.add(registrableDomain, &process);
2117     if (!result.isNewEntry)
2118         result.iterator->value = &process;
2119
2120     LOG(ProcessSwapping, "(ProcessSwapping) Registrable domain %s just saved a cached process with pid %i", registrableDomain.string().utf8().data(), process.processIdentifier());
2121     if (!result.isNewEntry)
2122         LOG(ProcessSwapping, "(ProcessSwapping) Note: It already had one saved");
2123 }
2124
2125 void WebProcessPool::removeProcessFromOriginCacheSet(WebProcessProxy& process)
2126 {
2127     LOG(ProcessSwapping, "(ProcessSwapping) Removing process with pid %i from the origin cache set", process.processIdentifier());
2128
2129     // FIXME: This can be very inefficient as the number of remembered origins and processes grows
2130     Vector<WebCore::RegistrableDomain> registrableDomainsToRemove;
2131     for (auto entry : m_swappedProcessesPerRegistrableDomain) {
2132         if (entry.value == &process)
2133             registrableDomainsToRemove.append(entry.key);
2134     }
2135
2136     for (auto& registrableDomain : registrableDomainsToRemove)
2137         m_swappedProcessesPerRegistrableDomain.remove(registrableDomain);
2138 }
2139
2140 void WebProcessPool::processForNavigation(WebPageProxy& page, const API::Navigation& navigation, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient processSwapRequestedByClient, Ref<WebsiteDataStore>&& dataStore, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&& completionHandler)
2141 {
2142     processForNavigationInternal(page, navigation, sourceProcess.copyRef(), sourceURL, processSwapRequestedByClient, WTFMove(dataStore), [this, page = makeRefPtr(page), navigation = makeRef(navigation), sourceProcess = sourceProcess.copyRef(), sourceURL, processSwapRequestedByClient, completionHandler = WTFMove(completionHandler)](Ref<WebProcessProxy>&& process, SuspendedPageProxy* suspendedPage, const String& reason) mutable {
2143         // We are process-swapping so automatic process prewarming would be beneficial if the client has not explicitly enabled / disabled it.
2144         bool doingAnAutomaticProcessSwap = processSwapRequestedByClient == ProcessSwapRequestedByClient::No && process.ptr() != sourceProcess.ptr();
2145         if (doingAnAutomaticProcessSwap && !configuration().wasAutomaticProcessWarmingSetByClient() && !configuration().clientWouldBenefitFromAutomaticProcessPrewarming()) {
2146             RELEASE_LOG(PerformanceLogging, "Automatically turning on process prewarming because the client would benefit from it");
2147             configuration().setClientWouldBenefitFromAutomaticProcessPrewarming(true);
2148         }
2149
2150         if (m_configuration->alwaysKeepAndReuseSwappedProcesses() && process.ptr() != sourceProcess.ptr()) {
2151             static std::once_flag onceFlag;
2152             std::call_once(onceFlag, [] {
2153                 WTFLogAlways("WARNING: The option to always keep swapped web processes alive is active. This is meant for debugging and testing only.");
2154             });
2155
2156             addProcessToOriginCacheSet(sourceProcess, sourceURL);
2157
2158             LOG(ProcessSwapping, "(ProcessSwapping) Navigating from %s to %s, keeping around old process. Now holding on to old processes for %u origins.", sourceURL.string().utf8().data(), navigation->currentRequest().url().string().utf8().data(), m_swappedProcessesPerRegistrableDomain.size());
2159         }
2160
2161         completionHandler(WTFMove(process), suspendedPage, reason);
2162     });
2163 }
2164
2165 void WebProcessPool::processForNavigationInternal(WebPageProxy& page, const API::Navigation& navigation, Ref<WebProcessProxy>&& sourceProcess, const URL& pageSourceURL, ProcessSwapRequestedByClient processSwapRequestedByClient, Ref<WebsiteDataStore>&& dataStore, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&& completionHandler)
2166 {
2167     auto& targetURL = navigation.currentRequest().url();
2168     auto targetRegistrableDomain = WebCore::RegistrableDomain { targetURL };
2169
2170     auto createNewProcess = [this, protectedThis = makeRef(*this), page = makeRef(page), targetRegistrableDomain, dataStore = dataStore.copyRef()] () -> Ref<WebProcessProxy> {
2171         return processForRegistrableDomain(dataStore, page.ptr(), targetRegistrableDomain);
2172     };
2173
2174     if (usesSingleWebProcess())
2175         return completionHandler(WTFMove(sourceProcess), nullptr, "Single WebProcess mode is enabled"_s);
2176
2177     if (processSwapRequestedByClient == ProcessSwapRequestedByClient::Yes)
2178         return completionHandler(createNewProcess(), nullptr, "Process swap was requested by the client"_s);
2179
2180     if (!m_configuration->processSwapsOnNavigation())
2181         return completionHandler(WTFMove(sourceProcess), nullptr, "Feature is disabled"_s);
2182
2183     if (m_automationSession)
2184         return completionHandler(WTFMove(sourceProcess), nullptr, "An automation session is active"_s);
2185
2186     if (!sourceProcess->hasCommittedAnyProvisionalLoads()) {
2187         tryPrewarmWithDomainInformation(sourceProcess, targetRegistrableDomain);
2188         return completionHandler(WTFMove(sourceProcess), nullptr, "Process has not yet committed any provisional loads"_s);
2189     }
2190
2191     // FIXME: We should support process swap when a window has been opened via window.open() without 'noopener'.
2192     // The issue is that the opener has a handle to the WindowProxy.
2193     if (navigation.openedByDOMWithOpener() && !m_configuration->processSwapsOnWindowOpenWithOpener())
2194         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context been opened by DOM without 'noopener'"_s);
2195
2196     // FIXME: We should support process swap when a window has opened other windows via window.open.
2197     if (navigation.hasOpenedFrames())
2198         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context has opened other windows"_s);
2199
2200     if (auto* targetItem = navigation.targetItem()) {
2201         if (auto* suspendedPage = targetItem->suspendedPage()) {
2202             return suspendedPage->waitUntilReadyToUnsuspend([createNewProcess = WTFMove(createNewProcess), completionHandler = WTFMove(completionHandler)](SuspendedPageProxy* suspendedPage) mutable {
2203                 if (!suspendedPage)
2204                     return completionHandler(createNewProcess(), nullptr, "Using new process because target back/forward item's suspended page is not reusable"_s);
2205                 Ref<WebProcessProxy> process = suspendedPage->process();
2206                 completionHandler(WTFMove(process), suspendedPage, "Using target back/forward item's process and suspended page"_s);
2207             });
2208         }
2209
2210         if (RefPtr<WebProcessProxy> process = WebProcessProxy::processForIdentifier(targetItem->lastProcessIdentifier())) {
2211             if (process->state() != WebProcessProxy::State::Terminated) {
2212                 // Make sure we remove the process from the cache if it is in there since we're about to use it.
2213                 if (process->isInProcessCache()) {
2214                     webProcessCache().removeProcess(*process, WebProcessCache::ShouldShutDownProcess::No);
2215                     ASSERT(!process->isInProcessCache());
2216                 }
2217
2218                 return completionHandler(process.releaseNonNull(), nullptr, "Using target back/forward item's process"_s);
2219             }
2220         }
2221     }
2222
2223     if (navigation.treatAsSameOriginNavigation())
2224         return completionHandler(WTFMove(sourceProcess), nullptr, "The treatAsSameOriginNavigation flag is set"_s);
2225
2226     URL sourceURL;
2227     if (page.isPageOpenedByDOMShowingInitialEmptyDocument() && !navigation.requesterOrigin().isEmpty())
2228         sourceURL = URL { URL(), navigation.requesterOrigin().toString() };
2229     else
2230         sourceURL = pageSourceURL;
2231
2232     if (sourceURL.isEmpty() && page.configuration().relatedPage()) {
2233         sourceURL = URL { { }, page.configuration().relatedPage()->pageLoadState().url() };
2234         RELEASE_LOG(ProcessSwapping, "Using related page %p's URL as source URL for process swap decision", page.configuration().relatedPage());
2235     }
2236
2237     if (!sourceURL.isValid() || !targetURL.isValid() || sourceURL.isEmpty() || sourceURL.protocolIsAbout() || targetRegistrableDomain.matches(sourceURL))
2238         return completionHandler(WTFMove(sourceProcess), nullptr, "Navigation is same-site"_s);
2239
2240     String reason = "Navigation is cross-site"_s;
2241     
2242     if (m_configuration->alwaysKeepAndReuseSwappedProcesses()) {
2243         LOG(ProcessSwapping, "(ProcessSwapping) Considering re-use of a previously cached process for domain %s", targetRegistrableDomain.string().utf8().data());
2244
2245         if (auto* process = m_swappedProcessesPerRegistrableDomain.get(targetRegistrableDomain)) {
2246             if (&process->websiteDataStore() == dataStore.ptr()) {
2247                 LOG(ProcessSwapping, "(ProcessSwapping) Reusing a previously cached process with pid %i to continue navigation to URL %s", process->processIdentifier(), targetURL.string().utf8().data());
2248
2249                 return completionHandler(makeRef(*process), nullptr, reason);
2250             }
2251         }
2252     }
2253
2254     return completionHandler(createNewProcess(), nullptr, reason);
2255 }
2256
2257 void WebProcessPool::addMockMediaDevice(const MockMediaDevice& device)
2258 {
2259 #if ENABLE(MEDIA_STREAM)
2260     MockRealtimeMediaSourceCenter::addDevice(device);
2261     sendToAllProcesses(Messages::WebProcess::AddMockMediaDevice { device });
2262 #endif
2263 }
2264
2265 void WebProcessPool::clearMockMediaDevices()
2266 {
2267 #if ENABLE(MEDIA_STREAM)
2268     MockRealtimeMediaSourceCenter::setDevices({ });
2269     sendToAllProcesses(Messages::WebProcess::ClearMockMediaDevices { });
2270 #endif
2271 }
2272
2273 void WebProcessPool::removeMockMediaDevice(const String& persistentId)
2274 {
2275 #if ENABLE(MEDIA_STREAM)
2276     MockRealtimeMediaSourceCenter::removeDevice(persistentId);
2277     sendToAllProcesses(Messages::WebProcess::RemoveMockMediaDevice { persistentId });
2278 #endif
2279 }
2280
2281 void WebProcessPool::resetMockMediaDevices()
2282 {
2283 #if ENABLE(MEDIA_STREAM)
2284     MockRealtimeMediaSourceCenter::resetDevices();
2285     sendToAllProcesses(Messages::WebProcess::ResetMockMediaDevices { });
2286 #endif
2287 }
2288
2289 void WebProcessPool::sendDisplayConfigurationChangedMessageForTesting()
2290 {
2291 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
2292     auto display = CGSMainDisplayID();
2293
2294     for (auto& processPool : WebProcessPool::allProcessPools()) {
2295         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplayBeginConfigurationFlag));
2296         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplaySetModeFlag | kCGDisplayDesktopShapeChangedFlag));
2297     }
2298 #endif
2299 }
2300
2301 void WebProcessPool::didCollectPrewarmInformation(const WebCore::RegistrableDomain& registrableDomain, const WebCore::PrewarmInformation& prewarmInformation)
2302 {
2303     static const size_t maximumSizeToPreventUnlimitedGrowth = 100;
2304     if (m_prewarmInformationPerRegistrableDomain.size() == maximumSizeToPreventUnlimitedGrowth)
2305         m_prewarmInformationPerRegistrableDomain.remove(m_prewarmInformationPerRegistrableDomain.random());
2306
2307     auto& value = m_prewarmInformationPerRegistrableDomain.ensure(registrableDomain, [] {
2308         return makeUnique<WebCore::PrewarmInformation>();
2309     }).iterator->value;
2310
2311     *value = prewarmInformation;
2312 }
2313
2314 void WebProcessPool::tryPrewarmWithDomainInformation(WebProcessProxy& process, const RegistrableDomain& registrableDomain)
2315 {
2316     auto* prewarmInformation = m_prewarmInformationPerRegistrableDomain.get(registrableDomain);
2317     if (!prewarmInformation)
2318         return;
2319     process.send(Messages::WebProcess::PrewarmWithDomainInformation(*prewarmInformation), 0);
2320 }
2321
2322 void WebProcessPool::clearCurrentModifierStateForTesting()
2323 {
2324     sendToAllProcesses(Messages::WebProcess::ClearCurrentModifierStateForTesting());
2325 }
2326
2327 #if ENABLE(RESOURCE_LOAD_STATISTICS)
2328 void WebProcessPool::didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID sessionID, const RegistrableDomain& fromDomain, const RegistrableDomain& toDomain, OptionSet<CrossSiteNavigationDataTransfer::Flag> navigationDataTransfer, WebPageProxyIdentifier webPageProxyID, PageIdentifier webPageID)
2329 {
2330     if (!m_networkProcess)
2331         return;
2332
2333     m_networkProcess->didCommitCrossSiteLoadWithDataTransfer(sessionID, fromDomain, toDomain, navigationDataTransfer, webPageProxyID, webPageID);
2334 }
2335 #endif
2336
2337 void WebProcessPool::setWebProcessHasUploads(ProcessIdentifier processID)
2338 {
2339     ASSERT(processID);
2340     auto* process = WebProcessProxy::processForIdentifier(processID);
2341     ASSERT(process);
2342
2343     if (!process)
2344         return;
2345
2346     RELEASE_LOG(ProcessSuspension, "Web process pid %u now has uploads in progress", (unsigned)process->processIdentifier());
2347
2348     if (m_processesWithUploads.isEmpty()) {
2349         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now one. Taking Networking and UI process assertions.");
2350
2351         ASSERT(m_networkProcess);
2352         m_networkProcess->takeUploadAssertion();
2353         
2354         ASSERT(!m_uiProcessUploadAssertion);
2355         m_uiProcessUploadAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2356     }
2357     
2358     auto result = m_processesWithUploads.add(processID, nullptr);
2359     ASSERT(result.isNewEntry);
2360     result.iterator->value = makeUnique<ProcessAssertion>(process->processIdentifier(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2361 }
2362
2363 void WebProcessPool::clearWebProcessHasUploads(ProcessIdentifier processID)
2364 {
2365     ASSERT(processID);
2366     auto result = m_processesWithUploads.take(processID);
2367     if (!result)
2368         return;
2369
2370     auto* process = WebProcessProxy::processForIdentifier(processID);
2371     ASSERT_UNUSED(process, process);
2372     RELEASE_LOG(ProcessSuspension, "Web process pid %u no longer has uploads in progress", (unsigned)process->processIdentifier());
2373
2374     if (m_processesWithUploads.isEmpty()) {
2375         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now zero. Releasing Networking and UI process assertions.");
2376
2377         if (m_networkProcess)
2378             m_networkProcess->clearUploadAssertion();
2379         
2380         ASSERT(m_uiProcessUploadAssertion);
2381         m_uiProcessUploadAssertion = nullptr;
2382     }
2383     
2384 }
2385
2386 void WebProcessPool::setWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier processID)
2387 {
2388     auto* process = WebProcessProxy::processForIdentifier(processID);
2389     ASSERT(process);
2390
2391     RELEASE_LOG(ProcessSuspension, "Web process pid %u is now playing audible media", (unsigned)process->processIdentifier());
2392
2393     if (m_processesPlayingAudibleMedia.isEmpty()) {
2394         RELEASE_LOG(ProcessSuspension, "The number of processes playing audible media is now one. Taking UI process assertion.");
2395
2396         ASSERT(!m_uiProcessMediaPlaybackAssertion);
2397         m_uiProcessMediaPlaybackAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit Media Playback"_s, AssertionState::Foreground, AssertionReason::MediaPlayback);
2398     }
2399
2400     auto result = m_processesPlayingAudibleMedia.add(processID, nullptr);
2401     ASSERT(result.isNewEntry);
2402     result.iterator->value = makeUnique<ProcessAssertion>(process->processIdentifier(), "WebKit Media Playback"_s, AssertionState::Foreground, AssertionReason::MediaPlayback);
2403 }
2404
2405 void WebProcessPool::clearWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier processID)
2406 {
2407     auto result = m_processesPlayingAudibleMedia.take(processID);
2408     ASSERT_UNUSED(result, result);
2409
2410     auto* process = WebProcessProxy::processForIdentifier(processID);
2411     ASSERT_UNUSED(process, process);
2412
2413     RELEASE_LOG(ProcessSuspension, "Web process pid %u is no longer playing audible media", (unsigned)process->processIdentifier());
2414
2415     if (m_processesPlayingAudibleMedia.isEmpty()) {
2416         RELEASE_LOG(ProcessSuspension, "The number of processes playing audible media now zero. Releasing UI process assertion.");
2417
2418         ASSERT(m_uiProcessMediaPlaybackAssertion);
2419         m_uiProcessMediaPlaybackAssertion = nullptr;
2420     }
2421 }
2422
2423 } // namespace WebKit