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