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