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