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