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