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