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