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