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