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