Delay WebProcess launch until a load is triggered in a Web view
[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::addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver& messageReceiver)
1636 {
1637     m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
1638 }
1639
1640 void WebProcessPool::addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
1641 {
1642     m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
1643 }
1644
1645 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName)
1646 {
1647     m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
1648 }
1649
1650 void WebProcessPool::removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID)
1651 {
1652     m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
1653 }
1654
1655 bool WebProcessPool::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
1656 {
1657     return m_messageReceiverMap.dispatchMessage(connection, decoder);
1658 }
1659
1660 bool WebProcessPool::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
1661 {
1662     return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
1663 }
1664
1665 void WebProcessPool::setEnhancedAccessibility(bool flag)
1666 {
1667     sendToAllProcesses(Messages::WebProcess::SetEnhancedAccessibility(flag));
1668 }
1669     
1670 void WebProcessPool::startMemorySampler(const double interval)
1671 {    
1672     // For new WebProcesses we will also want to start the Memory Sampler
1673     m_memorySamplerEnabled = true;
1674     m_memorySamplerInterval = interval;
1675     
1676     // For UIProcess
1677 #if ENABLE(MEMORY_SAMPLER)
1678     WebMemorySampler::singleton()->start(interval);
1679 #endif
1680     
1681     // For WebProcess
1682     SandboxExtension::Handle sampleLogSandboxHandle;    
1683     WallTime now = WallTime::now();
1684     String sampleLogFilePath = makeString("WebProcess", static_cast<unsigned long long>(now.secondsSinceEpoch().seconds()));
1685     sampleLogFilePath = SandboxExtension::createHandleForTemporaryFile(sampleLogFilePath, SandboxExtension::Type::ReadWrite, sampleLogSandboxHandle);
1686     
1687     sendToAllProcesses(Messages::WebProcess::StartMemorySampler(sampleLogSandboxHandle, sampleLogFilePath, interval));
1688 }
1689
1690 void WebProcessPool::stopMemorySampler()
1691 {    
1692     // For WebProcess
1693     m_memorySamplerEnabled = false;
1694     
1695     // For UIProcess
1696 #if ENABLE(MEMORY_SAMPLER)
1697     WebMemorySampler::singleton()->stop();
1698 #endif
1699
1700     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
1701 }
1702
1703 void WebProcessPool::useTestingNetworkSession()
1704 {
1705     ASSERT(m_processes.isEmpty());
1706     ASSERT(!m_networkProcess);
1707
1708     if (m_networkProcess)
1709         return;
1710
1711     if (!m_processes.isEmpty())
1712         return;
1713
1714     m_shouldUseTestingNetworkSession = true;
1715 }
1716
1717 template<typename T, typename U>
1718 void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
1719 {
1720     if (m_networkProcess && m_networkProcess->canSendMessage())
1721         m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
1722 }
1723
1724 void WebProcessPool::setAllowsAnySSLCertificateForWebSocket(bool allows)
1725 {
1726     sendSyncToNetworkingProcess(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply());
1727 }
1728
1729 void WebProcessPool::clearCachedCredentials()
1730 {
1731     if (m_networkProcess)
1732         m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(), 0);
1733 }
1734
1735 void WebProcessPool::terminateNetworkProcess()
1736 {
1737     if (!m_networkProcess)
1738         return;
1739     
1740     m_networkProcess->terminate();
1741     m_networkProcess = nullptr;
1742     m_didNetworkProcessCrash = true;
1743 }
1744
1745 void WebProcessPool::terminateServiceWorkerProcesses()
1746 {
1747 #if ENABLE(SERVICE_WORKER)
1748     auto protectedThis = makeRef(*this);
1749     while (!m_serviceWorkerProcesses.isEmpty())
1750         m_serviceWorkerProcesses.begin()->value->requestTermination(ProcessTerminationReason::RequestedByClient);
1751 #endif
1752 }
1753
1754 void WebProcessPool::syncNetworkProcessCookies()
1755 {
1756     ensureNetworkProcess().syncAllCookies();
1757 }
1758
1759 void WebProcessPool::setIDBPerOriginQuota(uint64_t quota)
1760 {
1761 #if ENABLE(INDEXED_DATABASE)
1762     ensureNetworkProcess().send(Messages::NetworkProcess::SetIDBPerOriginQuota(quota), 0);
1763 #endif
1764 }
1765
1766 void WebProcessPool::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
1767 {
1768     ensureNetworkProcess();
1769     m_networkProcess->send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
1770 }
1771
1772 void WebProcessPool::updateAutomationCapabilities() const
1773 {
1774 #if ENABLE(REMOTE_INSPECTOR)
1775     Inspector::RemoteInspector::singleton().clientCapabilitiesDidChange();
1776 #endif
1777 }
1778
1779 void WebProcessPool::setAutomationSession(RefPtr<WebAutomationSession>&& automationSession)
1780 {
1781     if (m_automationSession)
1782         m_automationSession->setProcessPool(nullptr);
1783     
1784     m_automationSession = WTFMove(automationSession);
1785
1786 #if ENABLE(REMOTE_INSPECTOR)
1787     if (m_automationSession) {
1788         m_automationSession->init();
1789         m_automationSession->setProcessPool(this);
1790
1791         sendToAllProcesses(Messages::WebProcess::EnsureAutomationSessionProxy(m_automationSession->sessionIdentifier()));
1792     } else
1793         sendToAllProcesses(Messages::WebProcess::DestroyAutomationSessionProxy());
1794 #endif
1795 }
1796
1797 void WebProcessPool::setHTTPPipeliningEnabled(bool enabled)
1798 {
1799 #if PLATFORM(COCOA)
1800     ResourceRequest::setHTTPPipeliningEnabled(enabled);
1801 #else
1802     UNUSED_PARAM(enabled);
1803 #endif
1804 }
1805
1806 bool WebProcessPool::httpPipeliningEnabled() const
1807 {
1808 #if PLATFORM(COCOA)
1809     return ResourceRequest::httpPipeliningEnabled();
1810 #else
1811     return false;
1812 #endif
1813 }
1814
1815 void WebProcessPool::getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&& callbackFunction)
1816 {
1817     if (!statisticsMask) {
1818         callbackFunction(nullptr, CallbackBase::Error::Unknown);
1819         return;
1820     }
1821
1822     auto request = StatisticsRequest::create(DictionaryCallback::create(WTFMove(callbackFunction)));
1823
1824     if (statisticsMask & StatisticsRequestTypeWebContent)
1825         requestWebContentStatistics(request.get());
1826     
1827     if (statisticsMask & StatisticsRequestTypeNetworking)
1828         requestNetworkingStatistics(request.get());
1829 }
1830
1831 void WebProcessPool::requestWebContentStatistics(StatisticsRequest& request)
1832 {
1833     // FIXME (Multi-WebProcess) <rdar://problem/13200059>: Make getting statistics from multiple WebProcesses work.
1834 }
1835
1836 void WebProcessPool::requestNetworkingStatistics(StatisticsRequest& request)
1837 {
1838     if (!m_networkProcess) {
1839         LOG_ERROR("Attempt to get NetworkProcess statistics but the NetworkProcess is unavailable");
1840         return;
1841     }
1842
1843     uint64_t requestID = request.addOutstandingRequest();
1844     m_statisticsRequests.set(requestID, &request);
1845     m_networkProcess->send(Messages::NetworkProcess::GetNetworkProcessStatistics(requestID), 0);
1846 }
1847
1848 static WebProcessProxy* webProcessProxyFromConnection(IPC::Connection& connection, const Vector<RefPtr<WebProcessProxy>>& processes)
1849 {
1850     for (auto& process : processes) {
1851         if (process->hasConnection(connection))
1852             return process.get();
1853     }
1854
1855     ASSERT_NOT_REACHED();
1856     return nullptr;
1857 }
1858
1859 void WebProcessPool::handleMessage(IPC::Connection& connection, const String& messageName, const WebKit::UserData& messageBody)
1860 {
1861     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1862     if (!webProcessProxy)
1863         return;
1864     m_injectedBundleClient->didReceiveMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get());
1865 }
1866
1867 void WebProcessPool::handleSynchronousMessage(IPC::Connection& connection, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&& completionHandler)
1868 {
1869     auto* webProcessProxy = webProcessProxyFromConnection(connection, m_processes);
1870     if (!webProcessProxy)
1871         return completionHandler({ });
1872
1873     RefPtr<API::Object> returnData;
1874     m_injectedBundleClient->didReceiveSynchronousMessageFromInjectedBundle(*this, messageName, webProcessProxy->transformHandlesToObjects(messageBody.object()).get(), returnData);
1875     completionHandler(UserData(webProcessProxy->transformObjectsToHandles(returnData.get())));
1876 }
1877
1878 void WebProcessPool::didGetStatistics(const StatisticsData& statisticsData, uint64_t requestID)
1879 {
1880     RefPtr<StatisticsRequest> request = m_statisticsRequests.take(requestID);
1881     if (!request) {
1882         LOG_ERROR("Cannot report networking statistics.");
1883         return;
1884     }
1885
1886     request->completedRequest(requestID, statisticsData);
1887 }
1888
1889 #if ENABLE(GAMEPAD)
1890
1891 void WebProcessPool::startedUsingGamepads(IPC::Connection& connection)
1892 {
1893     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1894     if (!proxy)
1895         return;
1896
1897     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1898
1899     ASSERT(!m_processesUsingGamepads.contains(proxy));
1900     m_processesUsingGamepads.add(proxy);
1901
1902     if (!wereAnyProcessesUsingGamepads)
1903         UIGamepadProvider::singleton().processPoolStartedUsingGamepads(*this);
1904
1905     proxy->send(Messages::WebProcess::SetInitialGamepads(UIGamepadProvider::singleton().snapshotGamepads()), 0);
1906 }
1907
1908 void WebProcessPool::stoppedUsingGamepads(IPC::Connection& connection)
1909 {
1910     auto* proxy = webProcessProxyFromConnection(connection, m_processes);
1911     if (!proxy)
1912         return;
1913
1914     ASSERT(m_processesUsingGamepads.contains(proxy));
1915     processStoppedUsingGamepads(*proxy);
1916 }
1917
1918 void WebProcessPool::processStoppedUsingGamepads(WebProcessProxy& process)
1919 {
1920     bool wereAnyProcessesUsingGamepads = !m_processesUsingGamepads.isEmpty();
1921
1922     ASSERT(m_processesUsingGamepads.contains(&process));
1923     m_processesUsingGamepads.remove(&process);
1924
1925     if (wereAnyProcessesUsingGamepads && m_processesUsingGamepads.isEmpty())
1926         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
1927 }
1928
1929 void WebProcessPool::gamepadConnected(const UIGamepad& gamepad)
1930 {
1931     for (auto& process : m_processesUsingGamepads)
1932         process->send(Messages::WebProcess::GamepadConnected(gamepad.fullGamepadData()), 0);
1933 }
1934
1935 void WebProcessPool::gamepadDisconnected(const UIGamepad& gamepad)
1936 {
1937     for (auto& process : m_processesUsingGamepads)
1938         process->send(Messages::WebProcess::GamepadDisconnected(gamepad.index()), 0);
1939 }
1940
1941 void WebProcessPool::setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>& gamepads)
1942 {
1943     Vector<GamepadData> gamepadDatas;
1944     gamepadDatas.grow(gamepads.size());
1945     for (size_t i = 0; i < gamepads.size(); ++i) {
1946         if (!gamepads[i])
1947             continue;
1948         gamepadDatas[i] = gamepads[i]->fullGamepadData();
1949     }
1950
1951     for (auto& process : m_processesUsingGamepads)
1952         process->send(Messages::WebProcess::SetInitialGamepads(gamepadDatas), 0);
1953 }
1954
1955 #endif // ENABLE(GAMEPAD)
1956
1957 void WebProcessPool::setJavaScriptConfigurationFileEnabled(bool flag)
1958 {
1959     m_javaScriptConfigurationFileEnabled = flag;
1960 }
1961
1962 void WebProcessPool::garbageCollectJavaScriptObjects()
1963 {
1964     sendToAllProcesses(Messages::WebProcess::GarbageCollectJavaScriptObjects());
1965 }
1966
1967 void WebProcessPool::setJavaScriptGarbageCollectorTimerEnabled(bool flag)
1968 {
1969     sendToAllProcesses(Messages::WebProcess::SetJavaScriptGarbageCollectorTimerEnabled(flag));
1970 }
1971
1972 void WebProcessPool::addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID sessionID)
1973 {
1974     m_plugInAutoStartProvider.addAutoStartOriginHash(pageOrigin, plugInOriginHash, sessionID);
1975 }
1976
1977 void WebProcessPool::plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID sessionID)
1978 {
1979     m_plugInAutoStartProvider.didReceiveUserInteraction(plugInOriginHash, sessionID);
1980 }
1981
1982 Ref<API::Dictionary> WebProcessPool::plugInAutoStartOriginHashes() const
1983 {
1984     return m_plugInAutoStartProvider.autoStartOriginsTableCopy();
1985 }
1986
1987 void WebProcessPool::setPlugInAutoStartOriginHashes(API::Dictionary& dictionary)
1988 {
1989     m_plugInAutoStartProvider.setAutoStartOriginsTable(dictionary);
1990 }
1991
1992 void WebProcessPool::setPlugInAutoStartOrigins(API::Array& array)
1993 {
1994     m_plugInAutoStartProvider.setAutoStartOriginsArray(array);
1995 }
1996
1997 void WebProcessPool::setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary& dictionary, WallTime time)
1998 {
1999     m_plugInAutoStartProvider.setAutoStartOriginsFilteringOutEntriesAddedAfterTime(dictionary, time);
2000 }
2001
2002 void WebProcessPool::registerSchemeForCustomProtocol(const String& scheme)
2003 {
2004 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
2005     if (!globalURLSchemesWithCustomProtocolHandlers().contains(scheme))
2006         m_urlSchemesRegisteredForCustomProtocols.add(scheme);
2007     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::RegisterScheme(scheme));
2008 #endif
2009 }
2010
2011 void WebProcessPool::unregisterSchemeForCustomProtocol(const String& scheme)
2012 {
2013 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
2014     m_urlSchemesRegisteredForCustomProtocols.remove(scheme);
2015     sendToNetworkingProcess(Messages::LegacyCustomProtocolManager::UnregisterScheme(scheme));
2016 #endif
2017 }
2018
2019 #if ENABLE(NETSCAPE_PLUGIN_API)
2020 void WebProcessPool::setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy policy, const String& host, const String& bundleIdentifier, const String& versionString)
2021 {
2022     auto& policiesForHost = m_pluginLoadClientPolicies.ensure(host, [] { return HashMap<String, HashMap<String, uint8_t>>(); }).iterator->value;
2023     auto& versionsToPolicies = policiesForHost.ensure(bundleIdentifier, [] { return HashMap<String, uint8_t>(); }).iterator->value;
2024     versionsToPolicies.set(versionString, policy);
2025
2026     sendToAllProcesses(Messages::WebProcess::SetPluginLoadClientPolicy(policy, host, bundleIdentifier, versionString));
2027 }
2028
2029 void WebProcessPool::resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&& pluginLoadClientPolicies)
2030 {
2031     m_pluginLoadClientPolicies = WTFMove(pluginLoadClientPolicies);
2032     sendToAllProcesses(Messages::WebProcess::ResetPluginLoadClientPolicies(m_pluginLoadClientPolicies));
2033 }
2034
2035 void WebProcessPool::clearPluginClientPolicies()
2036 {
2037     m_pluginLoadClientPolicies.clear();
2038     sendToAllProcesses(Messages::WebProcess::ClearPluginClientPolicies());
2039 }
2040 #endif
2041
2042 void WebProcessPool::addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions)
2043 {
2044 #if ENABLE(NETSCAPE_PLUGIN_API)
2045     m_pluginInfoStore.addSupportedPlugin(WTFMove(matchingDomain), WTFMove(name), WTFMove(mimeTypes), WTFMove(extensions));
2046 #else
2047     UNUSED_PARAM(matchingDomain);
2048     UNUSED_PARAM(name);
2049     UNUSED_PARAM(mimeTypes);
2050     UNUSED_PARAM(extensions);
2051 #endif
2052 }
2053
2054 void WebProcessPool::clearSupportedPlugins()
2055 {
2056 #if ENABLE(NETSCAPE_PLUGIN_API)
2057     m_pluginInfoStore.clearSupportedPlugins();
2058 #endif
2059 }
2060
2061 void WebProcessPool::setMemoryCacheDisabled(bool disabled)
2062 {
2063     m_memoryCacheDisabled = disabled;
2064     sendToAllProcesses(Messages::WebProcess::SetMemoryCacheDisabled(disabled));
2065 }
2066
2067 void WebProcessPool::setFontWhitelist(API::Array* array)
2068 {
2069     m_fontWhitelist.clear();
2070     if (array) {
2071         for (size_t i = 0; i < array->size(); ++i) {
2072             if (API::String* font = array->at<API::String>(i))
2073                 m_fontWhitelist.append(font->string());
2074         }
2075     }
2076 }
2077
2078 void WebProcessPool::updateHiddenPageThrottlingAutoIncreaseLimit()
2079 {
2080     // We're estimating an upper bound for a set of background timer fires for a page to be 200ms
2081     // (including all timer fires, all paging-in, and any resulting GC). To ensure this does not
2082     // result in more than 1% CPU load allow for one timer fire per 100x this duration.
2083     static int maximumTimerThrottlePerPageInMS = 200 * 100;
2084
2085     int limitInMilliseconds = maximumTimerThrottlePerPageInMS * m_hiddenPageThrottlingAutoIncreasesCounter.value();
2086     sendToAllProcesses(Messages::WebProcess::SetHiddenPageDOMTimerThrottlingIncreaseLimit(limitInMilliseconds));
2087 }
2088
2089 void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState)
2090 {
2091 #if PLATFORM(MAC)
2092     if (m_perActivityStateCPUUsageSampler)
2093         m_perActivityStateCPUUsageSampler->reportWebContentCPUTime(cpuTime, static_cast<WebCore::ActivityStateForCPUSampling>(activityState));
2094 #else
2095     UNUSED_PARAM(cpuTime);
2096     UNUSED_PARAM(activityState);
2097 #endif
2098 }
2099
2100 void WebProcessPool::updateProcessAssertions()
2101 {
2102 #if PLATFORM(IOS_FAMILY)
2103 #if ENABLE(SERVICE_WORKER)
2104     auto updateServiceWorkerProcessAssertion = [&] {
2105         if (!m_serviceWorkerProcesses.isEmpty() && m_foregroundWebProcessCounter.value()) {
2106             // FIXME: We can do better than this once we have process per origin.
2107             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2108                 auto& registrableDomain = serviceWorkerProcess->registrableDomain();
2109                 if (!m_foregroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2110                     m_foregroundTokensForServiceWorkerProcesses.add(registrableDomain, serviceWorkerProcess->throttler().foregroundActivityToken());
2111             }
2112             m_backgroundTokensForServiceWorkerProcesses.clear();
2113             return;
2114         }
2115         if (!m_serviceWorkerProcesses.isEmpty() && m_backgroundWebProcessCounter.value()) {
2116             // FIXME: We can do better than this once we have process per origin.
2117             for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2118                 auto& registrableDomain = serviceWorkerProcess->registrableDomain();
2119                 if (!m_backgroundTokensForServiceWorkerProcesses.contains(registrableDomain))
2120                     m_backgroundTokensForServiceWorkerProcesses.add(registrableDomain, serviceWorkerProcess->throttler().backgroundActivityToken());
2121             }
2122             m_foregroundTokensForServiceWorkerProcesses.clear();
2123             return;
2124         }
2125         m_foregroundTokensForServiceWorkerProcesses.clear();
2126         m_backgroundTokensForServiceWorkerProcesses.clear();
2127     };
2128     updateServiceWorkerProcessAssertion();
2129 #endif
2130
2131     auto updateNetworkProcessAssertion = [&] {
2132         auto& networkProcess = ensureNetworkProcess();
2133
2134         if (m_foregroundWebProcessCounter.value()) {
2135             if (!m_foregroundTokenForNetworkProcess) {
2136                 m_foregroundTokenForNetworkProcess = networkProcess.throttler().foregroundActivityToken();
2137                 networkProcess.sendProcessDidTransitionToForeground();
2138             }
2139             m_backgroundTokenForNetworkProcess = nullptr;
2140             return;
2141         }
2142         if (m_backgroundWebProcessCounter.value()) {
2143             if (!m_backgroundTokenForNetworkProcess) {
2144                 m_backgroundTokenForNetworkProcess = networkProcess.throttler().backgroundActivityToken();
2145                 networkProcess.sendProcessDidTransitionToBackground();
2146             }
2147             m_foregroundTokenForNetworkProcess = nullptr;
2148             return;
2149         }
2150         m_foregroundTokenForNetworkProcess = nullptr;
2151         m_backgroundTokenForNetworkProcess = nullptr;
2152     };
2153     updateNetworkProcessAssertion();
2154 #endif
2155 }
2156
2157 #if ENABLE(SERVICE_WORKER)
2158 void WebProcessPool::postMessageToServiceWorkerClient(const ServiceWorkerClientIdentifier& destination, MessageWithMessagePorts&& message, ServiceWorkerIdentifier source, const String& sourceOrigin)
2159 {
2160     sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::PostMessageToServiceWorkerClient(destination, WTFMove(message), source, sourceOrigin));
2161 }
2162
2163 void WebProcessPool::postMessageToServiceWorker(ServiceWorkerIdentifier destination, MessageWithMessagePorts&& message, const ServiceWorkerOrClientIdentifier& source, SWServerConnectionIdentifier connectionIdentifier)
2164 {
2165     sendToNetworkingProcessRelaunchingIfNecessary(Messages::NetworkProcess::PostMessageToServiceWorker(destination, WTFMove(message), source, connectionIdentifier));
2166 }
2167 #endif
2168
2169 void WebProcessPool::reinstateNetworkProcessAssertionState(NetworkProcessProxy& newNetworkProcessProxy)
2170 {
2171 #if PLATFORM(IOS_FAMILY)
2172     // The network process crashed; take new tokens for the new network process.
2173     if (m_backgroundTokenForNetworkProcess)
2174         m_backgroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().backgroundActivityToken();
2175     else if (m_foregroundTokenForNetworkProcess)
2176         m_foregroundTokenForNetworkProcess = newNetworkProcessProxy.throttler().foregroundActivityToken();
2177 #else
2178     UNUSED_PARAM(newNetworkProcessProxy);
2179 #endif
2180 }
2181
2182 #if ENABLE(SERVICE_WORKER)
2183 ServiceWorkerProcessProxy* WebProcessPool::serviceWorkerProcessProxyFromPageID(uint64_t pageID) const
2184 {
2185     // FIXME: This is inefficient.
2186     for (auto* serviceWorkerProcess : m_serviceWorkerProcesses.values()) {
2187         if (serviceWorkerProcess->pageID() == pageID)
2188             return serviceWorkerProcess;
2189     }
2190     return nullptr;
2191 }
2192 #endif
2193
2194 void WebProcessPool::addProcessToOriginCacheSet(WebProcessProxy& process, const URL& url)
2195 {
2196     auto registrableDomain = WebCore::RegistrableDomain { url };
2197     auto result = m_swappedProcessesPerRegistrableDomain.add(registrableDomain, &process);
2198     if (!result.isNewEntry)
2199         result.iterator->value = &process;
2200
2201     LOG(ProcessSwapping, "(ProcessSwapping) Registrable domain %s just saved a cached process with pid %i", registrableDomain.string().utf8().data(), process.processIdentifier());
2202     if (!result.isNewEntry)
2203         LOG(ProcessSwapping, "(ProcessSwapping) Note: It already had one saved");
2204 }
2205
2206 void WebProcessPool::removeProcessFromOriginCacheSet(WebProcessProxy& process)
2207 {
2208     LOG(ProcessSwapping, "(ProcessSwapping) Removing process with pid %i from the origin cache set", process.processIdentifier());
2209
2210     // FIXME: This can be very inefficient as the number of remembered origins and processes grows
2211     Vector<WebCore::RegistrableDomain> registrableDomainsToRemove;
2212     for (auto entry : m_swappedProcessesPerRegistrableDomain) {
2213         if (entry.value == &process)
2214             registrableDomainsToRemove.append(entry.key);
2215     }
2216
2217     for (auto& registrableDomain : registrableDomainsToRemove)
2218         m_swappedProcessesPerRegistrableDomain.remove(registrableDomain);
2219 }
2220
2221 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)
2222 {
2223     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 {
2224         // We are process-swapping so automatic process prewarming would be beneficial if the client has not explicitly enabled / disabled it.
2225         bool doingAnAutomaticProcessSwap = processSwapRequestedByClient == ProcessSwapRequestedByClient::No && process.ptr() != sourceProcess.ptr();
2226         if (doingAnAutomaticProcessSwap && !configuration().wasAutomaticProcessWarmingSetByClient() && !configuration().clientWouldBenefitFromAutomaticProcessPrewarming()) {
2227             RELEASE_LOG(PerformanceLogging, "Automatically turning on process prewarming because the client would benefit from it");
2228             configuration().setClientWouldBenefitFromAutomaticProcessPrewarming(true);
2229         }
2230
2231         if (m_configuration->alwaysKeepAndReuseSwappedProcesses() && process.ptr() != sourceProcess.ptr()) {
2232             static std::once_flag onceFlag;
2233             std::call_once(onceFlag, [] {
2234                 WTFLogAlways("WARNING: The option to always keep swapped web processes alive is active. This is meant for debugging and testing only.");
2235             });
2236
2237             addProcessToOriginCacheSet(sourceProcess, sourceURL);
2238
2239             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());
2240         }
2241
2242         completionHandler(WTFMove(process), suspendedPage, reason);
2243     });
2244 }
2245
2246 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)
2247 {
2248     auto& targetURL = navigation.currentRequest().url();
2249     auto targetRegistrableDomain = WebCore::RegistrableDomain { targetURL };
2250
2251     auto createNewProcess = [this, protectedThis = makeRef(*this), page = makeRef(page), targetRegistrableDomain, dataStore = dataStore.copyRef()] () -> Ref<WebProcessProxy> {
2252         return processForRegistrableDomain(dataStore, page.ptr(), targetRegistrableDomain);
2253     };
2254
2255     if (usesSingleWebProcess())
2256         return completionHandler(WTFMove(sourceProcess), nullptr, "Single WebProcess mode is enabled"_s);
2257
2258     if (processSwapRequestedByClient == ProcessSwapRequestedByClient::Yes)
2259         return completionHandler(createNewProcess(), nullptr, "Process swap was requested by the client"_s);
2260
2261     if (!m_configuration->processSwapsOnNavigation())
2262         return completionHandler(WTFMove(sourceProcess), nullptr, "Feature is disabled"_s);
2263
2264     if (m_automationSession)
2265         return completionHandler(WTFMove(sourceProcess), nullptr, "An automation session is active"_s);
2266
2267     if (!sourceProcess->hasCommittedAnyProvisionalLoads()) {
2268         tryPrewarmWithDomainInformation(sourceProcess, targetRegistrableDomain);
2269         return completionHandler(WTFMove(sourceProcess), nullptr, "Process has not yet committed any provisional loads"_s);
2270     }
2271
2272     // FIXME: We should support process swap when a window has been opened via window.open() without 'noopener'.
2273     // The issue is that the opener has a handle to the WindowProxy.
2274     if (navigation.openedByDOMWithOpener() && !m_configuration->processSwapsOnWindowOpenWithOpener())
2275         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context been opened by DOM without 'noopener'"_s);
2276
2277     // FIXME: We should support process swap when a window has opened other windows via window.open.
2278     if (navigation.hasOpenedFrames())
2279         return completionHandler(WTFMove(sourceProcess), nullptr, "Browsing context has opened other windows"_s);
2280
2281     if (auto* targetItem = navigation.targetItem()) {
2282         if (auto* suspendedPage = targetItem->suspendedPage()) {
2283             return suspendedPage->waitUntilReadyToUnsuspend([createNewProcess = WTFMove(createNewProcess), completionHandler = WTFMove(completionHandler)](SuspendedPageProxy* suspendedPage) mutable {
2284                 if (!suspendedPage)
2285                     return completionHandler(createNewProcess(), nullptr, "Using new process because target back/forward item's suspended page is not reusable"_s);
2286                 Ref<WebProcessProxy> process = suspendedPage->process();
2287                 completionHandler(WTFMove(process), suspendedPage, "Using target back/forward item's process and suspended page"_s);
2288             });
2289         }
2290
2291         if (RefPtr<WebProcessProxy> process = WebProcessProxy::processForIdentifier(targetItem->lastProcessIdentifier())) {
2292             // FIXME: Architecturally we do not currently support multiple WebPage's with the same ID in a given WebProcess.
2293             // In the case where this WebProcess has a SuspendedPageProxy for this WebPage, we can throw it away to support
2294             // WebProcess re-use.
2295             removeAllSuspendedPagesForPage(page, process.get());
2296
2297             // Make sure we remove the process from the cache if it is in there since we're about to use it.
2298             if (process->isInProcessCache()) {
2299                 webProcessCache().removeProcess(*process, WebProcessCache::ShouldShutDownProcess::No);
2300                 ASSERT(!process->isInProcessCache());
2301             }
2302
2303             return completionHandler(process.releaseNonNull(), nullptr, "Using target back/forward item's process"_s);
2304         }
2305     }
2306
2307     if (navigation.treatAsSameOriginNavigation())
2308         return completionHandler(WTFMove(sourceProcess), nullptr, "The treatAsSameOriginNavigation flag is set"_s);
2309
2310     URL sourceURL;
2311     if (page.isPageOpenedByDOMShowingInitialEmptyDocument() && !navigation.requesterOrigin().isEmpty())
2312         sourceURL = URL { URL(), navigation.requesterOrigin().toString() };
2313     else
2314         sourceURL = pageSourceURL;
2315
2316     if (sourceURL.isEmpty() && page.configuration().relatedPage()) {
2317         sourceURL = URL { { }, page.configuration().relatedPage()->pageLoadState().url() };
2318         RELEASE_LOG(ProcessSwapping, "Using related page %p's URL as source URL for process swap decision", page.configuration().relatedPage());
2319     }
2320
2321     if (!sourceURL.isValid() || !targetURL.isValid() || sourceURL.isEmpty() || sourceURL.protocolIsAbout() || targetRegistrableDomain.matches(sourceURL))
2322         return completionHandler(WTFMove(sourceProcess), nullptr, "Navigation is same-site"_s);
2323
2324     String reason = "Navigation is cross-site"_s;
2325     
2326     if (m_configuration->alwaysKeepAndReuseSwappedProcesses()) {
2327         LOG(ProcessSwapping, "(ProcessSwapping) Considering re-use of a previously cached process for domain %s", targetRegistrableDomain.string().utf8().data());
2328
2329         if (auto* process = m_swappedProcessesPerRegistrableDomain.get(targetRegistrableDomain)) {
2330             if (&process->websiteDataStore() == dataStore.ptr()) {
2331                 LOG(ProcessSwapping, "(ProcessSwapping) Reusing a previously cached process with pid %i to continue navigation to URL %s", process->processIdentifier(), targetURL.string().utf8().data());
2332
2333                 // FIXME: Architecturally we do not currently support multiple WebPage's with the same ID in a given WebProcess.
2334                 // In the case where this WebProcess has a SuspendedPageProxy for this WebPage, we can throw it away to support
2335                 // WebProcess re-use.
2336                 // In the future it would be great to refactor-out this limitation (https://bugs.webkit.org/show_bug.cgi?id=191166).
2337                 removeAllSuspendedPagesForPage(page, process);
2338
2339                 return completionHandler(makeRef(*process), nullptr, reason);
2340             }
2341         }
2342     }
2343
2344     return completionHandler(createNewProcess(), nullptr, reason);
2345 }
2346
2347 RefPtr<WebProcessProxy> WebProcessPool::findReusableSuspendedPageProcess(const WebCore::RegistrableDomain& registrableDomain, WebPageProxy& page, WebsiteDataStore& dataStore)
2348 {
2349     auto it = m_suspendedPages.findIf([&](auto& suspendedPage) {
2350         return suspendedPage->registrableDomain() == registrableDomain && &suspendedPage->process().websiteDataStore() == &dataStore;
2351     });
2352     if (it == m_suspendedPages.end())
2353         return nullptr;
2354
2355     Ref<WebProcessProxy> process = (*it)->process();
2356
2357     // FIXME: If the SuspendedPage is for this page, then we need to destroy the suspended page as we do not support having
2358     // multiple WebPages with the same ID in a given WebProcess currently (https://bugs.webkit.org/show_bug.cgi?id=191166).
2359     if (&(*it)->page() == &page)
2360         m_suspendedPages.remove(it);
2361
2362
2363     return WTFMove(process);
2364 }
2365
2366 void WebProcessPool::addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&& suspendedPage)
2367 {
2368     if (!m_maxSuspendedPageCount)
2369         return;
2370
2371     if (m_suspendedPages.size() >= m_maxSuspendedPageCount)
2372         m_suspendedPages.removeFirst();
2373
2374     m_suspendedPages.append(WTFMove(suspendedPage));
2375 }
2376
2377 void WebProcessPool::removeAllSuspendedPagesForPage(WebPageProxy& page, WebProcessProxy* process)
2378 {
2379     m_suspendedPages.removeAllMatching([&page, process](auto& suspendedPage) {
2380         return &suspendedPage->page() == &page && (!process || &suspendedPage->process() == process);
2381     });
2382 }
2383
2384 void WebProcessPool::closeFailedSuspendedPagesForPage(WebPageProxy& page)
2385 {
2386     for (auto& suspendedPage : m_suspendedPages) {
2387         if (&suspendedPage->page() == &page && suspendedPage->failedToSuspend())
2388             suspendedPage->close();
2389     }
2390 }
2391
2392 std::unique_ptr<SuspendedPageProxy> WebProcessPool::takeSuspendedPage(SuspendedPageProxy& suspendedPage)
2393 {
2394     return m_suspendedPages.takeFirst([&suspendedPage](auto& item) {
2395         return item.get() == &suspendedPage;
2396     });
2397 }
2398
2399 void WebProcessPool::removeSuspendedPage(SuspendedPageProxy& suspendedPage)
2400 {
2401     auto it = m_suspendedPages.findIf([&suspendedPage](auto& item) {
2402         return item.get() == &suspendedPage;
2403     });
2404     if (it != m_suspendedPages.end())
2405         m_suspendedPages.remove(it);
2406 }
2407
2408 bool WebProcessPool::hasSuspendedPageFor(WebProcessProxy& process, WebPageProxy& page) const
2409 {
2410     return m_suspendedPages.findIf([&process, &page](auto& suspendedPage) {
2411         return &suspendedPage->process() == &process && &suspendedPage->page() == &page;
2412     }) != m_suspendedPages.end();
2413 }
2414
2415 void WebProcessPool::clearSuspendedPages(AllowProcessCaching allowProcessCaching)
2416 {
2417     HashSet<RefPtr<WebProcessProxy>> processes;
2418     for (auto& suspendedPage : m_suspendedPages)
2419         processes.add(&suspendedPage->process());
2420
2421     m_suspendedPages.clear();
2422
2423     for (auto& process : processes)
2424         process->maybeShutDown(allowProcessCaching);
2425 }
2426
2427 void WebProcessPool::addMockMediaDevice(const MockMediaDevice& device)
2428 {
2429 #if ENABLE(MEDIA_STREAM)
2430     MockRealtimeMediaSourceCenter::addDevice(device);
2431     sendToAllProcesses(Messages::WebProcess::AddMockMediaDevice { device });
2432 #endif
2433 }
2434
2435 void WebProcessPool::clearMockMediaDevices()
2436 {
2437 #if ENABLE(MEDIA_STREAM)
2438     MockRealtimeMediaSourceCenter::setDevices({ });
2439     sendToAllProcesses(Messages::WebProcess::ClearMockMediaDevices { });
2440 #endif
2441 }
2442
2443 void WebProcessPool::removeMockMediaDevice(const String& persistentId)
2444 {
2445 #if ENABLE(MEDIA_STREAM)
2446     MockRealtimeMediaSourceCenter::removeDevice(persistentId);
2447     sendToAllProcesses(Messages::WebProcess::RemoveMockMediaDevice { persistentId });
2448 #endif
2449 }
2450
2451 void WebProcessPool::resetMockMediaDevices()
2452 {
2453 #if ENABLE(MEDIA_STREAM)
2454     MockRealtimeMediaSourceCenter::resetDevices();
2455     sendToAllProcesses(Messages::WebProcess::ResetMockMediaDevices { });
2456 #endif
2457 }
2458
2459 void WebProcessPool::sendDisplayConfigurationChangedMessageForTesting()
2460 {
2461 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
2462     auto display = CGSMainDisplayID();
2463
2464     for (auto& processPool : WebProcessPool::allProcessPools()) {
2465         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplayBeginConfigurationFlag));
2466         processPool->sendToAllProcesses(Messages::WebProcess::DisplayConfigurationChanged(display, kCGDisplaySetModeFlag | kCGDisplayDesktopShapeChangedFlag));
2467     }
2468 #endif
2469 }
2470
2471 void WebProcessPool::didCollectPrewarmInformation(const WebCore::RegistrableDomain& registrableDomain, const WebCore::PrewarmInformation& prewarmInformation)
2472 {
2473     static const size_t maximumSizeToPreventUnlimitedGrowth = 100;
2474     if (m_prewarmInformationPerRegistrableDomain.size() == maximumSizeToPreventUnlimitedGrowth)
2475         m_prewarmInformationPerRegistrableDomain.remove(m_prewarmInformationPerRegistrableDomain.random());
2476
2477     auto& value = m_prewarmInformationPerRegistrableDomain.ensure(registrableDomain, [] {
2478         return std::make_unique<WebCore::PrewarmInformation>();
2479     }).iterator->value;
2480
2481     *value = prewarmInformation;
2482 }
2483
2484 void WebProcessPool::tryPrewarmWithDomainInformation(WebProcessProxy& process, const RegistrableDomain& registrableDomain)
2485 {
2486     auto* prewarmInformation = m_prewarmInformationPerRegistrableDomain.get(registrableDomain);
2487     if (!prewarmInformation)
2488         return;
2489     process.send(Messages::WebProcess::PrewarmWithDomainInformation(*prewarmInformation), 0);
2490 }
2491
2492 void WebProcessPool::clearCurrentModifierStateForTesting()
2493 {
2494     sendToAllProcesses(Messages::WebProcess::ClearCurrentModifierStateForTesting());
2495 }
2496
2497 void WebProcessPool::dumpAdClickAttribution(PAL::SessionID sessionID, CompletionHandler<void(const String&)>&& completionHandler)
2498 {
2499     if (!m_networkProcess) {
2500         completionHandler(emptyString());
2501         return;
2502     }
2503
2504     m_networkProcess->dumpAdClickAttribution(sessionID, WTFMove(completionHandler));
2505 }
2506
2507 void WebProcessPool::clearAdClickAttribution(PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
2508 {
2509     if (!m_networkProcess) {
2510         completionHandler();
2511         return;
2512     }
2513     
2514     m_networkProcess->clearAdClickAttribution(sessionID, WTFMove(completionHandler));
2515 }
2516     
2517 void WebProcessPool::committedCrossSiteLoadWithLinkDecoration(PAL::SessionID sessionID, const RegistrableDomain& fromDomain, const RegistrableDomain& toDomain, uint64_t pageID)
2518 {
2519 #if ENABLE(RESOURCE_LOAD_STATISTICS)
2520     if (!m_networkProcess)
2521         return;
2522
2523     m_networkProcess->committedCrossSiteLoadWithLinkDecoration(sessionID, fromDomain, toDomain, pageID, [] { });
2524 #else
2525     UNUSED_PARAM(sessionID);
2526     UNUSED_PARAM(fromDomain);
2527     UNUSED_PARAM(toDomain);
2528     UNUSED_PARAM(pageID);
2529 #endif
2530 }
2531
2532 void WebProcessPool::setWebProcessHasUploads(ProcessIdentifier processID)
2533 {
2534     auto* process = WebProcessProxy::processForIdentifier(processID);
2535     ASSERT(process);
2536
2537     RELEASE_LOG(ProcessSuspension, "Web process pid %u now has uploads in progress", (unsigned)process->processIdentifier());
2538
2539     if (m_processesWithUploads.isEmpty()) {
2540         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now one. Taking Networking and UI process assertions.");
2541
2542         ASSERT(m_networkProcess);
2543         m_networkProcess->takeUploadAssertion();
2544         
2545         ASSERT(!m_uiProcessUploadAssertion);
2546         m_uiProcessUploadAssertion = std::make_unique<ProcessAssertion>(getCurrentProcessID(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2547     }
2548     
2549     auto result = m_processesWithUploads.add(processID, nullptr);
2550     ASSERT(result.isNewEntry);
2551     result.iterator->value = std::make_unique<ProcessAssertion>(process->processIdentifier(), "WebKit uploads"_s, AssertionState::UnboundedNetworking);
2552 }
2553
2554 void WebProcessPool::clearWebProcessHasUploads(ProcessIdentifier processID)
2555 {
2556     auto result = m_processesWithUploads.take(processID);
2557     ASSERT_UNUSED(result, result);
2558
2559     auto* process = WebProcessProxy::processForIdentifier(processID);
2560     ASSERT(process);
2561     RELEASE_LOG(ProcessSuspension, "Web process pid %u no longer has uploads in progress", (unsigned)process->processIdentifier());
2562
2563     if (m_processesWithUploads.isEmpty()) {
2564         RELEASE_LOG(ProcessSuspension, "The number of uploads in progress is now zero. Releasing Networking and UI process assertions.");
2565
2566         if (m_networkProcess)
2567             m_networkProcess->clearUploadAssertion();
2568         
2569         ASSERT(m_uiProcessUploadAssertion);
2570         m_uiProcessUploadAssertion = nullptr;
2571     }
2572     
2573 }
2574
2575 } // namespace WebKit