Clearing Website data for a given session should not shut down cached processes for...
[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     // Clear back/forward cache first as processes removed from the back/forward cache will likely
1390     // be added to the WebProcess cache.
1391     m_backForwardCache->clear();
1392     m_webProcessCache->clear();
1393
1394     if (m_prewarmedProcess)
1395         m_prewarmedProcess->shutDown();
1396     ASSERT(!m_prewarmedProcess);
1397 }
1398
1399 #if ENABLE(NETSCAPE_PLUGIN_API)
1400 void WebProcessPool::setAdditionalPluginsDirectory(const String& directory)
1401 {
1402     Vector<String> directories;
1403     directories.append(directory);
1404
1405     m_pluginInfoStore.setAdditionalPluginsDirectories(directories);
1406 }
1407
1408 void WebProcessPool::refreshPlugins()
1409 {
1410     m_pluginInfoStore.refresh();
1411     sendToAllProcesses(Messages::WebProcess::RefreshPlugins());
1412 }
1413
1414 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1415
1416 ProcessID WebProcessPool::networkProcessIdentifier()
1417 {
1418     return m_networkProcess ? m_networkProcess->processIdentifier() : 0;
1419 }
1420
1421 ProcessID WebProcessPool::prewarmedProcessIdentifier()
1422 {
1423     return m_prewarmedProcess ? m_prewarmedProcess->processIdentifier() : 0;
1424 }
1425
1426 void WebProcessPool::activePagesOriginsInWebProcessForTesting(ProcessID pid, CompletionHandler<void(Vector<String>&&)>&& completionHandler)
1427 {
1428     for (auto& process : m_processes) {
1429         if (process->processIdentifier() == pid)
1430             return process->activePagesDomainsForTesting(WTFMove(completionHandler));
1431     }
1432     completionHandler({ });
1433 }
1434
1435 void WebProcessPool::setServiceWorkerTimeoutForTesting(Seconds seconds)
1436 {
1437     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting(seconds), Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting::Reply());
1438 }
1439
1440 void WebProcessPool::resetServiceWorkerTimeoutForTesting()
1441 {
1442     sendSyncToNetworkingProcess(Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting(), Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting::Reply());
1443 }
1444
1445 void WebProcessPool::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText)
1446 {
1447     m_alwaysUsesComplexTextCodePath = alwaysUseComplexText;
1448     sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText));
1449 }
1450
1451 void WebProcessPool::setShouldUseFontSmoothing(bool useFontSmoothing)
1452 {
1453     m_shouldUseFontSmoothing = useFontSmoothing;
1454     sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing));
1455 }
1456
1457 void WebProcessPool::clearResourceLoadStatistics()
1458 {
1459     sendToAllProcesses(Messages::WebProcess::ClearResourceLoadStatistics());
1460 }
1461
1462 void WebProcessPool::registerURLSchemeAsEmptyDocument(const String& urlScheme)
1463 {
1464     m_schemesToRegisterAsEmptyDocument.add(urlScheme);
1465     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme));
1466 }
1467
1468 void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme)
1469 {
1470     m_schemesToRegisterAsSecure.add(urlScheme);
1471     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
1472     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme));
1473 }
1474
1475 void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme)
1476 {
1477     m_schemesToRegisterAsBypassingContentSecurityPolicy.add(urlScheme);
1478     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1479     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1480 }
1481
1482 void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
1483 {
1484     m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme);
1485     sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme));
1486 }
1487
1488 void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme)
1489 {
1490     m_schemesToRegisterAsLocal.add(urlScheme);
1491     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme));
1492     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme));
1493 }
1494
1495 void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme)
1496 {
1497     m_schemesToRegisterAsNoAccess.add(urlScheme);
1498     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1499     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1500 }
1501
1502 void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme)
1503 {
1504     m_schemesToRegisterAsDisplayIsolated.add(urlScheme);
1505     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1506 }
1507
1508 void WebProcessPool::registerURLSchemeAsCORSEnabled(const String& urlScheme)
1509 {
1510     m_schemesToRegisterAsCORSEnabled.add(urlScheme);
1511     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1512     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1513 }
1514
1515 void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1516 {
1517     if (!urlScheme)
1518         return;
1519
1520     globalURLSchemesWithCustomProtocolHandlers().add(urlScheme);
1521     for (auto* processPool : allProcessPools()) {
1522         if (auto* networkProcess = processPool->networkProcess())
1523             networkProcess->registerSchemeForLegacyCustomProtocol(urlScheme);
1524     }
1525 }
1526
1527 void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1528 {
1529     if (!urlScheme)
1530         return;
1531
1532     globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme);
1533     for (auto* processPool : allProcessPools()) {
1534         if (auto* networkProcess = processPool->networkProcess())
1535             networkProcess->unregisterSchemeForLegacyCustomProtocol(urlScheme);
1536     }
1537 }
1538
1539 void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme)
1540 {
1541     m_schemesToRegisterAsCachePartitioned.add(urlScheme);
1542     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCachePartitioned(urlScheme));
1543 }
1544
1545 void WebProcessPool::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& urlScheme)
1546 {
1547     m_schemesToRegisterAsCanDisplayOnlyIfCanRequest.add(urlScheme);
1548     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1549     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1550 }
1551
1552 void WebProcessPool::updateBackForwardCacheCapacity()
1553 {
1554     if (!m_configuration->usesPageCache())
1555         return;
1556
1557     unsigned dummy = 0;
1558     Seconds dummyInterval;
1559     unsigned backForwardCacheCapacity = 0;
1560     calculateMemoryCacheSizes(LegacyGlobalSettings::singleton().cacheModel(), dummy, dummy, dummy, dummyInterval, backForwardCacheCapacity);
1561
1562     m_backForwardCache->setCapacity(backForwardCacheCapacity);
1563 }
1564
1565 void WebProcessPool::setCacheModel(CacheModel cacheModel)
1566 {
1567     updateBackForwardCacheCapacity();
1568
1569     sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel));
1570
1571     if (m_networkProcess)
1572         m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel, { }), 0);
1573 }
1574
1575 void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
1576 {
1577     sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval));
1578 }
1579
1580 DownloadProxy& WebProcessPool::createDownloadProxy(WebsiteDataStore& dataStore, const ResourceRequest& request, WebPageProxy* originatingPage)
1581 {
1582     auto& downloadProxy = ensureNetworkProcess().createDownloadProxy(dataStore, request);
1583     downloadProxy.setOriginatingPage(originatingPage);
1584     return downloadProxy;
1585 }
1586
1587 void WebProcessPool::synthesizeAppIsBackground(bool background)
1588 {
1589     ensureNetworkProcess().synthesizeAppIsBackground(background);
1590 }
1591
1592 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver)
1593 {
1594     m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
1595 }
1596
1597 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
1598 {
1599     m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
1600 }
1601
1602 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName)
1603 {
1604     m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
1605 }
1606
1607 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID)
1608 {
1609     m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
1610 }
1611
1612 bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
1613 {
1614     return m_messageReceiverMap.dispatchMessage(connection, decoder);
1615 }
1616
1617 bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
1618 {
1619     return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
1620 }
1621
1622 void WebProcessPool::setEnhancedAccessibility(bool flag)
1623 {
1624     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
1625 }
1626     
1627 void WebProcessPool::startMemorySampler(const double interval)
1628 {    
1629     // For new WebProcesses we will also want to start the Memory Sampler
1630     m_memorySamplerEnabled = true;
1631     m_memorySamplerInterval = interval;
1632     
1633     // For UIProcess
1634 #if ENABLE(MEMORY_SAMPLER)
1635     WebMemorySampler::singleton()->start(interval);
1636 #endif
1637     
1638     // For WebProcess
1639     SandboxExtension::Handle sampleLogSandboxHandle;    
1640     WallTime now = WallTime::now();
1641     String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()));
1642     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1643     
1644     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
1645 }
1646
1647 void WebProcessPool::stopMemorySampler()
1648 {    
1649     // For WebProcess
1650     m_memorySamplerEnabled = false;
1651     
1652     // For UIProcess
1653 #if ENABLE(MEMORY_SAMPLER)
1654     WebMemorySampler::singleton()->stop();
1655 #endif
1656
1657     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
1658 }
1659
1660 void WebProcessPool::useTestingNetworkSession()
1661 {
1662     ASSERT(m_processes.isEmpty());
1663     ASSERT(!m_networkProcess);
1664
1665     if (m_networkProcess)
1666         return;
1667
1668     if (!m_processes.isEmpty())
1669         return;
1670
1671     m_shouldUseTestingNetworkSession = true;
1672 }
1673
1674 template<typename T, typename U>
1675 void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
1676 {
1677     if (m_networkProcess && m_networkProcess->canSendMessage())
1678         m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
1679 }
1680
1681 void WebProcessPool::setAllowsAnySSLCertificateForWebSocket(bool allows)
1682 {
1683     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply());
1684 }
1685
1686 void WebProcessPool::clearCachedCredentials()
1687 {
1688     if (m_networkProcess)
1689         m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0);
1690 }
1691
1692 void WebProcessPool::terminateNetworkProcess()
1693 {
1694     if (!m_networkProcess)
1695         return;
1696     
1697     m_networkProcess->terminate();
1698     m_networkProcess = nullptr;
1699     m_didNetworkProcessCrash = true;
1700 }
1701
1702 void WebProcessPool::sendNetworkProcessWillSuspendImminentlyForTesting()
1703 {
1704     if (m_networkProcess)
1705         m_networkProcess->sendProcessWillSuspendImminentlyForTesting();
1706 }
1707
1708 void WebProcessPool::sendNetworkProcessDidResume()
1709 {
1710     if (m_networkProcess)
1711         m_networkProcess->sendProcessDidResume();
1712 }
1713
1714 void WebProcessPool::terminateServiceWorkerProcesses()
1715 {
1716 #if ENABLE(SERVICE_WORKER)
1717     auto protectedThis = makeRef(*this);
1718     while (!m_serviceWorkerProcesses.isEmpty())
1719         m_serviceWorkerProcesses.begin()->value->requestTermination(ProcessTerminationReason::RequestedByClient);
1720 #endif
1721 }
1722
1723 void WebProcessPool::syncNetworkProcessCookies()
1724 {
1725     ensureNetworkProcess().syncAllCookies();
1726 }
1727
1728 void WebProcessPool::syncLocalStorage(CompletionHandler<void()>&& completionHandler)
1729 {
1730     sendSyncToNetworkingProcess(Messages::NetworkProcess::SyncLocalStorage(), Messages::NetworkProcess::SyncLocalStorage::Reply());
1731     completionHandler();
1732 }
1733
1734 void WebProcessPool::clearLegacyPrivateBrowsingLocalStorage(CompletionHandler<void()>&& completionHandler)
1735 {
1736     if (m_networkProcess)
1737         m_networkProcess->send(Messages::NetworkProcess::ClearLegacyPrivateBrowsingLocalStorage(), 0);
1738     completionHandler();
1739 }
1740
1741 void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
1742 {
1743     ensureNetworkProcess();
1744     m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
1745 }
1746
1747 void WebProcessPool::updateAutomationCapabilities() const
1748 {
1749 #if ENABLE(REMOTE_INSPECTOR)
1750     Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange();
1751 #endif
1752 }
1753
1754 void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession)
1755 {
1756     if (m_automationSession)
1757         m_automationSession->setProcessPool(nullptr);
1758     
1759     m_automationSession = WTFMove(automationSession);
1760
1761 #if ENABLE(REMOTE_INSPECTOR)
1762     if (m_automationSession) {
1763         m_automationSession->init();
1764         m_automationSession->setProcessPool(this);
1765
1766         sendToAllProcesses(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()));
1767     } else
1768         sendToAllProcesses(Messages::WebProcess::DestroyAutomationSessionProxy());
1769 #endif
1770 }
1771
1772 void WebProcessPool::setHTTPPipeliningEnabled(bool enabled)
1773 {
1774 #if PLATFORM(COCOA)
1775     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1776 #else
1777     UNUSED_PARAM(enabled);
1778 #endif
1779 }
1780
1781 bool WebProcessPool::httpPipeliningEnabled() const
1782 {
1783 #if PLATFORM(COCOA)
1784     return ResourceRequest::httpPipeliningEnabled();
1785 #else
1786     return false;
1787 #endif
1788 }
1789
1790 void WebProcessPool::getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&& callbackFunction)
1791 {
1792     if (!statisticsMask) {
1793         callbackFunction(nullptr, CallbackBase::Error::Unknown);
1794         return;
1795     }
1796
1797     auto request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction)));
1798
1799     if (statisticsMask & StatisticsRequestTypeWebContent)
1800         requestWebContentStatistics(request.get());
1801 }
1802
1803 void WebProcessPool::requestWebContentStatistics(StatisticsRequest& request)
1804 {
1805     // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work.
1806 }
1807
1808 static WebProcessProxy* webProcessProxyFromConnection(IPC::Connection& connection, const Vector<RefPtr<WebProcessProxy>>& processes)
1809 {
1810     for (auto& process : processes) {
1811         if (process->hasConnection(connection))
1812             return process.get();
1813     }
1814
1815     ASSERT_NOT_REACHED();
1816     return nullptr;
1817 }
1818
1819 void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
1820 {
1821     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1822     if (!webProcessProxy)
1823         return;
1824     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get());
1825 }
1826
1827 void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&& completionHandler)
1828 {
1829     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1830     if (!webProcessProxy)
1831         return completionHandler({ });
1832
1833     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), [webProcessProxy = makeRef(*webProcessProxy), completionHandler = WTFMove(completionHandler)] (RefPtr<API::Object>&& returnData) mutable {
1834         completionHandler(UserData(webProcessProxy->transformObjectsToHandles(returnData.get())));
1835     });
1836 }
1837
1838 void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID)
1839 {
1840     RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID);
1841     if (!request) {
1842         LOG_ERROR("Cannot report networking statistics.");
1843         return;
1844     }
1845
1846     request->completedRequest(requestID, statisticsData);
1847 }
1848
1849 #if ENABLE(GAMEPAD)
1850
1851 void WebProcessPool::startedUsingGamepads(IPC::Connection& connection)
1852 {
1853     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1854     if (!proxy)
1855         return;
1856
1857     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1858
1859     ASSERT(!m_processesUsingGamepads.contains(proxy));
1860     m_processesUsingGamepads.add(proxy);
1861
1862     if (!wereAnyProcessesUsingGamepads)
1863         UIGamepadProvider::singleton().processPoolStartedUsingGamepads(*this);
1864
1865     proxy->send(Messages::WebProcess::SetInitialGamepads(UIGamepadProvider::singleton().snapshotGamepads()), 0);
1866 }
1867
1868 void WebProcessPool::stoppedUsingGamepads(IPC::Connection& connection)
1869 {
1870     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1871     if (!proxy)
1872         return;
1873
1874     ASSERT(m_processesUsingGamepads.contains(proxy));
1875     processStoppedUsingGamepads(*proxy);
1876 }
1877
1878 void WebProcessPool::processStoppedUsingGamepads(WebProcessProxy& process)
1879 {
1880     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1881
1882     ASSERT(m_processesUsingGamepads.contains(&process));
1883     m_processesUsingGamepads.remove(&process);
1884
1885     if (wereAnyProcessesUsingGamepads && m_processesUsingGamepads.isEmpty())
1886         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
1887 }
1888
1889 void WebProcessPool::gamepadConnected(const UIGamepad& gamepad)
1890 {
1891     for (auto& process : m_processesUsingGamepads)
1892         process->send(Messages::WebProcess::GamepadConnected(gamepad.fullGamepadData()), 0);
1893 }
1894
1895 void WebProcessPool::gamepadDisconnected(const UIGamepad& gamepad)
1896 {
1897     for (auto& process : m_processesUsingGamepads)
1898         process->send(Messages::WebProcess::GamepadDisconnected(gamepad.index()), 0);
1899 }
1900
1901 void WebProcessPool::setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>& gamepads)
1902 {
1903     Vector<GamepadData> gamepadDatas;
1904     gamepadDatas.grow(gamepads.size());
1905     for (size_t i = 0; i < gamepads.size(); ++i) {
1906         if (!gamepads[i])
1907             continue;
1908         gamepadDatas[i] = gamepads[i]->fullGamepadData();
1909     }
1910
1911     for (auto& process : m_processesUsingGamepads)
1912         process->send(Messages::WebProcess::SetInitialGamepads(gamepadDatas), 0);
1913 }
1914
1915 #endif // ENABLE(GAMEPAD)
1916
1917 void WebProcessPool::setJavaScriptConfigurationFileEnabled(bool flag)
1918 {
1919     m_javaScriptConfigurationFileEnabled = flag;
1920 }
1921
1922 void WebProcessPool::garbageCollectJavaScriptObjects()
1923 {
1924     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1925 }
1926
1927 void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1928 {
1929     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1930 }
1931
1932 Ref<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const
1933 {
1934     return m_plugInAutoStartProvider.autoStartOriginsTableCopy();
1935 }
1936
1937 void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary)
1938 {
1939     m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary);
1940 }
1941
1942 void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array)
1943 {
1944     m_plugInAutoStartProvider.setAutoStartOriginsArray(array);
1945 }
1946
1947 void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, WallTime time)
1948 {
1949     m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time);
1950 }
1951
1952 #if ENABLE(NETSCAPE_PLUGIN_API)
1953 void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString)
1954 {
1955     auto& policiesForHost = m_pluginLoadClientPolicies.ensure(host, [] { return HashMap<String, HashMap<String, uint8_t>>(); }).iterator->value;
1956     auto& versionsToPolicies = policiesForHost.ensure(bundleIdentifier, [] { return HashMap<String, uint8_t>(); }).iterator->value;
1957     versionsToPolicies.set(versionString, policy);
1958
1959     sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString));
1960 }
1961
1962 void WebProcessPool::resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&& pluginLoadClientPolicies)
1963 {
1964     m_pluginLoadClientPolicies = WTFMove(pluginLoadClientPolicies);
1965     sendToAllProcesses(Messages::WebProcess::ResetPluginLoadClientPolicies(m_pluginLoadClientPolicies));
1966 }
1967
1968 void WebProcessPool::clearPluginClientPolicies()
1969 {
1970     m_pluginLoadClientPolicies.clear();
1971     sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies());
1972 }
1973 #endif
1974
1975 void WebProcessPool::addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions)
1976 {
1977 #if ENABLE(NETSCAPE_PLUGIN_API)
1978     m_pluginInfoStore.addSupportedPlugin(WTFMove(matchingDomain), WTFMove(name), WTFMove(mimeTypes), WTFMove(extensions));
1979 #else
1980     UNUSED_PARAM(matchingDomain);
1981     UNUSED_PARAM(name);
1982     UNUSED_PARAM(mimeTypes);
1983     UNUSED_PARAM(extensions);
1984 #endif
1985 }
1986
1987 void WebProcessPool::clearSupportedPlugins()
1988 {
1989 #if ENABLE(NETSCAPE_PLUGIN_API)
1990     m_pluginInfoStore.clearSupportedPlugins();
1991 #endif
1992 }
1993
1994 void WebProcessPool::setMemoryCacheDisabled(bool disabled)
1995 {
1996     m_memoryCacheDisabled = disabled;
1997     sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled));
1998 }
1999
2000 void WebProcessPool::setFontWhitelist(API::Array* array)
2001 {
2002     m_fontWhitelist.clear();
2003     if (array) {
2004         for (size_t i = 0; i < array->size(); ++i) {
2005             if (API::String* font = array->at<API::String>(i))
2006                 m_fontWhitelist.append(font->string());
2007         }
2008     }
2009 }
2010
2011 void WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit()
2012 {
2013     // We're estimating an upper bound for a set of background timer fires for a page to be 200ms
2014     // (including all timer fires, all paging-in, and any resulting GC). To ensure this does not
2015     // result in more than 1% CPU load allow for one timer fire per 100x this duration.
2016     static int maximumTimerThrottlePerPageInMS = 200 * 100;
2017
2018     int limitInMilliseconds = maximumTimerThrottlePerPageInMS * m_hiddenPageThrottlingAutoIncreasesCounter.value();
2019     sendToAllProcesses(Messages::WebProcess::SetHiddenPageDOMTimerThrottlingIncreaseLimit(limitInMilliseconds));
2020 }
2021
2022 void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState)
2023 {
2024 #if PLATFORM(MAC)
2025     if (m_perActivityStateCPUUsageSampler)
2026         m_perActivityStateCPUUsageSampler->reportWebContentCPUTime(cpuTime, static_cast<WebCore::ActivityStateForCPUSampling>(activityState));
2027 #else
2028     UNUSED_PARAM(cpuTime);
2029     UNUSED_PARAM(activityState);
2030 #endif
2031 }
2032
2033 void WebProcessPool::updateProcessAssertions()
2034 {
2035 #if PLATFORM(IOS_FAMILY)
2036 #if ENABLE(SERVICE_WORKER)
2037     auto updateServiceWorkerProcessAssertion = [&] {
2038         if (!m_serviceWorkerProcesses.isEmpty() && m_foregroundWebProcessCounter.value()) {
2039             // FIXME: We can do better than this once we have process per origin.
2040             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2041                 auto registrableDomain = serviceWorkerProcess->registrableDomain();
2042                 if (!m_foregroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2043                     m_foregroundTokensForServiceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcess->throttler().foregroundActivityToken());
2044             }
2045             m_backgroundTokensForServiceWorkerProcesses.clear();
2046             return;
2047         }
2048         if (!m_serviceWorkerProcesses.isEmpty() && m_backgroundWebProcessCounter.value()) {
2049             // FIXME: We can do better than this once we have process per origin.
2050             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2051                 auto registrableDomain = serviceWorkerProcess->registrableDomain();
2052                 if (!m_backgroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2053                     m_backgroundTokensForServiceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcess->throttler().backgroundActivityToken());
2054             }
2055             m_foregroundTokensForServiceWorkerProcesses.clear();
2056             return;
2057         }
2058         m_foregroundTokensForServiceWorkerProcesses.clear();
2059         m_backgroundTokensForServiceWorkerProcesses.clear();
2060     };
2061     updateServiceWorkerProcessAssertion();
2062 #endif
2063
2064     auto updateNetworkProcessAssertion = [&] {
2065         auto& networkProcess = ensureNetworkProcess();
2066
2067         if (m_foregroundWebProcessCounter.value()) {
2068             if (!m_foregroundTokenForNetworkProcess) {
2069                 m_foregroundTokenForNetworkProcess = networkProcess.throttler().foregroundActivityToken();
2070                 networkProcess.sendProcessDidTransitionToForeground();
2071             }
2072             m_backgroundTokenForNetworkProcess = nullptr;
2073             return;
2074         }
2075         if (m_backgroundWebProcessCounter.value()) {
2076             if (!m_backgroundTokenForNetworkProcess) {
2077                 m_backgroundTokenForNetworkProcess = networkProcess.throttler().backgroundActivityToken();
2078                 networkProcess.sendProcessDidTransitionToBackground();
2079             }
2080             m_foregroundTokenForNetworkProcess = nullptr;
2081             return;
2082         }
2083         m_foregroundTokenForNetworkProcess = nullptr;
2084         m_backgroundTokenForNetworkProcess = nullptr;
2085     };
2086     updateNetworkProcessAssertion();
2087 #endif
2088 }
2089
2090 void WebProcessPool::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy)
2091 {
2092 #if PLATFORM(IOS_FAMILY)
2093     // The network process crashed; take new tokens for the new network process.
2094     if (m_backgroundTokenForNetworkProcess)
2095         m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken();
2096     else if (m_foregroundTokenForNetworkProcess)
2097         m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken();
2098 #else
2099     UNUSED_PARAM(newNetworkProcessProxy);
2100 #endif
2101 }
2102
2103 bool WebProcessPool::isServiceWorkerPageID(WebPageProxyIdentifier pageID) const
2104 {
2105 #if ENABLE(SERVICE_WORKER)
2106     // FIXME: This is inefficient.
2107     return WTF::anyOf(m_serviceWorkerProcesses.values(), [pageID](auto* process) {
2108         return process->hasServiceWorkerPageProxy(pageID);
2109     });
2110 #endif
2111     return false;
2112 }
2113
2114 void WebProcessPool::addProcessToOriginCacheSet(WebProcessProxy& process, const URL& url)
2115 {
2116     auto registrableDomain = WebCore::RegistrableDomain { url };
2117     auto result = m_swappedProcessesPerRegistrableDomain.add(registrableDomain, &process);
2118     if (!result.isNewEntry)
2119         result.iterator->value = &process;
2120
2121     LOG(ProcessSwapping, "(ProcessSwapping) Registrable domain %s just saved a cached process with pid %i", registrableDomain.string().utf8().data(), process.processIdentifier());
2122     if (!result.isNewEntry)
2123         LOG(ProcessSwapping, "(ProcessSwapping) Note: It already had one saved");
2124 }
2125
2126 void WebProcessPool::removeProcessFromOriginCacheSet(WebProcessProxy& process)
2127 {
2128     LOG(ProcessSwapping, "(ProcessSwapping) Removing process with pid %i from the origin cache set", process.processIdentifier());
2129
2130     // FIXME: This can be very inefficient as the number of remembered origins and processes grows
2131     Vector<WebCore::RegistrableDomain> registrableDomainsToRemove;
2132     for (auto entry : m_swappedProcessesPerRegistrableDomain) {
2133         if (entry.value == &process)
2134             registrableDomainsToRemove.append(entry.key);
2135     }
2136
2137     for (auto& registrableDomain : registrableDomainsToRemove)
2138         m_swappedProcessesPerRegistrableDomain.remove(registrableDomain);
2139 }
2140
2141 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)
2142 {
2143     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 {
2144         // We are process-swapping so automatic process prewarming would be beneficial if the client has not explicitly enabled / disabled it.
2145         bool doingAnAutomaticProcessSwap = processSwapRequestedByClient == ProcessSwapRequestedByClient::No && process.ptr() != sourceProcess.ptr();
2146         if (doingAnAutomaticProcessSwap && !configuration().wasAutomaticProcessWarmingSetByClient() && !configuration().clientWouldBenefitFromAutomaticProcessPrewarming()) {
2147             RELEASE_LOG(PerformanceLogging, "Automatically turning on process prewarming because the client would benefit from it");
2148             configuration().setClientWouldBenefitFromAutomaticProcessPrewarming(true);
2149         }
2150
2151         if (m_configuration->alwaysKeepAndReuseSwappedProcesses() && process.ptr() != sourceProcess.ptr()) {
2152             static std::once_flag onceFlag;
2153             std::call_once(onceFlag, [] {
2154                 WTFLogAlways("WARNING: The option to always keep swapped web processes alive is active. This is meant for debugging and testing only.");
2155             });
2156
2157             addProcessToOriginCacheSet(sourceProcess, sourceURL);
2158
2159             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());
2160         }
2161
2162         completionHandler(WTFMove(process), suspendedPage, reason);
2163     });
2164 }
2165
2166 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)
2167 {
2168     auto& targetURL = navigation.currentRequest().url();
2169     auto targetRegistrableDomain = WebCore::RegistrableDomain { targetURL };
2170
2171     auto createNewProcess = [this, protectedThis = makeRef(*this), page = makeRef(page), targetRegistrableDomain, dataStore = dataStore.copyRef()] () -> Ref<WebProcessProxy> {
2172         return processForRegistrableDomain(dataStore, page.ptr(), targetRegistrableDomain);
2173     };
2174
2175     if (usesSingleWebProcess())
2176         return completionHandler(WTFMove(sourceProcess), nullptr, "Single WebProcess mode is enabled"_s);
2177
2178     if (processSwapRequestedByClient == ProcessSwapRequestedByClient::Yes)
2179         return completionHandler(createNewProcess(), nullptr, "Process swap was requested by the client"_s);
2180
2181     if (!m_configuration->processSwapsOnNavigation())
2182         return completionHandler(WTFMove(sourceProcess), nullptr, "Feature is disabled"_s);
2183
2184     if (m_automationSession)
2185         return completionHandler(WTFMove(sourceProcess), nullptr, "An automation session is active"_s);
2186
2187     if (!sourceProcess->hasCommittedAnyProvisionalLoads()) {
2188         tryPrewarmWithDomainInformation(sourceProcess, targetRegistrableDomain);
2189         return completionHandler(WTFMove(sourceProcess), nullptr, "Process has not yet committed any provisional loads"_s);
2190     }
2191
2192     // FIXME: We should support process swap when a window has been opened via window.open() without 'noopener'.
2193     // The issue is that the opener has a handle to the WindowProxy.
2194     if (navigation.openedByDOMWithOpener() && !m_configuration->processSwapsOnWindowOpenWithOpener())
2195         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context been opened by DOM without 'noopener'"_s);
2196
2197     // FIXME: We should support process swap when a window has opened other windows via window.open.
2198     if (navigation.hasOpenedFrames())
2199         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context has opened other windows"_s);
2200
2201     if (auto* targetItem = navigation.targetItem()) {
2202         if (auto* suspendedPage = targetItem->suspendedPage()) {
2203             return suspendedPage->waitUntilReadyToUnsuspend([createNewProcess = WTFMove(createNewProcess), completionHandler = WTFMove(completionHandler)](SuspendedPageProxy* suspendedPage) mutable {
2204                 if (!suspendedPage)
2205                     return completionHandler(createNewProcess(), nullptr, "Using new process because target back/forward item's suspended page is not reusable"_s);
2206                 Ref<WebProcessProxy> process = suspendedPage->process();
2207                 completionHandler(WTFMove(process), suspendedPage, "Using target back/forward item's process and suspended page"_s);
2208             });
2209         }
2210
2211         if (RefPtr<WebProcessProxy> process = WebProcessProxy::processForIdentifier(targetItem->lastProcessIdentifier())) {
2212             if (process->state() != WebProcessProxy::State::Terminated) {
2213                 // Make sure we remove the process from the cache if it is in there since we're about to use it.
2214                 if (process->isInProcessCache()) {
2215                     webProcessCache().removeProcess(*process, WebProcessCache::ShouldShutDownProcess::No);
2216                     ASSERT(!process->isInProcessCache());
2217                 }
2218
2219                 return completionHandler(process.releaseNonNull(), nullptr, "Using target back/forward item's process"_s);
2220             }
2221         }
2222     }
2223
2224     if (navigation.treatAsSameOriginNavigation())
2225         return completionHandler(WTFMove(sourceProcess), nullptr, "The treatAsSameOriginNavigation flag is set"_s);
2226
2227     URL sourceURL;
2228     if (page.isPageOpenedByDOMShowingInitialEmptyDocument() && !navigation.requesterOrigin().isEmpty())
2229         sourceURL = URL { URL(), navigation.requesterOrigin().toString() };
2230     else
2231         sourceURL = pageSourceURL;
2232
2233     if (sourceURL.isEmpty() && page.configuration().relatedPage()) {
2234         sourceURL = URL { { }, page.configuration().relatedPage()->pageLoadState().url() };
2235         RELEASE_LOG(ProcessSwapping, "Using related page %p's URL as source URL for process swap decision", page.configuration().relatedPage());
2236     }
2237
2238     if (!sourceURL.isValid() || !targetURL.isValid() || sourceURL.isEmpty() || sourceURL.protocolIsAbout() || targetRegistrableDomain.matches(sourceURL))
2239         return completionHandler(WTFMove(sourceProcess), nullptr, "Navigation is same-site"_s);
2240
2241     String reason = "Navigation is cross-site"_s;
2242     
2243     if (m_configuration->alwaysKeepAndReuseSwappedProcesses()) {
2244         LOG(ProcessSwapping, "(ProcessSwapping) Considering re-use of a previously cached process for domain %s", targetRegistrableDomain.string().utf8().data());
2245
2246         if (auto* process = m_swappedProcessesPerRegistrableDomain.get(targetRegistrableDomain)) {
2247             if (&process->websiteDataStore() == dataStore.ptr()) {
2248                 LOG(ProcessSwapping, "(ProcessSwapping) Reusing a previously cached process with pid %i to continue navigation to URL %s", process->processIdentifier(), targetURL.string().utf8().data());
2249
2250                 return completionHandler(makeRef(*process), nullptr, reason);
2251             }
2252         }
2253     }
2254
2255     return completionHandler(createNewProcess(), nullptr, reason);
2256 }
2257
2258 void WebProcessPool::addMockMediaDevice(const MockMediaDevice& device)
2259 {
2260 #if ENABLE(MEDIA_STREAM)
2261     MockRealtimeMediaSourceCenter::addDevice(device);
2262     sendToAllProcesses(Messages::WebProcess::AddMockMediaDevice { device });
2263 #endif
2264 }
2265
2266 void WebProcessPool::clearMockMediaDevices()
2267 {
2268 #if ENABLE(MEDIA_STREAM)
2269     MockRealtimeMediaSourceCenter::setDevices({ });
2270     sendToAllProcesses(Messages::WebProcess::ClearMockMediaDevices { });
2271 #endif
2272 }
2273
2274 void WebProcessPool::removeMockMediaDevice(const String& persistentId)
2275 {
2276 #if ENABLE(MEDIA_STREAM)
2277     MockRealtimeMediaSourceCenter::removeDevice(persistentId);
2278     sendToAllProcesses(Messages::WebProcess::RemoveMockMediaDevice { persistentId });
2279 #endif
2280 }
2281
2282 void WebProcessPool::resetMockMediaDevices()
2283 {
2284 #if ENABLE(MEDIA_STREAM)
2285     MockRealtimeMediaSourceCenter::resetDevices();
2286     sendToAllProcesses(Messages::WebProcess::ResetMockMediaDevices { });
2287 #endif
2288 }
2289
2290 void WebProcessPool::sendDisplayConfigurationChangedMessageForTesting()
2291 {
2292 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
2293     auto display = CGSMainDisplayID();
2294
2295     for (auto& processPool : WebProcessPool::allProcessPools()) {
2296         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplayBeginConfigurationFlag));
2297         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplaySetModeFlag | kCGDisplayDesktopShapeChangedFlag));
2298     }
2299 #endif
2300 }
2301
2302 void WebProcessPool::didCollectPrewarmInformation(const WebCore::RegistrableDomain& registrableDomain, const WebCore::PrewarmInformation& prewarmInformation)
2303 {
2304     static const size_t maximumSizeToPreventUnlimitedGrowth = 100;
2305     if (m_prewarmInformationPerRegistrableDomain.size() == maximumSizeToPreventUnlimitedGrowth)
2306         m_prewarmInformationPerRegistrableDomain.remove(m_prewarmInformationPerRegistrableDomain.random());
2307
2308     auto& value = m_prewarmInformationPerRegistrableDomain.ensure(registrableDomain, [] {
2309         return makeUnique<WebCore::PrewarmInformation>();
2310     }).iterator->value;
2311
2312     *value = prewarmInformation;
2313 }
2314
2315 void WebProcessPool::tryPrewarmWithDomainInformation(WebProcessProxy& process, const RegistrableDomain& registrableDomain)
2316 {
2317     auto* prewarmInformation = m_prewarmInformationPerRegistrableDomain.get(registrableDomain);
2318     if (!prewarmInformation)
2319         return;
2320     process.send(Messages::WebProcess::PrewarmWithDomainInformation(*prewarmInformation), 0);
2321 }
2322
2323 void WebProcessPool::clearCurrentModifierStateForTesting()
2324 {
2325     sendToAllProcesses(Messages::WebProcess::ClearCurrentModifierStateForTesting());
2326 }
2327
2328 #if ENABLE(RESOURCE_LOAD_STATISTICS)
2329 void WebProcessPool::didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID sessionID, const RegistrableDomain& fromDomain, const RegistrableDomain& toDomain, OptionSet<CrossSiteNavigationDataTransfer::Flag> navigationDataTransfer, WebPageProxyIdentifier webPageProxyID, PageIdentifier webPageID)
2330 {
2331     if (!m_networkProcess)
2332         return;
2333
2334     m_networkProcess->didCommitCrossSiteLoadWithDataTransfer(sessionID, fromDomain, toDomain, navigationDataTransfer, webPageProxyID, webPageID);
2335 }
2336 #endif
2337
2338 void WebProcessPool::setWebProcessHasUploads(ProcessIdentifier processID)
2339 {
2340     ASSERT(processID);
2341     auto* process = WebProcessProxy::processForIdentifier(processID);
2342     ASSERT(process);
2343
2344     if (!process)
2345         return;
2346
2347     RELEASE_LOG(ProcessSuspension, "Web process pid %u now has uploads in progress", (unsigned)process->processIdentifier());
2348
2349     if (m_processesWithUploads.isEmpty()) {
2350         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now one. Taking Networking and UI process assertions.");
2351
2352         ASSERT(m_networkProcess);
2353         m_networkProcess->takeUploadAssertion();
2354         
2355         ASSERT(!m_uiProcessUploadAssertion);
2356         m_uiProcessUploadAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2357     }
2358     
2359     auto result = m_processesWithUploads.add(processID, nullptr);
2360     ASSERT(result.isNewEntry);
2361     result.iterator->value = makeUnique<ProcessAssertion>(process->processIdentifier(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2362 }
2363
2364 void WebProcessPool::clearWebProcessHasUploads(ProcessIdentifier processID)
2365 {
2366     ASSERT(processID);
2367     auto result = m_processesWithUploads.take(processID);
2368     if (!result)
2369         return;
2370
2371     auto* process = WebProcessProxy::processForIdentifier(processID);
2372     ASSERT_UNUSED(process, process);
2373     RELEASE_LOG(ProcessSuspension, "Web process pid %u no longer has uploads in progress", (unsigned)process->processIdentifier());
2374
2375     if (m_processesWithUploads.isEmpty()) {
2376         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now zero. Releasing Networking and UI process assertions.");
2377
2378         if (m_networkProcess)
2379             m_networkProcess->clearUploadAssertion();
2380         
2381         ASSERT(m_uiProcessUploadAssertion);
2382         m_uiProcessUploadAssertion = nullptr;
2383     }
2384     
2385 }
2386
2387 void WebProcessPool::setWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier processID)
2388 {
2389     auto* process = WebProcessProxy::processForIdentifier(processID);
2390     ASSERT(process);
2391
2392     RELEASE_LOG(ProcessSuspension, "Web process pid %u is now playing audible media", (unsigned)process->processIdentifier());
2393
2394     if (m_processesPlayingAudibleMedia.isEmpty()) {
2395         RELEASE_LOG(ProcessSuspension, "The number of processes playing audible media is now one. Taking UI process assertion.");
2396
2397         ASSERT(!m_uiProcessMediaPlaybackAssertion);
2398         m_uiProcessMediaPlaybackAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit Media Playback"_s, AssertionState::Foreground, AssertionReason::MediaPlayback);
2399     }
2400
2401     auto result = m_processesPlayingAudibleMedia.add(processID, nullptr);
2402     ASSERT(result.isNewEntry);
2403     result.iterator->value = makeUnique<ProcessAssertion>(process->processIdentifier(), "WebKit Media Playback"_s, AssertionState::Foreground, AssertionReason::MediaPlayback);
2404 }
2405
2406 void WebProcessPool::clearWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier processID)
2407 {
2408     auto result = m_processesPlayingAudibleMedia.take(processID);
2409     ASSERT_UNUSED(result, result);
2410
2411     auto* process = WebProcessProxy::processForIdentifier(processID);
2412     ASSERT_UNUSED(process, process);
2413
2414     RELEASE_LOG(ProcessSuspension, "Web process pid %u is no longer playing audible media", (unsigned)process->processIdentifier());
2415
2416     if (m_processesPlayingAudibleMedia.isEmpty()) {
2417         RELEASE_LOG(ProcessSuspension, "The number of processes playing audible media now zero. Releasing UI process assertion.");
2418
2419         ASSERT(m_uiProcessMediaPlaybackAssertion);
2420         m_uiProcessMediaPlaybackAssertion = nullptr;
2421     }
2422 }
2423
2424 } // namespace WebKit