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