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