f19d22d792150f0069b7123214522f9a9b729bf9
[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.shouldUseTestingNetworkSession = m_shouldUseTestingNetworkSession;
539
540     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
541     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
542     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
543     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
544     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
545     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
546     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
547
548 #if ENABLE(INDEXED_DATABASE)
549     // *********
550     // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>)
551     // *********
552     parameters.defaultDataStoreParameters.indexedDatabaseDirectory = m_configuration->indexedDBDatabaseDirectory();
553     if (parameters.defaultDataStoreParameters.indexedDatabaseDirectory.isEmpty())
554         parameters.defaultDataStoreParameters.indexedDatabaseDirectory = API::WebsiteDataStore::defaultDataStore()->websiteDataStore().parameters().indexedDatabaseDirectory;
555     
556     SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.indexedDatabaseDirectory, parameters.defaultDataStoreParameters.indexedDatabaseDirectoryExtensionHandle);
557     m_networkProcess->createSymLinkForFileUpgrade(parameters.defaultDataStoreParameters.indexedDatabaseDirectory);
558 #endif
559
560 #if ENABLE(SERVICE_WORKER)
561     if (m_websiteDataStore)
562         parameters.serviceWorkerRegistrationDirectory = m_websiteDataStore->websiteDataStore().resolvedServiceWorkerRegistrationDirectory();
563     if (!parameters.serviceWorkerRegistrationDirectory)
564         parameters.serviceWorkerRegistrationDirectory =  API::WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
565     SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
566
567     if (!m_schemesServiceWorkersCanHandle.isEmpty())
568         parameters.urlSchemesServiceWorkersCanHandle = copyToVector(m_schemesServiceWorkersCanHandle);
569
570     parameters.shouldDisableServiceWorkerProcessTerminationDelay = m_shouldDisableServiceWorkerProcessTerminationDelay;
571 #endif
572
573     if (m_websiteDataStore)
574         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = m_websiteDataStore->websiteDataStore().resolvedResourceLoadStatisticsDirectory();
575     if (parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory.isEmpty())
576         parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory = API::WebsiteDataStore::defaultResourceLoadStatisticsDirectory();
577
578     SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectory, parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsDirectoryExtensionHandle);
579
580     bool enableResourceLoadStatistics = false;
581     bool shouldIncludeLocalhost = true;
582     bool enableResourceLoadStatisticsDebugMode = false;
583     WebCore::RegistrableDomain manualPrevalentResource { };
584     if (withWebsiteDataStore) {
585         enableResourceLoadStatistics = withWebsiteDataStore->resourceLoadStatisticsEnabled();
586         if (enableResourceLoadStatistics) {
587             auto networkSessionParameters = withWebsiteDataStore->parameters().networkSessionParameters;
588             shouldIncludeLocalhost = networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics;
589             enableResourceLoadStatisticsDebugMode = networkSessionParameters.enableResourceLoadStatisticsDebugMode;
590             manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsManualPrevalentResource;
591         }
592
593         parameters.defaultDataStoreParameters.perOriginStorageQuota = withWebsiteDataStore->perOriginStorageQuota();
594         parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = withWebsiteDataStore->perThirdPartyOriginStorageQuota();
595     } else if (m_websiteDataStore) {
596         enableResourceLoadStatistics = m_websiteDataStore->resourceLoadStatisticsEnabled();
597         if (enableResourceLoadStatistics) {
598             auto networkSessionParameters = m_websiteDataStore->websiteDataStore().parameters().networkSessionParameters;
599             shouldIncludeLocalhost = networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics;
600             enableResourceLoadStatisticsDebugMode = networkSessionParameters.enableResourceLoadStatisticsDebugMode;
601             manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsManualPrevalentResource;
602         }
603
604         parameters.defaultDataStoreParameters.perOriginStorageQuota = m_websiteDataStore->websiteDataStore().perOriginStorageQuota();
605         parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = m_websiteDataStore->websiteDataStore().perThirdPartyOriginStorageQuota();
606     }
607
608     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatistics = enableResourceLoadStatistics;
609     parameters.defaultDataStoreParameters.networkSessionParameters.shouldIncludeLocalhostInResourceLoadStatistics = shouldIncludeLocalhost;
610     parameters.defaultDataStoreParameters.networkSessionParameters.enableResourceLoadStatisticsDebugMode = enableResourceLoadStatisticsDebugMode;
611     parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsManualPrevalentResource = manualPrevalentResource;
612
613     // Add any platform specific parameters
614     platformInitializeNetworkProcess(parameters);
615
616     // Initialize the network process.
617     m_networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0);
618
619     if (WebPreferences::anyPagesAreUsingPrivateBrowsing())
620         m_networkProcess->send(Messages::NetworkProcess::AddWebsiteDataStore(WebsiteDataStoreParameters::legacyPrivateSessionParameters()), 0);
621
622 #if PLATFORM(COCOA)
623     m_networkProcess->send(Messages::NetworkProcess::SetQOS(networkProcessLatencyQOS(), networkProcessThroughputQOS()), 0);
624 #endif
625
626     if (m_didNetworkProcessCrash) {
627         m_didNetworkProcessCrash = false;
628         reinstateNetworkProcessAssertionState(*m_networkProcess);
629     }
630
631     if (withWebsiteDataStore) {
632         m_networkProcess->addSession(makeRef(*withWebsiteDataStore));
633         withWebsiteDataStore->clearPendingCookies();
634     }
635
636     // Make sure the network process knows about all the sessions that have been registered before it started.
637     for (auto& sessionID : m_sessionToPageIDsMap.keys()) {
638         if (auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID))
639             m_networkProcess->addSession(*websiteDataStore);
640     }
641
642     return *m_networkProcess;
643 }
644
645 void WebProcessPool::networkProcessCrashed(NetworkProcessProxy& networkProcessProxy, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&& pendingReplies)
646 {
647     ASSERT(m_networkProcess);
648     ASSERT(&networkProcessProxy == m_networkProcess.get());
649     m_didNetworkProcessCrash = true;
650
651     for (auto& supplement : m_supplements.values())
652         supplement->processDidClose(&networkProcessProxy);
653
654     m_client.networkProcessDidCrash(this);
655
656     if (m_automationSession)
657         m_automationSession->terminate();
658
659     // Leave the process proxy around during client call, so that the client could query the process identifier.
660     m_networkProcess = nullptr;
661
662     // Attempt to re-launch.
663     if (pendingReplies.isEmpty())
664         return;
665     auto& newNetworkProcess = ensureNetworkProcess();
666     for (auto& reply : pendingReplies)
667         newNetworkProcess.getNetworkProcessConnection(*reply.first, WTFMove(reply.second));
668 }
669
670 void WebProcessPool::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
671 {
672     ensureNetworkProcess();
673     ASSERT(m_networkProcess);
674
675     m_networkProcess->getNetworkProcessConnection(webProcessProxy, WTFMove(reply));
676 }
677
678 #if ENABLE(SERVICE_WORKER)
679 void WebProcessPool::establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy& proxy, RegistrableDomain&& registrableDomain, Optional<PAL::SessionID> sessionID)
680 {
681     ASSERT_UNUSED(proxy, &proxy == m_networkProcess.get());
682
683     if (m_serviceWorkerProcesses.contains(registrableDomain))
684         return;
685
686     m_mayHaveRegisteredServiceWorkers.clear();
687
688     WebsiteDataStore* websiteDataStore = nullptr;
689     if (sessionID)
690         websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(*sessionID);
691
692     if (!websiteDataStore) {
693         if (!m_websiteDataStore)
694             m_websiteDataStore = API::WebsiteDataStore::defaultDataStore().ptr();
695         websiteDataStore = &m_websiteDataStore->websiteDataStore();
696     }
697
698     if (m_serviceWorkerProcesses.isEmpty())
699         sendToAllProcesses(Messages::WebProcess::RegisterServiceWorkerClients { });
700
701     auto serviceWorkerProcessProxy = ServiceWorkerProcessProxy::create(*this, registrableDomain, *websiteDataStore);
702     m_serviceWorkerProcesses.add(WTFMove(registrableDomain), serviceWorkerProcessProxy.ptr());
703
704     updateProcessAssertions();
705     initializeNewWebProcess(serviceWorkerProcessProxy, websiteDataStore);
706
707     auto* serviceWorkerProcessProxyPtr = serviceWorkerProcessProxy.ptr();
708     m_processes.append(WTFMove(serviceWorkerProcessProxy));
709
710     serviceWorkerProcessProxyPtr->start(m_serviceWorkerPreferences ? m_serviceWorkerPreferences.value() : m_defaultPageGroup->preferences().store(), sessionID);
711     if (!m_serviceWorkerUserAgent.isNull())
712         serviceWorkerProcessProxyPtr->setUserAgent(m_serviceWorkerUserAgent);
713 }
714 #endif
715
716 void WebProcessPool::disableServiceWorkerProcessTerminationDelay()
717 {
718 #if ENABLE(SERVICE_WORKER)
719     if (m_shouldDisableServiceWorkerProcessTerminationDelay)
720         return;
721
722     m_shouldDisableServiceWorkerProcessTerminationDelay = true;
723     if (m_networkProcess)
724         m_networkProcess->send(Messages::NetworkProcess::DisableServiceWorkerProcessTerminationDelay(), 0);
725 #endif
726 }
727
728 void WebProcessPool::willStartUsingPrivateBrowsing()
729 {
730     for (auto* processPool : allProcessPools())
731         processPool->setAnyPageGroupMightHavePrivateBrowsingEnabled(true);
732 }
733
734 void WebProcessPool::willStopUsingPrivateBrowsing()
735 {
736     for (auto* processPool : allProcessPools())
737         processPool->setAnyPageGroupMightHavePrivateBrowsingEnabled(false);
738 }
739
740 void WebProcessPool::windowServerConnectionStateChanged()
741 {
742     size_t processCount = m_processes.size();
743     for (size_t i = 0; i < processCount; ++i)
744         m_processes[i]->windowServerConnectionStateChanged();
745 }
746
747 void WebProcessPool::setAnyPageGroupMightHavePrivateBrowsingEnabled(bool privateBrowsingEnabled)
748 {
749     if (privateBrowsingEnabled) {
750         ensureNetworkProcess().send(Messages::NetworkProcess::AddWebsiteDataStore(WebsiteDataStoreParameters::legacyPrivateSessionParameters()), 0);
751     } else {
752         if (auto* networkProcess = this->networkProcess())
753             networkProcess->removeSession(PAL::SessionID::legacyPrivateSessionID());
754     }
755 }
756
757 void (*s_invalidMessageCallback)(WKStringRef messageName);
758
759 void WebProcessPool::setInvalidMessageCallback(void (*invalidMessageCallback)(WKStringRef messageName))
760 {
761     s_invalidMessageCallback = invalidMessageCallback;
762 }
763
764 void WebProcessPool::didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName)
765 {
766     if (!s_invalidMessageCallback)
767         return;
768
769     StringBuilder messageNameStringBuilder;
770     messageNameStringBuilder.append(messageReceiverName.data(), messageReceiverName.size());
771     messageNameStringBuilder.append('.');
772     messageNameStringBuilder.append(messageName.data(), messageName.size());
773
774     s_invalidMessageCallback(toAPI(API::String::create(messageNameStringBuilder.toString()).ptr()));
775 }
776
777 void WebProcessPool::processDidCachePage(WebProcessProxy* process)
778 {
779     if (m_processWithPageCache && m_processWithPageCache != process)
780         m_processWithPageCache->releasePageCache();
781     m_processWithPageCache = process;
782 }
783
784 void WebProcessPool::resolvePathsForSandboxExtensions()
785 {
786     m_resolvedPaths.injectedBundlePath = resolvePathForSandboxExtension(injectedBundlePath());
787     m_resolvedPaths.applicationCacheDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->applicationCacheDirectory());
788     m_resolvedPaths.webSQLDatabaseDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->webSQLDatabaseDirectory());
789     m_resolvedPaths.mediaCacheDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->mediaCacheDirectory());
790     m_resolvedPaths.mediaKeyStorageDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->mediaKeysStorageDirectory());
791     m_resolvedPaths.indexedDatabaseDirectory = resolveAndCreateReadWriteDirectoryForSandboxExtension(m_configuration->indexedDBDatabaseDirectory());
792
793     m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.reserveCapacity(m_configuration->additionalReadAccessAllowedPaths().size());
794     for (const auto& path : m_configuration->additionalReadAccessAllowedPaths())
795         m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.uncheckedAppend(resolvePathForSandboxExtension(path.data()));
796
797     platformResolvePathsForSandboxExtensions();
798 }
799
800 WebProcessProxy& WebProcessPool::createNewWebProcess(WebsiteDataStore* websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
801 {
802     auto processProxy = WebProcessProxy::create(*this, websiteDataStore, isPrewarmed);
803     auto& process = processProxy.get();
804     initializeNewWebProcess(process, websiteDataStore, isPrewarmed);
805     m_processes.append(WTFMove(processProxy));
806
807     if (m_serviceWorkerProcessesTerminationTimer.isActive())
808         m_serviceWorkerProcessesTerminationTimer.stop();
809
810     return process;
811 }
812
813 RefPtr<WebProcessProxy> WebProcessPool::tryTakePrewarmedProcess(WebsiteDataStore& websiteDataStore)
814 {
815     if (!m_prewarmedProcess)
816         return nullptr;
817
818     ASSERT(m_prewarmedProcess->isPrewarmed());
819     m_prewarmedProcess->markIsNoLongerInPrewarmedPool();
820
821     m_prewarmedProcess->setWebsiteDataStore(websiteDataStore);
822     sendWebProcessDataStoreParameters(*m_prewarmedProcess, websiteDataStore);
823
824     return std::exchange(m_prewarmedProcess, nullptr);
825 }
826
827 #if PLATFORM(MAC)
828 static void displayReconfigurationCallBack(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *userInfo)
829 {
830     auto screenProperties = WebCore::collectScreenProperties();
831     for (auto& processPool : WebProcessPool::allProcessPools()) {
832         processPool->sendToAllProcesses(Messages::WebProcess::SetScreenProperties(screenProperties));
833 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
834         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, flags));
835 #endif
836     }
837 }
838
839 static void registerDisplayConfigurationCallback()
840 {
841     static std::once_flag onceFlag;
842     std::call_once(
843         onceFlag,
844         [] {
845             CGDisplayRegisterReconfigurationCallback(displayReconfigurationCallBack, nullptr);
846         });
847 }
848 #endif
849
850 void WebProcessPool::sendWebProcessDataStoreParameters(WebProcessProxy& process, WebsiteDataStore& websiteDataStore)
851 {
852     WebProcessDataStoreParameters parameters;
853
854     websiteDataStore.resolveDirectoriesIfNecessary();
855
856     parameters.applicationCacheDirectory = websiteDataStore.resolvedApplicationCacheDirectory();
857     if (parameters.applicationCacheDirectory.isEmpty())
858         parameters.applicationCacheDirectory = m_resolvedPaths.applicationCacheDirectory;
859     if (!parameters.applicationCacheDirectory.isEmpty())
860         SandboxExtension::createHandleWithoutResolvingPath(parameters.applicationCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.applicationCacheDirectoryExtensionHandle);
861     parameters.applicationCacheFlatFileSubdirectoryName = m_configuration->applicationCacheFlatFileSubdirectoryName();
862
863     parameters.webSQLDatabaseDirectory = websiteDataStore.resolvedDatabaseDirectory();
864     if (parameters.webSQLDatabaseDirectory.isEmpty())
865         parameters.webSQLDatabaseDirectory = m_resolvedPaths.webSQLDatabaseDirectory;
866     if (!parameters.webSQLDatabaseDirectory.isEmpty())
867         SandboxExtension::createHandleWithoutResolvingPath(parameters.webSQLDatabaseDirectory, SandboxExtension::Type::ReadWrite, parameters.webSQLDatabaseDirectoryExtensionHandle);
868
869     parameters.mediaCacheDirectory = websiteDataStore.resolvedMediaCacheDirectory();
870     if (parameters.mediaCacheDirectory.isEmpty())
871         parameters.mediaCacheDirectory = m_resolvedPaths.mediaCacheDirectory;
872     if (!parameters.mediaCacheDirectory.isEmpty())
873         SandboxExtension::createHandleWithoutResolvingPath(parameters.mediaCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.mediaCacheDirectoryExtensionHandle);
874
875     parameters.mediaKeyStorageDirectory = websiteDataStore.resolvedMediaKeysDirectory();
876     if (parameters.mediaKeyStorageDirectory.isEmpty())
877         parameters.mediaKeyStorageDirectory = m_resolvedPaths.mediaKeyStorageDirectory;
878     if (!parameters.mediaKeyStorageDirectory.isEmpty())
879         SandboxExtension::createHandleWithoutResolvingPath(parameters.mediaKeyStorageDirectory, SandboxExtension::Type::ReadWrite, parameters.mediaKeyStorageDirectoryExtensionHandle);
880
881     if (javaScriptConfigurationFileEnabled()) {
882         parameters.javaScriptConfigurationDirectory = websiteDataStore.resolvedJavaScriptConfigurationDirectory();
883         if (!parameters.javaScriptConfigurationDirectory.isEmpty())
884             SandboxExtension::createHandleWithoutResolvingPath(parameters.javaScriptConfigurationDirectory, SandboxExtension::Type::ReadWrite, parameters.javaScriptConfigurationDirectoryExtensionHandle);
885     }
886
887     parameters.resourceLoadStatisticsEnabled = websiteDataStore.resourceLoadStatisticsEnabled();
888
889     process.send(Messages::WebProcess::SetWebsiteDataStoreParameters(parameters), 0);
890 }
891
892 void WebProcessPool::initializeNewWebProcess(WebProcessProxy& process, WebsiteDataStore* websiteDataStore, WebProcessProxy::IsPrewarmed isPrewarmed)
893 {
894     auto initializationActivityToken = process.throttler().backgroundActivityToken();
895     auto scopeExit = makeScopeExit([&process, initializationActivityToken] {
896         // Round-trip to the Web Content process before releasing the
897         // initialization activity token, so that we're sure that all
898         // messages sent from this function have been handled.
899         process.isResponsive([initializationActivityToken] (bool) { });
900     });
901
902     ensureNetworkProcess();
903
904     WebProcessCreationParameters parameters;
905
906     parameters.injectedBundlePath = m_resolvedPaths.injectedBundlePath;
907     if (!parameters.injectedBundlePath.isEmpty())
908         SandboxExtension::createHandleWithoutResolvingPath(parameters.injectedBundlePath, SandboxExtension::Type::ReadOnly, parameters.injectedBundlePathExtensionHandle);
909
910     parameters.additionalSandboxExtensionHandles.allocate(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size());
911     for (size_t i = 0, size = m_resolvedPaths.additionalWebProcessSandboxExtensionPaths.size(); i < size; ++i)
912         SandboxExtension::createHandleWithoutResolvingPath(m_resolvedPaths.additionalWebProcessSandboxExtensionPaths[i], SandboxExtension::Type::ReadOnly, parameters.additionalSandboxExtensionHandles[i]);
913
914 #if PLATFORM(IOS_FAMILY)
915     setJavaScriptConfigurationFileEnabledFromDefaults();
916 #endif
917
918     parameters.cacheModel = cacheModel();
919     parameters.languages = configuration().overrideLanguages().isEmpty() ? userPreferredLanguages() : configuration().overrideLanguages();
920
921     parameters.urlSchemesRegisteredAsEmptyDocument = copyToVector(m_schemesToRegisterAsEmptyDocument);
922     parameters.urlSchemesRegisteredAsSecure = copyToVector(m_schemesToRegisterAsSecure);
923     parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(m_schemesToRegisterAsBypassingContentSecurityPolicy);
924     parameters.urlSchemesForWhichDomainRelaxationIsForbidden = copyToVector(m_schemesToSetDomainRelaxationForbiddenFor);
925     parameters.urlSchemesRegisteredAsLocal = copyToVector(m_schemesToRegisterAsLocal);
926     parameters.urlSchemesRegisteredAsNoAccess = copyToVector(m_schemesToRegisterAsNoAccess);
927     parameters.urlSchemesRegisteredAsDisplayIsolated = copyToVector(m_schemesToRegisterAsDisplayIsolated);
928     parameters.urlSchemesRegisteredAsCORSEnabled = copyToVector(m_schemesToRegisterAsCORSEnabled);
929     parameters.urlSchemesRegisteredAsAlwaysRevalidated = copyToVector(m_schemesToRegisterAsAlwaysRevalidated);
930     parameters.urlSchemesRegisteredAsCachePartitioned = copyToVector(m_schemesToRegisterAsCachePartitioned);
931     parameters.urlSchemesServiceWorkersCanHandle = copyToVector(m_schemesServiceWorkersCanHandle);
932     parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest = copyToVector(m_schemesToRegisterAsCanDisplayOnlyIfCanRequest);
933
934     parameters.shouldAlwaysUseComplexTextCodePath = m_alwaysUsesComplexTextCodePath;
935     parameters.shouldUseFontSmoothing = m_shouldUseFontSmoothing;
936
937     parameters.terminationTimeout = 0_s;
938
939     parameters.textCheckerState = TextChecker::state();
940
941     parameters.fullKeyboardAccessEnabled = WebProcessProxy::fullKeyboardAccessEnabled();
942
943     parameters.defaultRequestTimeoutInterval = API::URLRequest::defaultTimeoutInterval();
944
945 #if ENABLE(NOTIFICATIONS)
946     // FIXME: There should be a generic way for supplements to add to the intialization parameters.
947     parameters.notificationPermissions = supplement<WebNotificationManagerProxy>()->notificationPermissions();
948 #endif
949
950     parameters.plugInAutoStartOriginHashes = m_plugInAutoStartProvider.autoStartOriginHashesCopy();
951     parameters.plugInAutoStartOrigins = copyToVector(m_plugInAutoStartProvider.autoStartOrigins());
952
953     parameters.memoryCacheDisabled = m_memoryCacheDisabled;
954     parameters.attrStyleEnabled = m_configuration->attrStyleEnabled();
955
956 #if ENABLE(SERVICE_CONTROLS)
957     auto& serviceController = ServicesController::singleton();
958     parameters.hasImageServices = serviceController.hasImageServices();
959     parameters.hasSelectionServices = serviceController.hasSelectionServices();
960     parameters.hasRichContentServices = serviceController.hasRichContentServices();
961     serviceController.refreshExistingServices();
962 #endif
963
964 #if ENABLE(NETSCAPE_PLUGIN_API)
965     parameters.pluginLoadClientPolicies = m_pluginLoadClientPolicies;
966 #endif
967
968 #if OS(LINUX)
969     parameters.shouldEnableMemoryPressureReliefLogging = true;
970 #endif
971
972 #if PLATFORM(WAYLAND) && USE(EGL)
973     if (PlatformDisplay::sharedDisplay().type() == PlatformDisplay::Type::Wayland)
974         parameters.waylandCompositorDisplayName = WaylandCompositor::singleton().displayName();
975 #endif
976
977 #if ENABLE(MEDIA_STREAM)
978     parameters.shouldCaptureAudioInUIProcess = m_configuration->shouldCaptureAudioInUIProcess();
979     parameters.shouldCaptureVideoInUIProcess = m_configuration->shouldCaptureVideoInUIProcess();
980     parameters.shouldCaptureDisplayInUIProcess = m_configuration->shouldCaptureDisplayInUIProcess();
981 #endif
982
983     parameters.presentingApplicationPID = m_configuration->presentingApplicationPID();
984
985 #if PLATFORM(COCOA)
986     parameters.mediaMIMETypes = process.mediaMIMETypes();
987 #endif
988
989 #if PLATFORM(WPE)
990     parameters.isServiceWorkerProcess = process.isServiceWorkerProcess();
991 #endif
992
993     // Add any platform specific parameters
994     platformInitializeWebProcess(parameters);
995
996     RefPtr<API::Object> injectedBundleInitializationUserData = m_injectedBundleClient->getInjectedBundleInitializationUserData(*this);
997     if (!injectedBundleInitializationUserData)
998         injectedBundleInitializationUserData = m_injectedBundleInitializationUserData;
999     parameters.initializationUserData = UserData(process.transformObjectsToHandles(injectedBundleInitializationUserData.get()));
1000
1001     process.send(Messages::WebProcess::InitializeWebProcess(parameters), 0);
1002
1003 #if PLATFORM(COCOA)
1004     process.send(Messages::WebProcess::SetQOS(webProcessLatencyQOS(), webProcessThroughputQOS()), 0);
1005 #endif
1006
1007     if (websiteDataStore)
1008         sendWebProcessDataStoreParameters(process, *websiteDataStore);
1009
1010     if (m_automationSession)
1011         process.send(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()), 0);
1012
1013     ASSERT(m_messagesToInjectedBundlePostedToEmptyContext.isEmpty());
1014
1015     if (isPrewarmed == WebProcessProxy::IsPrewarmed::Yes) {
1016         ASSERT(!m_prewarmedProcess);
1017         m_prewarmedProcess = &process;
1018         process.send(Messages::WebProcess::PrewarmGlobally(), 0);
1019     }
1020
1021 #if PLATFORM(IOS)
1022     process.send(Messages::WebProcess::BacklightLevelDidChange(displayBrightness()), 0);
1023 #endif
1024
1025 #if ENABLE(REMOTE_INSPECTOR)
1026     // Initialize remote inspector connection now that we have a sub-process that is hosting one of our web views.
1027     Inspector::RemoteInspector::singleton(); 
1028 #endif
1029
1030 #if PLATFORM(MAC)
1031     registerDisplayConfigurationCallback();
1032 #endif
1033 }
1034
1035 void WebProcessPool::prewarmProcess()
1036 {
1037     if (m_prewarmedProcess)
1038         return;
1039
1040     RELEASE_LOG(PerformanceLogging, "Prewarming a WebProcess for performance");
1041     createNewWebProcess(nullptr, WebProcessProxy::IsPrewarmed::Yes);
1042 }
1043
1044 void WebProcessPool::enableProcessTermination()
1045 {
1046     m_processTerminationEnabled = true;
1047     Vector<RefPtr<WebProcessProxy>> processes = m_processes;
1048     for (size_t i = 0; i < processes.size(); ++i) {
1049         if (shouldTerminate(processes[i].get()))
1050             processes[i]->terminate();
1051     }
1052 }
1053
1054 bool WebProcessPool::shouldTerminate(WebProcessProxy* process)
1055 {
1056     ASSERT(m_processes.contains(process));
1057
1058     if (!m_processTerminationEnabled || m_configuration->alwaysKeepAndReuseSwappedProcesses())
1059         return false;
1060
1061     return true;
1062 }
1063
1064 void WebProcessPool::processDidFinishLaunching(WebProcessProxy* process)
1065 {
1066     ASSERT(m_processes.contains(process));
1067
1068     if (!m_visitedLinksPopulated) {
1069         populateVisitedLinks();
1070         m_visitedLinksPopulated = true;
1071     }
1072
1073     // Sometimes the memorySampler gets initialized after process initialization has happened but before the process has finished launching
1074     // so check if it needs to be started here
1075     if (m_memorySamplerEnabled) {
1076         SandboxExtension::Handle sampleLogSandboxHandle;        
1077         WallTime now = WallTime::now();
1078         String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()), "pid", process->processIdentifier());
1079         sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1080         
1081         process->send(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, m_memorySamplerInterval), 0);
1082     }
1083
1084     if (m_configuration->fullySynchronousModeIsAllowedForTesting())
1085         process->connection()->allowFullySynchronousModeForTesting();
1086
1087     if (m_configuration->ignoreSynchronousMessagingTimeoutsForTesting())
1088         process->connection()->ignoreTimeoutsForTesting();
1089
1090     m_connectionClient.didCreateConnection(this, process->webConnection());
1091
1092     if (m_websiteDataStore)
1093         m_websiteDataStore->websiteDataStore().didCreateNetworkProcess();
1094 }
1095
1096 void WebProcessPool::disconnectProcess(WebProcessProxy* process)
1097 {
1098     ASSERT(m_processes.contains(process));
1099
1100     if (m_prewarmedProcess == process) {
1101         ASSERT(m_prewarmedProcess->isPrewarmed());
1102         m_prewarmedProcess = nullptr;
1103     }
1104
1105     if (m_dummyProcessProxy == process)
1106         m_dummyProcessProxy = nullptr;
1107
1108     // 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.
1109     // Clearing everything causes assertion failures, so it's less trouble to skip that for now.
1110     RefPtr<WebProcessProxy> protect(process);
1111     if (m_processWithPageCache == process)
1112         m_processWithPageCache = nullptr;
1113
1114     m_suspendedPages.removeAllMatching([process](auto& suspendedPage) {
1115         return &suspendedPage->process() == process;
1116     });
1117
1118 #if ENABLE(SERVICE_WORKER)
1119     if (is<ServiceWorkerProcessProxy>(*process)) {
1120         auto* removedProcess = m_serviceWorkerProcesses.take(downcast<ServiceWorkerProcessProxy>(*process).registrableDomain());
1121         ASSERT_UNUSED(removedProcess, removedProcess == process);
1122         updateProcessAssertions();
1123     }
1124 #endif
1125
1126     static_cast<WebContextSupplement*>(supplement<WebGeolocationManagerProxy>())->processDidClose(process);
1127
1128     m_processes.removeFirst(process);
1129
1130 #if ENABLE(GAMEPAD)
1131     if (m_processesUsingGamepads.contains(process))
1132         processStoppedUsingGamepads(*process);
1133 #endif
1134
1135     removeProcessFromOriginCacheSet(*process);
1136
1137 #if ENABLE(SERVICE_WORKER)
1138     // FIXME: We should do better than this. For now, we just destroy the ServiceWorker process
1139     // whenever there is no regular WebContent process remaining.
1140     if (m_processes.size() == m_serviceWorkerProcesses.size()) {
1141         if (!m_serviceWorkerProcessesTerminationTimer.isActive())
1142             m_serviceWorkerProcessesTerminationTimer.startOneShot(serviceWorkerTerminationDelay);
1143     }
1144 #endif
1145 }
1146
1147 WebProcessProxy& WebProcessPool::processForRegistrableDomain(WebsiteDataStore& websiteDataStore, WebPageProxy* page, const RegistrableDomain& registrableDomain)
1148 {
1149     if (!registrableDomain.isEmpty()) {
1150         if (auto process = webProcessCache().takeProcess(registrableDomain, websiteDataStore))
1151             return *process;
1152
1153         // Check if we have a suspended page for the given registrable domain and use its process if we do, for performance reasons.
1154         if (auto process = page ? findReusableSuspendedPageProcess(registrableDomain, *page, websiteDataStore) : nullptr) {
1155             RELEASE_LOG(ProcessSwapping, "Using WebProcess %i from a SuspendedPage", process->processIdentifier());
1156             return *process;
1157         }
1158     }
1159
1160     if (auto process = tryTakePrewarmedProcess(websiteDataStore)) {
1161         RELEASE_LOG(ProcessSwapping, "Using prewarmed process %i", process->processIdentifier());
1162         if (!registrableDomain.isEmpty())
1163             tryPrewarmWithDomainInformation(*process, registrableDomain);
1164         return *process;
1165     }
1166
1167     if (!usesSingleWebProcess())
1168         return createNewWebProcess(&websiteDataStore);
1169
1170 #if PLATFORM(COCOA)
1171     bool mustMatchDataStore = API::WebsiteDataStore::defaultDataStoreExists() && &websiteDataStore != &API::WebsiteDataStore::defaultDataStore()->websiteDataStore();
1172 #else
1173     bool mustMatchDataStore = false;
1174 #endif
1175
1176     for (auto& process : m_processes) {
1177         if (process == m_prewarmedProcess || process == m_dummyProcessProxy)
1178             continue;
1179 #if ENABLE(SERVICE_WORKER)
1180         if (is<ServiceWorkerProcessProxy>(*process))
1181             continue;
1182 #endif
1183         if (mustMatchDataStore && &process->websiteDataStore() != &websiteDataStore)
1184             continue;
1185         return *process;
1186     }
1187     return createNewWebProcess(&websiteDataStore);
1188 }
1189
1190 Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API::PageConfiguration>&& pageConfiguration)
1191 {
1192     if (!pageConfiguration->pageGroup())
1193         pageConfiguration->setPageGroup(m_defaultPageGroup.ptr());
1194     if (!pageConfiguration->preferences())
1195         pageConfiguration->setPreferences(&pageConfiguration->pageGroup()->preferences());
1196     if (!pageConfiguration->userContentController())
1197         pageConfiguration->setUserContentController(&pageConfiguration->pageGroup()->userContentController());
1198     if (!pageConfiguration->visitedLinkStore())
1199         pageConfiguration->setVisitedLinkStore(m_visitedLinkStore.ptr());
1200
1201     if (!pageConfiguration->websiteDataStore()) {
1202         // We try to avoid creating the default data store as long as possible.
1203         // But if there is an attempt to create a web page without any specified data store, then we have to create it.
1204         if (!m_websiteDataStore)
1205             m_websiteDataStore = API::WebsiteDataStore::defaultDataStore().ptr();
1206
1207         ASSERT(!pageConfiguration->sessionID().isValid());
1208         pageConfiguration->setWebsiteDataStore(m_websiteDataStore.get());
1209         pageConfiguration->setSessionID(pageConfiguration->preferences()->privateBrowsingEnabled() ? PAL::SessionID::legacyPrivateSessionID() : m_websiteDataStore->websiteDataStore().sessionID());
1210     }
1211
1212     RefPtr<WebProcessProxy> process;
1213     if (pageConfiguration->relatedPage()) {
1214         // Sharing processes, e.g. when creating the page via window.open().
1215         process = &pageConfiguration->relatedPage()->process();
1216         // We do not support several WebsiteDataStores sharing a single process.
1217         ASSERT(process.get() == m_dummyProcessProxy || &pageConfiguration->websiteDataStore()->websiteDataStore() == &process->websiteDataStore());
1218         ASSERT(&pageConfiguration->relatedPage()->websiteDataStore() == &pageConfiguration->websiteDataStore()->websiteDataStore());
1219     } else if (!m_isDelayedWebProcessLaunchDisabled) {
1220         // In the common case, we delay process launch until something is actually loaded in the page.
1221         if (!m_dummyProcessProxy) {
1222             auto dummyProcessProxy = WebProcessProxy::create(*this, nullptr, WebProcessProxy::IsPrewarmed::No, WebProcessProxy::ShouldLaunchProcess::No);
1223             m_dummyProcessProxy = dummyProcessProxy.ptr();
1224             m_processes.append(WTFMove(dummyProcessProxy));
1225         }
1226         process = m_dummyProcessProxy;
1227     } else
1228         process = &processForRegistrableDomain(pageConfiguration->websiteDataStore()->websiteDataStore(), nullptr, { });
1229
1230     ASSERT(process);
1231
1232     auto page = process->createWebPage(pageClient, WTFMove(pageConfiguration));
1233
1234 #if ENABLE(SERVICE_WORKER)
1235     ASSERT(!is<ServiceWorkerProcessProxy>(*process));
1236
1237     if (!m_serviceWorkerPreferences) {
1238         m_serviceWorkerPreferences = page->preferencesStore();
1239         for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1240             serviceWorkerProcess->updatePreferencesStore(*m_serviceWorkerPreferences);
1241     }
1242 #endif
1243
1244     bool enableProcessSwapOnCrossSiteNavigation = page->preferences().processSwapOnCrossSiteNavigationEnabled();
1245 #if PLATFORM(IOS_FAMILY)
1246     if (WebCore::IOSApplication::isFirefox() && !linkedOnOrAfter(WebKit::SDKVersion::FirstWithProcessSwapOnCrossSiteNavigation))
1247         enableProcessSwapOnCrossSiteNavigation = false;
1248 #endif
1249
1250     bool wasProcessSwappingOnNavigationEnabled = m_configuration->processSwapsOnNavigation();
1251     m_configuration->setProcessSwapsOnNavigationFromExperimentalFeatures(enableProcessSwapOnCrossSiteNavigation);
1252     if (wasProcessSwappingOnNavigationEnabled != m_configuration->processSwapsOnNavigation())
1253         m_webProcessCache->updateCapacity(*this);
1254
1255     m_configuration->setShouldCaptureAudioInUIProcess(page->preferences().captureAudioInUIProcessEnabled());
1256     m_configuration->setShouldCaptureVideoInUIProcess(page->preferences().captureVideoInUIProcessEnabled());
1257
1258     return page;
1259 }
1260
1261 #if ENABLE(SERVICE_WORKER)
1262 void WebProcessPool::updateServiceWorkerUserAgent(const String& userAgent)
1263 {
1264     if (m_serviceWorkerUserAgent == userAgent)
1265         return;
1266     m_serviceWorkerUserAgent = userAgent;
1267     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values())
1268         serviceWorkerProcess->setUserAgent(m_serviceWorkerUserAgent);
1269 }
1270
1271 bool WebProcessPool::mayHaveRegisteredServiceWorkers(const WebsiteDataStore& store)
1272 {
1273     if (!m_serviceWorkerProcesses.isEmpty())
1274         return true;
1275
1276     String serviceWorkerRegistrationDirectory = store.resolvedServiceWorkerRegistrationDirectory();
1277     if (serviceWorkerRegistrationDirectory.isEmpty())
1278         serviceWorkerRegistrationDirectory = API::WebsiteDataStore::defaultDataStoreConfiguration()->serviceWorkerRegistrationDirectory();
1279
1280     return m_mayHaveRegisteredServiceWorkers.ensure(serviceWorkerRegistrationDirectory, [&] {
1281         // FIXME: Make this computation on a background thread.
1282         return ServiceWorkerProcessProxy::hasRegisteredServiceWorkers(serviceWorkerRegistrationDirectory);
1283     }).iterator->value;
1284 }
1285 #endif
1286
1287 void WebProcessPool::pageBeginUsingWebsiteDataStore(uint64_t pageID, WebsiteDataStore& dataStore)
1288 {
1289     auto result = m_sessionToPageIDsMap.add(dataStore.sessionID(), HashSet<uint64_t>()).iterator->value.add(pageID);
1290     ASSERT_UNUSED(result, result.isNewEntry);
1291
1292     auto sessionID = dataStore.sessionID();
1293     if (sessionID.isEphemeral()) {
1294         ASSERT(dataStore.parameters().networkSessionParameters.sessionID == sessionID);
1295         if (m_networkProcess) {
1296             m_networkProcess->addSession(makeRef(dataStore));
1297             dataStore.clearPendingCookies();
1298         }
1299     } else if (sessionID != PAL::SessionID::defaultSessionID()) {
1300         if (m_networkProcess) {
1301             m_networkProcess->addSession(makeRef(dataStore));
1302             dataStore.clearPendingCookies();
1303         }
1304     }
1305 }
1306
1307 void WebProcessPool::pageEndUsingWebsiteDataStore(uint64_t pageID, WebsiteDataStore& dataStore)
1308 {
1309     auto sessionID = dataStore.sessionID();
1310     auto iterator = m_sessionToPageIDsMap.find(sessionID);
1311     ASSERT(iterator != m_sessionToPageIDsMap.end());
1312
1313     auto takenPageID = iterator->value.take(pageID);
1314     ASSERT_UNUSED(takenPageID, takenPageID == pageID);
1315
1316     if (iterator->value.isEmpty()) {
1317         m_sessionToPageIDsMap.remove(iterator);
1318
1319         if (sessionID == PAL::SessionID::defaultSessionID())
1320             return;
1321
1322         // The last user of this non-default PAL::SessionID is gone, so clean it up in the child processes.
1323         if (networkProcess())
1324             networkProcess()->removeSession(sessionID);
1325
1326         m_webProcessCache->clearAllProcessesForSession(sessionID);
1327     }
1328 }
1329
1330 bool WebProcessPool::hasPagesUsingWebsiteDataStore(WebsiteDataStore& dataStore) const
1331 {
1332     return m_sessionToPageIDsMap.contains(dataStore.sessionID());
1333 }
1334
1335 DownloadProxy& WebProcessPool::download(WebPageProxy* initiatingPage, const ResourceRequest& request, const String& suggestedFilename)
1336 {
1337     auto& downloadProxy = createDownloadProxy(request, initiatingPage);
1338     PAL::SessionID sessionID = initiatingPage ? initiatingPage->sessionID() : PAL::SessionID::defaultSessionID();
1339
1340     if (initiatingPage)
1341         initiatingPage->handleDownloadRequest(downloadProxy);
1342
1343     if (networkProcess()) {
1344         ResourceRequest updatedRequest(request);
1345         // Request's firstPartyForCookies will be used as Original URL of the download request.
1346         // We set the value to top level document's URL.
1347         if (initiatingPage) {
1348             URL initiatingPageURL = URL { URL { }, initiatingPage->pageLoadState().url() };
1349             updatedRequest.setFirstPartyForCookies(initiatingPageURL);
1350             updatedRequest.setIsSameSite(areRegistrableDomainsEqual(initiatingPageURL, request.url()));
1351             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1352                 updatedRequest.setHTTPUserAgent(initiatingPage->userAgent());
1353         } else {
1354             updatedRequest.setFirstPartyForCookies(URL());
1355             updatedRequest.setIsSameSite(false);
1356             if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
1357                 updatedRequest.setHTTPUserAgent(WebPageProxy::standardUserAgent());
1358         }
1359         updatedRequest.setIsTopSite(false);
1360         networkProcess()->send(Messages::NetworkProcess::DownloadRequest(sessionID, downloadProxy.downloadID(), updatedRequest, suggestedFilename), 0);
1361         return downloadProxy;
1362     }
1363
1364     return downloadProxy;
1365 }
1366
1367 DownloadProxy& WebProcessPool::resumeDownload(WebPageProxy* initiatingPage, const API::Data* resumeData, const String& path)
1368 {
1369     auto& downloadProxy = createDownloadProxy(ResourceRequest(), initiatingPage);
1370     PAL::SessionID sessionID = initiatingPage ? initiatingPage->sessionID() : PAL::SessionID::defaultSessionID();
1371
1372     SandboxExtension::Handle sandboxExtensionHandle;
1373     if (!path.isEmpty())
1374         SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, sandboxExtensionHandle);
1375
1376     if (networkProcess()) {
1377         networkProcess()->send(Messages::NetworkProcess::ResumeDownload(sessionID, downloadProxy.downloadID(), resumeData->dataReference(), path, sandboxExtensionHandle), 0);
1378         return downloadProxy;
1379     }
1380
1381     return downloadProxy;
1382 }
1383
1384 void WebProcessPool::postMessageToInjectedBundle(const String& messageName, API::Object* messageBody)
1385 {
1386     for (auto& process : m_processes) {
1387         // FIXME: Return early if the message body contains any references to WKPageRefs/WKFrameRefs etc. since they're local to a process.
1388         process->send(Messages::WebProcess::HandleInjectedBundleMessage(messageName, UserData(process->transformObjectsToHandles(messageBody).get())), 0);
1389     }
1390 }
1391
1392 void WebProcessPool::didReachGoodTimeToPrewarm()
1393 {
1394     if (!configuration().isAutomaticProcessWarmingEnabled() || !configuration().processSwapsOnNavigation() || usesSingleWebProcess())
1395         return;
1396
1397     if (MemoryPressureHandler::singleton().isUnderMemoryPressure()) {
1398         if (!m_prewarmedProcess)
1399             RELEASE_LOG(PerformanceLogging, "Not automatically prewarming a WebProcess due to memory pressure");
1400         return;
1401     }
1402
1403     prewarmProcess();
1404 }
1405
1406 void WebProcessPool::populateVisitedLinks()
1407 {
1408     m_historyClient->populateVisitedLinks(*this);
1409 }
1410
1411 WebProcessPool::Statistics& WebProcessPool::statistics()
1412 {
1413     static Statistics statistics = Statistics();
1414
1415     return statistics;
1416 }
1417
1418 void WebProcessPool::handleMemoryPressureWarning(Critical)
1419 {
1420     RELEASE_LOG(PerformanceLogging, "%p - WebProcessPool::handleMemoryPressureWarning", this);
1421
1422
1423     clearSuspendedPages(AllowProcessCaching::No);
1424     m_webProcessCache->clear();
1425
1426     if (m_prewarmedProcess)
1427         m_prewarmedProcess->shutDown();
1428     ASSERT(!m_prewarmedProcess);
1429 }
1430
1431 #if ENABLE(NETSCAPE_PLUGIN_API)
1432 void WebProcessPool::setAdditionalPluginsDirectory(const String& directory)
1433 {
1434     Vector<String> directories;
1435     directories.append(directory);
1436
1437     m_pluginInfoStore.setAdditionalPluginsDirectories(directories);
1438 }
1439
1440 void WebProcessPool::refreshPlugins()
1441 {
1442     m_pluginInfoStore.refresh();
1443     sendToAllProcesses(Messages::WebProcess::RefreshPlugins());
1444 }
1445
1446 #endif // ENABLE(NETSCAPE_PLUGIN_API)
1447
1448 ProcessID WebProcessPool::networkProcessIdentifier()
1449 {
1450     return m_networkProcess ? m_networkProcess->processIdentifier() : 0;
1451 }
1452
1453 ProcessID WebProcessPool::prewarmedProcessIdentifier()
1454 {
1455     return m_prewarmedProcess ? m_prewarmedProcess->processIdentifier() : 0;
1456 }
1457
1458 void WebProcessPool::activePagesOriginsInWebProcessForTesting(ProcessID pid, CompletionHandler<void(Vector<String>&&)>&& completionHandler)
1459 {
1460     for (auto& process : m_processes) {
1461         if (process->processIdentifier() == pid)
1462             return process->activePagesDomainsForTesting(WTFMove(completionHandler));
1463     }
1464     completionHandler({ });
1465 }
1466
1467 void WebProcessPool::setAlwaysUsesComplexTextCodePath(bool alwaysUseComplexText)
1468 {
1469     m_alwaysUsesComplexTextCodePath = alwaysUseComplexText;
1470     sendToAllProcesses(Messages::WebProcess::SetAlwaysUsesComplexTextCodePath(alwaysUseComplexText));
1471 }
1472
1473 void WebProcessPool::setShouldUseFontSmoothing(bool useFontSmoothing)
1474 {
1475     m_shouldUseFontSmoothing = useFontSmoothing;
1476     sendToAllProcesses(Messages::WebProcess::SetShouldUseFontSmoothing(useFontSmoothing));
1477 }
1478
1479 void WebProcessPool::setResourceLoadStatisticsEnabled(bool enabled)
1480 {
1481     sendToAllProcesses(Messages::WebProcess::SetResourceLoadStatisticsEnabled(enabled));
1482 }
1483
1484 void WebProcessPool::clearResourceLoadStatistics()
1485 {
1486     sendToAllProcesses(Messages::WebProcess::ClearResourceLoadStatistics());
1487 }
1488
1489 void WebProcessPool::registerURLSchemeAsEmptyDocument(const String& urlScheme)
1490 {
1491     m_schemesToRegisterAsEmptyDocument.add(urlScheme);
1492     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsEmptyDocument(urlScheme));
1493 }
1494
1495 void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme)
1496 {
1497     m_schemesToRegisterAsSecure.add(urlScheme);
1498     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
1499     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme));
1500 }
1501
1502 void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme)
1503 {
1504     m_schemesToRegisterAsBypassingContentSecurityPolicy.add(urlScheme);
1505     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1506     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
1507 }
1508
1509 void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
1510 {
1511     m_schemesToSetDomainRelaxationForbiddenFor.add(urlScheme);
1512     sendToAllProcesses(Messages::WebProcess::SetDomainRelaxationForbiddenForURLScheme(urlScheme));
1513 }
1514
1515 void WebProcessPool::setCanHandleHTTPSServerTrustEvaluation(bool value)
1516 {
1517     m_canHandleHTTPSServerTrustEvaluation = value;
1518     if (m_networkProcess) {
1519         m_networkProcess->send(Messages::NetworkProcess::SetCanHandleHTTPSServerTrustEvaluation(value), 0);
1520         return;
1521     }
1522 }
1523
1524 void WebProcessPool::preconnectToServer(const URL& url)
1525 {
1526     if (!url.isValid() || !url.protocolIsInHTTPFamily())
1527         return;
1528
1529     ensureNetworkProcess().send(Messages::NetworkProcess::PreconnectTo(url, StoredCredentialsPolicy::Use), 0);
1530 }
1531
1532 void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme)
1533 {
1534     m_schemesToRegisterAsLocal.add(urlScheme);
1535     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme));
1536     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme));
1537 }
1538
1539 void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme)
1540 {
1541     m_schemesToRegisterAsNoAccess.add(urlScheme);
1542     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1543     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme));
1544 }
1545
1546 void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme)
1547 {
1548     m_schemesToRegisterAsDisplayIsolated.add(urlScheme);
1549     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1550     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsDisplayIsolated(urlScheme));
1551 }
1552
1553 void WebProcessPool::registerURLSchemeAsCORSEnabled(const String& urlScheme)
1554 {
1555     m_schemesToRegisterAsCORSEnabled.add(urlScheme);
1556     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1557     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCORSEnabled(urlScheme));
1558 }
1559
1560 void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1561 {
1562     if (!urlScheme)
1563         return;
1564
1565     globalURLSchemesWithCustomProtocolHandlers().add(urlScheme);
1566     for (auto* processPool : allProcessPools())
1567         processPool->registerSchemeForCustomProtocol(urlScheme);
1568 }
1569
1570 void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
1571 {
1572     if (!urlScheme)
1573         return;
1574
1575     globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme);
1576     for (auto* processPool : allProcessPools())
1577         processPool->unregisterSchemeForCustomProtocol(urlScheme);
1578 }
1579
1580 void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme)
1581 {
1582     m_schemesToRegisterAsCachePartitioned.add(urlScheme);
1583     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCachePartitioned(urlScheme));
1584 }
1585
1586 void WebProcessPool::registerURLSchemeServiceWorkersCanHandle(const String& urlScheme)
1587 {
1588     m_schemesServiceWorkersCanHandle.add(urlScheme);
1589     sendToAllProcesses(Messages::AuxiliaryProcess::RegisterURLSchemeServiceWorkersCanHandle(urlScheme));
1590     if (m_networkProcess)
1591         m_networkProcess->send(Messages::AuxiliaryProcess::RegisterURLSchemeServiceWorkersCanHandle(urlScheme), 0);
1592 }
1593
1594 void WebProcessPool::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& urlScheme)
1595 {
1596     m_schemesToRegisterAsCanDisplayOnlyIfCanRequest.add(urlScheme);
1597     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1598     sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsCanDisplayOnlyIfCanRequest(urlScheme));
1599 }
1600
1601 void WebProcessPool::updateMaxSuspendedPageCount()
1602 {
1603     unsigned dummy = 0;
1604     Seconds dummyInterval;
1605     unsigned pageCacheSize = 0;
1606     calculateMemoryCacheSizes(m_configuration->cacheModel(), dummy, dummy, dummy, dummyInterval, pageCacheSize);
1607
1608     m_maxSuspendedPageCount = pageCacheSize;
1609
1610     while (m_suspendedPages.size() > m_maxSuspendedPageCount)
1611         m_suspendedPages.removeFirst();
1612 }
1613
1614 void WebProcessPool::setCacheModel(CacheModel cacheModel)
1615 {
1616     m_configuration->setCacheModel(cacheModel);
1617     updateMaxSuspendedPageCount();
1618
1619     sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel));
1620
1621     if (m_networkProcess)
1622         m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel), 0);
1623 }
1624
1625 void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
1626 {
1627     sendToAllProcesses(Messages::WebProcess::SetDefaultRequestTimeoutInterval(timeoutInterval));
1628 }
1629
1630 DownloadProxy& WebProcessPool::createDownloadProxy(const ResourceRequest& request, WebPageProxy* originatingPage)
1631 {
1632     auto& downloadProxy = ensureNetworkProcess().createDownloadProxy(request);
1633     downloadProxy.setOriginatingPage(originatingPage);
1634     return downloadProxy;
1635 }
1636
1637 void WebProcessPool::synthesizeAppIsBackground(bool background)
1638 {
1639     ensureNetworkProcess().synthesizeAppIsBackground(background);
1640 }
1641
1642 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver)
1643 {
1644     m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
1645 }
1646
1647 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
1648 {
1649     m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
1650 }
1651
1652 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName)
1653 {
1654     m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
1655 }
1656
1657 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID)
1658 {
1659     m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
1660 }
1661
1662 bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
1663 {
1664     return m_messageReceiverMap.dispatchMessage(connection, decoder);
1665 }
1666
1667 bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
1668 {
1669     return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
1670 }
1671
1672 void WebProcessPool::setEnhancedAccessibility(bool flag)
1673 {
1674     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
1675 }
1676     
1677 void WebProcessPool::startMemorySampler(const double interval)
1678 {    
1679     // For new WebProcesses we will also want to start the Memory Sampler
1680     m_memorySamplerEnabled = true;
1681     m_memorySamplerInterval = interval;
1682     
1683     // For UIProcess
1684 #if ENABLE(MEMORY_SAMPLER)
1685     WebMemorySampler::singleton()->start(interval);
1686 #endif
1687     
1688     // For WebProcess
1689     SandboxExtension::Handle sampleLogSandboxHandle;    
1690     WallTime now = WallTime::now();
1691     String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()));
1692     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1693     
1694     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
1695 }
1696
1697 void WebProcessPool::stopMemorySampler()
1698 {    
1699     // For WebProcess
1700     m_memorySamplerEnabled = false;
1701     
1702     // For UIProcess
1703 #if ENABLE(MEMORY_SAMPLER)
1704     WebMemorySampler::singleton()->stop();
1705 #endif
1706
1707     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
1708 }
1709
1710 void WebProcessPool::useTestingNetworkSession()
1711 {
1712     ASSERT(m_processes.isEmpty());
1713     ASSERT(!m_networkProcess);
1714
1715     if (m_networkProcess)
1716         return;
1717
1718     if (!m_processes.isEmpty())
1719         return;
1720
1721     m_shouldUseTestingNetworkSession = true;
1722 }
1723
1724 template<typename T, typename U>
1725 void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
1726 {
1727     if (m_networkProcess && m_networkProcess->canSendMessage())
1728         m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
1729 }
1730
1731 void WebProcessPool::setAllowsAnySSLCertificateForWebSocket(bool allows)
1732 {
1733     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply());
1734 }
1735
1736 void WebProcessPool::clearCachedCredentials()
1737 {
1738     if (m_networkProcess)
1739         m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0);
1740 }
1741
1742 void WebProcessPool::terminateNetworkProcess()
1743 {
1744     if (!m_networkProcess)
1745         return;
1746     
1747     m_networkProcess->terminate();
1748     m_networkProcess = nullptr;
1749     m_didNetworkProcessCrash = true;
1750 }
1751
1752 void WebProcessPool::terminateServiceWorkerProcesses()
1753 {
1754 #if ENABLE(SERVICE_WORKER)
1755     auto protectedThis = makeRef(*this);
1756     while (!m_serviceWorkerProcesses.isEmpty())
1757         m_serviceWorkerProcesses.begin()->value->requestTermination(ProcessTerminationReason::RequestedByClient);
1758 #endif
1759 }
1760
1761 void WebProcessPool::syncNetworkProcessCookies()
1762 {
1763     ensureNetworkProcess().syncAllCookies();
1764 }
1765
1766 void WebProcessPool::setIDBPerOriginQuota(uint64_t quota)
1767 {
1768 #if ENABLE(INDEXED_DATABASE)
1769     ensureNetworkProcess().send(Messages::NetworkProcess::SetIDBPerOriginQuota(quota), 0);
1770 #endif
1771 }
1772
1773 void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
1774 {
1775     ensureNetworkProcess();
1776     m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
1777 }
1778
1779 void WebProcessPool::updateAutomationCapabilities() const
1780 {
1781 #if ENABLE(REMOTE_INSPECTOR)
1782     Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange();
1783 #endif
1784 }
1785
1786 void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession)
1787 {
1788     if (m_automationSession)
1789         m_automationSession->setProcessPool(nullptr);
1790     
1791     m_automationSession = WTFMove(automationSession);
1792
1793 #if ENABLE(REMOTE_INSPECTOR)
1794     if (m_automationSession) {
1795         m_automationSession->init();
1796         m_automationSession->setProcessPool(this);
1797
1798         sendToAllProcesses(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()));
1799     } else
1800         sendToAllProcesses(Messages::WebProcess::DestroyAutomationSessionProxy());
1801 #endif
1802 }
1803
1804 void WebProcessPool::setHTTPPipeliningEnabled(bool enabled)
1805 {
1806 #if PLATFORM(COCOA)
1807     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1808 #else
1809     UNUSED_PARAM(enabled);
1810 #endif
1811 }
1812
1813 bool WebProcessPool::httpPipeliningEnabled() const
1814 {
1815 #if PLATFORM(COCOA)
1816     return ResourceRequest::httpPipeliningEnabled();
1817 #else
1818     return false;
1819 #endif
1820 }
1821
1822 void WebProcessPool::getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&& callbackFunction)
1823 {
1824     if (!statisticsMask) {
1825         callbackFunction(nullptr, CallbackBase::Error::Unknown);
1826         return;
1827     }
1828
1829     auto request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction)));
1830
1831     if (statisticsMask & StatisticsRequestTypeWebContent)
1832         requestWebContentStatistics(request.get());
1833     
1834     if (statisticsMask & StatisticsRequestTypeNetworking)
1835         requestNetworkingStatistics(request.get());
1836 }
1837
1838 void WebProcessPool::requestWebContentStatistics(StatisticsRequest& request)
1839 {
1840     // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work.
1841 }
1842
1843 void WebProcessPool::requestNetworkingStatistics(StatisticsRequest& request)
1844 {
1845     if (!m_networkProcess) {
1846         LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable");
1847         return;
1848     }
1849
1850     uint64_t requestID = request.addOutstandingRequest();
1851     m_statisticsRequests.set(requestID, &request);
1852     m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0);
1853 }
1854
1855 static WebProcessProxy* webProcessProxyFromConnection(IPC::Connection& connection, const Vector<RefPtr<WebProcessProxy>>& processes)
1856 {
1857     for (auto& process : processes) {
1858         if (process->hasConnection(connection))
1859             return process.get();
1860     }
1861
1862     ASSERT_NOT_REACHED();
1863     return nullptr;
1864 }
1865
1866 void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
1867 {
1868     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1869     if (!webProcessProxy)
1870         return;
1871     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get());
1872 }
1873
1874 void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&& completionHandler)
1875 {
1876     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1877     if (!webProcessProxy)
1878         return completionHandler({ });
1879
1880     RefPtr<API::Object> returnData;
1881     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), returnData);
1882     completionHandler(UserData(webProcessProxy->transformObjectsToHandles(returnData.get())));
1883 }
1884
1885 void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID)
1886 {
1887     RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID);
1888     if (!request) {
1889         LOG_ERROR("Cannot report networking statistics.");
1890         return;
1891     }
1892
1893     request->completedRequest(requestID, statisticsData);
1894 }
1895
1896 #if ENABLE(GAMEPAD)
1897
1898 void WebProcessPool::startedUsingGamepads(IPC::Connection& connection)
1899 {
1900     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1901     if (!proxy)
1902         return;
1903
1904     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1905
1906     ASSERT(!m_processesUsingGamepads.contains(proxy));
1907     m_processesUsingGamepads.add(proxy);
1908
1909     if (!wereAnyProcessesUsingGamepads)
1910         UIGamepadProvider::singleton().processPoolStartedUsingGamepads(*this);
1911
1912     proxy->send(Messages::WebProcess::SetInitialGamepads(UIGamepadProvider::singleton().snapshotGamepads()), 0);
1913 }
1914
1915 void WebProcessPool::stoppedUsingGamepads(IPC::Connection& connection)
1916 {
1917     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1918     if (!proxy)
1919         return;
1920
1921     ASSERT(m_processesUsingGamepads.contains(proxy));
1922     processStoppedUsingGamepads(*proxy);
1923 }
1924
1925 void WebProcessPool::processStoppedUsingGamepads(WebProcessProxy& process)
1926 {
1927     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1928
1929     ASSERT(m_processesUsingGamepads.contains(&process));
1930     m_processesUsingGamepads.remove(&process);
1931
1932     if (wereAnyProcessesUsingGamepads && m_processesUsingGamepads.isEmpty())
1933         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
1934 }
1935
1936 void WebProcessPool::gamepadConnected(const UIGamepad& gamepad)
1937 {
1938     for (auto& process : m_processesUsingGamepads)
1939         process->send(Messages::WebProcess::GamepadConnected(gamepad.fullGamepadData()), 0);
1940 }
1941
1942 void WebProcessPool::gamepadDisconnected(const UIGamepad& gamepad)
1943 {
1944     for (auto& process : m_processesUsingGamepads)
1945         process->send(Messages::WebProcess::GamepadDisconnected(gamepad.index()), 0);
1946 }
1947
1948 void WebProcessPool::setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>& gamepads)
1949 {
1950     Vector<GamepadData> gamepadDatas;
1951     gamepadDatas.grow(gamepads.size());
1952     for (size_t i = 0; i < gamepads.size(); ++i) {
1953         if (!gamepads[i])
1954             continue;
1955         gamepadDatas[i] = gamepads[i]->fullGamepadData();
1956     }
1957
1958     for (auto& process : m_processesUsingGamepads)
1959         process->send(Messages::WebProcess::SetInitialGamepads(gamepadDatas), 0);
1960 }
1961
1962 #endif // ENABLE(GAMEPAD)
1963
1964 void WebProcessPool::setJavaScriptConfigurationFileEnabled(bool flag)
1965 {
1966     m_javaScriptConfigurationFileEnabled = flag;
1967 }
1968
1969 void WebProcessPool::garbageCollectJavaScriptObjects()
1970 {
1971     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1972 }
1973
1974 void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1975 {
1976     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1977 }
1978
1979 void WebProcessPool::addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID sessionID)
1980 {
1981     m_plugInAutoStartProvider.addAutoStartOriginHash(pageOrigin, plugInOriginHash, sessionID);
1982 }
1983
1984 void WebProcessPool::plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID sessionID)
1985 {
1986     m_plugInAutoStartProvider.didReceiveUserInteraction(plugInOriginHash, sessionID);
1987 }
1988
1989 Ref<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const
1990 {
1991     return m_plugInAutoStartProvider.autoStartOriginsTableCopy();
1992 }
1993
1994 void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary)
1995 {
1996     m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary);
1997 }
1998
1999 void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array)
2000 {
2001     m_plugInAutoStartProvider.setAutoStartOriginsArray(array);
2002 }
2003
2004 void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, WallTime time)
2005 {
2006     m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time);
2007 }
2008
2009 void WebProcessPool::registerSchemeForCustomProtocol(const String& scheme)
2010 {
2011 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
2012     if (!globalURLSchemesWithCustomProtocolHandlers().contains(scheme))
2013         m_urlSchemesRegisteredForCustomProtocols.add(scheme);
2014     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::RegisterScheme(scheme));
2015 #endif
2016 }
2017
2018 void WebProcessPool::unregisterSchemeForCustomProtocol(const String& scheme)
2019 {
2020 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
2021     m_urlSchemesRegisteredForCustomProtocols.remove(scheme);
2022     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::UnregisterScheme(scheme));
2023 #endif
2024 }
2025
2026 #if ENABLE(NETSCAPE_PLUGIN_API)
2027 void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString)
2028 {
2029     auto& policiesForHost = m_pluginLoadClientPolicies.ensure(host, [] { return HashMap<String, HashMap<String, uint8_t>>(); }).iterator->value;
2030     auto& versionsToPolicies = policiesForHost.ensure(bundleIdentifier, [] { return HashMap<String, uint8_t>(); }).iterator->value;
2031     versionsToPolicies.set(versionString, policy);
2032
2033     sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString));
2034 }
2035
2036 void WebProcessPool::resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&& pluginLoadClientPolicies)
2037 {
2038     m_pluginLoadClientPolicies = WTFMove(pluginLoadClientPolicies);
2039     sendToAllProcesses(Messages::WebProcess::ResetPluginLoadClientPolicies(m_pluginLoadClientPolicies));
2040 }
2041
2042 void WebProcessPool::clearPluginClientPolicies()
2043 {
2044     m_pluginLoadClientPolicies.clear();
2045     sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies());
2046 }
2047 #endif
2048
2049 void WebProcessPool::addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions)
2050 {
2051 #if ENABLE(NETSCAPE_PLUGIN_API)
2052     m_pluginInfoStore.addSupportedPlugin(WTFMove(matchingDomain), WTFMove(name), WTFMove(mimeTypes), WTFMove(extensions));
2053 #else
2054     UNUSED_PARAM(matchingDomain);
2055     UNUSED_PARAM(name);
2056     UNUSED_PARAM(mimeTypes);
2057     UNUSED_PARAM(extensions);
2058 #endif
2059 }
2060
2061 void WebProcessPool::clearSupportedPlugins()
2062 {
2063 #if ENABLE(NETSCAPE_PLUGIN_API)
2064     m_pluginInfoStore.clearSupportedPlugins();
2065 #endif
2066 }
2067
2068 void WebProcessPool::setMemoryCacheDisabled(bool disabled)
2069 {
2070     m_memoryCacheDisabled = disabled;
2071     sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled));
2072 }
2073
2074 void WebProcessPool::setFontWhitelist(API::Array* array)
2075 {
2076     m_fontWhitelist.clear();
2077     if (array) {
2078         for (size_t i = 0; i < array->size(); ++i) {
2079             if (API::String* font = array->at<API::String>(i))
2080                 m_fontWhitelist.append(font->string());
2081         }
2082     }
2083 }
2084
2085 void WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit()
2086 {
2087     // We're estimating an upper bound for a set of background timer fires for a page to be 200ms
2088     // (including all timer fires, all paging-in, and any resulting GC). To ensure this does not
2089     // result in more than 1% CPU load allow for one timer fire per 100x this duration.
2090     static int maximumTimerThrottlePerPageInMS = 200 * 100;
2091
2092     int limitInMilliseconds = maximumTimerThrottlePerPageInMS * m_hiddenPageThrottlingAutoIncreasesCounter.value();
2093     sendToAllProcesses(Messages::WebProcess::SetHiddenPageDOMTimerThrottlingIncreaseLimit(limitInMilliseconds));
2094 }
2095
2096 void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState)
2097 {
2098 #if PLATFORM(MAC)
2099     if (m_perActivityStateCPUUsageSampler)
2100         m_perActivityStateCPUUsageSampler->reportWebContentCPUTime(cpuTime, static_cast<WebCore::ActivityStateForCPUSampling>(activityState));
2101 #else
2102     UNUSED_PARAM(cpuTime);
2103     UNUSED_PARAM(activityState);
2104 #endif
2105 }
2106
2107 void WebProcessPool::updateProcessAssertions()
2108 {
2109 #if PLATFORM(IOS_FAMILY)
2110 #if ENABLE(SERVICE_WORKER)
2111     auto updateServiceWorkerProcessAssertion = [&] {
2112         if (!m_serviceWorkerProcesses.isEmpty() && m_foregroundWebProcessCounter.value()) {
2113             // FIXME: We can do better than this once we have process per origin.
2114             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2115                 auto& registrableDomain = serviceWorkerProcess->registrableDomain();
2116                 if (!m_foregroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2117                     m_foregroundTokensForServiceWorkerProcesses.add(registrableDomain, serviceWorkerProcess->throttler().foregroundActivityToken());
2118             }
2119             m_backgroundTokensForServiceWorkerProcesses.clear();
2120             return;
2121         }
2122         if (!m_serviceWorkerProcesses.isEmpty() && m_backgroundWebProcessCounter.value()) {
2123             // FIXME: We can do better than this once we have process per origin.
2124             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2125                 auto& registrableDomain = serviceWorkerProcess->registrableDomain();
2126                 if (!m_backgroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2127                     m_backgroundTokensForServiceWorkerProcesses.add(registrableDomain, serviceWorkerProcess->throttler().backgroundActivityToken());
2128             }
2129             m_foregroundTokensForServiceWorkerProcesses.clear();
2130             return;
2131         }
2132         m_foregroundTokensForServiceWorkerProcesses.clear();
2133         m_backgroundTokensForServiceWorkerProcesses.clear();
2134     };
2135     updateServiceWorkerProcessAssertion();
2136 #endif
2137
2138     auto updateNetworkProcessAssertion = [&] {
2139         auto& networkProcess = ensureNetworkProcess();
2140
2141         if (m_foregroundWebProcessCounter.value()) {
2142             if (!m_foregroundTokenForNetworkProcess) {
2143                 m_foregroundTokenForNetworkProcess = networkProcess.throttler().foregroundActivityToken();
2144                 networkProcess.sendProcessDidTransitionToForeground();
2145             }
2146             m_backgroundTokenForNetworkProcess = nullptr;
2147             return;
2148         }
2149         if (m_backgroundWebProcessCounter.value()) {
2150             if (!m_backgroundTokenForNetworkProcess) {
2151                 m_backgroundTokenForNetworkProcess = networkProcess.throttler().backgroundActivityToken();
2152                 networkProcess.sendProcessDidTransitionToBackground();
2153             }
2154             m_foregroundTokenForNetworkProcess = nullptr;
2155             return;
2156         }
2157         m_foregroundTokenForNetworkProcess = nullptr;
2158         m_backgroundTokenForNetworkProcess = nullptr;
2159     };
2160     updateNetworkProcessAssertion();
2161 #endif
2162 }
2163
2164 #if ENABLE(SERVICE_WORKER)
2165 void WebProcessPool::postMessageToServiceWorkerClient(const ServiceWorkerClientIdentifier& destination, MessageWithMessagePorts&& message, ServiceWorkerIdentifier source, const String& sourceOrigin)
2166 {
2167     sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::PostMessageToServiceWorkerClient(destination, WTFMove(message), source, sourceOrigin));
2168 }
2169
2170 void WebProcessPool::postMessageToServiceWorker(ServiceWorkerIdentifier destination, MessageWithMessagePorts&& message, const ServiceWorkerOrClientIdentifier& source, SWServerConnectionIdentifier connectionIdentifier)
2171 {
2172     sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::PostMessageToServiceWorker(destination, WTFMove(message), source, connectionIdentifier));
2173 }
2174 #endif
2175
2176 void WebProcessPool::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy)
2177 {
2178 #if PLATFORM(IOS_FAMILY)
2179     // The network process crashed; take new tokens for the new network process.
2180     if (m_backgroundTokenForNetworkProcess)
2181         m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken();
2182     else if (m_foregroundTokenForNetworkProcess)
2183         m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken();
2184 #else
2185     UNUSED_PARAM(newNetworkProcessProxy);
2186 #endif
2187 }
2188
2189 #if ENABLE(SERVICE_WORKER)
2190 ServiceWorkerProcessProxy* WebProcessPool::serviceWorkerProcessProxyFromPageID(uint64_t pageID) const
2191 {
2192     // FIXME: This is inefficient.
2193     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2194         if (serviceWorkerProcess->pageID() == pageID)
2195             return serviceWorkerProcess;
2196     }
2197     return nullptr;
2198 }
2199 #endif
2200
2201 void WebProcessPool::addProcessToOriginCacheSet(WebProcessProxy& process, const URL& url)
2202 {
2203     auto registrableDomain = WebCore::RegistrableDomain { url };
2204     auto result = m_swappedProcessesPerRegistrableDomain.add(registrableDomain, &process);
2205     if (!result.isNewEntry)
2206         result.iterator->value = &process;
2207
2208     LOG(ProcessSwapping, "(ProcessSwapping) Registrable domain %s just saved a cached process with pid %i", registrableDomain.string().utf8().data(), process.processIdentifier());
2209     if (!result.isNewEntry)
2210         LOG(ProcessSwapping, "(ProcessSwapping) Note: It already had one saved");
2211 }
2212
2213 void WebProcessPool::removeProcessFromOriginCacheSet(WebProcessProxy& process)
2214 {
2215     LOG(ProcessSwapping, "(ProcessSwapping) Removing process with pid %i from the origin cache set", process.processIdentifier());
2216
2217     // FIXME: This can be very inefficient as the number of remembered origins and processes grows
2218     Vector<WebCore::RegistrableDomain> registrableDomainsToRemove;
2219     for (auto entry : m_swappedProcessesPerRegistrableDomain) {
2220         if (entry.value == &process)
2221             registrableDomainsToRemove.append(entry.key);
2222     }
2223
2224     for (auto& registrableDomain : registrableDomainsToRemove)
2225         m_swappedProcessesPerRegistrableDomain.remove(registrableDomain);
2226 }
2227
2228 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)
2229 {
2230     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 {
2231         // We are process-swapping so automatic process prewarming would be beneficial if the client has not explicitly enabled / disabled it.
2232         bool doingAnAutomaticProcessSwap = processSwapRequestedByClient == ProcessSwapRequestedByClient::No && process.ptr() != sourceProcess.ptr();
2233         if (doingAnAutomaticProcessSwap && !configuration().wasAutomaticProcessWarmingSetByClient() && !configuration().clientWouldBenefitFromAutomaticProcessPrewarming()) {
2234             RELEASE_LOG(PerformanceLogging, "Automatically turning on process prewarming because the client would benefit from it");
2235             configuration().setClientWouldBenefitFromAutomaticProcessPrewarming(true);
2236         }
2237
2238         if (m_configuration->alwaysKeepAndReuseSwappedProcesses() && process.ptr() != sourceProcess.ptr()) {
2239             static std::once_flag onceFlag;
2240             std::call_once(onceFlag, [] {
2241                 WTFLogAlways("WARNING: The option to always keep swapped web processes alive is active. This is meant for debugging and testing only.");
2242             });
2243
2244             addProcessToOriginCacheSet(sourceProcess, sourceURL);
2245
2246             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());
2247         }
2248
2249         completionHandler(WTFMove(process), suspendedPage, reason);
2250     });
2251 }
2252
2253 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)
2254 {
2255     auto& targetURL = navigation.currentRequest().url();
2256     auto targetRegistrableDomain = WebCore::RegistrableDomain { targetURL };
2257
2258     auto createNewProcess = [this, protectedThis = makeRef(*this), page = makeRef(page), targetRegistrableDomain, dataStore = dataStore.copyRef()] () -> Ref<WebProcessProxy> {
2259         return processForRegistrableDomain(dataStore, page.ptr(), targetRegistrableDomain);
2260     };
2261
2262     if (usesSingleWebProcess())
2263         return completionHandler(WTFMove(sourceProcess), nullptr, "Single WebProcess mode is enabled"_s);
2264
2265     if (processSwapRequestedByClient == ProcessSwapRequestedByClient::Yes)
2266         return completionHandler(createNewProcess(), nullptr, "Process swap was requested by the client"_s);
2267
2268     if (!m_configuration->processSwapsOnNavigation())
2269         return completionHandler(WTFMove(sourceProcess), nullptr, "Feature is disabled"_s);
2270
2271     if (m_automationSession)
2272         return completionHandler(WTFMove(sourceProcess), nullptr, "An automation session is active"_s);
2273
2274     if (!sourceProcess->hasCommittedAnyProvisionalLoads()) {
2275         tryPrewarmWithDomainInformation(sourceProcess, targetRegistrableDomain);
2276         return completionHandler(WTFMove(sourceProcess), nullptr, "Process has not yet committed any provisional loads"_s);
2277     }
2278
2279     // FIXME: We should support process swap when a window has been opened via window.open() without 'noopener'.
2280     // The issue is that the opener has a handle to the WindowProxy.
2281     if (navigation.openedByDOMWithOpener() && !m_configuration->processSwapsOnWindowOpenWithOpener())
2282         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context been opened by DOM without 'noopener'"_s);
2283
2284     // FIXME: We should support process swap when a window has opened other windows via window.open.
2285     if (navigation.hasOpenedFrames())
2286         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context has opened other windows"_s);
2287
2288     if (auto* targetItem = navigation.targetItem()) {
2289         if (auto* suspendedPage = targetItem->suspendedPage()) {
2290             return suspendedPage->waitUntilReadyToUnsuspend([createNewProcess = WTFMove(createNewProcess), completionHandler = WTFMove(completionHandler)](SuspendedPageProxy* suspendedPage) mutable {
2291                 if (!suspendedPage)
2292                     return completionHandler(createNewProcess(), nullptr, "Using new process because target back/forward item's suspended page is not reusable"_s);
2293                 Ref<WebProcessProxy> process = suspendedPage->process();
2294                 completionHandler(WTFMove(process), suspendedPage, "Using target back/forward item's process and suspended page"_s);
2295             });
2296         }
2297
2298         if (RefPtr<WebProcessProxy> process = WebProcessProxy::processForIdentifier(targetItem->lastProcessIdentifier())) {
2299             if (process->state() != WebProcessProxy::State::Terminated) {
2300                 // FIXME: Architecturally we do not currently support multiple WebPage's with the same ID in a given WebProcess.
2301                 // In the case where this WebProcess has a SuspendedPageProxy for this WebPage, we can throw it away to support
2302                 // WebProcess re-use.
2303                 removeAllSuspendedPagesForPage(page, process.get());
2304
2305                 // Make sure we remove the process from the cache if it is in there since we're about to use it.
2306                 if (process->isInProcessCache()) {
2307                     webProcessCache().removeProcess(*process, WebProcessCache::ShouldShutDownProcess::No);
2308                     ASSERT(!process->isInProcessCache());
2309                 }
2310
2311                 return completionHandler(process.releaseNonNull(), nullptr, "Using target back/forward item's process"_s);
2312             }
2313         }
2314     }
2315
2316     if (navigation.treatAsSameOriginNavigation())
2317         return completionHandler(WTFMove(sourceProcess), nullptr, "The treatAsSameOriginNavigation flag is set"_s);
2318
2319     URL sourceURL;
2320     if (page.isPageOpenedByDOMShowingInitialEmptyDocument() && !navigation.requesterOrigin().isEmpty())
2321         sourceURL = URL { URL(), navigation.requesterOrigin().toString() };
2322     else
2323         sourceURL = pageSourceURL;
2324
2325     if (sourceURL.isEmpty() && page.configuration().relatedPage()) {
2326         sourceURL = URL { { }, page.configuration().relatedPage()->pageLoadState().url() };
2327         RELEASE_LOG(ProcessSwapping, "Using related page %p's URL as source URL for process swap decision", page.configuration().relatedPage());
2328     }
2329
2330     if (!sourceURL.isValid() || !targetURL.isValid() || sourceURL.isEmpty() || sourceURL.protocolIsAbout() || targetRegistrableDomain.matches(sourceURL))
2331         return completionHandler(WTFMove(sourceProcess), nullptr, "Navigation is same-site"_s);
2332
2333     String reason = "Navigation is cross-site"_s;
2334     
2335     if (m_configuration->alwaysKeepAndReuseSwappedProcesses()) {
2336         LOG(ProcessSwapping, "(ProcessSwapping) Considering re-use of a previously cached process for domain %s", targetRegistrableDomain.string().utf8().data());
2337
2338         if (auto* process = m_swappedProcessesPerRegistrableDomain.get(targetRegistrableDomain)) {
2339             if (&process->websiteDataStore() == dataStore.ptr()) {
2340                 LOG(ProcessSwapping, "(ProcessSwapping) Reusing a previously cached process with pid %i to continue navigation to URL %s", process->processIdentifier(), targetURL.string().utf8().data());
2341
2342                 // FIXME: Architecturally we do not currently support multiple WebPage's with the same ID in a given WebProcess.
2343                 // In the case where this WebProcess has a SuspendedPageProxy for this WebPage, we can throw it away to support
2344                 // WebProcess re-use.
2345                 // In the future it would be great to refactor-out this limitation (https://bugs.webkit.org/show_bug.cgi?id=191166).
2346                 removeAllSuspendedPagesForPage(page, process);
2347
2348                 return completionHandler(makeRef(*process), nullptr, reason);
2349             }
2350         }
2351     }
2352
2353     return completionHandler(createNewProcess(), nullptr, reason);
2354 }
2355
2356 RefPtr<WebProcessProxy> WebProcessPool::findReusableSuspendedPageProcess(const WebCore::RegistrableDomain& registrableDomain, WebPageProxy& page, WebsiteDataStore& dataStore)
2357 {
2358     auto it = m_suspendedPages.findIf([&](auto& suspendedPage) {
2359         return suspendedPage->process().registrableDomain() == registrableDomain && &suspendedPage->process().websiteDataStore() == &dataStore;
2360     });
2361     if (it == m_suspendedPages.end())
2362         return nullptr;
2363
2364     Ref<WebProcessProxy> process = (*it)->process();
2365
2366     // FIXME: If the SuspendedPage is for this page, then we need to destroy the suspended page as we do not support having
2367     // multiple WebPages with the same ID in a given WebProcess currently (https://bugs.webkit.org/show_bug.cgi?id=191166).
2368     if (&(*it)->page() == &page)
2369         m_suspendedPages.remove(it);
2370
2371
2372     return process;
2373 }
2374
2375 void WebProcessPool::addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&& suspendedPage)
2376 {
2377     if (!m_maxSuspendedPageCount)
2378         return;
2379
2380     if (m_suspendedPages.size() >= m_maxSuspendedPageCount)
2381         m_suspendedPages.removeFirst();
2382
2383     m_suspendedPages.append(WTFMove(suspendedPage));
2384 }
2385
2386 void WebProcessPool::removeAllSuspendedPagesForPage(WebPageProxy& page, WebProcessProxy* process)
2387 {
2388     m_suspendedPages.removeAllMatching([&page, process](auto& suspendedPage) {
2389         return &suspendedPage->page() == &page && (!process || &suspendedPage->process() == process);
2390     });
2391 }
2392
2393 void WebProcessPool::closeFailedSuspendedPagesForPage(WebPageProxy& page)
2394 {
2395     for (auto& suspendedPage : m_suspendedPages) {
2396         if (&suspendedPage->page() == &page && suspendedPage->failedToSuspend())
2397             suspendedPage->close();
2398     }
2399 }
2400
2401 std::unique_ptr<SuspendedPageProxy> WebProcessPool::takeSuspendedPage(SuspendedPageProxy& suspendedPage)
2402 {
2403     return m_suspendedPages.takeFirst([&suspendedPage](auto& item) {
2404         return item.get() == &suspendedPage;
2405     });
2406 }
2407
2408 void WebProcessPool::removeSuspendedPage(SuspendedPageProxy& suspendedPage)
2409 {
2410     auto it = m_suspendedPages.findIf([&suspendedPage](auto& item) {
2411         return item.get() == &suspendedPage;
2412     });
2413     if (it != m_suspendedPages.end())
2414         m_suspendedPages.remove(it);
2415 }
2416
2417 bool WebProcessPool::hasSuspendedPageFor(WebProcessProxy& process, WebPageProxy& page) const
2418 {
2419     return m_suspendedPages.findIf([&process, &page](auto& suspendedPage) {
2420         return &suspendedPage->process() == &process && &suspendedPage->page() == &page;
2421     }) != m_suspendedPages.end();
2422 }
2423
2424 void WebProcessPool::clearSuspendedPages(AllowProcessCaching allowProcessCaching)
2425 {
2426     HashSet<RefPtr<WebProcessProxy>> processes;
2427     for (auto& suspendedPage : m_suspendedPages)
2428         processes.add(&suspendedPage->process());
2429
2430     m_suspendedPages.clear();
2431
2432     for (auto& process : processes)
2433         process->maybeShutDown(allowProcessCaching);
2434 }
2435
2436 void WebProcessPool::addMockMediaDevice(const MockMediaDevice& device)
2437 {
2438 #if ENABLE(MEDIA_STREAM)
2439     MockRealtimeMediaSourceCenter::addDevice(device);
2440     sendToAllProcesses(Messages::WebProcess::AddMockMediaDevice { device });
2441 #endif
2442 }
2443
2444 void WebProcessPool::clearMockMediaDevices()
2445 {
2446 #if ENABLE(MEDIA_STREAM)
2447     MockRealtimeMediaSourceCenter::setDevices({ });
2448     sendToAllProcesses(Messages::WebProcess::ClearMockMediaDevices { });
2449 #endif
2450 }
2451
2452 void WebProcessPool::removeMockMediaDevice(const String& persistentId)
2453 {
2454 #if ENABLE(MEDIA_STREAM)
2455     MockRealtimeMediaSourceCenter::removeDevice(persistentId);
2456     sendToAllProcesses(Messages::WebProcess::RemoveMockMediaDevice { persistentId });
2457 #endif
2458 }
2459
2460 void WebProcessPool::resetMockMediaDevices()
2461 {
2462 #if ENABLE(MEDIA_STREAM)
2463     MockRealtimeMediaSourceCenter::resetDevices();
2464     sendToAllProcesses(Messages::WebProcess::ResetMockMediaDevices { });
2465 #endif
2466 }
2467
2468 void WebProcessPool::sendDisplayConfigurationChangedMessageForTesting()
2469 {
2470 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
2471     auto display = CGSMainDisplayID();
2472
2473     for (auto& processPool : WebProcessPool::allProcessPools()) {
2474         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplayBeginConfigurationFlag));
2475         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplaySetModeFlag | kCGDisplayDesktopShapeChangedFlag));
2476     }
2477 #endif
2478 }
2479
2480 void WebProcessPool::didCollectPrewarmInformation(const WebCore::RegistrableDomain& registrableDomain, const WebCore::PrewarmInformation& prewarmInformation)
2481 {
2482     static const size_t maximumSizeToPreventUnlimitedGrowth = 100;
2483     if (m_prewarmInformationPerRegistrableDomain.size() == maximumSizeToPreventUnlimitedGrowth)
2484         m_prewarmInformationPerRegistrableDomain.remove(m_prewarmInformationPerRegistrableDomain.random());
2485
2486     auto& value = m_prewarmInformationPerRegistrableDomain.ensure(registrableDomain, [] {
2487         return std::make_unique<WebCore::PrewarmInformation>();
2488     }).iterator->value;
2489
2490     *value = prewarmInformation;
2491 }
2492
2493 void WebProcessPool::tryPrewarmWithDomainInformation(WebProcessProxy& process, const RegistrableDomain& registrableDomain)
2494 {
2495     auto* prewarmInformation = m_prewarmInformationPerRegistrableDomain.get(registrableDomain);
2496     if (!prewarmInformation)
2497         return;
2498     process.send(Messages::WebProcess::PrewarmWithDomainInformation(*prewarmInformation), 0);
2499 }
2500
2501 void WebProcessPool::clearCurrentModifierStateForTesting()
2502 {
2503     sendToAllProcesses(Messages::WebProcess::ClearCurrentModifierStateForTesting());
2504 }
2505
2506 void WebProcessPool::dumpAdClickAttribution(PAL::SessionID sessionID, CompletionHandler<void(const String&)>&& completionHandler)
2507 {
2508     if (!m_networkProcess) {
2509         completionHandler(emptyString());
2510         return;
2511     }
2512
2513     m_networkProcess->dumpAdClickAttribution(sessionID, WTFMove(completionHandler));
2514 }
2515
2516 void WebProcessPool::clearAdClickAttribution(PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
2517 {
2518     if (!m_networkProcess) {
2519         completionHandler();
2520         return;
2521     }
2522     
2523     m_networkProcess->clearAdClickAttribution(sessionID, WTFMove(completionHandler));
2524 }
2525     
2526 void WebProcessPool::committedCrossSiteLoadWithLinkDecoration(PAL::SessionID sessionID, const RegistrableDomain& fromDomain, const RegistrableDomain& toDomain, uint64_t pageID)
2527 {
2528 #if ENABLE(RESOURCE_LOAD_STATISTICS)
2529     if (!m_networkProcess)
2530         return;
2531
2532     m_networkProcess->committedCrossSiteLoadWithLinkDecoration(sessionID, fromDomain, toDomain, pageID, [] { });
2533 #else
2534     UNUSED_PARAM(sessionID);
2535     UNUSED_PARAM(fromDomain);
2536     UNUSED_PARAM(toDomain);
2537     UNUSED_PARAM(pageID);
2538 #endif
2539 }
2540
2541 void WebProcessPool::setWebProcessHasUploads(ProcessIdentifier processID)
2542 {
2543     auto* process = WebProcessProxy::processForIdentifier(processID);
2544     ASSERT(process);
2545
2546     RELEASE_LOG(ProcessSuspension, "Web process pid %u now has uploads in progress", (unsigned)process->processIdentifier());
2547
2548     if (m_processesWithUploads.isEmpty()) {
2549         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now one. Taking Networking and UI process assertions.");
2550
2551         ASSERT(m_networkProcess);
2552         m_networkProcess->takeUploadAssertion();
2553         
2554         ASSERT(!m_uiProcessUploadAssertion);
2555         m_uiProcessUploadAssertion = std::make_unique<ProcessAssertion>(getCurrentProcessID(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2556     }
2557     
2558     auto result = m_processesWithUploads.add(processID, nullptr);
2559     ASSERT(result.isNewEntry);
2560     result.iterator->value = std::make_unique<ProcessAssertion>(process->processIdentifier(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2561 }
2562
2563 void WebProcessPool::clearWebProcessHasUploads(ProcessIdentifier processID)
2564 {
2565     auto result = m_processesWithUploads.take(processID);
2566     ASSERT_UNUSED(result, result);
2567
2568     auto* process = WebProcessProxy::processForIdentifier(processID);
2569     ASSERT(process);
2570     RELEASE_LOG(ProcessSuspension, "Web process pid %u no longer has uploads in progress", (unsigned)process->processIdentifier());
2571
2572     if (m_processesWithUploads.isEmpty()) {
2573         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now zero. Releasing Networking and UI process assertions.");
2574
2575         if (m_networkProcess)
2576             m_networkProcess->clearUploadAssertion();
2577         
2578         ASSERT(m_uiProcessUploadAssertion);
2579         m_uiProcessUploadAssertion = nullptr;
2580     }
2581     
2582 }
2583
2584 } // namespace WebKit